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,500
test_source_svn.py
buildbot_buildbot/master/buildbot/test/unit/steps/test_source_svn.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.internet import error from twisted.python.reflect import namedModule from twisted.trial import unittest from buildbot import config from buildbot.interfaces import WorkerSetupError from buildbot.process import buildstep from buildbot.process import remotetransfer from buildbot.process.results import FAILURE from buildbot.process.results import RETRY from buildbot.process.results import SUCCESS from buildbot.steps.source import svn from buildbot.test.reactor import TestReactorMixin from buildbot.test.steps import ExpectCpdir from buildbot.test.steps import ExpectDownloadFile from buildbot.test.steps import ExpectRemoteRef from buildbot.test.steps import ExpectRmdir from buildbot.test.steps import ExpectShell from buildbot.test.steps import ExpectStat from buildbot.test.util import sourcesteps from buildbot.test.util.properties import ConstantRenderable class TestSVN(sourcesteps.SourceStepMixin, TestReactorMixin, unittest.TestCase): svn_st_xml = """<?xml version="1.0"?> <status> <target path="."> <entry path="svn_external_path"> <wc-status props="none" item="external"> </wc-status> </entry> <entry path="svn_external_path/unversioned_file1"> <wc-status props="none" item="unversioned"> </wc-status> </entry> <entry path="svn_external_path/unversioned_file2_uniçode"> <wc-status props="none" item="unversioned"> </wc-status> </entry> </target> </status> """ svn_st_xml_corrupt = """<?xml version="1.0"?> <target path="."> <entry path="svn_external_path"> <wc-status props="none" item="external"> </wc-status> </entry> <entry path="svn_external_path/unversioned_file"> <wc-status props="none" item="unversioned"> </wc-status> </entry> </target> </status> """ svn_st_xml_empty = """<?xml version="1.0"?> <status> <target path="."> </target> </status>""" svn_info_stdout_xml = """<?xml version="1.0"?> <info> <entry kind="dir" path="." revision="100"> <url>http://svn.red-bean.com/repos/test</url> <repository> <root>http://svn.red-bean.com/repos/test</root> <uuid>5e7d134a-54fb-0310-bd04-b611643e5c25</uuid> </repository> <wc-info> <schedule>normal</schedule> <depth>infinity</depth> </wc-info> <commit revision="90"> <author>sally</author> <date>2003-01-15T23:35:12.847647Z</date> </commit> </entry> </info>""" svn_info_stdout_xml_nonintegerrevision = """<?xml version="1.0"?> <info> <entry kind="dir" path="." revision="a10"> <url>http://svn.red-bean.com/repos/test</url> <repository> <root>http://svn.red-bean.com/repos/test</root> <uuid>5e7d134a-54fb-0310-bd04-b611643e5c25</uuid> </repository> <wc-info> <schedule>normal</schedule> <depth>infinity</depth> </wc-info> <commit revision="a10"> <author>sally</author> <date>2003-01-15T23:35:12.847647Z</date> </commit> </entry> </info>""" def setUp(self): self.setup_test_reactor(auto_tear_down=False) return self.setUpSourceStep() @defer.inlineCallbacks def tearDown(self): yield self.tearDownSourceStep() yield self.tear_down_test_reactor() def patch_workerVersionIsOlderThan(self, result): self.patch(svn.SVN, 'workerVersionIsOlderThan', lambda x, y, z: result) def test_no_repourl(self): with self.assertRaises(config.ConfigErrors): svn.SVN() def test_incorrect_mode(self): with self.assertRaises(config.ConfigErrors): svn.SVN(repourl='http://svn.local/app/trunk', mode='invalid') def test_incorrect_method(self): with self.assertRaises(config.ConfigErrors): svn.SVN(repourl='http://svn.local/app/trunk', method='invalid') def test_svn_not_installed(self): self.setup_step(svn.SVN(repourl='http://svn.local/app/trunk')) self.expect_commands(ExpectShell(workdir='wkdir', command=['svn', '--version']).exit(1)) self.expect_exception(WorkerSetupError) return self.run_step() def test_corrupt_xml(self): self.setup_step(svn.SVN(repourl='http://svn.local/app/trunk')) self.expect_commands( ExpectShell(workdir='wkdir', command=['svn', '--version']).exit(0), ExpectStat(file='wkdir/.buildbot-patched', log_environ=True).exit(1), ExpectStat(file='wkdir/.svn', log_environ=True).exit(0), ExpectShell( workdir='wkdir', command=['svn', 'info', '--xml', '--non-interactive', '--no-auth-cache'], ) .stdout('<?xml version="1.0"?><url>http://svn.local/app/trunk</url>') .exit(0), ExpectShell( workdir='wkdir', command=['svn', 'update', '--non-interactive', '--no-auth-cache'] ).exit(0), ExpectShell(workdir='wkdir', command=['svn', 'info', '--xml']) .stdout(self.svn_st_xml_corrupt) .exit(0), ) self.expect_outcome(result=FAILURE) return self.run_step() @defer.inlineCallbacks def test_revision_noninteger(self): svnTestStep = svn.SVN(repourl='http://svn.local/app/trunk') self.setup_step(svnTestStep) self.expect_commands( ExpectShell(workdir='wkdir', command=['svn', '--version']).exit(0), ExpectStat(file='wkdir/.buildbot-patched', log_environ=True).exit(1), ExpectStat(file='wkdir/.svn', log_environ=True).exit(0), ExpectShell( workdir='wkdir', command=['svn', 'info', '--xml', '--non-interactive', '--no-auth-cache'], ) .stdout('<?xml version="1.0"?><url>http://svn.local/app/trunk</url>') .exit(0), ExpectShell( workdir='wkdir', command=['svn', 'update', '--non-interactive', '--no-auth-cache'] ).exit(0), ExpectShell(workdir='wkdir', command=['svn', 'info', '--xml']) .stdout(self.svn_info_stdout_xml_nonintegerrevision) .exit(0), ) self.expect_outcome(result=SUCCESS) self.expect_property('got_revision', 'a10', 'SVN') yield self.run_step() revision = self.get_nth_step(0).getProperty('got_revision') with self.assertRaises(ValueError): int(revision) def test_revision_missing(self): """Fail if 'revision' tag isn't there""" svn_info_stdout = self.svn_info_stdout_xml.replace('entry', 'Blah') svnTestStep = svn.SVN(repourl='http://svn.local/app/trunk') self.setup_step(svnTestStep) self.expect_commands( ExpectShell(workdir='wkdir', command=['svn', '--version']).exit(0), ExpectStat(file='wkdir/.buildbot-patched', log_environ=True).exit(1), ExpectStat(file='wkdir/.svn', log_environ=True).exit(0), ExpectShell( workdir='wkdir', command=['svn', 'info', '--xml', '--non-interactive', '--no-auth-cache'], ) .stdout('<?xml version="1.0"?><url>http://svn.local/app/trunk</url>') .exit(0), ExpectShell( workdir='wkdir', command=['svn', 'update', '--non-interactive', '--no-auth-cache'] ).exit(0), ExpectShell(workdir='wkdir', command=['svn', 'info', '--xml']) .stdout(svn_info_stdout) .exit(0), ) self.expect_outcome(result=FAILURE) return self.run_step() def test_mode_incremental(self): self.setup_step( svn.SVN( repourl='http://svn.local/app/trunk', mode='incremental', username='user', password='pass', extra_args=['--random'], ) ) self.expect_commands( ExpectShell(workdir='wkdir', command=['svn', '--version']).exit(0), ExpectStat(file='wkdir/.buildbot-patched', log_environ=True).exit(1), ExpectStat(file='wkdir/.svn', log_environ=True).exit(0), ExpectShell( workdir='wkdir', command=[ 'svn', 'info', '--xml', '--non-interactive', '--no-auth-cache', '--username', 'user', '--password', ('obfuscated', 'pass', 'XXXXXX'), '--random', ], ) .stdout('<?xml version="1.0"?><url>http://svn.local/app/trunk</url>') .exit(0), ExpectShell( workdir='wkdir', command=[ 'svn', 'update', '--non-interactive', '--no-auth-cache', '--username', 'user', '--password', ('obfuscated', 'pass', 'XXXXXX'), '--random', ], ).exit(0), ExpectShell(workdir='wkdir', command=['svn', 'info', '--xml']) .stdout(self.svn_info_stdout_xml) .exit(0), ) self.expect_outcome(result=SUCCESS) self.expect_property('got_revision', '100', 'SVN') return self.run_step() def test_mode_incremental_timeout(self): self.setup_step( svn.SVN( repourl='http://svn.local/app/trunk', mode='incremental', username='user', timeout=1, password='pass', extra_args=['--random'], ) ) self.expect_commands( ExpectShell(workdir='wkdir', timeout=1, command=['svn', '--version']).exit(0), ExpectStat(file='wkdir/.buildbot-patched', log_environ=True).exit(1), ExpectStat(file='wkdir/.svn', log_environ=True).exit(0), ExpectShell( workdir='wkdir', timeout=1, command=[ 'svn', 'info', '--xml', '--non-interactive', '--no-auth-cache', '--username', 'user', '--password', ('obfuscated', 'pass', 'XXXXXX'), '--random', ], ) .stdout('<?xml version="1.0"?><url>http://svn.local/app/trunk</url>') .exit(0), ExpectShell( workdir='wkdir', timeout=1, command=[ 'svn', 'update', '--non-interactive', '--no-auth-cache', '--username', 'user', '--password', ('obfuscated', 'pass', 'XXXXXX'), '--random', ], ).exit(0), ExpectShell(workdir='wkdir', timeout=1, command=['svn', 'info', '--xml']) .stdout(self.svn_info_stdout_xml) .exit(0), ) self.expect_outcome(result=SUCCESS) self.expect_property('got_revision', '100', 'SVN') return self.run_step() def test_mode_incremental_repourl_renderable(self): self.setup_step( svn.SVN(repourl=ConstantRenderable('http://svn.local/trunk'), mode='incremental') ) self.expect_commands( ExpectShell(workdir='wkdir', command=['svn', '--version']).exit(0), ExpectStat(file='wkdir/.buildbot-patched', log_environ=True).exit(1), ExpectStat(file='wkdir/.svn', log_environ=True).exit(0), ExpectShell( workdir='wkdir', command=['svn', 'info', '--xml', '--non-interactive', '--no-auth-cache'], ) .stdout("""<?xml version="1.0"?>""" + """<url>http://svn.local/trunk</url>""") .exit(0), ExpectShell( workdir='wkdir', command=['svn', 'update', '--non-interactive', '--no-auth-cache'] ).exit(0), ExpectShell(workdir='wkdir', command=['svn', 'info', '--xml']) .stdout(self.svn_info_stdout_xml) .exit(0), ) self.expect_outcome(result=SUCCESS) self.expect_property('got_revision', '100', 'SVN') return self.run_step() def test_mode_incremental_repourl_canonical(self): self.setup_step(svn.SVN(repourl='http://svn.local/trunk/test app', mode='incremental')) self.expect_commands( ExpectShell(workdir='wkdir', command=['svn', '--version']).exit(0), ExpectStat(file='wkdir/.buildbot-patched', log_environ=True).exit(1), ExpectStat(file='wkdir/.svn', log_environ=True).exit(0), ExpectShell( workdir='wkdir', command=['svn', 'info', '--xml', '--non-interactive', '--no-auth-cache'], ) .stdout('<?xml version="1.0"?><url>http://svn.local/trunk/test%20app</url>') .exit(0), ExpectShell( workdir='wkdir', command=['svn', 'update', '--non-interactive', '--no-auth-cache'] ).exit(0), ExpectShell(workdir='wkdir', command=['svn', 'info', '--xml']) .stdout(self.svn_info_stdout_xml) .exit(0), ) self.expect_outcome(result=SUCCESS) self.expect_property('got_revision', '100', 'SVN') return self.run_step() def test_mode_incremental_repourl_not_updatable(self): self.setup_step( svn.SVN( repourl=ConstantRenderable('http://svn.local/trunk/app'), mode='incremental', ) ) self.expect_commands( ExpectShell(workdir='wkdir', command=['svn', '--version']).exit(0), ExpectStat(file='wkdir/.buildbot-patched', log_environ=True).exit(1), ExpectStat(file='wkdir/.svn', log_environ=True).exit(1), ExpectRmdir(dir='wkdir', log_environ=True, timeout=1200).exit(0), ExpectShell( workdir='wkdir', command=[ 'svn', 'checkout', 'http://svn.local/trunk/app', '.', '--non-interactive', '--no-auth-cache', ], ).exit(0), ExpectShell(workdir='wkdir', command=['svn', 'info', '--xml']) .stdout(self.svn_info_stdout_xml) .exit(0), ) self.expect_outcome(result=SUCCESS) self.expect_property('got_revision', '100', 'SVN') return self.run_step() def test_mode_incremental_retry(self): self.setup_step( svn.SVN( repourl=ConstantRenderable('http://svn.local/trunk/app'), mode='incremental', retry=(0, 1), ) ) self.expect_commands( ExpectShell(workdir='wkdir', command=['svn', '--version']).exit(0), ExpectStat(file='wkdir/.buildbot-patched', log_environ=True).exit(1), ExpectStat(file='wkdir/.svn', log_environ=True).exit(1), ExpectRmdir(dir='wkdir', log_environ=True, timeout=1200).exit(0), ExpectShell( workdir='wkdir', command=[ 'svn', 'checkout', 'http://svn.local/trunk/app', '.', '--non-interactive', '--no-auth-cache', ], ).exit(1), ExpectRmdir(dir='wkdir', log_environ=True, timeout=1200).exit(0), ExpectShell( workdir='wkdir', command=[ 'svn', 'checkout', 'http://svn.local/trunk/app', '.', '--non-interactive', '--no-auth-cache', ], ).exit(0), ExpectShell(workdir='wkdir', command=['svn', 'info', '--xml']) .stdout(self.svn_info_stdout_xml) .exit(0), ) self.expect_outcome(result=SUCCESS) self.expect_property('got_revision', '100', 'SVN') return self.run_step() def test_mode_incremental_repourl_not_updatable_svninfo_mismatch(self): self.setup_step( svn.SVN(repourl=ConstantRenderable('http://svn.local/trunk/app'), mode='incremental') ) self.expect_commands( ExpectShell(workdir='wkdir', command=['svn', '--version']).exit(0), ExpectStat(file='wkdir/.buildbot-patched', log_environ=True).exit(1), ExpectStat(file='wkdir/.svn', log_environ=True).exit(0), ExpectShell( workdir='wkdir', command=['svn', 'info', '--xml', '--non-interactive', '--no-auth-cache'], ) # expecting ../trunk/app .stdout('<?xml version="1.0"?><url>http://svn.local/branch/foo/app</url>') .exit(0), ExpectRmdir(dir='wkdir', log_environ=True, timeout=1200).exit(0), ExpectShell( workdir='wkdir', command=[ 'svn', 'checkout', 'http://svn.local/trunk/app', '.', '--non-interactive', '--no-auth-cache', ], ).exit(0), ExpectShell(workdir='wkdir', command=['svn', 'info', '--xml']) .stdout(self.svn_info_stdout_xml) .exit(0), ) self.expect_outcome(result=SUCCESS) self.expect_property('got_revision', '100', 'SVN') return self.run_step() def test_mode_incremental_given_revision(self): self.setup_step( svn.SVN(repourl='http://svn.local/app/trunk', mode='incremental'), {"revision": '100'} ) self.expect_commands( ExpectShell(workdir='wkdir', command=['svn', '--version']).exit(0), ExpectStat(file='wkdir/.buildbot-patched', log_environ=True).exit(1), ExpectStat(file='wkdir/.svn', log_environ=True).exit(0), ExpectShell( workdir='wkdir', command=['svn', 'info', '--xml', '--non-interactive', '--no-auth-cache'], ) .stdout('<?xml version="1.0"?><url>http://svn.local/app/trunk</url>') .exit(0), ExpectShell( workdir='wkdir', command=[ 'svn', 'update', '--revision', '100', '--non-interactive', '--no-auth-cache', ], ).exit(0), ExpectShell(workdir='wkdir', command=['svn', 'info', '--xml']) .stdout(self.svn_info_stdout_xml) .exit(0), ) self.expect_outcome(result=SUCCESS) self.expect_property('got_revision', '100', 'SVN') return self.run_step() def test_mode_incremental_win32path(self): self.setup_step( svn.SVN( repourl='http://svn.local/app/trunk', mode='incremental', username='user', password='pass', extra_args=['--random'], ) ) self.build.path_module = namedModule("ntpath") self.expect_commands( ExpectShell(workdir='wkdir', command=['svn', '--version']).exit(0), ExpectStat(file=r'wkdir\.buildbot-patched', log_environ=True).exit(1), ExpectStat(file=r'wkdir\.svn', log_environ=True).exit(0), ExpectShell( workdir='wkdir', command=[ 'svn', 'info', '--xml', '--non-interactive', '--no-auth-cache', '--username', 'user', '--password', ('obfuscated', 'pass', 'XXXXXX'), '--random', ], ) .stdout('<?xml version="1.0"?><url>http://svn.local/app/trunk</url>') .exit(0), ExpectShell( workdir='wkdir', command=[ 'svn', 'update', '--non-interactive', '--no-auth-cache', '--username', 'user', '--password', ('obfuscated', 'pass', 'XXXXXX'), '--random', ], ).exit(0), ExpectShell(workdir='wkdir', command=['svn', 'info', '--xml']) .stdout(self.svn_info_stdout_xml) .exit(0), ) self.expect_outcome(result=SUCCESS) return self.run_step() def test_mode_incremental_preferLastChangedRev(self): """Give the last-changed rev if 'preferLastChangedRev' is set""" self.setup_step( svn.SVN( repourl='http://svn.local/app/trunk', mode='incremental', username='user', preferLastChangedRev=True, password='pass', extra_args=['--random'], ) ) self.expect_commands( ExpectShell(workdir='wkdir', command=['svn', '--version']).exit(0), ExpectStat(file='wkdir/.buildbot-patched', log_environ=True).exit(1), ExpectStat(file='wkdir/.svn', log_environ=True).exit(0), ExpectShell( workdir='wkdir', command=[ 'svn', 'info', '--xml', '--non-interactive', '--no-auth-cache', '--username', 'user', '--password', ('obfuscated', 'pass', 'XXXXXX'), '--random', ], ) .stdout('<?xml version="1.0"?><url>http://svn.local/app/trunk</url>') .exit(0), ExpectShell( workdir='wkdir', command=[ 'svn', 'update', '--non-interactive', '--no-auth-cache', '--username', 'user', '--password', ('obfuscated', 'pass', 'XXXXXX'), '--random', ], ).exit(0), ExpectShell(workdir='wkdir', command=['svn', 'info', '--xml']) .stdout(self.svn_info_stdout_xml) .exit(0), ) self.expect_outcome(result=SUCCESS) self.expect_property('got_revision', '90', 'SVN') return self.run_step() def test_mode_incremental_preferLastChangedRev_butMissing(self): """If 'preferLastChangedRev' is set, but missing, fall back to the regular revision value.""" svn_info_stdout = self.svn_info_stdout_xml.replace('commit', 'Blah') self.setup_step( svn.SVN( repourl='http://svn.local/app/trunk', mode='incremental', username='user', preferLastChangedRev=True, password='pass', extra_args=['--random'], ) ) self.expect_commands( ExpectShell(workdir='wkdir', command=['svn', '--version']).exit(0), ExpectStat(file='wkdir/.buildbot-patched', log_environ=True).exit(1), ExpectStat(file='wkdir/.svn', log_environ=True).exit(0), ExpectShell( workdir='wkdir', command=[ 'svn', 'info', '--xml', '--non-interactive', '--no-auth-cache', '--username', 'user', '--password', ('obfuscated', 'pass', 'XXXXXX'), '--random', ], ) .stdout('<?xml version="1.0"?><url>http://svn.local/app/trunk</url>') .exit(0), ExpectShell( workdir='wkdir', command=[ 'svn', 'update', '--non-interactive', '--no-auth-cache', '--username', 'user', '--password', ('obfuscated', 'pass', 'XXXXXX'), '--random', ], ).exit(0), ExpectShell(workdir='wkdir', command=['svn', 'info', '--xml']) .stdout(svn_info_stdout) .exit(0), ) self.expect_outcome(result=SUCCESS) self.expect_property('got_revision', '100', 'SVN') return self.run_step() def test_mode_full_clobber(self): self.setup_step( svn.SVN(repourl='http://svn.local/app/trunk', mode='full', method='clobber') ) self.expect_commands( ExpectShell(workdir='wkdir', command=['svn', '--version']).exit(0), ExpectStat(file='wkdir/.buildbot-patched', log_environ=True).exit(1), ExpectRmdir(dir='wkdir', log_environ=True, timeout=1200).exit(0), ExpectShell( workdir='wkdir', command=[ 'svn', 'checkout', 'http://svn.local/app/trunk', '.', '--non-interactive', '--no-auth-cache', ], ).exit(0), ExpectShell(workdir='wkdir', command=['svn', 'info', '--xml']) .stdout(self.svn_info_stdout_xml) .exit(0), ) self.expect_outcome(result=SUCCESS) self.expect_property('got_revision', '100', 'SVN') return self.run_step() def test_mode_full_clobber_given_revision(self): self.setup_step( svn.SVN(repourl='http://svn.local/app/trunk', mode='full', method='clobber'), {"revision": '100'}, ) self.expect_commands( ExpectShell(workdir='wkdir', command=['svn', '--version']).exit(0), ExpectStat(file='wkdir/.buildbot-patched', log_environ=True).exit(1), ExpectRmdir(dir='wkdir', log_environ=True, timeout=1200).exit(0), ExpectShell( workdir='wkdir', command=[ 'svn', 'checkout', 'http://svn.local/app/trunk', '.', '--revision', '100', '--non-interactive', '--no-auth-cache', ], ).exit(0), ExpectShell(workdir='wkdir', command=['svn', 'info', '--xml']) .stdout(self.svn_info_stdout_xml) .exit(0), ) self.expect_outcome(result=SUCCESS) self.expect_property('got_revision', '100', 'SVN') return self.run_step() def test_mode_full_fresh(self): self.setup_step( svn.SVN( repourl='http://svn.local/app/trunk', mode='full', method='fresh', depth='infinite' ) ) self.expect_commands( ExpectShell(workdir='wkdir', command=['svn', '--version']).exit(0), ExpectStat(file='wkdir/.buildbot-patched', log_environ=True).exit(1), ExpectStat(file='wkdir/.svn', log_environ=True).exit(0), ExpectShell( workdir='wkdir', command=[ 'svn', 'info', '--xml', '--non-interactive', '--no-auth-cache', '--depth', 'infinite', ], ) .stdout('<?xml version="1.0"?><url>http://svn.local/app/trunk</url>') .exit(0), ExpectShell( workdir='wkdir', command=[ 'svn', 'status', '--xml', '--no-ignore', '--non-interactive', '--no-auth-cache', '--depth', 'infinite', ], ) .stdout(self.svn_st_xml_empty) .exit(0), ExpectShell( workdir='wkdir', command=[ 'svn', 'update', '--non-interactive', '--no-auth-cache', '--depth', 'infinite', ], ).exit(0), ExpectShell(workdir='wkdir', command=['svn', 'info', '--xml']) .stdout(self.svn_info_stdout_xml) .stdout('\n') .exit(0), ) self.expect_outcome(result=SUCCESS) self.expect_property('got_revision', '100', 'SVN') return self.run_step() def test_mode_full_fresh_retry(self): self.setup_step( svn.SVN(repourl='http://svn.local/app/trunk', mode='full', method='fresh', retry=(0, 2)) ) self.expect_commands( ExpectShell(workdir='wkdir', command=['svn', '--version']).exit(0), ExpectStat(file='wkdir/.buildbot-patched', log_environ=True).exit(1), ExpectStat(file='wkdir/.svn', log_environ=True).exit(1), ExpectRmdir(dir='wkdir', log_environ=True, timeout=1200).exit(0), ExpectShell( workdir='wkdir', command=[ 'svn', 'checkout', 'http://svn.local/app/trunk', '.', '--non-interactive', '--no-auth-cache', ], ).exit(1), ExpectRmdir(dir='wkdir', log_environ=True, timeout=1200).exit(0), ExpectShell( workdir='wkdir', command=[ 'svn', 'checkout', 'http://svn.local/app/trunk', '.', '--non-interactive', '--no-auth-cache', ], ).exit(1), ExpectRmdir(dir='wkdir', log_environ=True, timeout=1200).exit(0), ExpectShell( workdir='wkdir', command=[ 'svn', 'checkout', 'http://svn.local/app/trunk', '.', '--non-interactive', '--no-auth-cache', ], ).exit(0), ExpectShell(workdir='wkdir', command=['svn', 'info', '--xml']) .stdout(self.svn_info_stdout_xml) .stdout('\n') .exit(0), ) self.expect_outcome(result=SUCCESS) self.expect_property('got_revision', '100', 'SVN') return self.run_step() def test_mode_full_fresh_given_revision(self): self.setup_step( svn.SVN( repourl='http://svn.local/app/trunk', mode='full', method='fresh', depth='infinite' ), {"revision": '100'}, ) self.expect_commands( ExpectShell(workdir='wkdir', command=['svn', '--version']).exit(0), ExpectStat(file='wkdir/.buildbot-patched', log_environ=True).exit(1), ExpectStat(file='wkdir/.svn', log_environ=True).exit(0), ExpectShell( workdir='wkdir', command=[ 'svn', 'info', '--xml', '--non-interactive', '--no-auth-cache', '--depth', 'infinite', ], ) .stdout('<?xml version="1.0"?><url>http://svn.local/app/trunk</url>') .exit(0), ExpectShell( workdir='wkdir', command=[ 'svn', 'status', '--xml', '--no-ignore', '--non-interactive', '--no-auth-cache', '--depth', 'infinite', ], ) .stdout(self.svn_st_xml_empty) .exit(0), ExpectShell( workdir='wkdir', command=[ 'svn', 'update', '--revision', '100', '--non-interactive', '--no-auth-cache', '--depth', 'infinite', ], ).exit(0), ExpectShell(workdir='wkdir', command=['svn', 'info', '--xml']) .stdout(self.svn_info_stdout_xml) .stdout('\n') .exit(0), ) self.expect_outcome(result=SUCCESS) self.expect_property('got_revision', '100', 'SVN') return self.run_step() def test_mode_full_fresh_keep_on_purge(self): self.setup_step( svn.SVN( repourl='http://svn.local/app/trunk', mode='full', keep_on_purge=['svn_external_path/unversioned_file1'], ) ) self.expect_commands( ExpectShell(workdir='wkdir', command=['svn', '--version']).exit(0), ExpectStat(file='wkdir/.buildbot-patched', log_environ=True).exit(1), ExpectStat(file='wkdir/.svn', log_environ=True).exit(0), ExpectShell( workdir='wkdir', command=['svn', 'info', '--xml', '--non-interactive', '--no-auth-cache'], ) .stdout('<?xml version="1.0"?><url>http://svn.local/app/trunk</url>') .exit(0), ExpectShell( workdir='wkdir', command=[ 'svn', 'status', '--xml', '--no-ignore', '--non-interactive', '--no-auth-cache', ], ) .stdout(self.svn_st_xml) .exit(0), ExpectRmdir( dir=['wkdir/svn_external_path/unversioned_file2_uniçode'], log_environ=True, timeout=1200, ).exit(0), ExpectShell( workdir='wkdir', command=['svn', 'update', '--non-interactive', '--no-auth-cache'] ).exit(0), ExpectShell(workdir='wkdir', command=['svn', 'info', '--xml']) .stdout(self.svn_info_stdout_xml) .exit(0), ) self.expect_outcome(result=SUCCESS) self.expect_property('got_revision', '100', 'SVN') return self.run_step() def test_mode_full_clean(self): self.setup_step(svn.SVN(repourl='http://svn.local/app/trunk', mode='full', method='clean')) self.expect_commands( ExpectShell(workdir='wkdir', command=['svn', '--version']).exit(0), ExpectStat(file='wkdir/.buildbot-patched', log_environ=True).exit(1), ExpectStat(file='wkdir/.svn', log_environ=True).exit(0), ExpectShell( workdir='wkdir', command=['svn', 'info', '--xml', '--non-interactive', '--no-auth-cache'], ) .stdout('<?xml version="1.0"?><url>http://svn.local/app/trunk</url>') .exit(0), ExpectShell( workdir='wkdir', command=['svn', 'status', '--xml', '--non-interactive', '--no-auth-cache'], ) .stdout(self.svn_st_xml_empty) .exit(0), ExpectShell( workdir='wkdir', command=['svn', 'update', '--non-interactive', '--no-auth-cache'] ).exit(0), ExpectShell(workdir='wkdir', command=['svn', 'info', '--xml']) .stdout(self.svn_info_stdout_xml) .exit(0), ) self.expect_outcome(result=SUCCESS) self.expect_property('got_revision', '100', 'SVN') return self.run_step() def test_mode_full_clean_given_revision(self): self.setup_step( svn.SVN(repourl='http://svn.local/app/trunk', mode='full', method='clean'), {"revision": '100'}, ) self.expect_commands( ExpectShell(workdir='wkdir', command=['svn', '--version']).exit(0), ExpectStat(file='wkdir/.buildbot-patched', log_environ=True).exit(1), ExpectStat(file='wkdir/.svn', log_environ=True).exit(0), ExpectShell( workdir='wkdir', command=['svn', 'info', '--xml', '--non-interactive', '--no-auth-cache'], ) .stdout('<?xml version="1.0"?><url>http://svn.local/app/trunk</url>') .exit(0), ExpectShell( workdir='wkdir', command=['svn', 'status', '--xml', '--non-interactive', '--no-auth-cache'], ) .stdout(self.svn_st_xml_empty) .exit(0), ExpectShell( workdir='wkdir', command=[ 'svn', 'update', '--revision', '100', '--non-interactive', '--no-auth-cache', ], ).exit(0), ExpectShell(workdir='wkdir', command=['svn', 'info', '--xml']) .stdout(self.svn_info_stdout_xml) .exit(0), ) self.expect_outcome(result=SUCCESS) self.expect_property('got_revision', '100', 'SVN') return self.run_step() def test_mode_full_not_updatable(self): self.setup_step(svn.SVN(repourl='http://svn.local/app/trunk', mode='full', method='clean')) self.expect_commands( ExpectShell(workdir='wkdir', command=['svn', '--version']).exit(0), ExpectStat(file='wkdir/.buildbot-patched', log_environ=True).exit(1), ExpectStat(file='wkdir/.svn', log_environ=True).exit(1), ExpectRmdir(dir='wkdir', log_environ=True, timeout=1200).exit(0), ExpectShell( workdir='wkdir', command=[ 'svn', 'checkout', 'http://svn.local/app/trunk', '.', '--non-interactive', '--no-auth-cache', ], ).exit(0), ExpectShell(workdir='wkdir', command=['svn', 'info', '--xml']) .stdout(self.svn_info_stdout_xml) .exit(0), ) self.expect_outcome(result=SUCCESS) self.expect_property('got_revision', '100', 'SVN') return self.run_step() def test_mode_full_not_updatable_given_revision(self): self.setup_step( svn.SVN(repourl='http://svn.local/app/trunk', mode='full', method='clean'), {"revision": '100'}, ) self.expect_commands( ExpectShell(workdir='wkdir', command=['svn', '--version']).exit(0), ExpectStat(file='wkdir/.buildbot-patched', log_environ=True).exit(1), ExpectStat(file='wkdir/.svn', log_environ=True).exit(1), ExpectRmdir(dir='wkdir', log_environ=True, timeout=1200).exit(0), ExpectShell( workdir='wkdir', command=[ 'svn', 'checkout', 'http://svn.local/app/trunk', '.', '--revision', '100', '--non-interactive', '--no-auth-cache', ], ).exit(0), ExpectShell(workdir='wkdir', command=['svn', 'info', '--xml']) .stdout(self.svn_info_stdout_xml) .exit(0), ) self.expect_outcome(result=SUCCESS) self.expect_property('got_revision', '100', 'SVN') return self.run_step() def test_mode_full_clean_old_rmdir(self): self.setup_step(svn.SVN(repourl='http://svn.local/app/trunk', mode='full', method='clean')) self.patch_workerVersionIsOlderThan(True) self.expect_commands( ExpectShell(workdir='wkdir', command=['svn', '--version']).exit(0), ExpectStat(file='wkdir/.buildbot-patched', log_environ=True).exit(1), ExpectStat(file='wkdir/.svn', log_environ=True).exit(0), ExpectShell( workdir='wkdir', command=['svn', 'info', '--xml', '--non-interactive', '--no-auth-cache'], ) .stdout('<?xml version="1.0"?><url>http://svn.local/app/trunk</url>') .exit(0), ExpectShell( workdir='wkdir', command=['svn', 'status', '--xml', '--non-interactive', '--no-auth-cache'], ) .stdout(self.svn_st_xml) .exit(0), ExpectRmdir( dir='wkdir/svn_external_path/unversioned_file1', log_environ=True, timeout=1200 ).exit(0), ExpectRmdir( dir='wkdir/svn_external_path/unversioned_file2_uniçode', log_environ=True, timeout=1200, ).exit(0), ExpectShell( workdir='wkdir', command=['svn', 'update', '--non-interactive', '--no-auth-cache'] ).exit(0), ExpectShell(workdir='wkdir', command=['svn', 'info', '--xml']) .stdout(self.svn_info_stdout_xml) .exit(0), ) self.expect_outcome(result=SUCCESS) self.expect_property('got_revision', '100', 'SVN') return self.run_step() def test_mode_full_clean_new_rmdir(self): self.setup_step(svn.SVN(repourl='http://svn.local/app/trunk', mode='full', method='clean')) self.patch_workerVersionIsOlderThan(False) self.expect_commands( ExpectShell(workdir='wkdir', command=['svn', '--version']).exit(0), ExpectStat(file='wkdir/.buildbot-patched', log_environ=True).exit(1), ExpectStat(file='wkdir/.svn', log_environ=True).exit(0), ExpectShell( workdir='wkdir', command=['svn', 'info', '--xml', '--non-interactive', '--no-auth-cache'], ) .stdout('<?xml version="1.0"?><url>http://svn.local/app/trunk</url>') .exit(0), ExpectShell( workdir='wkdir', command=['svn', 'status', '--xml', '--non-interactive', '--no-auth-cache'], ) .stdout(self.svn_st_xml) .exit(0), ExpectRmdir( dir=[ 'wkdir/svn_external_path/unversioned_file1', 'wkdir/svn_external_path/unversioned_file2_uniçode', ], log_environ=True, timeout=1200, ).exit(0), ExpectShell( workdir='wkdir', command=['svn', 'update', '--non-interactive', '--no-auth-cache'] ).exit(0), ExpectShell(workdir='wkdir', command=['svn', 'info', '--xml']) .stdout(self.svn_info_stdout_xml) .exit(0), ) self.expect_outcome(result=SUCCESS) self.expect_property('got_revision', '100', 'SVN') return self.run_step() def test_mode_full_copy(self): self.setup_step( svn.SVN( repourl='http://svn.local/app/trunk', mode='full', method='copy', codebase='app' ) ) self.expect_commands( ExpectShell(workdir='wkdir', command=['svn', '--version']).exit(0), ExpectStat(file='wkdir/.buildbot-patched', log_environ=True).exit(1), ExpectRmdir(dir='wkdir', log_environ=True, timeout=1200).exit(0), ExpectStat(file='source/app/.svn', log_environ=True).exit(0), ExpectShell( workdir='source/app', command=['svn', 'info', '--xml', '--non-interactive', '--no-auth-cache'], ) .stdout('<?xml version="1.0"?><url>http://svn.local/app/trunk</url>') .exit(0), ExpectShell( workdir='source/app', command=['svn', 'update', '--non-interactive', '--no-auth-cache'], ).exit(0), ExpectCpdir(fromdir='source/app', todir='wkdir', log_environ=True).exit(0), ExpectShell(workdir='wkdir', command=['svn', 'info', '--xml']) .stdout(self.svn_info_stdout_xml) .exit(0), ) self.expect_outcome(result=SUCCESS) self.expect_property('got_revision', {'app': '100'}, 'SVN') return self.run_step() def test_mode_full_copy_given_revision(self): self.setup_step( svn.SVN(repourl='http://svn.local/app/trunk', mode='full', method='copy'), {"revision": '100'}, ) self.expect_commands( ExpectShell(workdir='wkdir', command=['svn', '--version']).exit(0), ExpectStat(file='wkdir/.buildbot-patched', log_environ=True).exit(1), ExpectRmdir(dir='wkdir', log_environ=True, timeout=1200).exit(0), ExpectStat(file='source/.svn', log_environ=True).exit(0), ExpectShell( workdir='source', command=['svn', 'info', '--xml', '--non-interactive', '--no-auth-cache'], ) .stdout('<?xml version="1.0"?><url>http://svn.local/app/trunk</url>') .exit(0), ExpectShell( workdir='source', command=[ 'svn', 'update', '--revision', '100', '--non-interactive', '--no-auth-cache', ], ).exit(0), ExpectCpdir(fromdir='source', todir='wkdir', log_environ=True).exit(0), ExpectShell(workdir='wkdir', command=['svn', 'info', '--xml']) .stdout(self.svn_info_stdout_xml) .exit(0), ) self.expect_outcome(result=SUCCESS) self.expect_property('got_revision', '100', 'SVN') return self.run_step() def test_mode_full_export(self): self.setup_step(svn.SVN(repourl='http://svn.local/app/trunk', mode='full', method='export')) self.expect_commands( ExpectShell(workdir='wkdir', command=['svn', '--version']).exit(0), ExpectStat(file='wkdir/.buildbot-patched', log_environ=True).exit(1), ExpectRmdir(dir='wkdir', log_environ=True, timeout=1200).exit(0), ExpectStat(file='source/.svn', log_environ=True).exit(0), ExpectShell( workdir='source', command=['svn', 'info', '--xml', '--non-interactive', '--no-auth-cache'], ) .stdout('<?xml version="1.0"?><url>http://svn.local/app/trunk</url>') .exit(0), ExpectShell( workdir='source', command=['svn', 'update', '--non-interactive', '--no-auth-cache'] ).exit(0), ExpectShell(workdir='', command=['svn', 'export', 'source', 'wkdir']).exit(0), ExpectShell(workdir='source', command=['svn', 'info', '--xml']) .stdout(self.svn_info_stdout_xml) .exit(0), ) self.expect_outcome(result=SUCCESS) self.expect_property('got_revision', '100', 'SVN') return self.run_step() def test_mode_full_export_patch(self): self.setup_step( svn.SVN(repourl='http://svn.local/app/trunk', mode='full', method='export'), patch=(1, 'patch'), ) self.expect_commands( ExpectShell(workdir='wkdir', command=['svn', '--version']).exit(0), ExpectStat(file='wkdir/.buildbot-patched', log_environ=True).exit(0), ExpectShell( workdir='wkdir', command=['svn', 'status', '--xml', '--non-interactive', '--no-auth-cache'], ) .stdout(self.svn_st_xml) .exit(0), ExpectRmdir( dir=[ 'wkdir/svn_external_path/unversioned_file1', 'wkdir/svn_external_path/unversioned_file2_uniçode', ], log_environ=True, timeout=1200, ).exit(0), ExpectRmdir(dir='wkdir', log_environ=True, timeout=1200).exit(0), ExpectStat(file='source/.svn', log_environ=True).exit(0), ExpectShell( workdir='source', command=['svn', 'info', '--xml', '--non-interactive', '--no-auth-cache'], ) .stdout('<?xml version="1.0"?><url>http://svn.local/app/trunk</url>') .exit(0), ExpectShell( workdir='source', command=['svn', 'update', '--non-interactive', '--no-auth-cache'] ).exit(0), ExpectShell(workdir='', command=['svn', 'export', 'source', 'wkdir']).exit(0), ExpectDownloadFile( blocksize=32768, maxsize=None, reader=ExpectRemoteRef(remotetransfer.StringFileReader), workerdest='.buildbot-diff', workdir='wkdir', mode=None, ).exit(0), ExpectDownloadFile( blocksize=32768, maxsize=None, reader=ExpectRemoteRef(remotetransfer.StringFileReader), workerdest='.buildbot-patched', workdir='wkdir', mode=None, ).exit(0), ExpectShell( workdir='wkdir', command=[ 'patch', '-p1', '--remove-empty-files', '--force', '--forward', '-i', '.buildbot-diff', ], ).exit(0), ExpectRmdir(dir='wkdir/.buildbot-diff', log_environ=True).exit(0), ExpectShell(workdir='source', command=['svn', 'info', '--xml']) .stdout(self.svn_info_stdout_xml) .exit(0), ) self.expect_outcome(result=SUCCESS) self.expect_property('got_revision', '100', 'SVN') return self.run_step() def test_mode_full_export_patch_worker_2_16(self): self.setup_build(worker_version={'*': '2.16'}) self.setup_step( svn.SVN(repourl='http://svn.local/app/trunk', mode='full', method='export'), patch=(1, 'patch'), ) self.expect_commands( ExpectShell(workdir='wkdir', command=['svn', '--version']).exit(0), ExpectStat(file='wkdir/.buildbot-patched', log_environ=True).exit(0), ExpectShell( workdir='wkdir', command=['svn', 'status', '--xml', '--non-interactive', '--no-auth-cache'], ) .stdout(self.svn_st_xml) .exit(0), ExpectRmdir( dir=[ 'wkdir/svn_external_path/unversioned_file1', 'wkdir/svn_external_path/unversioned_file2_uniçode', ], log_environ=True, timeout=1200, ).exit(0), ExpectRmdir(dir='wkdir', log_environ=True, timeout=1200).exit(0), ExpectStat(file='source/.svn', log_environ=True).exit(0), ExpectShell( workdir='source', command=['svn', 'info', '--xml', '--non-interactive', '--no-auth-cache'], ) .stdout('<?xml version="1.0"?><url>http://svn.local/app/trunk</url>') .exit(0), ExpectShell( workdir='source', command=['svn', 'update', '--non-interactive', '--no-auth-cache'] ).exit(0), ExpectShell(workdir='', command=['svn', 'export', 'source', 'wkdir']).exit(0), ExpectDownloadFile( blocksize=32768, maxsize=None, reader=ExpectRemoteRef(remotetransfer.StringFileReader), slavedest='.buildbot-diff', workdir='wkdir', mode=None, ).exit(0), ExpectDownloadFile( blocksize=32768, maxsize=None, reader=ExpectRemoteRef(remotetransfer.StringFileReader), slavedest='.buildbot-patched', workdir='wkdir', mode=None, ).exit(0), ExpectShell( workdir='wkdir', command=[ 'patch', '-p1', '--remove-empty-files', '--force', '--forward', '-i', '.buildbot-diff', ], ).exit(0), ExpectRmdir(dir='wkdir/.buildbot-diff', log_environ=True).exit(0), ExpectShell(workdir='source', command=['svn', 'info', '--xml']) .stdout(self.svn_info_stdout_xml) .exit(0), ) self.expect_outcome(result=SUCCESS) self.expect_property('got_revision', '100', 'SVN') return self.run_step() def test_mode_full_export_timeout(self): self.setup_step( svn.SVN(repourl='http://svn.local/app/trunk', timeout=1, mode='full', method='export') ) self.expect_commands( ExpectShell(workdir='wkdir', timeout=1, command=['svn', '--version']).exit(0), ExpectStat(file='wkdir/.buildbot-patched', log_environ=True).exit(1), ExpectRmdir(dir='wkdir', log_environ=True, timeout=1).exit(0), ExpectStat(file='source/.svn', log_environ=True).exit(0), ExpectShell( workdir='source', timeout=1, command=['svn', 'info', '--xml', '--non-interactive', '--no-auth-cache'], ) .stdout('<?xml version="1.0"?><url>http://svn.local/app/trunk</url>') .exit(0), ExpectShell( workdir='source', timeout=1, command=['svn', 'update', '--non-interactive', '--no-auth-cache'], ).exit(0), ExpectShell(workdir='', timeout=1, command=['svn', 'export', 'source', 'wkdir']).exit( 0 ), ExpectShell(workdir='source', timeout=1, command=['svn', 'info', '--xml']) .stdout(self.svn_info_stdout_xml) .exit(0), ) self.expect_outcome(result=SUCCESS) self.expect_property('got_revision', '100', 'SVN') return self.run_step() def test_mode_full_export_given_revision(self): self.setup_step( svn.SVN(repourl='http://svn.local/app/trunk', mode='full', method='export'), {"revision": '100'}, ) self.expect_commands( ExpectShell(workdir='wkdir', command=['svn', '--version']).exit(0), ExpectStat(file='wkdir/.buildbot-patched', log_environ=True).exit(1), ExpectRmdir(dir='wkdir', log_environ=True, timeout=1200).exit(0), ExpectStat(file='source/.svn', log_environ=True).exit(0), ExpectShell( workdir='source', command=['svn', 'info', '--xml', '--non-interactive', '--no-auth-cache'], ) .stdout('<?xml version="1.0"?><url>http://svn.local/app/trunk</url>') .exit(0), ExpectShell( workdir='source', command=[ 'svn', 'update', '--revision', '100', '--non-interactive', '--no-auth-cache', ], ).exit(0), ExpectShell( workdir='', command=['svn', 'export', '--revision', '100', 'source', 'wkdir'] ).exit(0), ExpectShell(workdir='source', command=['svn', 'info', '--xml']) .stdout(self.svn_info_stdout_xml) .exit(0), ) self.expect_outcome(result=SUCCESS) self.expect_property('got_revision', '100', 'SVN') return self.run_step() def test_mode_full_export_auth(self): self.setup_step( svn.SVN( repourl='http://svn.local/app/trunk', mode='full', method='export', username='svn_username', password='svn_password', ) ) self.expect_commands( ExpectShell(workdir='wkdir', command=['svn', '--version']).exit(0), ExpectStat(file='wkdir/.buildbot-patched', log_environ=True).exit(1), ExpectRmdir(dir='wkdir', log_environ=True, timeout=1200).exit(0), ExpectStat(file='source/.svn', log_environ=True).exit(0), ExpectShell( workdir='source', command=[ 'svn', 'info', '--xml', '--non-interactive', '--no-auth-cache', '--username', 'svn_username', '--password', ('obfuscated', 'svn_password', 'XXXXXX'), ], ) .stdout('<?xml version="1.0"?><url>http://svn.local/app/trunk</url>') .exit(0), ExpectShell( workdir='source', command=[ 'svn', 'update', '--non-interactive', '--no-auth-cache', '--username', 'svn_username', '--password', ('obfuscated', 'svn_password', 'XXXXXX'), ], ).exit(0), ExpectShell( workdir='', command=[ 'svn', 'export', '--username', 'svn_username', '--password', ('obfuscated', 'svn_password', 'XXXXXX'), 'source', 'wkdir', ], ).exit(0), ExpectShell(workdir='source', command=['svn', 'info', '--xml']) .stdout(self.svn_info_stdout_xml) .exit(0), ) self.expect_outcome(result=SUCCESS) self.expect_property('got_revision', '100', 'SVN') return self.run_step() def test_mode_incremental_with_env(self): self.setup_step( svn.SVN( repourl='http://svn.local/app/trunk', mode='incremental', username='user', password='pass', extra_args=['--random'], env={'abc': '123'}, ) ) self.expect_commands( ExpectShell(workdir='wkdir', command=['svn', '--version'], env={'abc': '123'}).exit(0), ExpectStat(file='wkdir/.buildbot-patched', log_environ=True).exit(1), ExpectStat(file='wkdir/.svn', log_environ=True).exit(0), ExpectShell( workdir='wkdir', command=[ 'svn', 'info', '--xml', '--non-interactive', '--no-auth-cache', '--username', 'user', '--password', ('obfuscated', 'pass', 'XXXXXX'), '--random', ], env={'abc': '123'}, ) .stdout('<?xml version="1.0"?><url>http://svn.local/app/trunk</url>') .exit(0), ExpectShell( workdir='wkdir', command=[ 'svn', 'update', '--non-interactive', '--no-auth-cache', '--username', 'user', '--password', ('obfuscated', 'pass', 'XXXXXX'), '--random', ], env={'abc': '123'}, ).exit(0), ExpectShell(workdir='wkdir', command=['svn', 'info', '--xml'], env={'abc': '123'}) .stdout(self.svn_info_stdout_xml) .exit(0), ) self.expect_outcome(result=SUCCESS) self.expect_property('got_revision', '100', 'SVN') return self.run_step() def test_mode_incremental_log_environ(self): self.setup_step( svn.SVN( repourl='http://svn.local/app/trunk', mode='incremental', username='user', password='pass', extra_args=['--random'], logEnviron=False, ) ) self.expect_commands( ExpectShell(workdir='wkdir', command=['svn', '--version'], log_environ=False).exit(0), ExpectStat(file='wkdir/.buildbot-patched', log_environ=False).exit(1), ExpectStat(file='wkdir/.svn', log_environ=False).exit(0), ExpectShell( workdir='wkdir', command=[ 'svn', 'info', '--xml', '--non-interactive', '--no-auth-cache', '--username', 'user', '--password', ('obfuscated', 'pass', 'XXXXXX'), '--random', ], log_environ=False, ) .stdout('<?xml version="1.0"?><url>http://svn.local/app/trunk</url>') .exit(0), ExpectShell( workdir='wkdir', command=[ 'svn', 'update', '--non-interactive', '--no-auth-cache', '--username', 'user', '--password', ('obfuscated', 'pass', 'XXXXXX'), '--random', ], log_environ=False, ).exit(0), ExpectShell(workdir='wkdir', command=['svn', 'info', '--xml'], log_environ=False) .stdout(self.svn_info_stdout_xml) .exit(0), ) self.expect_outcome(result=SUCCESS) self.expect_property('got_revision', '100', 'SVN') return self.run_step() def test_command_fails(self): self.setup_step( svn.SVN( repourl='http://svn.local/app/trunk', mode='incremental', username='user', password='pass', extra_args=['--random'], ) ) self.expect_commands( ExpectShell(workdir='wkdir', command=['svn', '--version']).exit(0), ExpectStat(file='wkdir/.buildbot-patched', log_environ=True).exit(1), ExpectStat(file='wkdir/.svn', log_environ=True).exit(0), ExpectShell( workdir='wkdir', command=[ 'svn', 'info', '--xml', '--non-interactive', '--no-auth-cache', '--username', 'user', '--password', ('obfuscated', 'pass', 'XXXXXX'), '--random', ], ) .stdout('<?xml version="1.0"?><url>http://svn.local/app/trunk</url>') .exit(0), ExpectShell( workdir='wkdir', command=[ 'svn', 'update', '--non-interactive', '--no-auth-cache', '--username', 'user', '--password', ('obfuscated', 'pass', 'XXXXXX'), '--random', ], ).exit(1), ) self.expect_outcome(result=FAILURE) return self.run_step() def test_bogus_svnversion(self): self.setup_step( svn.SVN( repourl='http://svn.local/app/trunk', mode='incremental', username='user', password='pass', extra_args=['--random'], ) ) self.expect_commands( ExpectShell(workdir='wkdir', command=['svn', '--version']).exit(0), ExpectStat(file='wkdir/.buildbot-patched', log_environ=True).exit(1), ExpectStat(file='wkdir/.svn', log_environ=True).exit(0), ExpectShell( workdir='wkdir', command=[ 'svn', 'info', '--xml', '--non-interactive', '--no-auth-cache', '--username', 'user', '--password', ('obfuscated', 'pass', 'XXXXXX'), '--random', ], ) .stdout( '<?xml version="1.0"?>' '<entry kind="dir" path="/a/b/c" revision="1">' '<url>http://svn.local/app/trunk</url>' '</entry>' ) .exit(0), ExpectShell( workdir='wkdir', command=[ 'svn', 'update', '--non-interactive', '--no-auth-cache', '--username', 'user', '--password', ('obfuscated', 'pass', 'XXXXXX'), '--random', ], ).exit(0), ExpectShell(workdir='wkdir', command=['svn', 'info', '--xml']).stdout('1x0y0').exit(0), ) self.expect_outcome(result=FAILURE) return self.run_step() def test_rmdir_fails_clobber(self): self.setup_step( svn.SVN(repourl='http://svn.local/app/trunk', mode='full', method='clobber') ) self.expect_commands( ExpectShell(workdir='wkdir', command=['svn', '--version']).exit(0), ExpectStat(file='wkdir/.buildbot-patched', log_environ=True).exit(1), ExpectRmdir(dir='wkdir', log_environ=True, timeout=1200).exit(1), ) self.expect_outcome(result=FAILURE) return self.run_step() def test_rmdir_fails_copy(self): self.setup_step(svn.SVN(repourl='http://svn.local/app/trunk', mode='full', method='copy')) self.expect_commands( ExpectShell(workdir='wkdir', command=['svn', '--version']).exit(0), ExpectStat(file='wkdir/.buildbot-patched', log_environ=True).exit(1), ExpectRmdir(dir='wkdir', log_environ=True, timeout=1200).exit(1), ) self.expect_outcome(result=FAILURE) return self.run_step() def test_cpdir_fails_copy(self): self.setup_step(svn.SVN(repourl='http://svn.local/app/trunk', mode='full', method='copy')) self.expect_commands( ExpectShell(workdir='wkdir', command=['svn', '--version']).exit(0), ExpectStat(file='wkdir/.buildbot-patched', log_environ=True).exit(1), ExpectRmdir(dir='wkdir', log_environ=True, timeout=1200).exit(0), ExpectStat(file='source/.svn', log_environ=True).exit(0), ExpectShell( workdir='source', command=['svn', 'info', '--xml', '--non-interactive', '--no-auth-cache'], ) .stdout('<?xml version="1.0"?><url>http://svn.local/app/trunk</url>') .exit(0), ExpectShell( workdir='source', command=['svn', 'update', '--non-interactive', '--no-auth-cache'] ).exit(0), ExpectCpdir(fromdir='source', todir='wkdir', log_environ=True).exit(1), ) self.expect_outcome(result=FAILURE) return self.run_step() def test_rmdir_fails_purge(self): self.setup_step( svn.SVN( repourl='http://svn.local/app/trunk', mode='full', keep_on_purge=['svn_external_path/unversioned_file1'], ) ) self.expect_commands( ExpectShell(workdir='wkdir', command=['svn', '--version']).exit(0), ExpectStat(file='wkdir/.buildbot-patched', log_environ=True).exit(1), ExpectStat(file='wkdir/.svn', log_environ=True).exit(0), ExpectShell( workdir='wkdir', command=['svn', 'info', '--xml', '--non-interactive', '--no-auth-cache'], ) .stdout('<?xml version="1.0"?><url>http://svn.local/app/trunk</url>') .exit(0), ExpectShell( workdir='wkdir', command=[ 'svn', 'status', '--xml', '--no-ignore', '--non-interactive', '--no-auth-cache', ], ) .stdout(self.svn_st_xml) .exit(0), ExpectRmdir( dir=['wkdir/svn_external_path/unversioned_file2_uniçode'], log_environ=True, timeout=1200, ).exit(1), ) self.expect_outcome(result=FAILURE) return self.run_step() def test_worker_connection_lost(self): self.setup_step( svn.SVN( repourl='http://svn.local/app/trunk', mode='incremental', username='user', password='pass', extra_args=['--random'], ) ) self.expect_commands( ExpectShell(workdir='wkdir', command=['svn', '--version']).error(error.ConnectionLost()) ) self.expect_outcome(result=RETRY, state_string="update (retry)") return self.run_step() def test_empty_password(self): self.setup_step( svn.SVN( repourl='http://svn.local/app/trunk', mode='incremental', username='user', password='', extra_args=['--random'], ) ) self.expect_commands( ExpectShell(workdir='wkdir', command=['svn', '--version']).exit(0), ExpectStat(file='wkdir/.buildbot-patched', log_environ=True).exit(1), ExpectStat(file='wkdir/.svn', log_environ=True).exit(0), ExpectShell( workdir='wkdir', command=[ 'svn', 'info', '--xml', '--non-interactive', '--no-auth-cache', '--username', 'user', '--password', ('obfuscated', '', 'XXXXXX'), '--random', ], ) .stdout('<?xml version="1.0"?><url>http://svn.local/app/trunk</url>') .exit(0), ExpectShell( workdir='wkdir', command=[ 'svn', 'update', '--non-interactive', '--no-auth-cache', '--username', 'user', '--password', ('obfuscated', '', 'XXXXXX'), '--random', ], ).exit(0), ExpectShell(workdir='wkdir', command=['svn', 'info', '--xml']) .stdout(self.svn_info_stdout_xml) .exit(0), ) self.expect_outcome(result=SUCCESS) return self.run_step() def test_omit_password(self): self.setup_step( svn.SVN( repourl='http://svn.local/app/trunk', mode='incremental', username='user', extra_args=['--random'], ) ) self.expect_commands( ExpectShell(workdir='wkdir', command=['svn', '--version']).exit(0), ExpectStat(file='wkdir/.buildbot-patched', log_environ=True).exit(1), ExpectStat(file='wkdir/.svn', log_environ=True).exit(0), ExpectShell( workdir='wkdir', command=[ 'svn', 'info', '--xml', '--non-interactive', '--no-auth-cache', '--username', 'user', '--random', ], ) .stdout('<?xml version="1.0"?><url>http://svn.local/app/trunk</url>') .exit(0), ExpectShell( workdir='wkdir', command=[ 'svn', 'update', '--non-interactive', '--no-auth-cache', '--username', 'user', '--random', ], ).exit(0), ExpectShell(workdir='wkdir', command=['svn', 'info', '--xml']) .stdout(self.svn_info_stdout_xml) .exit(0), ) self.expect_outcome(result=SUCCESS) return self.run_step() class TestGetUnversionedFiles(unittest.TestCase): def test_getUnversionedFiles_does_not_list_externals(self): svn_st_xml = """<?xml version="1.0"?> <status> <target path="."> <entry path="svn_external_path"> <wc-status props="none" item="external"> </wc-status> </entry> <entry path="svn_external_path/unversioned_file"> <wc-status props="none" item="unversioned"> </wc-status> </entry> </target> </status> """ unversioned_files = list(svn.SVN.getUnversionedFiles(svn_st_xml, [])) self.assertEqual(["svn_external_path/unversioned_file"], unversioned_files) def test_getUnversionedFiles_does_not_list_missing(self): svn_st_xml = """<?xml version="1.0"?> <status> <target path="."> <entry path="missing_file"> <wc-status props="none" item="missing"></wc-status> </entry> </target> </status> """ unversioned_files = list(svn.SVN.getUnversionedFiles(svn_st_xml, [])) self.assertEqual([], unversioned_files) def test_getUnversionedFiles_corrupted_xml(self): svn_st_xml_corrupt = """<?xml version="1.0"?> <target path="."> <entry path="svn_external_path"> <wc-status props="none" item="external"> </wc-status> </entry> <entry path="svn_external_path/unversioned_file"> <wc-status props="none" item="unversioned"> </wc-status> </entry> </target> </status> """ with self.assertRaises(buildstep.BuildStepFailed): list(svn.SVN.getUnversionedFiles(svn_st_xml_corrupt, [])) def test_getUnversionedFiles_no_path(self): svn_st_xml = """<?xml version="1.0"?> <status> <target path="."> <entry path="svn_external_path"> <wc-status props="none" item="external"> </wc-status> </entry> <entry> <wc-status props="none" item="unversioned"> </wc-status> </entry> </target> </status> """ unversioned_files = list(svn.SVN.getUnversionedFiles(svn_st_xml, [])) self.assertEqual([], unversioned_files) def test_getUnversionedFiles_no_item(self): svn_st_xml = """<?xml version="1.0"?> <status> <target path="."> <entry path="svn_external_path"> <wc-status props="none" item="external"> </wc-status> </entry> <entry path="svn_external_path/unversioned_file"> <wc-status props="none"> </wc-status> </entry> </target> </status> """ unversioned_files = list(svn.SVN.getUnversionedFiles(svn_st_xml, [])) self.assertEqual(["svn_external_path/unversioned_file"], unversioned_files) def test_getUnversionedFiles_unicode(self): svn_st_xml = """<?xml version="1.0"?> <status> <target path="."> <entry path="Path/To/Content/Developers/François"> <wc-status item="unversioned" props="none"> </wc-status> </entry> </target> </status> """ unversioned_files = list(svn.SVN.getUnversionedFiles(svn_st_xml, [])) self.assertEqual(["Path/To/Content/Developers/François"], unversioned_files) class TestSvnUriCanonicalize(unittest.TestCase): @parameterized.expand([ ("empty", "", ""), ("canonical", "http://foo.com/bar", "http://foo.com/bar"), ("lc_scheme", "hTtP://foo.com/bar", "http://foo.com/bar"), ("trailing_dot", "http://foo.com./bar", "http://foo.com/bar"), ("lc_hostname", "http://foO.COm/bar", "http://foo.com/bar"), ("lc_hostname_with_user", "http://[email protected]/bar", "http://[email protected]/bar"), ( "lc_hostname_with_user_pass", "http://Jimmy:[email protected]/bar", "http://Jimmy:[email protected]/bar", ), ("trailing_slash", "http://foo.com/bar/", "http://foo.com/bar"), ("trailing_slash_scheme", "http://", "http://"), ("trailing_slash_hostname", "http://foo.com/", "http://foo.com"), ("trailing_double_slash", "http://foo.com/x//", "http://foo.com/x"), ("double_slash", "http://foo.com/x//y", "http://foo.com/x/y"), ("slash", "/", "/"), ("dot", "http://foo.com/x/./y", "http://foo.com/x/y"), ("dot_dot", "http://foo.com/x/../y", "http://foo.com/y"), ("double_dot_dot", "http://foo.com/x/y/../../z", "http://foo.com/z"), ("dot_dot_root", "http://foo.com/../x/y", "http://foo.com/x/y"), ( "quote_spaces", "svn+ssh://user@host:123/My Stuff/file.doc", "svn+ssh://user@host:123/My%20Stuff/file.doc", ), ("remove_port_80", "http://foo.com:80/bar", "http://foo.com/bar"), ("dont_remove_port_80", "https://foo.com:80/bar", "https://foo.com:80/bar"), # not http ("remove_port_443", "https://foo.com:443/bar", "https://foo.com/bar"), ("dont_remove_port_443", "svn://foo.com:443/bar", "svn://foo.com:443/bar"), # not https ("remove_port_3690", "svn://foo.com:3690/bar", "svn://foo.com/bar"), ("dont_remove_port_3690", "http://foo.com:3690/bar", "http://foo.com:3690/bar"), # not svn ("dont_remove_port_other", "https://foo.com:2093/bar", "https://foo.com:2093/bar"), ("quote_funny_chars", "http://foo.com/\x10\xe6%", "http://foo.com/%10%E6%25"), ( "overquoted", "http://foo.com/%68%65%6c%6c%6f%20%77%6f%72%6c%64", "http://foo.com/hello%20world", ), ]) def test_svn_uri(self, name, input, exp): self.assertEqual(svn.SVN.svnUriCanonicalize(input), exp)
83,079
Python
.py
2,038
26.143278
100
0.468337
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,501
test_vstudio.py
buildbot_buildbot/master/buildbot/test/unit/steps/test_vstudio.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 Mock from twisted.internet import defer from twisted.trial import unittest from buildbot import config from buildbot.process import results from buildbot.process.buildstep import create_step_from_step_or_factory from buildbot.process.properties import Property from buildbot.process.results import FAILURE from buildbot.process.results import SKIPPED from buildbot.process.results import SUCCESS from buildbot.process.results import WARNINGS from buildbot.steps import vstudio from buildbot.test.reactor import TestReactorMixin from buildbot.test.steps import ExpectShell from buildbot.test.steps import TestBuildStepMixin real_log = r""" 1>------ Build started: Project: lib1, Configuration: debug Win32 ------ 1>Compiling... 1>SystemLog.cpp 1>c:\absolute\path\to\systemlog.cpp(7) : warning C4100: 'op' : unreferenced formal parameter 1>c:\absolute\path\to\systemlog.cpp(12) : warning C4100: 'statusword' : unreferenced formal parameter 1>c:\absolute\path\to\systemlog.cpp(12) : warning C4100: 'op' : unreferenced formal parameter 1>c:\absolute\path\to\systemlog.cpp(17) : warning C4100: 'retryCounter' : unreferenced formal parameter 1>c:\absolute\path\to\systemlog.cpp(17) : warning C4100: 'op' : unreferenced formal parameter 1>c:\absolute\path\to\systemlog.cpp(22) : warning C4100: 'op' : unreferenced formal parameter 1>Creating library... 1>Build log was saved at "file://c:\another\absolute\path\to\debug\BuildLog.htm" 1>lib1 - 0 error(s), 6 warning(s) 2>------ Build started: Project: product, Configuration: debug Win32 ------ 2>Linking... 2>LINK : fatal error LNK1168: cannot open ../../debug/directory/dllname.dll for writing 2>Build log was saved at "file://c:\another\similar\path\to\debug\BuildLog.htm" 2>product - 1 error(s), 0 warning(s) ========== Build: 1 succeeded, 1 failed, 6 up-to-date, 0 skipped ========== """ class TestAddEnvPath(unittest.TestCase): def do_test(self, initial_env, name, value, expected_env): step = create_step_from_step_or_factory(vstudio.VisualStudio()) step.env = initial_env step.add_env_path(name, value) self.assertEqual(step.env, expected_env) def test_new(self): self.do_test({}, 'PATH', r'C:\NOTHING', {'PATH': r'C:\NOTHING;'}) def test_new_semi(self): self.do_test({}, 'PATH', r'C:\NOTHING;', {'PATH': r'C:\NOTHING;'}) def test_existing(self): self.do_test({'PATH': '/bin'}, 'PATH', r'C:\NOTHING', {'PATH': r'/bin;C:\NOTHING;'}) def test_existing_semi(self): self.do_test({'PATH': '/bin;'}, 'PATH', r'C:\NOTHING', {'PATH': r'/bin;C:\NOTHING;'}) def test_existing_both_semi(self): self.do_test({'PATH': '/bin;'}, 'PATH', r'C:\NOTHING;', {'PATH': r'/bin;C:\NOTHING;'}) class MSLogLineObserver(unittest.TestCase): def setUp(self): self.warnings = [] lw = Mock() lw.addStdout = lambda l: self.warnings.append(l.rstrip()) self.errors = [] self.errors_stderr = [] le = Mock() le.addStdout = lambda l: self.errors.append(('o', l.rstrip())) le.addStderr = lambda l: self.errors.append(('e', l.rstrip())) self.llo = vstudio.MSLogLineObserver(lw, le) self.progress = {} self.llo.step = Mock() self.llo.step.setProgress = self.progress.__setitem__ def receiveLines(self, *lines): for line in lines: self.llo.outLineReceived(line) def assertResult( self, nbFiles=0, nbProjects=0, nbWarnings=0, nbErrors=0, errors=None, warnings=None, progress=None, ): if errors is None: errors = [] if warnings is None: warnings = [] if progress is None: progress = {} self.assertEqual( { "nbFiles": self.llo.nbFiles, "nbProjects": self.llo.nbProjects, "nbWarnings": self.llo.nbWarnings, "nbErrors": self.llo.nbErrors, "errors": self.errors, "warnings": self.warnings, "progress": self.progress, }, { "nbFiles": nbFiles, "nbProjects": nbProjects, "nbWarnings": nbWarnings, "nbErrors": nbErrors, "errors": errors, "warnings": warnings, "progress": progress, }, ) def test_outLineReceived_empty(self): self.llo.outLineReceived('abcd\r\n') self.assertResult() def test_outLineReceived_projects(self): lines = [ "123>----- some project 1 -----", "123>----- some project 2 -----", ] self.receiveLines(*lines) self.assertResult( nbProjects=2, progress={"projects": 2}, errors=[('o', l) for l in lines], warnings=lines ) def test_outLineReceived_files(self): lines = [ "123>SomeClass.cpp", "123>SomeStuff.c", "123>SomeStuff.h", # .h files not recognized ] self.receiveLines(*lines) self.assertResult(nbFiles=2, progress={"files": 2}) def test_outLineReceived_warnings(self): lines = [ "abc: warning ABC123: xyz!", "def : warning DEF456: wxy!", ] self.receiveLines(*lines) self.assertResult(nbWarnings=2, progress={"warnings": 2}, warnings=lines) def test_outLineReceived_errors(self): lines = [ "error ABC123: foo", " error DEF456 : bar", " error : bar", " error: bar", # NOTE: not matched ] self.receiveLines(*lines) self.assertResult( nbErrors=3, # note: no progress errors=[ ('e', "error ABC123: foo"), ('e', " error DEF456 : bar"), ('e', " error : bar"), ], ) def test_outLineReceived_real(self): # based on a real logfile donated by Ben Allard lines = real_log.split("\n") self.receiveLines(*lines) errors = [ ('o', '1>------ Build started: Project: lib1, Configuration: debug Win32 ------'), ('o', '2>------ Build started: Project: product, Configuration: debug Win32 ------'), ( 'e', '2>LINK : fatal error LNK1168: cannot open ../../debug/directory/dllname.dll for writing', ), ] warnings = [ '1>------ Build started: Project: lib1, Configuration: debug Win32 ------', "1>c:\\absolute\\path\\to\\systemlog.cpp(7) : warning C4100: 'op' : unreferenced formal parameter", "1>c:\\absolute\\path\\to\\systemlog.cpp(12) : warning C4100: 'statusword' : unreferenced formal parameter", "1>c:\\absolute\\path\\to\\systemlog.cpp(12) : warning C4100: 'op' : unreferenced formal parameter", "1>c:\\absolute\\path\\to\\systemlog.cpp(17) : warning C4100: 'retryCounter' : unreferenced formal parameter", "1>c:\\absolute\\path\\to\\systemlog.cpp(17) : warning C4100: 'op' : unreferenced formal parameter", "1>c:\\absolute\\path\\to\\systemlog.cpp(22) : warning C4100: 'op' : unreferenced formal parameter", '2>------ Build started: Project: product, Configuration: debug Win32 ------', ] self.assertResult( nbFiles=1, nbErrors=1, nbProjects=2, nbWarnings=6, progress={'files': 1, 'projects': 2, 'warnings': 6}, errors=errors, warnings=warnings, ) class VCx(vstudio.VisualStudio): def run(self): self.command = ["command", "here"] return super().run() class VisualStudio(TestBuildStepMixin, TestReactorMixin, unittest.TestCase): """ Test L{VisualStudio} with a simple subclass, L{VCx}. """ 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_default_config(self): vs = vstudio.VisualStudio() self.assertEqual(vs.config, 'release') def test_simple(self): self.setup_step(VCx()) self.expect_commands(ExpectShell(workdir='wkdir', command=['command', 'here']).exit(0)) self.expect_outcome(result=SUCCESS, state_string="compile 0 projects 0 files") return self.run_step() def test_skipped(self): self.setup_step(VCx(doStepIf=False)) self.expect_commands() self.expect_outcome(result=SKIPPED, state_string="") return self.run_step() @defer.inlineCallbacks def test_installdir(self): self.setup_step(VCx(installdir=r'C:\I')) self.get_nth_step(0).exp_installdir = r'C:\I' self.expect_commands(ExpectShell(workdir='wkdir', command=['command', 'here']).exit(0)) self.expect_outcome(result=SUCCESS, state_string="compile 0 projects 0 files") yield self.run_step() self.assertEqual(self.get_nth_step(0).installdir, r'C:\I') def test_evaluate_result_failure(self): self.setup_step(VCx()) self.expect_commands(ExpectShell(workdir='wkdir', command=['command', 'here']).exit(1)) self.expect_outcome(result=FAILURE, state_string="compile 0 projects 0 files (failure)") return self.run_step() def test_evaluate_result_errors(self): self.setup_step(VCx()) self.expect_commands( ExpectShell(workdir='wkdir', command=['command', 'here']) .stdout('error ABC123: foo\r\n') .exit(0) ) self.expect_outcome( result=FAILURE, state_string="compile 0 projects 0 files 1 errors (failure)" ) return self.run_step() def test_evaluate_result_warnings(self): self.setup_step(VCx()) self.expect_commands( ExpectShell(workdir='wkdir', command=['command', 'here']) .stdout('foo: warning ABC123: foo\r\n') .exit(0) ) self.expect_outcome( result=WARNINGS, state_string="compile 0 projects 0 files 1 warnings (warnings)" ) return self.run_step() def test_env_setup(self): self.setup_step( VCx( INCLUDE=[r'c:\INC1', r'c:\INC2'], LIB=[r'c:\LIB1', r'C:\LIB2'], PATH=[r'c:\P1', r'C:\P2'], ) ) self.expect_commands( ExpectShell( workdir="wkdir", command=["command", "here"], env={ "INCLUDE": r"c:\INC1;c:\INC2;", "LIB": r"c:\LIB1;C:\LIB2;", "PATH": r"c:\P1;C:\P2;", }, ).exit(0) ) self.expect_outcome(result=SUCCESS, state_string="compile 0 projects 0 files") return self.run_step() def test_env_setup_existing(self): self.setup_step( VCx( INCLUDE=[r'c:\INC1', r'c:\INC2'], LIB=[r'c:\LIB1', r'C:\LIB2'], PATH=[r'c:\P1', r'C:\P2'], ) ) self.expect_commands( ExpectShell( workdir="wkdir", command=["command", "here"], env={ "INCLUDE": r"c:\INC1;c:\INC2;", "LIB": r"c:\LIB1;C:\LIB2;", "PATH": r"c:\P1;C:\P2;", }, ).exit(0) ) self.expect_outcome(result=SUCCESS, state_string="compile 0 projects 0 files") return self.run_step() @defer.inlineCallbacks def test_rendering(self): self.setup_step(VCx(projectfile=Property('a'), config=Property('b'), project=Property('c'))) self.build.setProperty('a', 'aa', 'Test') self.build.setProperty('b', 'bb', 'Test') self.build.setProperty('c', 'cc', 'Test') self.expect_commands(ExpectShell(workdir='wkdir', command=['command', 'here']).exit(0)) self.expect_outcome(result=SUCCESS, state_string="compile 0 projects 0 files") yield self.run_step() step = self.get_nth_step(0) self.assertEqual([step.projectfile, step.config, step.project], ['aa', 'bb', 'cc']) class TestVC6(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() def getExpectedEnv(self, installdir, LIB=None, p=None, i=None): include = [ installdir + r'\VC98\INCLUDE;', installdir + r'\VC98\ATL\INCLUDE;', installdir + r'\VC98\MFC\INCLUDE;', ] lib = [ installdir + r'\VC98\LIB;', installdir + r'\VC98\MFC\LIB;', ] path = [ installdir + r'\Common\msdev98\BIN;', installdir + r'\VC98\BIN;', installdir + r'\Common\TOOLS\WINNT;', installdir + r'\Common\TOOLS;', ] if p: path.insert(0, f'{p};') if i: include.insert(0, f'{i};') if LIB: lib.insert(0, f'{LIB};') return { "INCLUDE": ''.join(include), "LIB": ''.join(lib), "PATH": ''.join(path), } def test_args(self): self.setup_step(vstudio.VC6(projectfile='pf', config='cfg', project='pj')) self.expect_commands( ExpectShell( workdir='wkdir', command=['msdev', 'pf', '/MAKE', 'pj - cfg', '/REBUILD'], env=self.getExpectedEnv(r'C:\Program Files\Microsoft Visual Studio'), ).exit(0) ) self.expect_outcome(result=SUCCESS, state_string="compile 0 projects 0 files") return self.run_step() def test_clean(self): self.setup_step(vstudio.VC6(projectfile='pf', config='cfg', project='pj', mode='clean')) self.expect_commands( ExpectShell( workdir='wkdir', command=['msdev', 'pf', '/MAKE', 'pj - cfg', '/CLEAN'], env=self.getExpectedEnv(r'C:\Program Files\Microsoft Visual Studio'), ).exit(0) ) self.expect_outcome(result=SUCCESS, state_string="compile 0 projects 0 files") return self.run_step() def test_noproj_build(self): self.setup_step(vstudio.VC6(projectfile='pf', config='cfg', mode='build')) self.expect_commands( ExpectShell( workdir='wkdir', command=['msdev', 'pf', '/MAKE', 'ALL - cfg', '/BUILD'], env=self.getExpectedEnv(r'C:\Program Files\Microsoft Visual Studio'), ).exit(0) ) self.expect_outcome(result=SUCCESS, state_string="compile 0 projects 0 files") return self.run_step() def test_env_prepend(self): self.setup_step( vstudio.VC6( projectfile='pf', config='cfg', project='pj', PATH=['p'], INCLUDE=['i'], LIB=['l'] ) ) self.expect_commands( ExpectShell( workdir='wkdir', command=[ 'msdev', 'pf', '/MAKE', 'pj - cfg', '/REBUILD', '/USEENV', ], # note extra param env=self.getExpectedEnv( r'C:\Program Files\Microsoft Visual Studio', LIB='l', p='p', i='i' ), ).exit(0) ) self.expect_outcome(result=SUCCESS, state_string="compile 0 projects 0 files") return self.run_step() class TestVC7(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() def getExpectedEnv(self, installdir, LIB=None, p=None, i=None): include = [ installdir + r'\VC7\INCLUDE;', installdir + r'\VC7\ATLMFC\INCLUDE;', installdir + r'\VC7\PlatformSDK\include;', installdir + r'\SDK\v1.1\include;', ] lib = [ installdir + r'\VC7\LIB;', installdir + r'\VC7\ATLMFC\LIB;', installdir + r'\VC7\PlatformSDK\lib;', installdir + r'\SDK\v1.1\lib;', ] path = [ installdir + r'\Common7\IDE;', installdir + r'\VC7\BIN;', installdir + r'\Common7\Tools;', installdir + r'\Common7\Tools\bin;', ] if p: path.insert(0, f'{p};') if i: include.insert(0, f'{i};') if LIB: lib.insert(0, f'{LIB};') return { "INCLUDE": ''.join(include), "LIB": ''.join(lib), "PATH": ''.join(path), } def test_args(self): self.setup_step(vstudio.VC7(projectfile='pf', config='cfg', project='pj')) self.expect_commands( ExpectShell( workdir='wkdir', command=['devenv.com', 'pf', '/Rebuild', 'cfg', '/Project', 'pj'], env=self.getExpectedEnv(r'C:\Program Files\Microsoft Visual Studio .NET 2003'), ).exit(0) ) self.expect_outcome(result=SUCCESS, state_string="compile 0 projects 0 files") return self.run_step() def test_clean(self): self.setup_step(vstudio.VC7(projectfile='pf', config='cfg', project='pj', mode='clean')) self.expect_commands( ExpectShell( workdir='wkdir', command=['devenv.com', 'pf', '/Clean', 'cfg', '/Project', 'pj'], env=self.getExpectedEnv(r'C:\Program Files\Microsoft Visual Studio .NET 2003'), ).exit(0) ) self.expect_outcome(result=SUCCESS, state_string="compile 0 projects 0 files") return self.run_step() def test_noproj_build(self): self.setup_step(vstudio.VC7(projectfile='pf', config='cfg', mode='build')) self.expect_commands( ExpectShell( workdir='wkdir', command=['devenv.com', 'pf', '/Build', 'cfg'], env=self.getExpectedEnv(r'C:\Program Files\Microsoft Visual Studio .NET 2003'), ).exit(0) ) self.expect_outcome(result=SUCCESS, state_string="compile 0 projects 0 files") return self.run_step() def test_env_prepend(self): self.setup_step( vstudio.VC7( projectfile='pf', config='cfg', project='pj', PATH=['p'], INCLUDE=['i'], LIB=['l'] ) ) self.expect_commands( ExpectShell( workdir='wkdir', command=['devenv.com', 'pf', '/Rebuild', 'cfg', '/UseEnv', '/Project', 'pj'], env=self.getExpectedEnv( r'C:\Program Files\Microsoft Visual Studio .NET 2003', LIB='l', p='p', i='i' ), ).exit(0) ) self.expect_outcome(result=SUCCESS, state_string="compile 0 projects 0 files") return self.run_step() class VC8ExpectedEnvMixin: # used for VC8 and VC9Express def getExpectedEnv(self, installdir, x64=False, LIB=None, i=None, p=None): include = [ installdir + r'\VC\INCLUDE;', installdir + r'\VC\ATLMFC\include;', installdir + r'\VC\PlatformSDK\include;', ] lib = [ installdir + r'\VC\LIB;', installdir + r'\VC\ATLMFC\LIB;', installdir + r'\VC\PlatformSDK\lib;', installdir + r'\SDK\v2.0\lib;', ] path = [ installdir + r'\Common7\IDE;', installdir + r'\VC\BIN;', installdir + r'\Common7\Tools;', installdir + r'\Common7\Tools\bin;', installdir + r'\VC\PlatformSDK\bin;', installdir + r'\SDK\v2.0\bin;', installdir + r'\VC\VCPackages;', r'${PATH};', ] if x64: path.insert(1, installdir + r'\VC\BIN\x86_amd64;') lib = [lb[:-1] + r'\amd64;' for lb in lib] if LIB: lib.insert(0, f'{LIB};') if p: path.insert(0, f'{p};') if i: include.insert(0, f'{i};') return { "INCLUDE": ''.join(include), "LIB": ''.join(lib), "PATH": ''.join(path), } class TestVC8(VC8ExpectedEnvMixin, 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() def test_args(self): self.setup_step(vstudio.VC8(projectfile='pf', config='cfg', project='pj', arch='arch')) self.expect_commands( ExpectShell( workdir='wkdir', command=['devenv.com', 'pf', '/Rebuild', 'cfg', '/Project', 'pj'], env=self.getExpectedEnv(r'C:\Program Files\Microsoft Visual Studio 8'), ).exit(0) ) self.expect_outcome(result=SUCCESS, state_string="compile 0 projects 0 files") return self.run_step() def test_args_x64(self): self.setup_step(vstudio.VC8(projectfile='pf', config='cfg', project='pj', arch='x64')) self.expect_commands( ExpectShell( workdir='wkdir', command=['devenv.com', 'pf', '/Rebuild', 'cfg', '/Project', 'pj'], env=self.getExpectedEnv(r'C:\Program Files\Microsoft Visual Studio 8', x64=True), ).exit(0) ) self.expect_outcome(result=SUCCESS, state_string="compile 0 projects 0 files") return self.run_step() def test_clean(self): self.setup_step(vstudio.VC8(projectfile='pf', config='cfg', project='pj', mode='clean')) self.expect_commands( ExpectShell( workdir='wkdir', command=['devenv.com', 'pf', '/Clean', 'cfg', '/Project', 'pj'], env=self.getExpectedEnv(r'C:\Program Files\Microsoft Visual Studio 8'), ).exit(0) ) self.expect_outcome(result=SUCCESS, state_string="compile 0 projects 0 files") return self.run_step() @defer.inlineCallbacks def test_rendering(self): self.setup_step(vstudio.VC8(projectfile='pf', config='cfg', arch=Property('a'))) self.build.setProperty('a', 'x64', 'Test') self.expect_commands( ExpectShell( workdir='wkdir', command=['devenv.com', 'pf', '/Rebuild', 'cfg'], env=self.getExpectedEnv(r'C:\Program Files\Microsoft Visual Studio 8', x64=True), ).exit(0) # property has expected effect ) self.expect_outcome(result=SUCCESS, state_string="compile 0 projects 0 files") yield self.run_step() self.assertEqual(self.get_nth_step(0).arch, 'x64') class TestVCExpress9(VC8ExpectedEnvMixin, 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() def test_args(self): self.setup_step(vstudio.VCExpress9(projectfile='pf', config='cfg', project='pj')) self.expect_commands( ExpectShell( workdir='wkdir', command=['vcexpress', 'pf', '/Rebuild', 'cfg', '/Project', 'pj'], env=self.getExpectedEnv( # note: still uses version 8 (?!) r'C:\Program Files\Microsoft Visual Studio 8' ), ).exit(0) ) self.expect_outcome(result=SUCCESS, state_string="compile 0 projects 0 files") return self.run_step() def test_clean(self): self.setup_step( vstudio.VCExpress9(projectfile='pf', config='cfg', project='pj', mode='clean') ) self.expect_commands( ExpectShell( workdir='wkdir', command=['vcexpress', 'pf', '/Clean', 'cfg', '/Project', 'pj'], env=self.getExpectedEnv( # note: still uses version 8 (?!) r'C:\Program Files\Microsoft Visual Studio 8' ), ).exit(0) ) self.expect_outcome(result=SUCCESS, state_string="compile 0 projects 0 files") return self.run_step() def test_mode_build_env(self): self.setup_step( vstudio.VCExpress9( projectfile='pf', config='cfg', project='pj', mode='build', INCLUDE=['i'] ) ) self.expect_commands( ExpectShell( workdir='wkdir', command=['vcexpress', 'pf', '/Build', 'cfg', '/UseEnv', '/Project', 'pj'], env=self.getExpectedEnv(r'C:\Program Files\Microsoft Visual Studio 8', i='i'), ).exit(0) ) self.expect_outcome(result=SUCCESS, state_string="compile 0 projects 0 files") return self.run_step() class TestVC9(VC8ExpectedEnvMixin, 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() def test_installdir(self): self.setup_step(vstudio.VC9(projectfile='pf', config='cfg', project='pj')) self.expect_commands( ExpectShell( workdir='wkdir', command=['devenv.com', 'pf', '/Rebuild', 'cfg', '/Project', 'pj'], env=self.getExpectedEnv(r'C:\Program Files\Microsoft Visual Studio 9.0'), ).exit(0) ) self.expect_outcome(result=SUCCESS, state_string="compile 0 projects 0 files") return self.run_step() class TestVC10(VC8ExpectedEnvMixin, 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() def test_installdir(self): self.setup_step(vstudio.VC10(projectfile='pf', config='cfg', project='pj')) self.expect_commands( ExpectShell( workdir='wkdir', command=['devenv.com', 'pf', '/Rebuild', 'cfg', '/Project', 'pj'], env=self.getExpectedEnv(r'C:\Program Files\Microsoft Visual Studio 10.0'), ).exit(0) ) self.expect_outcome(result=SUCCESS, state_string="compile 0 projects 0 files") return self.run_step() class TestVC11(VC8ExpectedEnvMixin, 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() def test_installdir(self): self.setup_step(vstudio.VC11(projectfile='pf', config='cfg', project='pj')) self.expect_commands( ExpectShell( workdir='wkdir', command=['devenv.com', 'pf', '/Rebuild', 'cfg', '/Project', 'pj'], env=self.getExpectedEnv(r'C:\Program Files\Microsoft Visual Studio 11.0'), ).exit(0) ) self.expect_outcome(result=SUCCESS, state_string="compile 0 projects 0 files") return self.run_step() class TestMsBuild(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_no_platform(self): self.setup_step( vstudio.MsBuild(projectfile='pf', config='cfg', platform=None, project='pj') ) self.expect_outcome(result=results.EXCEPTION, state_string="built pj for cfg|None") yield self.run_step() self.assertEqual(len(self.flushLoggedErrors(config.ConfigErrors)), 1) def test_rebuild_project(self): self.setup_step( vstudio.MsBuild(projectfile='pf', config='cfg', platform='Win32', project='pj') ) self.expect_commands( ExpectShell( workdir='wkdir', command='"%VCENV_BAT%" x86 && msbuild "pf" /p:Configuration="cfg" /p:Platform="Win32" /maxcpucount /t:"pj"', env={'VCENV_BAT': r'${VS110COMNTOOLS}..\..\VC\vcvarsall.bat'}, ).exit(0) ) self.expect_outcome(result=SUCCESS, state_string="built pj for cfg|Win32") return self.run_step() def test_build_project(self): self.setup_step( vstudio.MsBuild( projectfile='pf', config='cfg', platform='Win32', project='pj', mode='build' ) ) self.expect_commands( ExpectShell( workdir='wkdir', command='"%VCENV_BAT%" x86 && msbuild "pf" /p:Configuration="cfg" /p:Platform="Win32" /maxcpucount /t:"pj:Build"', env={'VCENV_BAT': r'${VS110COMNTOOLS}..\..\VC\vcvarsall.bat'}, ).exit(0) ) self.expect_outcome(result=SUCCESS, state_string="built pj for cfg|Win32") return self.run_step() def test_clean_project(self): self.setup_step( vstudio.MsBuild( projectfile='pf', config='cfg', platform='Win32', project='pj', mode='clean' ) ) self.expect_commands( ExpectShell( workdir='wkdir', command='"%VCENV_BAT%" x86 && msbuild "pf" /p:Configuration="cfg" /p:Platform="Win32" /maxcpucount /t:"pj:Clean"', env={'VCENV_BAT': r'${VS110COMNTOOLS}..\..\VC\vcvarsall.bat'}, ).exit(0) ) self.expect_outcome(result=SUCCESS, state_string="built pj for cfg|Win32") return self.run_step() def test_rebuild_project_with_defines(self): self.setup_step( vstudio.MsBuild( projectfile='pf', config='cfg', platform='Win32', project='pj', defines=['Define1', 'Define2=42'], ) ) self.expect_commands( ExpectShell( workdir='wkdir', command='"%VCENV_BAT%" x86 && msbuild "pf" /p:Configuration="cfg" /p:Platform="Win32" /maxcpucount /t:"pj" /p:DefineConstants="Define1;Define2=42"', env={'VCENV_BAT': r'${VS110COMNTOOLS}..\..\VC\vcvarsall.bat'}, ).exit(0) ) self.expect_outcome(result=SUCCESS, state_string="built pj for cfg|Win32") return self.run_step() def test_rebuild_solution(self): self.setup_step(vstudio.MsBuild(projectfile='pf', config='cfg', platform='x64')) self.expect_commands( ExpectShell( workdir='wkdir', command='"%VCENV_BAT%" x86 && msbuild "pf" /p:Configuration="cfg" /p:Platform="x64" /maxcpucount /t:Rebuild', env={'VCENV_BAT': r'${VS110COMNTOOLS}..\..\VC\vcvarsall.bat'}, ).exit(0) ) self.expect_outcome(result=SUCCESS, state_string="built solution for cfg|x64") return self.run_step() class TestMsBuild141(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_no_platform(self): self.setup_step( vstudio.MsBuild(projectfile='pf', config='cfg', platform=None, project='pj') ) self.expect_outcome(result=results.EXCEPTION, state_string="built pj for cfg|None") yield self.run_step() self.assertEqual(len(self.flushLoggedErrors(config.ConfigErrors)), 1) def test_rebuild_project(self): self.setup_step( vstudio.MsBuild141(projectfile='pf', config='cfg', platform='Win32', project='pj') ) self.expect_commands( ExpectShell( workdir='wkdir', command='FOR /F "tokens=*" %%I in (\'vswhere.exe -version "[15.0,16.0)" -products * -property installationPath\') do "%%I\\%VCENV_BAT%" x86 && msbuild "pf" /p:Configuration="cfg" /p:Platform="Win32" /maxcpucount /t:"pj"', env={ 'VCENV_BAT': r'\VC\Auxiliary\Build\vcvarsall.bat', 'PATH': 'C:\\Program Files (x86)\\Microsoft Visual Studio\\Installer\\;C:\\Program Files\\Microsoft Visual Studio\\Installer\\;${PATH};', }, ).exit(0) ) self.expect_outcome(result=SUCCESS, state_string="compile 0 projects 0 files") return self.run_step() def test_build_project(self): self.setup_step( vstudio.MsBuild141( projectfile='pf', config='cfg', platform='Win32', project='pj', mode='build' ) ) self.expect_commands( ExpectShell( workdir='wkdir', command='FOR /F "tokens=*" %%I in (\'vswhere.exe -version "[15.0,16.0)" -products * -property installationPath\') do "%%I\\%VCENV_BAT%" x86 && msbuild "pf" /p:Configuration="cfg" /p:Platform="Win32" /maxcpucount /t:"pj:Build"', env={ 'VCENV_BAT': r'\VC\Auxiliary\Build\vcvarsall.bat', 'PATH': 'C:\\Program Files (x86)\\Microsoft Visual Studio\\Installer\\;C:\\Program Files\\Microsoft Visual Studio\\Installer\\;${PATH};', }, ).exit(0) ) self.expect_outcome(result=SUCCESS, state_string="compile 0 projects 0 files") return self.run_step() def test_clean_project(self): self.setup_step( vstudio.MsBuild141( projectfile='pf', config='cfg', platform='Win32', project='pj', mode='clean' ) ) self.expect_commands( ExpectShell( workdir='wkdir', command='FOR /F "tokens=*" %%I in (\'vswhere.exe -version "[15.0,16.0)" -products * -property installationPath\') do "%%I\\%VCENV_BAT%" x86 && msbuild "pf" /p:Configuration="cfg" /p:Platform="Win32" /maxcpucount /t:"pj:Clean"', env={ 'VCENV_BAT': r'\VC\Auxiliary\Build\vcvarsall.bat', 'PATH': 'C:\\Program Files (x86)\\Microsoft Visual Studio\\Installer\\;C:\\Program Files\\Microsoft Visual Studio\\Installer\\;${PATH};', }, ).exit(0) ) self.expect_outcome(result=SUCCESS, state_string="compile 0 projects 0 files") return self.run_step() def test_rebuild_project_with_defines(self): self.setup_step( vstudio.MsBuild141( projectfile='pf', config='cfg', platform='Win32', project='pj', defines=['Define1', 'Define2=42'], ) ) self.expect_commands( ExpectShell( workdir='wkdir', command='FOR /F "tokens=*" %%I in (\'vswhere.exe -version "[15.0,16.0)" -products * -property installationPath\') do "%%I\\%VCENV_BAT%" x86 && msbuild "pf" /p:Configuration="cfg" /p:Platform="Win32" /maxcpucount /t:"pj" /p:DefineConstants="Define1;Define2=42"', env={ 'VCENV_BAT': r'\VC\Auxiliary\Build\vcvarsall.bat', 'PATH': 'C:\\Program Files (x86)\\Microsoft Visual Studio\\Installer\\;C:\\Program Files\\Microsoft Visual Studio\\Installer\\;${PATH};', }, ).exit(0) ) self.expect_outcome(result=SUCCESS, state_string="compile 0 projects 0 files") return self.run_step() def test_rebuild_solution(self): self.setup_step(vstudio.MsBuild141(projectfile='pf', config='cfg', platform='x64')) self.expect_commands( ExpectShell( workdir='wkdir', command='FOR /F "tokens=*" %%I in (\'vswhere.exe -version "[15.0,16.0)" -products * -property installationPath\') do "%%I\\%VCENV_BAT%" x86 && msbuild "pf" /p:Configuration="cfg" /p:Platform="x64" /maxcpucount /t:Rebuild', env={ 'VCENV_BAT': r'\VC\Auxiliary\Build\vcvarsall.bat', 'PATH': 'C:\\Program Files (x86)\\Microsoft Visual Studio\\Installer\\;C:\\Program Files\\Microsoft Visual Studio\\Installer\\;${PATH};', }, ).exit(0) ) self.expect_outcome(result=SUCCESS, state_string="compile 0 projects 0 files") return self.run_step() def test_aliases_MsBuild15(self): self.assertIdentical(vstudio.MsBuild141, vstudio.MsBuild15) class TestMsBuild16(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() def test_version_range_is_correct(self): self.setup_step( vstudio.MsBuild16(projectfile='pf', config='cfg', platform='Win32', project='pj') ) self.expect_commands( ExpectShell( workdir='wkdir', command='FOR /F "tokens=*" %%I in (\'vswhere.exe -version "[16.0,17.0)" -products * -property installationPath\') do "%%I\\%VCENV_BAT%" x86 && msbuild "pf" /p:Configuration="cfg" /p:Platform="Win32" /maxcpucount /t:"pj"', env={ 'VCENV_BAT': r'\VC\Auxiliary\Build\vcvarsall.bat', 'PATH': 'C:\\Program Files (x86)\\Microsoft Visual Studio\\Installer\\;C:\\Program Files\\Microsoft Visual Studio\\Installer\\;${PATH};', }, ).exit(0) ) self.expect_outcome(result=SUCCESS, state_string="compile 0 projects 0 files") return self.run_step() class TestMsBuild17(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() def test_version_range_is_correct(self): self.setup_step( vstudio.MsBuild17(projectfile='pf', config='cfg', platform='Win32', project='pj') ) self.expect_commands( ExpectShell( workdir='wkdir', command='FOR /F "tokens=*" %%I in (\'vswhere.exe -version "[17.0,18.0)" -products * -property installationPath\') do "%%I\\%VCENV_BAT%" x86 && msbuild "pf" /p:Configuration="cfg" /p:Platform="Win32" /maxcpucount /t:"pj"', env={ 'VCENV_BAT': r'\VC\Auxiliary\Build\vcvarsall.bat', 'PATH': 'C:\\Program Files (x86)\\Microsoft Visual Studio\\Installer\\;C:\\Program Files\\Microsoft Visual Studio\\Installer\\;${PATH};', }, ).exit(0) ) self.expect_outcome(result=SUCCESS, state_string="compile 0 projects 0 files") return self.run_step() class Aliases(unittest.TestCase): def test_vs2003(self): self.assertIdentical(vstudio.VS2003, vstudio.VC7) def test_vs2005(self): self.assertIdentical(vstudio.VS2005, vstudio.VC8) def test_vs2008(self): self.assertIdentical(vstudio.VS2008, vstudio.VC9) def test_vs2010(self): self.assertIdentical(vstudio.VS2010, vstudio.VC10) def test_vs2012(self): self.assertIdentical(vstudio.VS2012, vstudio.VC11)
41,864
Python
.py
945
33.661376
278
0.578287
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,502
test_source_gitlab.py
buildbot_buildbot/master/buildbot/test/unit/steps/test_source_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 twisted.internet import defer from twisted.trial import unittest from buildbot.process.results import SUCCESS from buildbot.steps.source import gitlab from buildbot.test.reactor import TestReactorMixin from buildbot.test.steps import ExpectListdir from buildbot.test.steps import ExpectShell from buildbot.test.steps import ExpectStat from buildbot.test.util import config from buildbot.test.util import sourcesteps class TestGitLab( sourcesteps.SourceStepMixin, config.ConfigErrorsMixin, TestReactorMixin, unittest.TestCase ): stepClass = gitlab.GitLab def setUp(self): self.setup_test_reactor(auto_tear_down=False) self.sourceName = self.stepClass.__name__ return self.setUpSourceStep() def setup_step(self, step, args, **kwargs): step = super().setup_step(step, args, **kwargs) step.build.properties.setProperty("source_branch", "ms-viewport", "gitlab source branch") step.build.properties.setProperty( "source_git_ssh_url", "[email protected]:build/awesome_project.git", "gitlab source git ssh url", ) step.build.properties.setProperty("source_project_id", 2337, "gitlab source project ID") step.build.properties.setProperty("target_branch", "master", "gitlab target branch") step.build.properties.setProperty( "target_git_ssh_url", "[email protected]:mmusterman/awesome_project.git", "gitlab target git ssh url", ) step.build.properties.setProperty("target_project_id", 239, "gitlab target project ID") return step @defer.inlineCallbacks def tearDown(self): yield self.tearDownSourceStep() yield self.tear_down_test_reactor() def test_with_merge_branch(self): self.setup_step( self.stepClass( repourl='[email protected]:mmusterman/awesome_project.git', mode='full', method='clean', ), {"branch": 'master', "revision": '12345678'}, ) self.expect_commands( ExpectShell(workdir='wkdir', command=['git', '--version']) .stdout('git version 1.7.5') .exit(0), ExpectStat(file='wkdir/.buildbot-patched', log_environ=True).exit(1), ExpectListdir(dir='wkdir').files(['.git']).exit(0), ExpectShell(workdir='wkdir', command=['git', 'clean', '-f', '-f', '-d']).exit(0), # here we always ignore revision, and fetch the merge branch ExpectShell( workdir='wkdir', command=[ 'git', 'fetch', '-f', '--progress', '[email protected]:build/awesome_project.git', 'ms-viewport', ], ).exit(0), ExpectShell(workdir='wkdir', command=['git', 'checkout', '-f', 'FETCH_HEAD']).exit(0), ExpectShell(workdir='wkdir', command=['git', 'checkout', '-B', 'ms-viewport']).exit(0), ExpectShell(workdir='wkdir', command=['git', 'rev-parse', 'HEAD']) .stdout('f6ad368298bd941e934a41f3babc827b2aa95a1d') .exit(0), ) self.expect_outcome(result=SUCCESS) self.expect_property('got_revision', 'f6ad368298bd941e934a41f3babc827b2aa95a1d', 'GitLab') return self.run_step()
4,166
Python
.py
90
37.455556
99
0.647898
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,503
test_source_gerrit.py
buildbot_buildbot/master/buildbot/test/unit/steps/test_source_gerrit.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.results import SUCCESS from buildbot.steps.source import gerrit from buildbot.test.reactor import TestReactorMixin from buildbot.test.steps import ExpectListdir from buildbot.test.steps import ExpectShell from buildbot.test.steps import ExpectStat from buildbot.test.util import config from buildbot.test.util import sourcesteps class TestGerrit( sourcesteps.SourceStepMixin, config.ConfigErrorsMixin, TestReactorMixin, unittest.TestCase ): def setUp(self): self.setup_test_reactor(auto_tear_down=False) return self.setUpSourceStep() @defer.inlineCallbacks def tearDown(self): yield self.tearDownSourceStep() yield self.tear_down_test_reactor() def test_mode_full_clean(self): self.setup_step( gerrit.Gerrit( repourl='http://github.com/buildbot/buildbot.git', mode='full', method='clean' ) ) self.build.setProperty("event.change.project", "buildbot") self.sourcestamp.project = 'buildbot' self.build.setProperty("event.patchSet.ref", "gerrit_branch") self.expect_commands( ExpectShell(workdir='wkdir', command=['git', '--version']) .stdout('git version 1.7.5') .exit(0), ExpectStat(file='wkdir/.buildbot-patched', log_environ=True).exit(1), ExpectListdir(dir='wkdir').files(['.git']).exit(0), ExpectShell(workdir='wkdir', command=['git', 'clean', '-f', '-f', '-d']).exit(0), ExpectShell( workdir='wkdir', command=[ 'git', 'fetch', '-f', '--progress', 'http://github.com/buildbot/buildbot.git', 'gerrit_branch', ], ).exit(0), ExpectShell(workdir='wkdir', command=['git', 'checkout', '-f', 'FETCH_HEAD']).exit(0), ExpectShell(workdir='wkdir', command=['git', 'checkout', '-B', 'gerrit_branch']).exit( 0 ), ExpectShell(workdir='wkdir', command=['git', 'rev-parse', 'HEAD']) .stdout('f6ad368298bd941e934a41f3babc827b2aa95a1d') .exit(0), ) self.expect_outcome(result=SUCCESS) self.expect_property('got_revision', 'f6ad368298bd941e934a41f3babc827b2aa95a1d', 'Gerrit') return self.run_step() def test_mode_full_clean_force_build(self): self.setup_step( gerrit.Gerrit( repourl='http://github.com/buildbot/buildbot.git', mode='full', method='clean' ) ) self.build.setProperty("event.change.project", "buildbot") self.sourcestamp.project = 'buildbot' self.build.setProperty("gerrit_change", "1234/567") self.expect_commands( ExpectShell(workdir='wkdir', command=['git', '--version']) .stdout('git version 1.7.5') .exit(0), ExpectStat(file='wkdir/.buildbot-patched', log_environ=True).exit(1), ExpectListdir(dir='wkdir').files(['.git']).exit(0), ExpectShell(workdir='wkdir', command=['git', 'clean', '-f', '-f', '-d']).exit(0), ExpectShell( workdir='wkdir', command=[ 'git', 'fetch', '-f', '--progress', 'http://github.com/buildbot/buildbot.git', 'refs/changes/34/1234/567', ], ).exit(0), ExpectShell(workdir='wkdir', command=['git', 'checkout', '-f', 'FETCH_HEAD']).exit(0), ExpectShell( workdir='wkdir', command=['git', 'checkout', '-B', 'refs/changes/34/1234/567'] ).exit(0), ExpectShell(workdir='wkdir', command=['git', 'rev-parse', 'HEAD']) .stdout('f6ad368298bd941e934a41f3babc827b2aa95a1d') .exit(0), ) self.expect_outcome(result=SUCCESS) self.expect_property('got_revision', 'f6ad368298bd941e934a41f3babc827b2aa95a1d', 'Gerrit') return self.run_step() def test_mode_full_clean_force_same_project(self): self.setup_step( gerrit.Gerrit( repourl='http://github.com/buildbot/buildbot.git', mode='full', method='clean', codebase='buildbot', ) ) self.build.setProperty("event.change.project", "buildbot") self.sourcestamp.project = 'buildbot' self.build.setProperty("gerrit_change", "1234/567") self.expect_commands( ExpectShell(workdir='wkdir', command=['git', '--version']) .stdout('git version 1.7.5') .exit(0), ExpectStat(file='wkdir/.buildbot-patched', log_environ=True).exit(1), ExpectListdir(dir='wkdir').files(['.git']).exit(0), ExpectShell(workdir='wkdir', command=['git', 'clean', '-f', '-f', '-d']).exit(0), ExpectShell( workdir='wkdir', command=[ 'git', 'fetch', '-f', '--progress', 'http://github.com/buildbot/buildbot.git', 'refs/changes/34/1234/567', ], ).exit(0), ExpectShell(workdir='wkdir', command=['git', 'checkout', '-f', 'FETCH_HEAD']).exit(0), ExpectShell( workdir='wkdir', command=['git', 'checkout', '-B', 'refs/changes/34/1234/567'] ).exit(0), ExpectShell(workdir='wkdir', command=['git', 'rev-parse', 'HEAD']) .stdout('f6ad368298bd941e934a41f3babc827b2aa95a1d') .exit(0), ) self.expect_outcome(result=SUCCESS) self.expect_property( 'got_revision', {'buildbot': 'f6ad368298bd941e934a41f3babc827b2aa95a1d'}, 'Gerrit' ) return self.run_step() def test_mode_full_clean_different_project(self): self.setup_step( gerrit.Gerrit( repourl='http://github.com/buildbot/buildbot.git', mode='full', method='clean', codebase='buildbot', ) ) self.build.setProperty("event.change.project", "buildbot") self.sourcestamp.project = 'not_buildbot' self.build.setProperty("gerrit_change", "1234/567") self.expect_commands( ExpectShell(workdir='wkdir', command=['git', '--version']) .stdout('git version 1.7.5') .exit(0), ExpectStat(file='wkdir/.buildbot-patched', log_environ=True).exit(1), ExpectListdir(dir='wkdir').files(['.git']).exit(0), ExpectShell(workdir='wkdir', command=['git', 'clean', '-f', '-f', '-d']).exit(0), ExpectShell( workdir='wkdir', command=[ 'git', 'fetch', '-f', '--progress', 'http://github.com/buildbot/buildbot.git', 'HEAD', ], ).exit(0), ExpectShell(workdir='wkdir', command=['git', 'checkout', '-f', 'FETCH_HEAD']).exit(0), ExpectShell(workdir='wkdir', command=['git', 'rev-parse', 'HEAD']) .stdout('f6ad368298bd941e934a41f3babc827b2aa95a1d') .exit(0), ) self.expect_outcome(result=SUCCESS) return self.run_step()
8,370
Python
.py
190
32.352632
98
0.565201
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,504
test_shellsequence.py
buildbot_buildbot/master/buildbot/test/unit/steps/test_shellsequence.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.properties import WithProperties from buildbot.process.results import EXCEPTION from buildbot.process.results import FAILURE from buildbot.process.results import SUCCESS from buildbot.process.results import WARNINGS from buildbot.steps import master from buildbot.steps import shellsequence from buildbot.test.reactor import TestReactorMixin from buildbot.test.steps import ExpectShell from buildbot.test.steps import TestBuildStepMixin from buildbot.test.util import config as configmixin class DynamicRun(shellsequence.ShellSequence): def run(self): return self.runShellSequence(self.dynamicCommands) class TestOneShellCommand( TestBuildStepMixin, configmixin.ConfigErrorsMixin, TestReactorMixin, unittest.TestCase ): def setUp(self): self.setup_test_reactor(auto_tear_down=False) return self.setup_test_build_step() def tearDown(self): return self.tear_down_test_build_step() def testShellArgInput(self): with self.assertRaisesConfigError("the 'command' parameter of ShellArg must not be None"): shellsequence.ShellArg(command=None) arg1 = shellsequence.ShellArg(command=1) with self.assertRaisesConfigError("1 is an invalid command, it must be a string or a list"): arg1.validateAttributes() arg2 = shellsequence.ShellArg(command=["make", 1]) with self.assertRaisesConfigError("['make', 1] must only have strings in it"): arg2.validateAttributes() for goodcmd in ["make p1", ["make", "p1"]]: arg = shellsequence.ShellArg(command=goodcmd) arg.validateAttributes() def testShellArgsAreRendered(self): arg1 = shellsequence.ShellArg(command=WithProperties('make %s', 'project')) self.setup_step(shellsequence.ShellSequence(commands=[arg1], workdir='build')) self.build.setProperty("project", "BUILDBOT-TEST", "TEST") self.expect_commands(ExpectShell(workdir='build', command='make BUILDBOT-TEST').exit(0)) # TODO: need to factor command-summary stuff into a utility method and # use it here self.expect_outcome(result=SUCCESS, state_string="'make BUILDBOT-TEST'") return self.run_step() def createDynamicRun(self, commands): DynamicRun.dynamicCommands = commands return DynamicRun() def testSanityChecksAreDoneInRuntimeWhenDynamicCmdIsNone(self): self.setup_step(self.createDynamicRun(None)) self.expect_outcome(result=EXCEPTION, state_string="finished (exception)") return self.run_step() def testSanityChecksAreDoneInRuntimeWhenDynamicCmdIsString(self): self.setup_step(self.createDynamicRun(["one command"])) self.expect_outcome(result=EXCEPTION, state_string='finished (exception)') return self.run_step() def testSanityChecksAreDoneInRuntimeWhenDynamicCmdIsInvalidShellArg(self): self.setup_step(self.createDynamicRun([shellsequence.ShellArg(command=1)])) self.expect_outcome(result=EXCEPTION, state_string='finished (exception)') return self.run_step() def testMultipleCommandsAreRun(self): arg1 = shellsequence.ShellArg(command='make p1') arg2 = shellsequence.ShellArg(command='deploy p1') self.setup_step(shellsequence.ShellSequence(commands=[arg1, arg2], workdir='build')) self.expect_commands( ExpectShell(workdir='build', command='make p1').exit(0), ExpectShell(workdir='build', command='deploy p1').exit(0), ) self.expect_outcome(result=SUCCESS, state_string="'deploy p1'") return self.run_step() def testSkipWorks(self): arg1 = shellsequence.ShellArg(command='make p1') arg2 = shellsequence.ShellArg(command='') arg3 = shellsequence.ShellArg(command='deploy p1') self.setup_step(shellsequence.ShellSequence(commands=[arg1, arg2, arg3], workdir='build')) self.expect_commands( ExpectShell(workdir='build', command='make p1').exit(0), ExpectShell(workdir='build', command='deploy p1').exit(0), ) self.expect_outcome(result=SUCCESS, state_string="'deploy p1'") return self.run_step() def testWarningWins(self): arg1 = shellsequence.ShellArg(command='make p1', warnOnFailure=True, flunkOnFailure=False) arg2 = shellsequence.ShellArg(command='deploy p1') self.setup_step(shellsequence.ShellSequence(commands=[arg1, arg2], workdir='build')) self.expect_commands( ExpectShell(workdir='build', command='make p1').exit(1), ExpectShell(workdir='build', command='deploy p1').exit(0), ) self.expect_outcome(result=WARNINGS, state_string="'deploy p1' (warnings)") return self.run_step() def testSequenceStopsOnHaltOnFailure(self): arg1 = shellsequence.ShellArg(command='make p1', haltOnFailure=True) arg2 = shellsequence.ShellArg(command='deploy p1') self.setup_step(shellsequence.ShellSequence(commands=[arg1, arg2], workdir='build')) self.expect_commands(ExpectShell(workdir='build', command='make p1').exit(1)) self.expect_outcome(result=FAILURE, state_string="'make p1' (failure)") return self.run_step() @defer.inlineCallbacks def testShellArgsAreRenderedAnewAtEachInvocation(self): """Unit test to ensure that ShellArg instances are properly re-rendered. This unit test makes sure that ShellArg instances are rendered anew at each invocation """ arg = shellsequence.ShellArg(command=WithProperties('make %s', 'project')) step = shellsequence.ShellSequence(commands=[arg], workdir='build') self.setup_step(step) self.setup_step(master.SetProperty(property="project", value="BUILDBOT-TEST-2")) self.setup_step(step) self.build.setProperty("project", "BUILDBOT-TEST-1", "TEST") self.expect_commands( ExpectShell(workdir='build', command='make BUILDBOT-TEST-1').exit(0), ExpectShell(workdir='build', command='make BUILDBOT-TEST-2').exit(0), ) self.expect_outcome(result=SUCCESS, state_string="'make BUILDBOT-TEST-1'") self.expect_outcome(result=SUCCESS, state_string="Set") self.expect_outcome(result=SUCCESS, state_string="'make BUILDBOT-TEST-2'") yield self.run_step()
7,187
Python
.py
131
47.625954
100
0.718124
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,505
test_shell.py
buildbot_buildbot/master/buildbot/test/unit/steps/test_shell.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 import textwrap from twisted.internet import defer from twisted.trial import unittest from buildbot import config from buildbot.process import properties from buildbot.process import remotetransfer from buildbot.process.results import EXCEPTION from buildbot.process.results import FAILURE from buildbot.process.results import SKIPPED from buildbot.process.results import SUCCESS from buildbot.process.results import WARNINGS from buildbot.steps import shell from buildbot.test.reactor import TestReactorMixin from buildbot.test.steps import ExpectRemoteRef from buildbot.test.steps import ExpectShell from buildbot.test.steps import ExpectUploadFile from buildbot.test.steps import TestBuildStepMixin from buildbot.test.util import config as configmixin class TestShellCommandExecution( TestBuildStepMixin, configmixin.ConfigErrorsMixin, 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() def test_doStepIf_False(self): self.setup_step(shell.ShellCommand(command="echo hello", doStepIf=False)) self.expect_outcome(result=SKIPPED, state_string="'echo hello' (skipped)") return self.run_step() def test_constructor_args_validity(self): # this checks that an exception is raised for invalid arguments with self.assertRaisesConfigError("Invalid argument(s) passed to ShellCommand: "): shell.ShellCommand( workdir='build', command="echo Hello World", wrongArg1=1, wrongArg2='two' ) def test_run_simple(self): self.setup_step(shell.ShellCommand(workdir='build', command="echo hello")) self.expect_commands(ExpectShell(workdir='build', command='echo hello').exit(0)) self.expect_outcome(result=SUCCESS, state_string="'echo hello'") return self.run_step() def test_run_list(self): self.setup_step( shell.ShellCommand(workdir='build', command=['trial', '-b', '-B', 'buildbot.test']) ) self.expect_commands( ExpectShell(workdir='build', command=['trial', '-b', '-B', 'buildbot.test']).exit(0) ) self.expect_outcome(result=SUCCESS, state_string="'trial -b ...'") return self.run_step() def test_run_nested_description(self): self.setup_step( shell.ShellCommand( workdir='build', command=properties.FlattenList(['trial', ['-b', '-B'], 'buildbot.test']), descriptionDone=properties.FlattenList(['test', ['done']]), descriptionSuffix=properties.FlattenList(['suff', ['ix']]), ) ) self.expect_commands( ExpectShell(workdir='build', command=['trial', '-b', '-B', 'buildbot.test']).exit(0) ) self.expect_outcome(result=SUCCESS, state_string='test done suff ix') return self.run_step() def test_run_nested_command(self): self.setup_step( shell.ShellCommand(workdir='build', command=['trial', ['-b', '-B'], 'buildbot.test']) ) self.expect_commands( ExpectShell(workdir='build', command=['trial', '-b', '-B', 'buildbot.test']).exit(0) ) self.expect_outcome(result=SUCCESS, state_string="'trial -b ...'") return self.run_step() def test_run_nested_deeply_command(self): self.setup_step( shell.ShellCommand( workdir='build', command=[['trial', ['-b', ['-B']]], 'buildbot.test'] ) ) self.expect_commands( ExpectShell(workdir='build', command=['trial', '-b', '-B', 'buildbot.test']).exit(0) ) self.expect_outcome(result=SUCCESS, state_string="'trial -b ...'") return self.run_step() def test_run_nested_empty_command(self): self.setup_step( shell.ShellCommand(workdir='build', command=['trial', [], '-b', [], 'buildbot.test']) ) self.expect_commands( ExpectShell(workdir='build', command=['trial', '-b', 'buildbot.test']).exit(0) ) self.expect_outcome(result=SUCCESS, state_string="'trial -b ...'") return self.run_step() def test_run_env(self): self.setup_build(worker_env={"DEF": 'HERE'}) self.setup_step(shell.ShellCommand(workdir='build', command="echo hello")) self.expect_commands( ExpectShell(workdir='build', command='echo hello', env={"DEF": 'HERE'}).exit(0) ) self.expect_outcome(result=SUCCESS) return self.run_step() def test_run_env_override(self): self.setup_build(worker_env={"ABC": 'XXX', "DEF": 'HERE'}) self.setup_step( shell.ShellCommand(workdir='build', env={'ABC': '123'}, command="echo hello"), ) self.expect_commands( ExpectShell( workdir='build', command='echo hello', env={"ABC": '123', "DEF": 'HERE'} ).exit(0) ) self.expect_outcome(result=SUCCESS) return self.run_step() def test_run_usePTY(self): self.setup_step(shell.ShellCommand(workdir='build', command="echo hello", usePTY=False)) self.expect_commands( ExpectShell(workdir='build', command='echo hello', use_pty=False).exit(0) ) self.expect_outcome(result=SUCCESS) return self.run_step() def test_run_usePTY_old_worker(self): self.setup_build(worker_version={"shell": '1.1'}) self.setup_step(shell.ShellCommand(workdir='build', command="echo hello", usePTY=True)) self.expect_commands(ExpectShell(workdir='build', command='echo hello').exit(0)) self.expect_outcome(result=SUCCESS) return self.run_step() def test_run_decodeRC(self, rc=1, results=WARNINGS, extra_text=" (warnings)"): self.setup_step( shell.ShellCommand(workdir='build', command="echo hello", decodeRC={1: WARNINGS}) ) self.expect_commands(ExpectShell(workdir='build', command='echo hello').exit(rc)) self.expect_outcome(result=results, state_string="'echo hello'" + extra_text) return self.run_step() def test_run_decodeRC_defaults(self): return self.test_run_decodeRC(2, FAILURE, extra_text=" (failure)") def test_run_decodeRC_defaults_0_is_failure(self): return self.test_run_decodeRC(0, FAILURE, extra_text=" (failure)") def test_missing_command_error(self): # this checks that an exception is raised for invalid arguments with self.assertRaisesConfigError("ShellCommand's `command' argument is not specified"): shell.ShellCommand() class TreeSize(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() def test_run_success(self): self.setup_step(shell.TreeSize()) self.expect_commands( ExpectShell(workdir='wkdir', command=['du', '-s', '-k', '.']) .stdout('9292 .\n') .exit(0) ) self.expect_outcome(result=SUCCESS, state_string="treesize 9292 KiB") self.expect_property('tree-size-KiB', 9292) return self.run_step() def test_run_misparsed(self): self.setup_step(shell.TreeSize()) self.expect_commands( ExpectShell(workdir='wkdir', command=['du', '-s', '-k', '.']).stdout('abcdef\n').exit(0) ) self.expect_outcome(result=WARNINGS, state_string="treesize unknown (warnings)") return self.run_step() def test_run_failed(self): self.setup_step(shell.TreeSize()) self.expect_commands( ExpectShell(workdir='wkdir', command=['du', '-s', '-k', '.']).stderr('abcdef\n').exit(1) ) self.expect_outcome(result=FAILURE, state_string="treesize unknown (failure)") return self.run_step() class SetPropertyFromCommand(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() def test_constructor_conflict(self): with self.assertRaises(config.ConfigErrors): shell.SetPropertyFromCommand(property='foo', extract_fn=lambda: None) def test_run_property(self): self.setup_step(shell.SetPropertyFromCommand(property="res", command="cmd")) self.expect_commands( ExpectShell(workdir='wkdir', command="cmd").stdout('\n\nabcdef\n').exit(0) ) self.expect_outcome(result=SUCCESS, state_string="property 'res' set") self.expect_property("res", "abcdef") # note: stripped self.expect_log_file('property changes', r"res: " + repr('abcdef')) return self.run_step() def test_renderable_workdir(self): self.setup_step( shell.SetPropertyFromCommand( property="res", command="cmd", workdir=properties.Interpolate('wkdir') ) ) self.expect_commands( ExpectShell(workdir='wkdir', command="cmd").stdout('\n\nabcdef\n').exit(0) ) self.expect_outcome(result=SUCCESS, state_string="property 'res' set") self.expect_property("res", "abcdef") # note: stripped self.expect_log_file('property changes', r"res: " + repr('abcdef')) return self.run_step() def test_run_property_no_strip(self): self.setup_step(shell.SetPropertyFromCommand(property="res", command="cmd", strip=False)) self.expect_commands( ExpectShell(workdir='wkdir', command="cmd").stdout('\n\nabcdef\n').exit(0) ) self.expect_outcome(result=SUCCESS, state_string="property 'res' set") self.expect_property("res", "\n\nabcdef\n") self.expect_log_file('property changes', r"res: " + repr('\n\nabcdef\n')) return self.run_step() def test_run_failure(self): self.setup_step(shell.SetPropertyFromCommand(property="res", command="blarg")) self.expect_commands( ExpectShell(workdir='wkdir', command="blarg") .stderr('cannot blarg: File not found') .exit(1) ) self.expect_outcome(result=FAILURE, state_string="'blarg' (failure)") self.expect_no_property("res") return self.run_step() def test_run_extract_fn(self): def extract_fn(rc, stdout, stderr): self.assertEqual((rc, stdout, stderr), (0, 'startend\n', 'STARTEND\n')) return {"a": 1, "b": 2} self.setup_step(shell.SetPropertyFromCommand(extract_fn=extract_fn, command="cmd")) self.expect_commands( ExpectShell(workdir='wkdir', command="cmd") .stdout('start') .stderr('START') .stdout('end') .stderr('END') .exit(0) ) self.expect_outcome(result=SUCCESS, state_string="2 properties set") self.expect_log_file('property changes', 'a: 1\nb: 2') self.expect_property("a", 1) self.expect_property("b", 2) return self.run_step() def test_run_extract_fn_cmdfail(self): def extract_fn(rc, stdout, stderr): self.assertEqual((rc, stdout, stderr), (3, '', '')) return {"a": 1, "b": 2} self.setup_step(shell.SetPropertyFromCommand(extract_fn=extract_fn, command="cmd")) self.expect_commands(ExpectShell(workdir='wkdir', command="cmd").exit(3)) # note that extract_fn *is* called anyway self.expect_outcome(result=FAILURE, state_string="2 properties set (failure)") self.expect_log_file('property changes', 'a: 1\nb: 2') return self.run_step() def test_run_extract_fn_cmdfail_empty(self): def extract_fn(rc, stdout, stderr): self.assertEqual((rc, stdout, stderr), (3, '', '')) return {} self.setup_step(shell.SetPropertyFromCommand(extract_fn=extract_fn, command="cmd")) self.expect_commands(ExpectShell(workdir='wkdir', command="cmd").exit(3)) # note that extract_fn *is* called anyway, but returns no properties self.expect_outcome(result=FAILURE, state_string="'cmd' (failure)") return self.run_step() @defer.inlineCallbacks def test_run_extract_fn_exception(self): def extract_fn(rc, stdout, stderr): raise RuntimeError("oh noes") self.setup_step(shell.SetPropertyFromCommand(extract_fn=extract_fn, command="cmd")) self.expect_commands(ExpectShell(workdir='wkdir', command="cmd").exit(0)) # note that extract_fn *is* called anyway, but returns no properties self.expect_outcome(result=EXCEPTION, state_string="'cmd' (exception)") yield self.run_step() self.assertEqual(len(self.flushLoggedErrors(RuntimeError)), 1) def test_error_both_set(self): """ If both ``extract_fn`` and ``property`` are defined, ``SetPropertyFromCommand`` reports a config error. """ with self.assertRaises(config.ConfigErrors): shell.SetPropertyFromCommand( command=["echo", "value"], property="propname", extract_fn=lambda x: {"propname": "hello"}, ) def test_error_none_set(self): """ If neither ``extract_fn`` and ``property`` are defined, ``SetPropertyFromCommand`` reports a config error. """ with self.assertRaises(config.ConfigErrors): shell.SetPropertyFromCommand(command=["echo", "value"]) class PerlModuleTest(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() def test_new_version_success(self): self.setup_step(shell.PerlModuleTest(command="cmd")) self.expect_commands( ExpectShell(workdir='wkdir', command="cmd") .stdout( textwrap.dedent("""\ This junk ignored Test Summary Report Result: PASS Tests: 10 Failed: 0 Tests: 10 Failed: 0 Files=93, Tests=20""") ) .exit(0) ) self.expect_outcome(result=SUCCESS, state_string='20 tests 20 passed') return self.run_step() def test_new_version_warnings(self): self.setup_step(shell.PerlModuleTest(command="cmd", warningPattern='^OHNOES')) self.expect_commands( ExpectShell(workdir='wkdir', command="cmd") .stdout( textwrap.dedent("""\ This junk ignored Test Summary Report ------------------- foo.pl (Wstat: 0 Tests: 10 Failed: 0) Failed test: 0 OHNOES 1 OHNOES 2 Files=93, Tests=20, 0 wallclock secs ... Result: PASS""") ) .exit(0) ) self.expect_outcome( result=WARNINGS, state_string='20 tests 20 passed 2 warnings (warnings)' ) return self.run_step() def test_new_version_failed(self): self.setup_step(shell.PerlModuleTest(command="cmd")) self.expect_commands( ExpectShell(workdir='wkdir', command="cmd") .stdout( textwrap.dedent("""\ foo.pl .. 1/4""") ) .stderr( textwrap.dedent("""\ # Failed test 2 in foo.pl at line 6 # foo.pl line 6 is: ok(0);""") ) .stdout( textwrap.dedent("""\ foo.pl .. Failed 1/4 subtests Test Summary Report ------------------- foo.pl (Wstat: 0 Tests: 4 Failed: 1) Failed test: 0 Files=1, Tests=4, 0 wallclock secs ( 0.06 usr 0.01 sys + 0.03 cusr 0.01 csys = 0.11 CPU) Result: FAIL""") ) .stderr( textwrap.dedent("""\ Failed 1/1 test programs. 1/4 subtests failed.""") ) .exit(1) ) self.expect_outcome(result=FAILURE, state_string='4 tests 3 passed 1 failed (failure)') return self.run_step() def test_old_version_success(self): self.setup_step(shell.PerlModuleTest(command="cmd")) self.expect_commands( ExpectShell(workdir='wkdir', command="cmd") .stdout( textwrap.dedent("""\ This junk ignored All tests successful Files=10, Tests=20, 100 wall blah blah""") ) .exit(0) ) self.expect_outcome(result=SUCCESS, state_string='20 tests 20 passed') return self.run_step() def test_old_version_failed(self): self.setup_step(shell.PerlModuleTest(command="cmd")) self.expect_commands( ExpectShell(workdir='wkdir', command="cmd") .stdout( textwrap.dedent("""\ This junk ignored Failed 1/1 test programs, 3/20 subtests failed.""") ) .exit(1) ) self.expect_outcome(result=FAILURE, state_string='20 tests 17 passed 3 failed (failure)') return self.run_step() class Configure(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() def test_class_attrs(self): step = shell.Configure() self.assertEqual(step.command, ['./configure']) def test_run(self): self.setup_step(shell.Configure()) self.expect_commands(ExpectShell(workdir='wkdir', command=["./configure"]).exit(0)) self.expect_outcome(result=SUCCESS) return self.run_step() class WarningCountingShellCommand( TestBuildStepMixin, configmixin.ConfigErrorsMixin, 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() def test_no_warnings(self): self.setup_step(shell.WarningCountingShellCommand(workdir='w', command=['make'])) self.expect_commands( ExpectShell(workdir='w', command=["make"]).stdout('blarg success!').exit(0) ) self.expect_outcome(result=SUCCESS) self.expect_property("warnings-count", 0) return self.run_step() def test_default_pattern(self): self.setup_step(shell.WarningCountingShellCommand(command=['make'])) self.expect_commands( ExpectShell(workdir='wkdir', command=["make"]) .stdout('normal: foo\nwarning: blarg!\nalso normal\nWARNING: blarg!\n') .exit(0) ) self.expect_outcome(result=WARNINGS) self.expect_property("warnings-count", 2) self.expect_log_file("warnings (2)", "warning: blarg!\nWARNING: blarg!\n") return self.run_step() def test_custom_pattern(self): self.setup_step( shell.WarningCountingShellCommand(command=['make'], warningPattern=r"scary:.*") ) self.expect_commands( ExpectShell(workdir='wkdir', command=["make"]) .stdout('scary: foo\nwarning: bar\nscary: bar') .exit(0) ) self.expect_outcome(result=WARNINGS) self.expect_property("warnings-count", 2) self.expect_log_file("warnings (2)", "scary: foo\nscary: bar\n") return self.run_step() def test_maxWarnCount(self): self.setup_step(shell.WarningCountingShellCommand(command=['make'], maxWarnCount=9)) self.expect_commands( ExpectShell(workdir='wkdir', command=["make"]).stdout('warning: noo!\n' * 10).exit(0) ) self.expect_outcome(result=FAILURE) self.expect_property("warnings-count", 10) return self.run_step() def test_fail_with_warnings(self): self.setup_step(shell.WarningCountingShellCommand(command=['make'])) self.expect_commands( ExpectShell(workdir='wkdir', command=["make"]).stdout('warning: I might fail').exit(3) ) self.expect_outcome(result=FAILURE) self.expect_property("warnings-count", 1) self.expect_log_file("warnings (1)", "warning: I might fail\n") return self.run_step() def test_warn_with_decoderc(self): self.setup_step(shell.WarningCountingShellCommand(command=['make'], decodeRC={3: WARNINGS})) self.expect_commands( ExpectShell( workdir='wkdir', command=["make"], ) .stdout('I might fail with rc') .exit(3) ) self.expect_outcome(result=WARNINGS) self.expect_property("warnings-count", 0) return self.run_step() def do_test_suppressions( self, step, supps_file='', stdout='', exp_warning_count=0, exp_warning_log='', exp_exception=False, props=None, ): self.setup_step(step) if props is not None: for key in props: self.build.setProperty(key, props[key], "") if supps_file is not None: self.expect_commands( # step will first get the remote suppressions file ExpectUploadFile( blocksize=32768, maxsize=None, workersrc='supps', workdir='wkdir', writer=ExpectRemoteRef(remotetransfer.StringFileWriter), ) .upload_string(supps_file) .exit(0), # and then run the command ExpectShell(workdir='wkdir', command=["make"]).stdout(stdout).exit(0), ) else: self.expect_commands( ExpectShell(workdir='wkdir', command=["make"]).stdout(stdout).exit(0) ) if exp_exception: self.expect_outcome(result=EXCEPTION, state_string="'make' (exception)") else: if exp_warning_count != 0: self.expect_outcome(result=WARNINGS, state_string="'make' (warnings)") self.expect_log_file(f"warnings ({exp_warning_count})", exp_warning_log) else: self.expect_outcome(result=SUCCESS, state_string="'make'") self.expect_property("warnings-count", exp_warning_count) return self.run_step() def test_suppressions(self): step = shell.WarningCountingShellCommand(command=['make'], suppressionFile='supps') supps_file = textwrap.dedent("""\ # example suppressions file amar.c : .*unused variable.* holding.c : .*invalid access to non-static.* """).strip() stdout = textwrap.dedent("""\ /bin/sh ../libtool --tag=CC --silent --mode=link gcc blah /bin/sh ../libtool --tag=CC --silent --mode=link gcc blah amar.c: In function 'write_record': amar.c:164: warning: unused variable 'x' amar.c:164: warning: this should show up /bin/sh ../libtool --tag=CC --silent --mode=link gcc blah /bin/sh ../libtool --tag=CC --silent --mode=link gcc blah holding.c: In function 'holding_thing': holding.c:984: warning: invalid access to non-static 'y' """) exp_warning_log = textwrap.dedent("""\ amar.c:164: warning: this should show up """) return self.do_test_suppressions(step, supps_file, stdout, 1, exp_warning_log) def test_suppressions_directories(self): def warningExtractor(step, line, match): return line.split(':', 2) step = shell.WarningCountingShellCommand( command=['make'], suppressionFile='supps', warningExtractor=warningExtractor ) supps_file = textwrap.dedent("""\ # these should be suppressed: amar-src/amar.c : XXX .*/server-src/.* : AAA # these should not, as the dirs do not match: amar.c : YYY server-src.* : BBB """).strip() # note that this uses the unicode smart-quotes that gcc loves so much stdout = textwrap.dedent("""\ make: Entering directory \u2019amar-src\u2019 amar.c:164: warning: XXX amar.c:165: warning: YYY make: Leaving directory 'amar-src' make: Entering directory "subdir" make: Entering directory 'server-src' make: Entering directory `one-more-dir` holding.c:999: warning: BBB holding.c:1000: warning: AAA """) exp_warning_log = textwrap.dedent("""\ amar.c:165: warning: YYY holding.c:999: warning: BBB """) return self.do_test_suppressions(step, supps_file, stdout, 2, exp_warning_log) def test_suppressions_directories_custom(self): def warningExtractor(step, line, match): return line.split(':', 2) step = shell.WarningCountingShellCommand( command=['make'], suppressionFile='supps', warningExtractor=warningExtractor, directoryEnterPattern="^IN: (.*)", directoryLeavePattern="^OUT:", ) supps_file = "dir1/dir2/abc.c : .*" stdout = textwrap.dedent("""\ IN: dir1 IN: decoy OUT: decoy IN: dir2 abc.c:123: warning: hello """) return self.do_test_suppressions(step, supps_file, stdout, 0, '') def test_suppressions_linenos(self): def warningExtractor(step, line, match): return line.split(':', 2) step = shell.WarningCountingShellCommand( command=['make'], suppressionFile='supps', warningExtractor=warningExtractor ) supps_file = "abc.c:.*:100-199\ndef.c:.*:22" stdout = textwrap.dedent("""\ abc.c:99: warning: seen 1 abc.c:150: warning: unseen def.c:22: warning: unseen abc.c:200: warning: seen 2 """) exp_warning_log = textwrap.dedent("""\ abc.c:99: warning: seen 1 abc.c:200: warning: seen 2 """) return self.do_test_suppressions(step, supps_file, stdout, 2, exp_warning_log) @defer.inlineCallbacks def test_suppressions_warningExtractor_exc(self): def warningExtractor(step, line, match): raise RuntimeError("oh noes") step = shell.WarningCountingShellCommand( command=['make'], suppressionFile='supps', warningExtractor=warningExtractor ) # need at least one supp to trigger warningExtractor supps_file = 'x:y' stdout = "abc.c:99: warning: seen 1" yield self.do_test_suppressions(step, supps_file, stdout, exp_exception=True) self.assertEqual(len(self.flushLoggedErrors(RuntimeError)), 1) def test_suppressions_addSuppression(self): # call addSuppression "manually" from a subclass class MyWCSC(shell.WarningCountingShellCommand): def run(self): self.addSuppression([('.*', '.*unseen.*', None, None)]) return super().run() def warningExtractor(step, line, match): return line.split(':', 2) step = MyWCSC(command=['make'], suppressionFile='supps', warningExtractor=warningExtractor) stdout = textwrap.dedent("""\ abc.c:99: warning: seen 1 abc.c:150: warning: unseen abc.c:200: warning: seen 2 """) exp_warning_log = textwrap.dedent("""\ abc.c:99: warning: seen 1 abc.c:200: warning: seen 2 """) return self.do_test_suppressions(step, '', stdout, 2, exp_warning_log) def test_suppressions_suppressionsParameter(self): def warningExtractor(step, line, match): return line.split(':', 2) supps = ( ("abc.c", ".*", 100, 199), ("def.c", ".*", 22, 22), ) step = shell.WarningCountingShellCommand( command=['make'], suppressionList=supps, warningExtractor=warningExtractor ) stdout = textwrap.dedent("""\ abc.c:99: warning: seen 1 abc.c:150: warning: unseen def.c:22: warning: unseen abc.c:200: warning: seen 2 """) exp_warning_log = textwrap.dedent("""\ abc.c:99: warning: seen 1 abc.c:200: warning: seen 2 """) return self.do_test_suppressions(step, None, stdout, 2, exp_warning_log) def test_suppressions_suppressionsRenderableParameter(self): def warningExtractor(step, line, match): return line.split(':', 2) supps = ( ("abc.c", ".*", 100, 199), ("def.c", ".*", 22, 22), ) step = shell.WarningCountingShellCommand( command=['make'], suppressionList=properties.Property("suppressionsList"), warningExtractor=warningExtractor, ) stdout = textwrap.dedent("""\ abc.c:99: warning: seen 1 abc.c:150: warning: unseen def.c:22: warning: unseen abc.c:200: warning: seen 2 """) exp_warning_log = textwrap.dedent("""\ abc.c:99: warning: seen 1 abc.c:200: warning: seen 2 """) return self.do_test_suppressions( step, None, stdout, 2, exp_warning_log, props={"suppressionsList": supps} ) def test_warnExtractFromRegexpGroups(self): step = shell.WarningCountingShellCommand(command=['make']) we = shell.WarningCountingShellCommand.warnExtractFromRegexpGroups line, pat, exp_file, exp_lineNo, exp_text = ( 'foo:123:text', '(.*):(.*):(.*)', 'foo', 123, 'text', ) self.assertEqual(we(step, line, re.match(pat, line)), (exp_file, exp_lineNo, exp_text)) def test_missing_command_error(self): # this checks that an exception is raised for invalid arguments with self.assertRaisesConfigError( "WarningCountingShellCommand's 'command' argument is not specified" ): shell.WarningCountingShellCommand() class Compile(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() def test_class_args(self): # since this step is just a pre-configured WarningCountingShellCommand, # there' not much to test! step = self.setup_step(shell.Compile()) self.assertEqual(step.name, "compile") self.assertTrue(step.haltOnFailure) self.assertTrue(step.flunkOnFailure) self.assertEqual(step.description, ["compiling"]) self.assertEqual(step.descriptionDone, ["compile"]) self.assertEqual(step.command, ["make", "all"]) class Test(TestBuildStepMixin, configmixin.ConfigErrorsMixin, TestReactorMixin, unittest.TestCase): def setUp(self): self.setup_test_reactor(auto_tear_down=False) 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_setTestResults(self): step = self.setup_step(shell.Test()) step.setTestResults(total=10, failed=3, passed=5, warnings=3) self.assertEqual( step.statistics, { 'tests-total': 10, 'tests-failed': 3, 'tests-passed': 5, 'tests-warnings': 3, }, ) # ensure that they're additive step.setTestResults(total=1, failed=2, passed=3, warnings=4) self.assertEqual( step.statistics, { 'tests-total': 11, 'tests-failed': 5, 'tests-passed': 8, 'tests-warnings': 7, }, ) def test_describe_not_done(self): step = self.setup_step(shell.Test()) step.results = SUCCESS step.rendered = True self.assertEqual(step.getResultSummary(), {'step': 'test'}) def test_describe_done(self): step = self.setup_step(shell.Test()) step.rendered = True step.results = SUCCESS step.statistics['tests-total'] = 93 step.statistics['tests-failed'] = 10 step.statistics['tests-passed'] = 20 step.statistics['tests-warnings'] = 30 self.assertEqual( step.getResultSummary(), {'step': '93 tests 20 passed 30 warnings 10 failed'} ) def test_describe_done_no_total(self): step = self.setup_step(shell.Test()) step.rendered = True step.results = SUCCESS step.statistics['tests-total'] = 0 step.statistics['tests-failed'] = 10 step.statistics['tests-passed'] = 20 step.statistics['tests-warnings'] = 30 # describe calculates 60 = 10+20+30 self.assertEqual( step.getResultSummary(), {'step': '60 tests 20 passed 30 warnings 10 failed'} )
35,505
Python
.py
805
33.802484
100
0.602804
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,506
test_source_repo.py
buildbot_buildbot/master/buildbot/test/unit/steps/test_source_repo.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.changes.changes import Change from buildbot.process.properties import Properties from buildbot.process.results import FAILURE from buildbot.process.results import SUCCESS from buildbot.steps.source import repo from buildbot.test.reactor import TestReactorMixin from buildbot.test.steps import ExpectMkdir from buildbot.test.steps import ExpectRmdir from buildbot.test.steps import ExpectShell from buildbot.test.steps import ExpectStat from buildbot.test.util import sourcesteps class RepoURL(unittest.TestCase): # testcases taken from old_source/Repo test def oneTest(self, props, expected): p = Properties() p.update(props, "test") r = repo.RepoDownloadsFromProperties(list(props)) self.assertEqual(sorted(r.getRenderingFor(p)), sorted(expected)) def test_parse1(self): self.oneTest({'a': "repo download test/bla 564/12"}, ["test/bla 564/12"]) def test_parse2(self): self.oneTest( {'a': "repo download test/bla 564/12 repo download test/bla 564/2"}, ["test/bla 564/12", "test/bla 564/2"], ) self.oneTest( {'a': "repo download test/bla 564/12", 'b': "repo download test/bla 564/2"}, ["test/bla 564/12", "test/bla 564/2"], ) def test_parse3(self): self.oneTest( {'a': "repo download test/bla 564/12 repo download test/bla 564/2 test/foo 5/1"}, ["test/bla 564/12", "test/bla 564/2", "test/foo 5/1"], ) self.oneTest({'a': "repo download test/bla 564/12"}, ["test/bla 564/12"]) class TestRepo(sourcesteps.SourceStepMixin, TestReactorMixin, unittest.TestCase): def setUp(self): self.setup_test_reactor(auto_tear_down=False) self.shouldRetry = False self.logEnviron = True return self.setUpSourceStep() @defer.inlineCallbacks def tearDown(self): yield self.tearDownSourceStep() yield self.tear_down_test_reactor() def shouldLogEnviron(self): r = self.logEnviron self.logEnviron = False return r def ExpectShell(self, **kw): if 'workdir' not in kw: kw['workdir'] = 'wkdir' if 'log_environ' not in kw: kw['log_environ'] = self.shouldLogEnviron() return ExpectShell(**kw) def mySetupStep(self, **kwargs): if "repoDownloads" not in kwargs: kwargs.update({ "repoDownloads": repo.RepoDownloadsFromProperties([ "repo_download", "repo_download2", ]) }) self.setup_step( repo.Repo( manifestURL='git://myrepo.com/manifest.git', manifestBranch="mb", manifestFile="mf", **kwargs, ) ) self.build.allChanges = lambda x=None: [] def myRunStep(self, result=SUCCESS, state_string=None): self.expect_outcome(result=result, state_string=state_string) return self.run_step() def expectClobber(self): # stat return 1 so we clobber self.expect_commands( ExpectStat(file='wkdir/.repo', log_environ=self.logEnviron).exit(1), ExpectRmdir(dir='wkdir', log_environ=self.logEnviron).exit(0), ExpectMkdir(dir='wkdir', log_environ=self.logEnviron).exit(0), ) def expectnoClobber(self): # stat return 0, so nothing self.expect_commands(ExpectStat(file='wkdir/.repo', log_environ=self.logEnviron).exit(0)) def expectRepoSync( self, which_fail=-1, breakatfail=False, depth=0, initoptions=None, syncoptions=None, override_commands=None, ): if initoptions is None: initoptions = [] if syncoptions is None: syncoptions = ["-c"] if override_commands is None: override_commands = [] commands = [ self.ExpectShell(command=["bash", "-c", self.get_nth_step(0)._getCleanupCommand()]), self.ExpectShell( command=[ "repo", "init", "-u", "git://myrepo.com/manifest.git", "-b", "mb", "-m", "mf", "--depth", str(depth), *initoptions, ] ), *override_commands, self.ExpectShell(command=["repo", "sync", "--force-sync", *syncoptions]), self.ExpectShell(command=["repo", "manifest", "-r", "-o", "manifest-original.xml"]), ] for i, command in enumerate(commands): self.expect_commands(command.exit(which_fail == i and 1 or 0)) if which_fail == i and breakatfail: break def test_basic(self): """basic first time repo sync""" self.mySetupStep(repoDownloads=None) self.expectClobber() self.expectRepoSync() return self.myRunStep() def test_basic_depth(self): """basic first time repo sync""" self.mySetupStep(repoDownloads=None, depth=2) self.expectClobber() self.expectRepoSync(depth=2) return self.myRunStep() def test_basic_submodule(self): """basic first time repo sync with submodule""" self.mySetupStep(repoDownloads=None, submodules=True) self.expectClobber() self.expectRepoSync(initoptions=["--submodules"]) return self.myRunStep() def test_update(self): """basic second time repo sync""" self.mySetupStep() self.expectnoClobber() self.expectRepoSync() return self.myRunStep() def test_jobs(self): """basic first time repo sync with jobs""" self.mySetupStep(jobs=2) self.expectClobber() self.expectRepoSync(syncoptions=["-j2", "-c"]) return self.myRunStep() def test_sync_all_branches(self): """basic first time repo sync with all branches""" self.mySetupStep(syncAllBranches=True) self.expectClobber() self.expectRepoSync(syncoptions=[]) return self.myRunStep() def test_manifest_override(self): """repo sync with manifest_override_url property set download via wget """ self.mySetupStep(manifestOverrideUrl="http://u.rl/test.manifest", syncAllBranches=True) self.expectClobber() override_commands = [ ExpectStat(file='wkdir/http://u.rl/test.manifest', log_environ=False), self.ExpectShell( log_environ=False, command=['wget', 'http://u.rl/test.manifest', '-O', 'manifest_override.xml'], ), self.ExpectShell( log_environ=False, workdir='wkdir/.repo', command=['ln', '-sf', '../manifest_override.xml', 'manifest.xml'], ), ] self.expectRepoSync(which_fail=2, syncoptions=[], override_commands=override_commands) return self.myRunStep() def test_manifest_override_local(self): """repo sync with manifest_override_url property set copied from local FS """ self.mySetupStep(manifestOverrideUrl="test.manifest", syncAllBranches=True) self.expectClobber() override_commands = [ ExpectStat(file='wkdir/test.manifest', log_environ=False), self.ExpectShell( log_environ=False, command=['cp', '-f', 'test.manifest', 'manifest_override.xml'] ), self.ExpectShell( log_environ=False, workdir='wkdir/.repo', command=['ln', '-sf', '../manifest_override.xml', 'manifest.xml'], ), ] self.expectRepoSync(syncoptions=[], override_commands=override_commands) return self.myRunStep() def test_tarball(self): """repo sync using the tarball cache""" self.mySetupStep(tarball="/tarball.tar") self.expectClobber() self.expect_commands(self.ExpectShell(command=['tar', '-xvf', '/tarball.tar']).exit(0)) self.expectRepoSync() self.expect_commands( self.ExpectShell(command=['stat', '-c%Y', '/tarball.tar']).stdout(str(10000)).exit(0) ) self.expect_commands( self.ExpectShell(command=['stat', '-c%Y', '.']) .stdout(str(10000 + 7 * 24 * 3600)) .exit(0) ) return self.myRunStep() def test_create_tarball(self): """repo sync create the tarball if its not here""" self.mySetupStep(tarball="/tarball.tgz") self.expectClobber() self.expect_commands( self.ExpectShell(command=['tar', '-z', '-xvf', '/tarball.tgz']).exit(1), self.ExpectShell(command=['rm', '-f', '/tarball.tgz']).exit(1), ExpectRmdir(dir='wkdir/.repo', log_environ=False).exit(1), ) self.expectRepoSync() self.expect_commands( self.ExpectShell(command=['stat', '-c%Y', '/tarball.tgz']) .stderr("file not found!") .exit(1), self.ExpectShell(command=['tar', '-z', '-cvf', '/tarball.tgz', '.repo']).exit(0), ) return self.myRunStep() def do_test_update_tarball(self, suffix, option): """repo sync update the tarball cache at the end (tarball older than a week)""" self.mySetupStep(tarball="/tarball." + suffix) self.expectClobber() self.expect_commands( self.ExpectShell(command=["tar", *option, "-xvf", "/tarball." + suffix]).exit(0) ) self.expectRepoSync() self.expect_commands( self.ExpectShell(command=['stat', '-c%Y', '/tarball.' + suffix]) .stdout(str(10000)) .exit(0), self.ExpectShell(command=['stat', '-c%Y', '.']) .stdout(str(10001 + 7 * 24 * 3600)) .exit(0), self.ExpectShell(command=["tar", *option, "-cvf", "/tarball." + suffix, ".repo"]).exit( 0 ), ) return self.myRunStep() def test_update_tarball(self): self.do_test_update_tarball("tar", []) def test_update_tarball_gz(self): """tarball compression variants""" self.do_test_update_tarball("tar.gz", ["-z"]) def test_update_tarball_tgz(self): self.do_test_update_tarball("tgz", ["-z"]) def test_update_tarball_pigz(self): self.do_test_update_tarball("pigz", ["-I", "pigz"]) def test_update_tarball_bzip(self): self.do_test_update_tarball("tar.bz2", ["-j"]) def test_update_tarball_lzma(self): self.do_test_update_tarball("tar.lzma", ["--lzma"]) def test_update_tarball_lzop(self): self.do_test_update_tarball("tar.lzop", ["--lzop"]) def test_update_tarball_fail1(self, suffix="tar", option=None): """tarball extract fail -> remove the tarball + remove .repo dir""" if option is None: option = [] self.mySetupStep(tarball="/tarball." + suffix) self.expectClobber() self.expect_commands( self.ExpectShell(command=["tar", *option, "-xvf", "/tarball." + suffix]).exit(1), self.ExpectShell(command=['rm', '-f', '/tarball.tar']).exit(0), ExpectRmdir(dir='wkdir/.repo', log_environ=False).exit(0), ) self.expectRepoSync() self.expect_commands( self.ExpectShell(command=['stat', '-c%Y', '/tarball.' + suffix]) .stdout(str(10000)) .exit(0), self.ExpectShell(command=['stat', '-c%Y', '.']) .stdout(str(10001 + 7 * 24 * 3600)) .exit(0), self.ExpectShell(command=["tar", *option, "-cvf", "/tarball." + suffix, ".repo"]).exit( 0 ), ) return self.myRunStep() def test_update_tarball_fail2(self, suffix="tar", option=None): """tarball update fail -> remove the tarball + continue repo download""" if option is None: option = [] self.mySetupStep(tarball="/tarball." + suffix) self.build.setProperty("repo_download", "repo download test/bla 564/12", "test") self.expectClobber() self.expect_commands( self.ExpectShell(command=["tar", *option, "-xvf", "/tarball." + suffix]).exit(0) ) self.expectRepoSync() self.expect_commands( self.ExpectShell(command=['stat', '-c%Y', '/tarball.' + suffix]) .stdout(str(10000)) .exit(0), self.ExpectShell(command=['stat', '-c%Y', '.']) .stdout(str(10001 + 7 * 24 * 3600)) .exit(0), self.ExpectShell(command=["tar", *option, "-cvf", "/tarball." + suffix, ".repo"]).exit( 1 ), self.ExpectShell(command=['rm', '-f', '/tarball.tar']).exit(0), self.ExpectShell(command=['repo', 'download', 'test/bla', '564/12']).exit(0), ) return self.myRunStep() def test_repo_downloads(self): """basic repo download, and check that repo_downloaded is updated""" self.mySetupStep() self.build.setProperty("repo_download", "repo download test/bla 564/12", "test") self.expectnoClobber() self.expectRepoSync() self.expect_commands( self.ExpectShell(command=['repo', 'download', 'test/bla', '564/12']) .exit(0) .stderr("test/bla refs/changes/64/564/12 -> FETCH_HEAD\n") .stderr("HEAD is now at 0123456789abcdef...\n") ) self.expect_property("repo_downloaded", "564/12 0123456789abcdef ", "Source") return self.myRunStep() def test_repo_downloads2(self): """2 repo downloads""" self.mySetupStep() self.build.setProperty("repo_download", "repo download test/bla 564/12", "test") self.build.setProperty("repo_download2", "repo download test/bla2 565/12", "test") self.expectnoClobber() self.expectRepoSync() self.expect_commands( self.ExpectShell(command=['repo', 'download', 'test/bla', '564/12']).exit(0), self.ExpectShell(command=['repo', 'download', 'test/bla2', '565/12']).exit(0), ) return self.myRunStep() def test_repo_download_manifest(self): """2 repo downloads, with one manifest patch""" self.mySetupStep() self.build.setProperty("repo_download", "repo download test/bla 564/12", "test") self.build.setProperty("repo_download2", "repo download manifest 565/12", "test") self.expectnoClobber() self.expect_commands( self.ExpectShell( command=['bash', '-c', self.get_nth_step(0)._getCleanupCommand()] ).exit(0), self.ExpectShell( command=[ 'repo', 'init', '-u', 'git://myrepo.com/manifest.git', '-b', 'mb', '-m', 'mf', '--depth', '0', ] ).exit(0), self.ExpectShell( workdir='wkdir/.repo/manifests', command=['git', 'fetch', 'git://myrepo.com/manifest.git', 'refs/changes/65/565/12'], ).exit(0), self.ExpectShell( workdir='wkdir/.repo/manifests', command=['git', 'cherry-pick', 'FETCH_HEAD'] ).exit(0), self.ExpectShell(command=['repo', 'sync', '--force-sync', '-c']).exit(0), self.ExpectShell( command=['repo', 'manifest', '-r', '-o', 'manifest-original.xml'] ).exit(0), ) self.expect_commands( self.ExpectShell(command=['repo', 'download', 'test/bla', '564/12']).exit(0) ) return self.myRunStep() def test_repo_downloads_mirror_sync(self): """repo downloads, with mirror synchronization issues""" self.mySetupStep() # we don't really want the test to wait... self.get_nth_step(0).mirror_sync_sleep = 0.001 self.build.setProperty("repo_download", "repo download test/bla 564/12", "test") self.expectnoClobber() self.expectRepoSync() self.expect_commands( self.ExpectShell(command=['repo', 'download', 'test/bla', '564/12']) .exit(1) .stderr("fatal: Couldn't find remote ref \n"), self.ExpectShell(command=['repo', 'download', 'test/bla', '564/12']) .exit(1) .stderr("fatal: Couldn't find remote ref \n"), self.ExpectShell(command=['repo', 'download', 'test/bla', '564/12']).exit(0), ) return self.myRunStep() def test_repo_downloads_change_missing(self): """repo downloads, with no actual mirror synchronization issues (still retries 2 times)""" self.mySetupStep() # we don't really want the test to wait... self.get_nth_step(0).mirror_sync_sleep = 0.001 self.get_nth_step(0).mirror_sync_retry = 1 # on retry once self.build.setProperty("repo_download", "repo download test/bla 564/12", "test") self.expectnoClobber() self.expectRepoSync() self.expect_commands( self.ExpectShell(command=['repo', 'download', 'test/bla', '564/12']) .exit(1) .stderr("fatal: Couldn't find remote ref \n"), self.ExpectShell(command=['repo', 'download', 'test/bla', '564/12']) .exit(1) .stderr("fatal: Couldn't find remote ref \n"), ) return self.myRunStep( result=FAILURE, state_string="repo: change test/bla 564/12 does not exist (failure)" ) def test_repo_downloads_fail1(self): """repo downloads, cherry-pick returns 1""" self.mySetupStep() self.build.setProperty("repo_download", "repo download test/bla 564/12", "test") self.expectnoClobber() self.expectRepoSync() self.expect_commands( self.ExpectShell(command=['repo', 'download', 'test/bla', '564/12']) .exit(1) .stderr("patch \n"), self.ExpectShell(command=['repo', 'forall', '-c', 'git', 'diff', 'HEAD']).exit(0), ) return self.myRunStep( result=FAILURE, state_string="download failed: test/bla 564/12 (failure)" ) def test_repo_downloads_fail2(self): """repo downloads, cherry-pick returns 0 but error in stderr""" self.mySetupStep() self.build.setProperty("repo_download", "repo download test/bla 564/12", "test") self.expectnoClobber() self.expectRepoSync() self.expect_commands( self.ExpectShell(command=['repo', 'download', 'test/bla', '564/12']) .exit(0) .stderr("Automatic cherry-pick failed \n"), self.ExpectShell(command=['repo', 'forall', '-c', 'git', 'diff', 'HEAD']).exit(0), ) return self.myRunStep( result=FAILURE, state_string="download failed: test/bla 564/12 (failure)" ) def test_repo_downloads_from_change_source(self): """basic repo download from change source, and check that repo_downloaded is updated""" self.mySetupStep(repoDownloads=repo.RepoDownloadsFromChangeSource()) change = Change( None, None, None, properties={ 'event.change.owner.email': '[email protected]', 'event.change.subject': 'fix 1234', 'event.change.project': 'pr', 'event.change.owner.name': 'Dustin', 'event.change.number': '4321', 'event.change.url': 'http://buildbot.net', 'event.change.branch': 'br', 'event.type': 'patchset-created', 'event.patchSet.revision': 'abcdef', 'event.patchSet.number': '12', 'event.source': 'GerritChangeSource', }, ) self.build.allChanges = lambda x=None: [change] self.expectnoClobber() self.expectRepoSync() self.expect_commands( self.ExpectShell(command=['repo', 'download', 'pr', '4321/12']) .exit(0) .stderr("test/bla refs/changes/64/564/12 -> FETCH_HEAD\n") .stderr("HEAD is now at 0123456789abcdef...\n") ) self.expect_property("repo_downloaded", "564/12 0123456789abcdef ", "Source") return self.myRunStep() def test_repo_downloads_from_change_source_codebase(self): """basic repo download from change source, and check that repo_downloaded is updated""" self.mySetupStep(repoDownloads=repo.RepoDownloadsFromChangeSource("mycodebase")) change = Change( None, None, None, properties={ 'event.change.owner.email': '[email protected]', 'event.change.subject': 'fix 1234', 'event.change.project': 'pr', 'event.change.owner.name': 'Dustin', 'event.change.number': '4321', 'event.change.url': 'http://buildbot.net', 'event.change.branch': 'br', 'event.type': 'patchset-created', 'event.patchSet.revision': 'abcdef', 'event.patchSet.number': '12', 'event.source': 'GerritChangeSource', }, ) # getSourceStamp is faked by SourceStepMixin ss = self.build.getSourceStamp("") ss.changes = [change] self.expectnoClobber() self.expectRepoSync() self.expect_commands( self.ExpectShell(command=['repo', 'download', 'pr', '4321/12']) .exit(0) .stderr("test/bla refs/changes/64/564/12 -> FETCH_HEAD\n") .stderr("HEAD is now at 0123456789abcdef...\n") ) self.expect_property("repo_downloaded", "564/12 0123456789abcdef ", "Source") return self.myRunStep() def test_update_fail1(self): """fail at cleanup: ignored""" self.mySetupStep() self.expectnoClobber() self.expectRepoSync(which_fail=0, breakatfail=False) return self.myRunStep() def test_update_fail2(self): """fail at repo init: clobber""" self.mySetupStep() self.expectnoClobber() self.expectRepoSync(which_fail=1, breakatfail=True) self.expectClobber() self.expectRepoSync() self.shouldRetry = True return self.myRunStep() def test_update_fail3(self): """fail at repo sync: clobber""" self.mySetupStep() self.expectnoClobber() self.expectRepoSync(which_fail=2, breakatfail=True) self.expectClobber() self.expectRepoSync() self.shouldRetry = True return self.myRunStep() def test_update_fail4(self): """fail at repo manifest: clobber""" self.mySetupStep() self.expectnoClobber() self.expectRepoSync(which_fail=3, breakatfail=True) self.expectClobber() self.expectRepoSync() self.shouldRetry = True return self.myRunStep() def test_update_doublefail(self): """fail at repo manifest: clobber but still fail""" self.mySetupStep() self.expectnoClobber() self.expectRepoSync(which_fail=3, breakatfail=True) self.expectClobber() self.expectRepoSync(which_fail=3, breakatfail=True) self.shouldRetry = True return self.myRunStep( result=FAILURE, state_string="repo failed at: repo manifest (failure)" ) def test_update_doublefail2(self): """fail at repo sync: clobber but still fail""" self.mySetupStep() self.expectnoClobber() self.expectRepoSync(which_fail=2, breakatfail=True) self.expectClobber() self.expectRepoSync(which_fail=2, breakatfail=True) self.shouldRetry = True return self.myRunStep(result=FAILURE, state_string="repo failed at: repo sync (failure)") def test_update_doublefail3(self): """fail at repo init: clobber but still fail""" self.mySetupStep() self.expectnoClobber() self.expectRepoSync(which_fail=1, breakatfail=True) self.expectClobber() self.expectRepoSync(which_fail=1, breakatfail=True) self.shouldRetry = True return self.myRunStep(result=FAILURE, state_string="repo failed at: repo init (failure)") def test_basic_fail(self): """fail at repo init: no need to re-clobber but still fail""" self.mySetupStep() self.expectClobber() self.expectRepoSync(which_fail=1, breakatfail=True) self.shouldRetry = True return self.myRunStep(result=FAILURE, state_string="repo failed at: repo init (failure)")
25,928
Python
.py
601
32.725458
100
0.586064
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,507
test_http.py
buildbot_buildbot/master/buildbot/test/unit/steps/test_http.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.trial import unittest from twisted.web.resource import Resource from twisted.web.util import redirectTo from buildbot.process import properties from buildbot.process.results import FAILURE from buildbot.process.results import SUCCESS from buildbot.steps import http from buildbot.test.reactor import TestReactorMixin from buildbot.test.steps import TestBuildStepMixin from buildbot.test.util.site import SiteWithClose try: import txrequests assert txrequests import requests assert requests except ImportError: txrequests = requests = None # We use twisted's internal webserver instead of mocking requests # to be sure we use the correct requests interfaces class TestPage(Resource): isLeaf = True def render_GET(self, request): if request.uri == b"/404": request.setResponseCode(404) return b"404" elif request.uri == b'/redirect': return redirectTo(b'/redirected-path', request) elif request.uri == b"/header": return b"".join(request.requestHeaders.getRawHeaders(b"X-Test")) return b"OK" def render_POST(self, request): if request.uri == b"/404": request.setResponseCode(404) return b"404" return b"OK:" + request.content.read() class TestHTTPStep(TestBuildStepMixin, TestReactorMixin, unittest.TestCase): def setUp(self): self.setup_test_reactor(auto_tear_down=False) if txrequests is None: raise unittest.SkipTest("Need to install txrequests to test http steps") # ignore 'http_proxy' environment variable when running tests session = http.getSession() session.trust_env = False # port 0 means random unused port self.site = SiteWithClose(TestPage()) self.listener = reactor.listenTCP(0, self.site) self.port = self.listener.getHost().port return self.setup_test_build_step() @defer.inlineCallbacks def tearDown(self): http.closeSession() try: yield self.listener.stopListening() yield self.site.stopFactory() yield self.site.close_connections() finally: yield self.tear_down_test_build_step() yield self.tear_down_test_reactor() def get_connection_string(self): return f"http://127.0.0.1:{self.port}" def getURL(self, path=""): return f'{self.get_connection_string()}/{path}' def test_get(self): url = self.getURL() self.setup_step(http.GET(url)) self.expect_log_file('log', f"URL: {url}\nStatus: 200\n ------ Content ------\nOK") self.expect_log_file('content', "OK") self.expect_outcome(result=SUCCESS, state_string="Status code: 200") return self.run_step() def test_connection_error(self): def throwing_request(*args, **kwargs): raise requests.exceptions.ConnectionError("failed to connect") with mock.patch.object(http.getSession(), 'request', throwing_request): url = self.getURL("path") self.setup_step(http.GET(url)) self.expect_outcome(result=FAILURE, state_string="Requested (failure)") return self.run_step() def test_redirect(self): url = self.getURL("redirect") self.setup_step(http.GET(url)) expected_log = f""" Redirected 1 times: URL: {self.get_connection_string()}/redirect ------ Content ------ <html> <head> <meta http-equiv="refresh" content="0;URL=/redirected-path"> </head> <body bgcolor="#FFFFFF" text="#000000"> <a href="/redirected-path">click here</a> </body> </html> ============================================================ URL: {self.get_connection_string()}/redirected-path Status: 200 ------ Content ------ OK""" self.expect_log_file('log', expected_log) self.expect_log_file('content', "OK") self.expect_outcome(result=SUCCESS, state_string="Status code: 200") return self.run_step() def test_404(self): url = self.getURL("404") self.setup_step(http.GET(url)) self.expect_log_file('log', f"URL: {url}\n ------ Content ------\n404") self.expect_log_file('content', "404") self.expect_outcome(result=FAILURE, state_string="Status code: 404 (failure)") return self.run_step() def test_method_not_allowed(self): url = self.getURL("path") self.setup_step(http.PUT(url)) self.expect_outcome(result=FAILURE, state_string="Status code: 501 (failure)") return self.run_step() def test_post(self): url = self.getURL("path") self.setup_step(http.POST(url)) self.expect_outcome(result=SUCCESS, state_string="Status code: 200") self.expect_log_file('log', f"URL: {url}\nStatus: 200\n ------ Content ------\nOK:") self.expect_log_file('content', "OK:") return self.run_step() def test_post_data(self): url = self.getURL("path") self.setup_step(http.POST(url, data='mydata')) self.expect_outcome(result=SUCCESS, state_string="Status code: 200") self.expect_log_file('log', f"URL: {url}\nStatus: 200\n ------ Content ------\nOK:mydata") self.expect_log_file('content', "OK:mydata") return self.run_step() def test_post_data_dict(self): url = self.getURL("path") self.setup_step(http.POST(url, data={'key1': 'value1'})) self.expect_outcome(result=SUCCESS, state_string="Status code: 200") self.expect_log_file( 'log', f"""\ URL: {url} Status: 200 ------ Content ------ OK:key1=value1""", ) self.expect_log_file('content', "OK:key1=value1") return self.run_step() def test_header(self): url = self.getURL("header") self.setup_step(http.GET(url, headers={"X-Test": "True"})) self.expect_log_file('log', f"URL: {url}\nStatus: 200\n ------ Content ------\nTrue") self.expect_outcome(result=SUCCESS, state_string="Status code: 200") return self.run_step() @defer.inlineCallbacks def test_hidden_header(self): url = self.getURL("header") self.setup_step( http.GET( url, headers={"X-Test": "True"}, hide_request_headers=["X-Test"], hide_response_headers=["Content-Length"], ) ) self.expect_log_file('log', f"URL: {url}\nStatus: 200\n ------ Content ------\nTrue") self.expect_outcome(result=SUCCESS, state_string="Status code: 200") yield self.run_step() self.assertIn("X-Test: <HIDDEN>", self.get_nth_step(0).logs['log'].header) self.assertIn("Content-Length: <HIDDEN>", self.get_nth_step(0).logs['log'].header) def test_params_renderable(self): url = self.getURL() self.setup_step(http.GET(url, params=properties.Property("x"))) self.build.setProperty("x", {"param_1": "param_1", "param_2": 2}, "here") self.expect_log_file( 'log', f"URL: {url}?param_1=param_1&param_2=2\nStatus: 200\n ------ Content ------\nOK" ) self.expect_log_file('content', "OK") self.expect_outcome(result=SUCCESS, state_string="Status code: 200") return self.run_step()
8,163
Python
.py
190
35.736842
99
0.64067
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,508
test_configurable.py
buildbot_buildbot/master/buildbot/test/unit/steps/test_configurable.py
# This file is part of Buildbot. Buildbot is free software: you can # redistribute it and/or modify it under the terms of the GNU General Public # License as published by the Free Software Foundation, version 2. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more # details. # # You should have received a copy of the GNU General Public License along with # this program; if not, write to the Free Software Foundation, Inc., 51 # Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # Copyright Buildbot Team Members from parameterized import parameterized from twisted.trial import unittest from buildbot.process.properties import Interpolate from buildbot.steps.configurable import BuildbotCiYml from buildbot.steps.configurable import evaluate_condition from buildbot.steps.configurable import parse_env_string from buildbot.steps.shell import ShellCommand class TestParseEnvString(unittest.TestCase): @parameterized.expand([ ('single', 'ABC=1', {'ABC': '1'}), ('multiple', 'ABC=1 EFG=2', {'ABC': '1', 'EFG': '2'}), ('multiple_empty_quotes', 'ABC=\'\' EFG=2', {'ABC': '', 'EFG': '2'}), ('multiple_empty_double_quotes', 'ABC="" EFG=2', {'ABC': '', 'EFG': '2'}), ('multiple_single_quotes', 'ABC=\'1\' EFG=2', {'ABC': '1', 'EFG': '2'}), ('multiple_double_quotes', 'ABC="1" EFG=2', {'ABC': '1', 'EFG': '2'}), ('multiple_with_equals_in_value', 'ABC=1=2 EFG=2', {'ABC': '1=2', 'EFG': '2'}), ( 'multiple_with_equals_in_value_single_quotes', 'ABC=\'1=2\' EFG=2', {'ABC': '1=2', 'EFG': '2'}, ), ( 'multiple_with_equals_in_value_double_quotes', 'ABC="1=2" EFG=2', {'ABC': '1=2', 'EFG': '2'}, ), ( 'multiple_with_space_in_value_single_quotes', 'ABC=\'1 2\' EFG=2', {'ABC': '1 2', 'EFG': '2'}, ), ( 'multiple_with_space_in_value_double_quotes', 'ABC="1 2" EFG=2', {'ABC': '1 2', 'EFG': '2'}, ), ]) def test_one(self, name, value, expected): self.assertEqual(parse_env_string(value), expected) @parameterized.expand([ ('dot', 'ABC=1.0', {'ABC': '1.0'}), ('dash', 'ABC=1-0', {'ABC': '1-0'}), ('plus', 'ABC=1+0', {'ABC': '1+0'}), ('multiply', 'ABC=1*0', {'ABC': '1*0'}), ('tilde', 'ABC=1~0', {'ABC': '1~0'}), ('hat', 'ABC=1^0', {'ABC': '1^0'}), ('comma', 'ABC=1,0', {'ABC': '1,0'}), ('colon', 'ABC=1:0', {'ABC': '1:0'}), ('slash', 'ABC=1/0', {'ABC': '1/0'}), ('pipe', 'ABC=1|0', {'ABC': '1|0'}), ('excl_mark', 'ABC=1!0', {'ABC': '1!0'}), ('question_mark', 'ABC=1?0', {'ABC': '1?0'}), ('left_paren', 'ABC=1(0', {'ABC': '1(0'}), ('right_paren', 'ABC=1)0', {'ABC': '1)0'}), ('left_brace', 'ABC=1[0', {'ABC': '1[0'}), ('right_brace', 'ABC=1]0', {'ABC': '1]0'}), ('left_curly_brace', 'ABC=1{0', {'ABC': '1{0'}), ('right_curly_brace', 'ABC=1}0', {'ABC': '1}0'}), ('left_angled_brace', 'ABC=1<0', {'ABC': '1<0'}), ('right_angled_brace', 'ABC=1>0', {'ABC': '1>0'}), ]) def test_special_characters(self, name, value, expected): self.assertEqual(parse_env_string(value), expected) def test_global_overridden(self): self.assertEqual( parse_env_string('K1=VE1 K2=VE2', {'K2': 'VG1', 'K3': 'VG3'}), {'K1': 'VE1', 'K2': 'VE2', 'K3': 'VG3'}, ) class TestEvaluateCondition(unittest.TestCase): def test_bool(self): self.assertTrue(evaluate_condition('True', {})) self.assertFalse(evaluate_condition('False', {})) def test_string_empty(self): self.assertFalse(evaluate_condition('VALUE', {'VALUE': ''})) self.assertTrue(evaluate_condition('VALUE', {'VALUE': 'abc'})) def test_string_equal(self): self.assertTrue(evaluate_condition('VALUE == "a"', {'VALUE': 'a'})) self.assertFalse(evaluate_condition('VALUE == "a"', {'VALUE': 'b'})) def test_string_in_tuple(self): cond = 'VALUE in ("a", "b", "c", "d")' self.assertTrue(evaluate_condition(cond, {'VALUE': 'a'})) self.assertFalse(evaluate_condition(cond, {'VALUE': 'not'})) def test_string_not_in_tuple(self): cond = 'VALUE not in ("a", "b", "c", "d")' self.assertFalse(evaluate_condition(cond, {'VALUE': 'a'})) self.assertTrue(evaluate_condition(cond, {'VALUE': 'not'})) class TestLoading(unittest.TestCase): def test_single_script(self): c = BuildbotCiYml.load_from_str(""" script: - echo success """) self.assertEqual( c.script_commands, { 'before_install': [], 'install': [], 'after_install': [], 'before_script': [], 'script': ['echo success'], 'after_script': [], }, ) def test_single_script_interpolated_no_replacement(self): c = BuildbotCiYml.load_from_str(""" script: - !i echo success """) self.assertEqual( c.script_commands, { 'before_install': [], 'install': [], 'after_install': [], 'before_script': [], 'script': [Interpolate("echo success")], 'after_script': [], }, ) def test_single_script_interpolated_with_replacement(self): c = BuildbotCiYml.load_from_str(""" script: - !i echo "%(prop:name)s" """) self.assertEqual( c.script_commands, { 'before_install': [], 'install': [], 'after_install': [], 'before_script': [], 'script': [Interpolate("echo %(prop:name)s")], 'after_script': [], }, ) def test_single_script_dict_interpolate_with_replacement(self): c = BuildbotCiYml.load_from_str(""" script: - title: mytitle - cmd: [ "echo", !i "%(prop:name)s" ] """) self.assertEqual( c.script_commands, { 'before_install': [], 'install': [], 'after_install': [], 'before_script': [], 'script': [{'title': 'mytitle'}, {'cmd': ['echo', Interpolate('%(prop:name)s')]}], 'after_script': [], }, ) def test_multiple_scripts(self): c = BuildbotCiYml.load_from_str(""" script: - echo success - echo success2 - echo success3 """) self.assertEqual( c.script_commands, { 'before_install': [], 'install': [], 'after_install': [], 'before_script': [], 'script': ['echo success', 'echo success2', 'echo success3'], 'after_script': [], }, ) def test_script_with_step(self): c = BuildbotCiYml.load_from_str(""" script: - !ShellCommand command: "echo success" """) self.assertEqual( c.script_commands, { 'before_install': [], 'install': [], 'after_install': [], 'before_script': [], 'script': [ShellCommand(command='echo success')], 'after_script': [], }, ) def test_matrix_include_simple(self): m = BuildbotCiYml.load_matrix( {'matrix': {'include': [{'env': 'ABC=10'}, {'env': 'ABC=11'}, {'env': 'ABC=12'}]}}, {} ) self.assertEqual( m, [{'env': {'ABC': '10'}}, {'env': {'ABC': '11'}}, {'env': {'ABC': '12'}}] ) def test_matrix_include_global(self): m = BuildbotCiYml.load_matrix( {'matrix': {'include': [{'env': 'ABC=10'}, {'env': 'ABC=11'}, {'env': 'ABC=12'}]}}, {'GLOBAL': 'GV'}, ) self.assertEqual( m, [ {'env': {'ABC': '10', 'GLOBAL': 'GV'}}, {'env': {'ABC': '11', 'GLOBAL': 'GV'}}, {'env': {'ABC': '12', 'GLOBAL': 'GV'}}, ], ) def test_matrix_include_global_with_override(self): m = BuildbotCiYml.load_matrix( {'matrix': {'include': [{'env': 'ABC=10'}, {'env': 'ABC=11'}, {'env': 'ABC=12'}]}}, {'ABC': 'GV'}, ) self.assertEqual( m, [ {'env': {'ABC': '10'}}, {'env': {'ABC': '11'}}, {'env': {'ABC': '12'}}, ], )
9,090
Python
.py
234
28.564103
98
0.487209
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,509
test_manager.py
buildbot_buildbot/master/buildbot/test/unit/worker/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 zope.interface import implementer from buildbot import interfaces from buildbot.process import botmaster from buildbot.test.fake import fakemaster from buildbot.test.reactor import TestReactorMixin from buildbot.util import service from buildbot.worker import manager as workermanager @implementer(interfaces.IWorker) class FakeWorker(service.BuildbotService): reconfig_count = 0 def __init__(self, workername): super().__init__(name=workername) def reconfigService(self): self.reconfig_count += 1 self.configured = True return defer.succeed(None) class FakeWorker2(FakeWorker): pass class TestWorkerManager(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, wantData=True) self.master.mq = self.master.mq self.workers = workermanager.WorkerManager(self.master) yield self.workers.setServiceParent(self.master) # workers expect a botmaster as well as a manager. self.master.botmaster.disownServiceParent() self.botmaster = botmaster.BotMaster() self.master.botmaster = self.botmaster yield self.master.botmaster.setServiceParent(self.master) self.new_config = mock.Mock() self.workers.startService() @defer.inlineCallbacks def tearDown(self): yield self.workers.stopService() yield self.tear_down_test_reactor() @defer.inlineCallbacks def test_reconfigServiceWorkers_add_remove(self): worker = FakeWorker('worker1') self.new_config.workers = [worker] yield self.workers.reconfigServiceWithBuildbotConfig(self.new_config) self.assertIdentical(worker.parent, self.workers) self.assertEqual(self.workers.workers, {'worker1': worker}) self.new_config.workers = [] self.assertEqual(worker.running, True) yield self.workers.reconfigServiceWithBuildbotConfig(self.new_config) self.assertEqual(worker.running, False) @defer.inlineCallbacks def test_reconfigServiceWorkers_reconfig(self): worker = FakeWorker('worker1') yield worker.setServiceParent(self.workers) worker.parent = self.master worker.manager = self.workers worker.botmaster = self.master.botmaster worker_new = FakeWorker('worker1') self.new_config.workers = [worker_new] yield self.workers.reconfigServiceWithBuildbotConfig(self.new_config) # worker was not replaced.. self.assertIdentical(self.workers.workers['worker1'], worker) @defer.inlineCallbacks def test_reconfigServiceWorkers_class_changes(self): worker = FakeWorker('worker1') yield worker.setServiceParent(self.workers) worker_new = FakeWorker2('worker1') self.new_config.workers = [worker_new] yield self.workers.reconfigServiceWithBuildbotConfig(self.new_config) # worker *was* replaced (different class) self.assertIdentical(self.workers.workers['worker1'], worker_new) @defer.inlineCallbacks def test_newConnection_remoteGetWorkerInfo_failure(self): class Error(RuntimeError): pass conn = mock.Mock() conn.remoteGetWorkerInfo = mock.Mock(return_value=defer.fail(Error())) yield self.assertFailure(self.workers.newConnection(conn, "worker"), Error)
4,301
Python
.py
93
39.989247
84
0.737736
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,510
test_openstack.py
buildbot_buildbot/master/buildbot/test/unit/worker/test_openstack.py
# This file is part of Buildbot. Buildbot is free software: you can # redistribute it and/or modify it under the terms of the GNU General Public # License as published by the Free Software Foundation, version 2. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more # details. # # You should have received a copy of the GNU General Public License along with # this program; if not, write to the Free Software Foundation, Inc., 51 # Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # Portions Copyright Buildbot Team Members # Portions Copyright 2013 Cray Inc. import hashlib from unittest import mock from twisted.internet import defer from twisted.trial import unittest import buildbot.test.fake.openstack as novaclient from buildbot import config from buildbot import interfaces from buildbot.process.properties import Interpolate from buildbot.process.properties import Properties from buildbot.test.fake import fakemaster from buildbot.test.reactor import TestReactorMixin from buildbot.worker import openstack class TestOpenStackWorker(TestReactorMixin, unittest.TestCase): os_auth = { "os_username": 'user', "os_password": 'pass', "os_tenant_name": 'tenant', "os_auth_url": 'auth', } os_auth_custom = {"token": 'openstack-token', "auth_type": 'token', "auth_url": 'auth'} bs_image_args = {"flavor": 1, "image": '28a65eb4-f354-4420-97dc-253b826547f7', **os_auth} def setUp(self): self.setup_test_reactor(auto_tear_down=False) self.patch(openstack, "client", novaclient) self.patch(openstack, "loading", novaclient) self.patch(openstack, "session", novaclient) self.patch(openstack, "NotFound", novaclient.NotFound) self.build = Properties( image=novaclient.TEST_UUIDS['image'], flavor=novaclient.TEST_UUIDS['flavor'], meta_value='value', ) self.masterhash = hashlib.sha1(b'fake:/master').hexdigest()[:6] @defer.inlineCallbacks def tearDown(self): yield self.tear_down_test_reactor() @defer.inlineCallbacks def setupWorker(self, *args, **kwargs): worker = openstack.OpenStackLatentWorker(*args, **kwargs) master = yield fakemaster.make_master(self, wantData=True) fakemaster.master = master worker.setServiceParent(master) yield master.startService() self.addCleanup(master.stopService) return worker @defer.inlineCallbacks def test_constructor_nonova(self): self.patch(openstack, "client", None) with self.assertRaises(config.ConfigErrors): yield self.setupWorker('bot', 'pass', **self.bs_image_args) @defer.inlineCallbacks def test_constructor_nokeystoneauth(self): self.patch(openstack, "loading", None) with self.assertRaises(config.ConfigErrors): yield self.setupWorker('bot', 'pass', **self.bs_image_args) @defer.inlineCallbacks def test_constructor_minimal(self): bs = yield self.setupWorker('bot', 'pass', **self.bs_image_args) self.assertEqual(bs.workername, 'bot') self.assertEqual(bs.password, 'pass') self.assertEqual(bs.flavor, 1) self.assertEqual(bs.image, '28a65eb4-f354-4420-97dc-253b826547f7') self.assertEqual(bs.block_devices, None) self.assertIsInstance(bs.novaclient, novaclient.Client) @defer.inlineCallbacks def test_builds_may_be_incompatible(self): # Minimal set of parameters bs = yield self.setupWorker('bot', 'pass', **self.bs_image_args) self.assertEqual(bs.builds_may_be_incompatible, True) @defer.inlineCallbacks def test_constructor_minimal_keystone_v3(self): bs = yield self.setupWorker( 'bot', 'pass', os_user_domain='test_oud', os_project_domain='test_opd', **self.bs_image_args, ) self.assertEqual(bs.workername, 'bot') self.assertEqual(bs.password, 'pass') self.assertEqual(bs.flavor, 1) self.assertEqual(bs.image, '28a65eb4-f354-4420-97dc-253b826547f7') self.assertEqual(bs.block_devices, None) self.assertIsInstance(bs.novaclient, novaclient.Client) self.assertEqual(bs.novaclient.session.auth.user_domain_name, 'test_oud') self.assertEqual(bs.novaclient.session.auth.project_domain_name, 'test_opd') @defer.inlineCallbacks def test_constructor_token_keystone_v3(self): bs = yield self.setupWorker( 'bot', 'pass', os_auth_args=self.os_auth_custom, **self.bs_image_args ) self.assertEqual(bs.workername, 'bot') self.assertEqual(bs.password, 'pass') self.assertEqual(bs.flavor, 1) self.assertEqual(bs.image, '28a65eb4-f354-4420-97dc-253b826547f7') self.assertEqual(bs.block_devices, None) self.assertIsInstance(bs.novaclient, novaclient.Client) self.assertEqual(bs.novaclient.session.auth.user_domain_name, 'token') self.assertEqual(bs.novaclient.session.auth.project_domain_name, 'token') @defer.inlineCallbacks def test_constructor_region(self): bs = yield self.setupWorker('bot', 'pass', region="test-region", **self.bs_image_args) self.assertEqual(bs.novaclient.client.region_name, "test-region") @defer.inlineCallbacks def test_constructor_block_devices_default(self): block_devices = [{'uuid': 'uuid', 'volume_size': 10}] bs = yield self.setupWorker( 'bot', 'pass', flavor=1, block_devices=block_devices, **self.os_auth ) self.assertEqual(bs.image, None) self.assertEqual(len(bs.block_devices), 1) self.assertEqual( bs.block_devices, [ { 'boot_index': 0, 'delete_on_termination': True, 'destination_type': 'volume', 'device_name': 'vda', 'source_type': 'image', 'volume_size': 10, 'uuid': 'uuid', } ], ) @defer.inlineCallbacks def test_constructor_block_devices_get_sizes(self): block_devices = [ {'source_type': 'image', 'uuid': novaclient.TEST_UUIDS['image']}, {'source_type': 'image', 'uuid': novaclient.TEST_UUIDS['image'], 'volume_size': 4}, {'source_type': 'volume', 'uuid': novaclient.TEST_UUIDS['volume']}, {'source_type': 'snapshot', 'uuid': novaclient.TEST_UUIDS['snapshot']}, ] def check_volume_sizes(_images, _flavors, block_devices, nova_args, metas): self.assertEqual(len(block_devices), 4) self.assertEqual(block_devices[0]['volume_size'], 1) self.assertIsInstance( block_devices[0]['volume_size'], int, "Volume size is an integer." ) self.assertEqual(block_devices[1]['volume_size'], 4) self.assertEqual(block_devices[2]['volume_size'], 4) self.assertEqual(block_devices[3]['volume_size'], 2) lw = yield self.setupWorker( 'bot', 'pass', flavor=1, block_devices=block_devices, **self.os_auth ) self.assertEqual(lw.image, None) self.assertEqual( lw.block_devices, [ { 'boot_index': 0, 'delete_on_termination': True, 'destination_type': 'volume', 'device_name': 'vda', 'source_type': 'image', 'volume_size': None, 'uuid': novaclient.TEST_UUIDS['image'], }, { 'boot_index': 0, 'delete_on_termination': True, 'destination_type': 'volume', 'device_name': 'vda', 'source_type': 'image', 'volume_size': 4, 'uuid': novaclient.TEST_UUIDS['image'], }, { 'boot_index': 0, 'delete_on_termination': True, 'destination_type': 'volume', 'device_name': 'vda', 'source_type': 'volume', 'volume_size': None, 'uuid': novaclient.TEST_UUIDS['volume'], }, { 'boot_index': 0, 'delete_on_termination': True, 'destination_type': 'volume', 'device_name': 'vda', 'source_type': 'snapshot', 'volume_size': None, 'uuid': novaclient.TEST_UUIDS['snapshot'], }, ], ) self.patch(lw, "_start_instance", check_volume_sizes) yield lw.start_instance(self.build) @defer.inlineCallbacks def test_constructor_block_devices_missing(self): block_devices = [ {'source_type': 'image', 'uuid': 'image-uuid'}, ] lw = yield self.setupWorker( 'bot', 'pass', flavor=1, block_devices=block_devices, **self.os_auth ) yield self.assertFailure(lw.start_instance(self.build), novaclient.NotFound) @defer.inlineCallbacks def test_constructor_no_image(self): """ Must have one of image or block_devices specified. """ with self.assertRaises(ValueError): yield self.setupWorker('bot', 'pass', flavor=1, **self.os_auth) @defer.inlineCallbacks def test_getImage_string(self): bs = yield self.setupWorker('bot', 'pass', **self.bs_image_args) image_uuid = yield bs._getImage(self.build) self.assertEqual('28a65eb4-f354-4420-97dc-253b826547f7', image_uuid) @defer.inlineCallbacks def test_getImage_renderable(self): bs = yield self.setupWorker( 'bot', 'pass', flavor=1, image=Interpolate('%(prop:image)s'), **self.os_auth ) image_uuid = yield bs._getImage(self.build) self.assertEqual(novaclient.TEST_UUIDS['image'], image_uuid) @defer.inlineCallbacks def test_getImage_name(self): bs = yield self.setupWorker('bot', 'pass', flavor=1, image='CirrOS 0.3.4', **self.os_auth) image_uuid = yield bs._getImage(self.build) self.assertEqual(novaclient.TEST_UUIDS['image'], image_uuid) @defer.inlineCallbacks def test_getFlavor_string(self): bs = yield self.setupWorker('bot', 'pass', **self.bs_image_args) flavor_uuid = yield bs._getFlavor(self.build) self.assertEqual(1, flavor_uuid) @defer.inlineCallbacks def test_getFlavor_renderable(self): bs = yield self.setupWorker( 'bot', 'pass', image="1", flavor=Interpolate('%(prop:flavor)s'), **self.os_auth ) flavor_uuid = yield bs._getFlavor(self.build) self.assertEqual(novaclient.TEST_UUIDS['flavor'], flavor_uuid) @defer.inlineCallbacks def test_getFlavor_name(self): bs = yield self.setupWorker('bot', 'pass', image="1", flavor='m1.small', **self.os_auth) flavor_uuid = yield bs._getFlavor(self.build) self.assertEqual(novaclient.TEST_UUIDS['flavor'], flavor_uuid) @defer.inlineCallbacks def test_start_instance_already_exists(self): bs = yield self.setupWorker('bot', 'pass', **self.bs_image_args) bs.instance = mock.Mock() yield self.assertFailure(bs.start_instance(self.build), ValueError) @defer.inlineCallbacks def test_start_instance_first_fetch_fail(self): bs = yield self.setupWorker('bot', 'pass', **self.bs_image_args) bs._poll_resolution = 0 self.patch(novaclient.Servers, 'fail_to_get', True) self.patch(novaclient.Servers, 'gets_until_disappears', 0) yield self.assertFailure( bs.start_instance(self.build), interfaces.LatentWorkerFailedToSubstantiate ) @defer.inlineCallbacks def test_start_instance_fail_to_find(self): bs = yield self.setupWorker('bot', 'pass', **self.bs_image_args) bs._poll_resolution = 0 self.patch(novaclient.Servers, 'fail_to_get', True) yield self.assertFailure( bs.start_instance(self.build), interfaces.LatentWorkerFailedToSubstantiate ) @defer.inlineCallbacks def test_start_instance_fail_to_start(self): bs = yield self.setupWorker('bot', 'pass', **self.bs_image_args) bs._poll_resolution = 0 self.patch(novaclient.Servers, 'fail_to_start', True) yield self.assertFailure( bs.start_instance(self.build), interfaces.LatentWorkerFailedToSubstantiate ) @defer.inlineCallbacks def test_start_instance_success(self): bs = yield self.setupWorker('bot', 'pass', **self.bs_image_args) bs._poll_resolution = 0 uuid, image_uuid, time_waiting = yield bs.start_instance(self.build) self.assertTrue(uuid) self.assertEqual(image_uuid, '28a65eb4-f354-4420-97dc-253b826547f7') self.assertTrue(time_waiting) @defer.inlineCallbacks def test_start_instance_check_meta(self): meta_arg = {'some_key': 'some-value', 'BUILDBOT:instance': self.masterhash} bs = yield self.setupWorker('bot', 'pass', meta=meta_arg, **self.bs_image_args) bs._poll_resolution = 0 yield bs.start_instance(self.build) self.assertIn('meta', bs.instance.boot_kwargs) self.assertEqual(bs.instance.metadata, meta_arg) @defer.inlineCallbacks def test_start_instance_check_meta_renderable(self): meta_arg = {'some_key': Interpolate('%(prop:meta_value)s')} bs = yield self.setupWorker('bot', 'pass', meta=meta_arg, **self.bs_image_args) bs._poll_resolution = 0 yield bs.start_instance(self.build) self.assertIn('meta', bs.instance.boot_kwargs) self.assertEqual( bs.instance.metadata, {'some_key': 'value', 'BUILDBOT:instance': self.masterhash} ) @defer.inlineCallbacks def test_start_instance_check_nova_args(self): nova_args = {'some-key': 'some-value'} bs = yield self.setupWorker('bot', 'pass', nova_args=nova_args, **self.bs_image_args) bs._poll_resolution = 0 yield bs.start_instance(self.build) self.assertIn('meta', bs.instance.boot_kwargs) self.assertEqual(bs.instance.boot_kwargs['some-key'], 'some-value') @defer.inlineCallbacks def test_start_instance_check_nova_args_renderable(self): nova_args = {'some-key': Interpolate('%(prop:meta_value)s')} bs = yield self.setupWorker('bot', 'pass', nova_args=nova_args, **self.bs_image_args) bs._poll_resolution = 0 yield bs.start_instance(self.build) self.assertIn('meta', bs.instance.boot_kwargs) self.assertEqual(bs.instance.boot_kwargs['some-key'], 'value') @defer.inlineCallbacks def test_interpolate_renderables_for_new_build(self): build1 = Properties(image=novaclient.TEST_UUIDS['image'], block_device="some-device") build2 = Properties(image="build2-image") block_devices = [{'uuid': Interpolate('%(prop:block_device)s'), 'volume_size': 10}] bs = yield self.setupWorker( 'bot', 'pass', block_devices=block_devices, **self.bs_image_args ) bs._poll_resolution = 0 yield bs.start_instance(build1) yield bs.stop_instance(build1) self.assertTrue((yield bs.isCompatibleWithBuild(build2))) @defer.inlineCallbacks def test_reject_incompatible_build_while_running(self): build1 = Properties(image=novaclient.TEST_UUIDS['image'], block_device="some-device") build2 = Properties(image="build2-image") block_devices = [{'uuid': Interpolate('%(prop:block_device)s'), 'volume_size': 10}] bs = yield self.setupWorker( 'bot', 'pass', block_devices=block_devices, **self.bs_image_args ) bs._poll_resolution = 0 yield bs.start_instance(build1) self.assertFalse((yield bs.isCompatibleWithBuild(build2))) @defer.inlineCallbacks def test_stop_instance_cleanup(self): """ Test cleaning up leftover instances before starting new. """ self.patch(novaclient.Servers, 'fail_to_get', False) self.patch(novaclient.Servers, 'gets_until_disappears', 9) novaclient.Servers().create( ['bot', novaclient.TEST_UUIDS['image'], novaclient.TEST_UUIDS['flavor']], meta={'BUILDBOT:instance': self.masterhash}, ) bs = yield self.setupWorker('bot', 'pass', **self.bs_image_args) bs._poll_resolution = 0 uuid, image_uuid, time_waiting = yield bs.start_instance(self.build) self.assertTrue(uuid) self.assertEqual(image_uuid, '28a65eb4-f354-4420-97dc-253b826547f7') self.assertTrue(time_waiting) @defer.inlineCallbacks def test_stop_instance_not_set(self): """ Test stopping the instance but with no instance to stop. """ bs = yield self.setupWorker('bot', 'pass', **self.bs_image_args) bs.instance = None stopped = yield bs.stop_instance() self.assertEqual(stopped, None) @defer.inlineCallbacks def test_stop_instance_missing(self): bs = yield self.setupWorker('bot', 'pass', **self.bs_image_args) instance = mock.Mock() instance.id = 'uuid' bs.instance = instance # TODO: Check log for instance not found. bs.stop_instance() @defer.inlineCallbacks def test_stop_instance_fast(self): bs = yield self.setupWorker('bot', 'pass', **self.bs_image_args) # Make instance immediately active. self.patch(novaclient.Servers, 'gets_until_active', 0) s = novaclient.Servers() bs.instance = inst = s.create() self.assertIn(inst.id, s.instances) bs.stop_instance(fast=True) self.assertNotIn(inst.id, s.instances) @defer.inlineCallbacks def test_stop_instance_notfast(self): bs = yield self.setupWorker('bot', 'pass', **self.bs_image_args) # Make instance immediately active. self.patch(novaclient.Servers, 'gets_until_active', 0) s = novaclient.Servers() bs.instance = inst = s.create() self.assertIn(inst.id, s.instances) bs.stop_instance(fast=False) self.assertNotIn(inst.id, s.instances) @defer.inlineCallbacks def test_stop_instance_unknown(self): bs = yield self.setupWorker('bot', 'pass', **self.bs_image_args) # Make instance immediately active. self.patch(novaclient.Servers, 'gets_until_active', 0) s = novaclient.Servers() bs.instance = inst = s.create() # Set status to DELETED. Instance should not be deleted when shutting # down as it already is. inst.status = novaclient.DELETED self.assertIn(inst.id, s.instances) bs.stop_instance() self.assertIn(inst.id, s.instances)
19,338
Python
.py
416
37.012019
98
0.631007
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,511
test_marathon.py
buildbot_buildbot/master/buildbot/test/unit/worker/test_marathon.py
# This file is part of Buildbot. Buildbot is free software: you can # redistribute it and/or modify it under the terms of the GNU General Public # License as published by the Free Software Foundation, version 2. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more # details. # # You should have received a copy of the GNU General Public License along with # this program; if not, write to the Free Software Foundation, Inc., 51 # Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # Copyright Buildbot Team Members from twisted.internet import defer from twisted.trial import unittest from buildbot.interfaces import LatentWorkerSubstantiatiationCancelled from buildbot.process.properties import Properties from buildbot.test.fake import fakebuild from buildbot.test.fake import fakemaster from buildbot.test.fake import httpclientservice as fakehttpclientservice from buildbot.test.fake.fakeprotocol import FakeTrivialConnection as FakeBot from buildbot.test.reactor import TestReactorMixin from buildbot.worker.marathon import MarathonLatentWorker class TestMarathonLatentWorker(unittest.TestCase, TestReactorMixin): def setUp(self): self.setup_test_reactor(auto_tear_down=False) self.build = Properties(image="busybox:latest", builder="docker_worker") self.worker = None @defer.inlineCallbacks def tearDown(self): if self.worker is not None: class FakeResult: code = 200 self._http.delete = lambda _: defer.succeed(FakeResult()) yield self.worker.master.stopService() self.flushLoggedErrors(LatentWorkerSubstantiatiationCancelled) yield self.tear_down_test_reactor() def test_constructor_normal(self): worker = MarathonLatentWorker('bot', 'tcp://marathon.local', 'foo', 'bar', 'debian:wheezy') # class instantiation configures nothing self.assertEqual(worker._http, None) @defer.inlineCallbacks def makeWorker(self, **kwargs): kwargs.setdefault('image', 'debian:wheezy') worker = MarathonLatentWorker('bot', 'tcp://marathon.local', **kwargs) self.worker = worker master = yield fakemaster.make_master(self, wantData=True) self._http = yield fakehttpclientservice.HTTPClientService.getService( master, self, 'tcp://marathon.local', auth=kwargs.get('auth') ) yield worker.setServiceParent(master) worker.reactor = self.reactor yield master.startService() worker.masterhash = "masterhash" return worker @defer.inlineCallbacks def test_builds_may_be_incompatible(self): worker = self.worker = yield self.makeWorker() # http is lazily created on worker substantiation self.assertEqual(worker.builds_may_be_incompatible, True) @defer.inlineCallbacks def test_start_service(self): worker = self.worker = yield self.makeWorker() # http is lazily created on worker substantiation self.assertNotEqual(worker._http, None) @defer.inlineCallbacks def test_start_worker(self): # http://mesosphere.github.io/marathon/docs/rest-api.html#post-v2-apps worker = yield self.makeWorker() worker.password = "pass" worker.masterFQDN = "master" self._http.expect(method='delete', ep='/v2/apps/buildbot-worker/buildbot-bot-masterhash') self._http.expect( method='post', ep='/v2/apps', json={ 'instances': 1, 'container': { 'docker': {'image': 'rendered:debian:wheezy', 'network': 'BRIDGE'}, 'type': 'DOCKER', }, 'id': 'buildbot-worker/buildbot-bot-masterhash', 'env': { 'BUILDMASTER': "master", 'BUILDMASTER_PORT': '1234', 'WORKERNAME': 'bot', 'WORKERPASS': "pass", }, }, code=201, content_json={'Id': 'id'}, ) self._http.expect(method='delete', ep='/v2/apps/buildbot-worker/buildbot-bot-masterhash') d = worker.substantiate(None, fakebuild.FakeBuildForRendering()) # we simulate a connection worker.attached(FakeBot()) yield d self.assertEqual(worker.instance, {'Id': 'id'}) yield worker.insubstantiate() @defer.inlineCallbacks def test_start_worker_but_no_connection_and_shutdown(self): worker = yield self.makeWorker() worker.password = "pass" worker.masterFQDN = "master" self._http.expect(method='delete', ep='/v2/apps/buildbot-worker/buildbot-bot-masterhash') self._http.expect( method='post', ep='/v2/apps', json={ 'instances': 1, 'container': { 'docker': {'image': 'rendered:debian:wheezy', 'network': 'BRIDGE'}, 'type': 'DOCKER', }, 'id': 'buildbot-worker/buildbot-bot-masterhash', 'env': { 'BUILDMASTER': "master", 'BUILDMASTER_PORT': '1234', 'WORKERNAME': 'bot', 'WORKERPASS': "pass", }, }, code=201, content_json={'Id': 'id'}, ) self._http.expect(method='delete', ep='/v2/apps/buildbot-worker/buildbot-bot-masterhash') d = worker.substantiate(None, fakebuild.FakeBuildForRendering()) self.assertEqual(worker.instance, {'Id': 'id'}) yield worker.insubstantiate() with self.assertRaises(LatentWorkerSubstantiatiationCancelled): yield d @defer.inlineCallbacks def test_start_worker_but_error(self): worker = yield self.makeWorker() self._http.expect(method='delete', ep='/v2/apps/buildbot-worker/buildbot-bot-masterhash') self._http.expect( method='post', ep='/v2/apps', json={ 'instances': 1, 'container': { 'docker': {'image': 'rendered:debian:wheezy', 'network': 'BRIDGE'}, 'type': 'DOCKER', }, 'id': 'buildbot-worker/buildbot-bot-masterhash', 'env': { 'BUILDMASTER': "master", 'BUILDMASTER_PORT': '1234', 'WORKERNAME': 'bot', 'WORKERPASS': "pass", }, }, code=404, content_json={'message': 'image not found'}, ) self._http.expect(method='delete', ep='/v2/apps/buildbot-worker/buildbot-bot-masterhash') d = worker.substantiate(None, fakebuild.FakeBuildForRendering()) self.reactor.advance(0.1) with self.assertRaises(AssertionError): yield d self.assertEqual(worker.instance, None) # teardown makes sure all containers are cleaned up @defer.inlineCallbacks def test_start_worker_with_params(self): # http://mesosphere.github.io/marathon/docs/rest-api.html#post-v2-apps worker = yield self.makeWorker( marathon_extra_config={ 'container': {'docker': {'network': None}}, 'env': {'PARAMETER': 'foo'}, } ) worker.password = "pass" worker.masterFQDN = "master" self._http.expect(method='delete', ep='/v2/apps/buildbot-worker/buildbot-bot-masterhash') self._http.expect( method='post', ep='/v2/apps', json={ 'instances': 1, 'container': { 'docker': {'image': 'rendered:debian:wheezy', 'network': None}, 'type': 'DOCKER', }, 'id': 'buildbot-worker/buildbot-bot-masterhash', 'env': { 'BUILDMASTER': "master", 'BUILDMASTER_PORT': '1234', 'WORKERNAME': 'bot', 'WORKERPASS': "pass", 'PARAMETER': 'foo', }, }, code=201, content_json={'Id': 'id'}, ) self._http.expect(method='delete', ep='/v2/apps/buildbot-worker/buildbot-bot-masterhash') d = worker.substantiate(None, fakebuild.FakeBuildForRendering()) # we simulate a connection worker.attached(FakeBot()) yield d self.assertEqual(worker.instance, {'Id': 'id'}) yield worker.insubstantiate()
8,831
Python
.py
203
32.551724
99
0.596234
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,512
test_libvirt.py
buildbot_buildbot/master/buildbot/test/unit/worker/test_libvirt.py
# This file is part of Buildbot. Buildbot is free software: you can # redistribute it and/or modify it under the terms of the GNU General Public # License as published by the Free Software Foundation, version 2. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more # details. # # You should have received a copy of the GNU General Public License along with # this program; if not, write to the Free Software Foundation, Inc., 51 # Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # Copyright Buildbot Team Members import socket from unittest import mock from parameterized import parameterized from twisted.internet import defer from twisted.trial import unittest from buildbot import config from buildbot.interfaces import LatentWorkerFailedToSubstantiate from buildbot.test.fake import libvirt as libvirtfake from buildbot.test.reactor import TestReactorMixin from buildbot.test.runprocess import ExpectMasterShell from buildbot.test.runprocess import MasterRunProcessMixin from buildbot.worker import libvirt as libvirtworker # The libvirt module has a singleton threadpool within the module which we can't use in tests as # this makes it impossible to run them concurrently. To work around this we introduce a per-test # threadpool and access it through a class instance class TestThreadWithQueue(libvirtworker.ThreadWithQueue): def __init__(self, pool, uri): super().__init__( pool, uri, connect_backoff_start_seconds=0, connect_backoff_multiplier=0, connect_backoff_max_wait_seconds=0, ) def libvirt_open(self): return self.pool.case.libvirt_open(self.uri) class TestServerThreadPool(libvirtworker.ServerThreadPool): ThreadClass = TestThreadWithQueue def __init__(self, case): super().__init__() self.case = case class TestLibvirtWorker(libvirtworker.LibVirtWorker): def __init__(self, case, *args, **kwargs): super().__init__(*args, **kwargs) self.case = case self.pool = case.threadpool class TestException(Exception): pass class TestLibVirtWorker(TestReactorMixin, MasterRunProcessMixin, unittest.TestCase): def setUp(self): self.setup_test_reactor(auto_tear_down=False) self.setup_master_run_process() self.connections = {} self.patch(libvirtworker, "libvirt", libvirtfake) self.threadpool = TestServerThreadPool(self) @defer.inlineCallbacks def tearDown(self): yield self.tear_down_test_reactor() def libvirt_open(self, uri): if uri not in self.connections: raise RuntimeError('Could not find test connection') return self.connections[uri] def add_fake_conn(self, uri): conn = libvirtfake.Connection(uri) self.connections[uri] = conn return conn def create_worker(self, *args, **kwargs): worker = TestLibvirtWorker(self, *args, **kwargs) worker.parent = mock.Mock() worker.parent.master = mock.Mock() worker.parent.master.reactor = self.reactor return worker def raise_libvirt_error(self): # Helper method to be used from lambdas as they don't accept statements raise libvirtfake.libvirtError() def test_constructor_nolibvirt(self): self.patch(libvirtworker, "libvirt", None) with self.assertRaises(config.ConfigErrors): self.create_worker('bot', 'pass', None, 'path', 'path') @defer.inlineCallbacks def test_get_domain_id(self): conn = self.add_fake_conn('fake:///conn') conn.fake_add('bot', 14) bs = self.create_worker('bot', 'pass', hd_image='p', base_image='o', uri='fake:///conn') id = yield bs._get_domain_id() self.assertEqual(id, 14) @defer.inlineCallbacks def test_prepare_base_image_none(self): bs = self.create_worker('bot', 'pass', hd_image='p', base_image=None) yield bs._prepare_base_image() self.assert_all_commands_ran() @defer.inlineCallbacks def test_prepare_base_image_cheap(self): self.expect_commands( ExpectMasterShell([ "qemu-img", "create", "-o", "backing_fmt=qcow2", "-b", "o", "-f", "qcow2", "p", ]) ) bs = self.create_worker('bot', 'pass', hd_image='p', base_image='o') yield bs._prepare_base_image() self.assert_all_commands_ran() @defer.inlineCallbacks def test_prepare_base_image_full(self): self.expect_commands(ExpectMasterShell(["cp", "o", "p"])) bs = self.create_worker('bot', 'pass', hd_image='p', base_image='o') bs.cheap_copy = False yield bs._prepare_base_image() self.assert_all_commands_ran() @defer.inlineCallbacks def test_prepare_base_image_fail(self): self.expect_commands(ExpectMasterShell(["cp", "o", "p"]).exit(1)) bs = self.create_worker('bot', 'pass', hd_image='p', base_image='o') bs.cheap_copy = False with self.assertRaises(LatentWorkerFailedToSubstantiate): yield bs._prepare_base_image() self.assert_all_commands_ran() @defer.inlineCallbacks def _test_stop_instance( self, graceful, fast, expected_destroy, expected_shutdown, shutdown_side_effect=None ): domain = mock.Mock() domain.ID.side_effect = lambda: 14 domain.shutdown.side_effect = shutdown_side_effect conn = self.add_fake_conn('fake:///conn') conn.fake_add_domain('name', domain) bs = self.create_worker( 'name', 'p', hd_image='p', base_image='o', uri='fake:///conn', xml='<xml/>' ) bs.graceful_shutdown = graceful with mock.patch('os.remove') as remove_mock: yield bs.stop_instance(fast=fast) self.assertEqual(int(expected_destroy), domain.destroy.call_count) self.assertEqual(int(expected_shutdown), domain.shutdown.call_count) remove_mock.assert_called_once_with('p') self.assert_all_commands_ran() @defer.inlineCallbacks def test_stop_instance_destroy(self): yield self._test_stop_instance( graceful=False, fast=False, expected_destroy=True, expected_shutdown=False ) @defer.inlineCallbacks def test_stop_instance_shutdown(self): yield self._test_stop_instance( graceful=True, fast=False, expected_destroy=False, expected_shutdown=True ) @defer.inlineCallbacks def test_stop_instance_shutdown_fails(self): yield self._test_stop_instance( graceful=True, fast=False, expected_destroy=True, expected_shutdown=True, shutdown_side_effect=TestException, ) @defer.inlineCallbacks def test_start_instance_connection_fails(self): bs = self.create_worker('b', 'p', hd_image='p', base_image='o', uri='unknown') prep = mock.Mock() prep.side_effect = lambda: defer.succeed(0) self.patch(bs, "_prepare_base_image", prep) with self.assertRaisesRegex(LatentWorkerFailedToSubstantiate, 'Did not receive connection'): yield bs.start_instance(mock.Mock()) self.assertFalse(prep.called) @defer.inlineCallbacks def test_start_instance_already_active(self): conn = self.add_fake_conn('fake:///conn') conn.fake_add('bot', 14) bs = self.create_worker( 'bot', 'p', hd_image='p', base_image='o', uri='fake:///conn', xml='<xml/>' ) prep = mock.Mock() self.patch(bs, "_prepare_base_image", prep) with self.assertRaisesRegex(LatentWorkerFailedToSubstantiate, 'it\'s already active'): yield bs.start_instance(mock.Mock()) self.assertFalse(prep.called) @defer.inlineCallbacks def test_start_instance_domain_id_error(self): conn = self.add_fake_conn('fake:///conn') domain = conn.fake_add('bot', 14) domain.ID = self.raise_libvirt_error bs = self.create_worker( 'bot', 'p', hd_image='p', base_image='o', uri='fake:///conn', xml='<xml/>' ) prep = mock.Mock() self.patch(bs, "_prepare_base_image", prep) with self.assertRaisesRegex(LatentWorkerFailedToSubstantiate, 'while retrieving domain ID'): yield bs.start_instance(mock.Mock()) self.assertFalse(prep.called) @defer.inlineCallbacks def test_start_instance_connection_create_fails(self): bs = self.create_worker( 'bot', 'p', hd_image='p', base_image='o', xml='<xml/>', uri='fake:///conn' ) conn = self.add_fake_conn('fake:///conn') conn.createXML = lambda _, __: self.raise_libvirt_error() prep = mock.Mock() prep.side_effect = lambda: defer.succeed(0) self.patch(bs, "_prepare_base_image", prep) with self.assertRaisesRegex(LatentWorkerFailedToSubstantiate, 'error while starting VM'): yield bs.start_instance(mock.Mock()) self.assertTrue(prep.called) @defer.inlineCallbacks def test_start_instance_domain_create_fails(self): bs = self.create_worker('bot', 'p', hd_image='p', base_image='o', uri='fake:///conn') conn = self.add_fake_conn('fake:///conn') domain = conn.fake_add('bot', -1) domain.create = self.raise_libvirt_error prep = mock.Mock() prep.side_effect = lambda: defer.succeed(0) self.patch(bs, "_prepare_base_image", prep) with self.assertRaisesRegex(LatentWorkerFailedToSubstantiate, 'error while starting VM'): yield bs.start_instance(mock.Mock()) self.assertTrue(prep.called) @defer.inlineCallbacks def test_start_instance_xml(self): self.add_fake_conn('fake:///conn') bs = self.create_worker( 'bot', 'p', hd_image='p', base_image='o', uri='fake:///conn', xml='<xml/>' ) prep = mock.Mock() prep.side_effect = lambda: defer.succeed(0) self.patch(bs, "_prepare_base_image", prep) started = yield bs.start_instance(mock.Mock()) self.assertEqual(started, True) @parameterized.expand([ ('set_fqdn', {'masterFQDN': 'somefqdn'}, 'somefqdn'), ('auto_fqdn', {}, socket.getfqdn()), ]) @defer.inlineCallbacks def test_start_instance_existing_domain(self, name, kwargs, expect_fqdn): conn = self.add_fake_conn('fake:///conn') domain = conn.fake_add('bot', -1) bs = self.create_worker( 'bot', 'p', hd_image='p', base_image='o', uri='fake:///conn', **kwargs ) prep = mock.Mock() prep.side_effect = lambda: defer.succeed(0) self.patch(bs, "_prepare_base_image", prep) started = yield bs.start_instance(mock.Mock()) self.assertEqual(started, True) self.assertEqual( domain.metadata, { 'buildbot': ( libvirtfake.VIR_DOMAIN_METADATA_ELEMENT, 'http://buildbot.net/', f'<auth username="bot" password="p" master="{expect_fqdn}"/>', libvirtfake.VIR_DOMAIN_AFFECT_CONFIG, ) }, )
11,591
Python
.py
263
35.555133
100
0.64021
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,513
test_upcloud.py
buildbot_buildbot/master/buildbot/test/unit/worker/test_upcloud.py
# This file is part of Buildbot. Buildbot is free software: you can # redistribute it and/or modify it under the terms of the GNU General Public # License as published by the Free Software Foundation, version 2. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more # details. # # You should have received a copy of the GNU General Public License along with # this program; if not, write to the Free Software Foundation, Inc., 51 # Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # Copyright Buildbot Team Members import hashlib from twisted.internet import defer from twisted.trial import unittest from buildbot import util from buildbot.config import ConfigErrors from buildbot.interfaces import LatentWorkerFailedToSubstantiate from buildbot.test.fake import fakemaster from buildbot.test.fake import httpclientservice as fakehttpclientservice from buildbot.test.fake.fakebuild import FakeBuildForRendering as FakeBuild from buildbot.test.fake.fakeprotocol import FakeTrivialConnection as FakeBot from buildbot.test.reactor import TestReactorMixin from buildbot.worker import upcloud # Please see https://developers.upcloud.com/ for details upcloudStorageTemplatePayload = { 'storages': { 'storage': [ { 'access': 'public', 'title': 'rendered:test-image', 'uuid': '8b47d21b-b4c3-445d-b75c-5a723ff39681', } ] } } upcloudServerCreatePayload = { 'server': { 'hostname': 'worker', 'password': 'supersecret', 'state': 'maintenance', 'uuid': '438b5b08-4147-4193-bf64-a5318f51d3bd', 'title': 'buildbot-worker-87de7e', 'plan': '1xCPU-1GB', } } upcloudServerStartedPayload = { 'server': { 'hostname': 'worker', 'password': 'supersecret', 'state': 'started', 'uuid': '438b5b08-4147-4193-bf64-a5318f51d3bd', 'title': 'buildbot-worker-87de7e', 'plan': '1xCPU-1GB', } } upcloudServerStoppedPayload = { 'server': { 'hostname': 'worker', 'password': 'supersecret', 'state': 'stopped', 'uuid': '438b5b08-4147-4193-bf64-a5318f51d3bd', 'title': 'buildbot-worker-87de7e', 'plan': '1xCPU-1GB', } } class TestUpcloudWorker(TestReactorMixin, unittest.TestCase): worker = None 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 setupWorker(self, *args, **kwargs): worker = upcloud.UpcloudLatentWorker( *args, api_username='test-api-user', api_password='test-api-password', **kwargs ) master = yield fakemaster.make_master(self, wantData=True) self._http = worker.client = yield fakehttpclientservice.HTTPClientService.getService( master, self, upcloud.DEFAULT_BASE_URL, auth=('test-api-user', 'test-api-password'), debug=False, ) worker.setServiceParent(master) yield master.startService() self.masterhash = hashlib.sha1(util.unicode2bytes(master.name)).hexdigest()[:6] self.addCleanup(master.stopService) self.worker = worker return worker def test_instantiate(self): worker = upcloud.UpcloudLatentWorker( 'test-worker', image='test-image', api_username='test-api-user', api_password='test-api-password', ) self.failUnlessIsInstance(worker, upcloud.UpcloudLatentWorker) def test_missing_config(self): worker = None with self.assertRaises(ConfigErrors): worker = upcloud.UpcloudLatentWorker('test-worker') with self.assertRaises(ConfigErrors): worker = upcloud.UpcloudLatentWorker('test-worker', image='test-image') with self.assertRaises(ConfigErrors): worker = upcloud.UpcloudLatentWorker( 'test-worker', image='test-image', api_username='test-api-user' ) self.assertTrue(worker is None) @defer.inlineCallbacks def test_missing_image(self): worker = yield self.setupWorker('worker', image='no-such-image') self._http.expect( method='get', ep='/storage/template', content_json=upcloudStorageTemplatePayload ) with self.assertRaises(LatentWorkerFailedToSubstantiate): yield worker.substantiate(None, FakeBuild()) @defer.inlineCallbacks def test_start_worker(self): worker = yield self.setupWorker('worker', image='test-image') # resolve image to storage uuid self._http.expect( method='get', ep='/storage/template', content_json=upcloudStorageTemplatePayload ) # actually start server self._http.expect( method='post', ep='/server', params=None, data=None, json={ 'server': { 'zone': 'de-fra1', 'title': 'buildbot-worker-87de7e', 'hostname': 'worker', 'user_data': '', 'login_user': {'username': 'root', 'ssh_keys': {'ssh_key': []}}, 'password_delivery': 'none', 'storage_devices': { 'storage_device': [ { 'action': 'clone', 'storage': '8b47d21b-b4c3-445d-b75c-5a723ff39681', 'title': f'buildbot-worker-{self.masterhash}', 'size': 10, 'tier': 'maxiops', } ] }, 'plan': '1xCPU-1GB', } }, content_json=upcloudServerCreatePayload, code=202, ) # determine it's up & running self._http.expect( method='get', ep='/server/438b5b08-4147-4193-bf64-a5318f51d3bd', content_json=upcloudServerStartedPayload, ) # get root password self._http.expect( method='get', ep='/server/438b5b08-4147-4193-bf64-a5318f51d3bd', content_json=upcloudServerStartedPayload, ) # stop server self._http.expect( method='post', ep='/server/438b5b08-4147-4193-bf64-a5318f51d3bd/stop', json={'stop_server': {'stop_type': 'hard', 'timeout': '1'}}, content_json=upcloudServerStartedPayload, ) # now it's stopped self._http.expect( method='get', ep='/server/438b5b08-4147-4193-bf64-a5318f51d3bd', content_json=upcloudServerStoppedPayload, ) # then delete it self._http.expect( method='delete', ep='/server/438b5b08-4147-4193-bf64-a5318f51d3bd?storages=1', code=204 ) d = worker.substantiate(None, FakeBuild()) yield worker.attached(FakeBot()) yield d
7,391
Python
.py
191
28.848168
99
0.604288
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,514
test_protocols_msgpack.py
buildbot_buildbot/master/buildbot/test/unit/worker/test_protocols_msgpack.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 unittest import mock from parameterized import parameterized from twisted.internet import defer from twisted.trial import unittest from buildbot.process import remotecommand from buildbot.test.fake import fakemaster from buildbot.test.reactor import TestReactorMixin from buildbot.test.util import protocols as util_protocols from buildbot.worker.protocols import base from buildbot.worker.protocols import msgpack class TestListener(TestReactorMixin, unittest.TestCase): @defer.inlineCallbacks def setUp(self): self.setup_test_reactor(auto_tear_down=False) self.master = yield fakemaster.make_master(self) @defer.inlineCallbacks def tearDown(self): yield self.tear_down_test_reactor() def test_constructor(self): listener = msgpack.Listener(self.master) self.assertEqual(listener.master, self.master) self.assertEqual(listener._registrations, {}) @defer.inlineCallbacks def test_update_registration_simple(self): listener = msgpack.Listener(self.master) reg = yield listener.updateRegistration('example', 'pass', 'tcp:1234') self.assertEqual(self.master.msgmanager._registrations, [('tcp:1234', 'example', 'pass')]) self.assertEqual(listener._registrations['example'], ('pass', 'tcp:1234', reg)) @defer.inlineCallbacks def test_update_registration_pass_changed(self): listener = msgpack.Listener(self.master) listener.updateRegistration('example', 'pass', 'tcp:1234') reg1 = yield listener.updateRegistration('example', 'pass1', 'tcp:1234') self.assertEqual(listener._registrations['example'], ('pass1', 'tcp:1234', reg1)) self.assertEqual(self.master.msgmanager._unregistrations, [('tcp:1234', 'example')]) @defer.inlineCallbacks def test_update_registration_port_changed(self): listener = msgpack.Listener(self.master) listener.updateRegistration('example', 'pass', 'tcp:1234') reg1 = yield listener.updateRegistration('example', 'pass', 'tcp:4321') self.assertEqual(listener._registrations['example'], ('pass', 'tcp:4321', reg1)) self.assertEqual(self.master.msgmanager._unregistrations, [('tcp:1234', 'example')]) @defer.inlineCallbacks def test_create_connection(self): listener = msgpack.Listener(self.master) listener.before_connection_setup = mock.Mock() worker = mock.Mock() worker.workername = 'test' protocol = mock.Mock() listener.updateRegistration('example', 'pass', 'tcp:1234') self.master.workers.register(worker) conn = yield listener._create_connection(protocol, worker.workername) listener.before_connection_setup.assert_called_once_with(protocol, worker.workername) self.assertIsInstance(conn, msgpack.Connection) class TestConnectionApi( util_protocols.ConnectionInterfaceTest, TestReactorMixin, unittest.TestCase ): @defer.inlineCallbacks def setUp(self): self.setup_test_reactor(auto_tear_down=False) self.master = yield fakemaster.make_master(self) self.conn = msgpack.Connection(self.master, mock.Mock(), mock.Mock()) @defer.inlineCallbacks def tearDown(self): yield self.tear_down_test_reactor() class TestConnection(TestReactorMixin, unittest.TestCase): @defer.inlineCallbacks def setUp(self): self.setup_test_reactor(auto_tear_down=False) self.master = yield fakemaster.make_master(self) self.protocol = mock.Mock() self.worker = mock.Mock() self.worker.workername = 'test_worker' self.conn = msgpack.Connection(self.master, self.worker, self.protocol) @defer.inlineCallbacks def tearDown(self): yield self.tear_down_test_reactor() def test_constructor(self): self.assertEqual(self.conn.protocol, self.protocol) self.assertEqual(self.conn.master, self.master) self.assertEqual(self.conn.worker, self.worker) @defer.inlineCallbacks def test_attached(self): self.conn.attached(self.protocol) self.worker.attached.assert_called_with(self.conn) self.reactor.pump([10] * 361) self.protocol.get_message_result.assert_called_once_with({'op': 'keepalive'}) self.conn.detached(self.protocol) yield self.conn.waitShutdown() @defer.inlineCallbacks def test_detached(self): self.conn.attached(self.protocol) self.conn.detached(self.protocol) self.assertEqual(self.conn.keepalive_timer, None) self.assertEqual(self.conn.protocol, None) yield self.conn.waitShutdown() def test_lose_connection(self): self.conn.loseConnection() self.assertEqual(self.conn.keepalive_timer, None) self.protocol.transport.abortConnection.assert_called() def test_do_keepalive(self): self.conn._do_keepalive() self.protocol.get_message_result.assert_called_once_with({'op': 'keepalive'}) @defer.inlineCallbacks def test_start_stop_keepalive_timer(self): self.conn.startKeepaliveTimer() self.protocol.get_message_result.assert_not_called() self.reactor.pump([10] * 361) expected_call = [ mock.call({'op': 'keepalive'}), ] self.assertEqual(self.protocol.get_message_result.call_args_list, expected_call) self.reactor.pump([10] * 361) expected_calls = [ mock.call({'op': 'keepalive'}), mock.call({'op': 'keepalive'}), ] self.assertEqual(self.protocol.get_message_result.call_args_list, expected_calls) self.conn.stopKeepaliveTimer() self.reactor.pump([10] * 361) expected_calls = [ mock.call({'op': 'keepalive'}), mock.call({'op': 'keepalive'}), ] self.assertEqual(self.protocol.get_message_result.call_args_list, expected_calls) yield self.conn.waitShutdown() @defer.inlineCallbacks def test_remote_keepalive(self): yield self.conn.remoteKeepalive() self.protocol.get_message_result.assert_called_once_with({'op': 'keepalive'}) @defer.inlineCallbacks def test_remote_print(self): yield self.conn.remotePrint(message='test') self.protocol.get_message_result.assert_called_once_with({'op': 'print', 'message': 'test'}) @defer.inlineCallbacks def test_remote_get_worker_info(self): self.protocol.get_message_result.return_value = defer.succeed({'system': 'posix'}) result = yield self.conn.remoteGetWorkerInfo() self.protocol.get_message_result.assert_called_once_with({'op': 'get_worker_info'}) self.assertEqual(result, {'system': 'posix'}) def set_up_set_builder_list(self, builders, delete_leftover_dirs=True): self.protocol.command_id_to_command_map = {} def get_message_result(*args): d = defer.Deferred() self.d_get_message_result = d return d self.protocol.get_message_result.side_effect = get_message_result self.conn.info = {'basedir': 'testdir'} self.conn.info['delete_leftover_dirs'] = delete_leftover_dirs self.conn.path_module = os.path d = self.conn.remoteSetBuilderList(builders) return d def check_message_send_response(self, command_name, args, update_msg): command_id = remotecommand.RemoteCommand.get_last_generated_command_id() self.protocol.get_message_result.assert_called_once_with({ 'op': 'start_command', 'command_id': command_id, 'command_name': command_name, 'args': args, }) self.protocol.get_message_result.reset_mock() self.d_get_message_result.callback(None) remote_command = self.protocol.command_id_to_command_map[command_id] remote_command.remote_update_msgpack(update_msg) remote_command.remote_complete(None) def check_message_set_worker_settings(self): newline_re = r'(\r\n|\r(?=.)|\033\[u|\033\[[0-9]+;[0-9]+[Hf]|\033\[2J|\x08+)' self.protocol.get_message_result.assert_called_once_with({ 'op': 'set_worker_settings', 'args': { 'newline_re': newline_re, 'max_line_length': 4096, 'buffer_timeout': 5, 'buffer_size': 64 * 1024, }, }) self.protocol.get_message_result.reset_mock() self.d_get_message_result.callback(None) @defer.inlineCallbacks def test_remote_set_builder_list_no_rmdir(self): d = self.set_up_set_builder_list([('builder1', 'test_dir1'), ('builder2', 'test_dir2')]) self.check_message_set_worker_settings() self.check_message_send_response( 'listdir', {'path': 'testdir'}, [('files', ['dir1', 'dir2', 'dir3']), ('rc', 0)] ) path = os.path.join('testdir', 'dir1') self.check_message_send_response('stat', {'path': path}, [('stat', (1,)), ('rc', 0)]) path = os.path.join('testdir', 'dir2') self.check_message_send_response('stat', {'path': path}, [('stat', (1,)), ('rc', 0)]) path = os.path.join('testdir', 'dir3') self.check_message_send_response('stat', {'path': path}, [('stat', (1,)), ('rc', 0)]) paths = [ os.path.join('testdir', 'info'), os.path.join('testdir', 'test_dir1'), os.path.join('testdir', 'test_dir2'), ] self.check_message_send_response('mkdir', {'paths': paths}, [('rc', 0)]) r = yield d self.assertEqual(r, ['builder1', 'builder2']) self.protocol.get_message_result.assert_not_called() @defer.inlineCallbacks def test_remote_set_builder_list_do_rmdir(self): d = self.set_up_set_builder_list([('builder1', 'test_dir1'), ('builder2', 'test_dir2')]) self.check_message_set_worker_settings() self.check_message_send_response( 'listdir', {'path': 'testdir'}, [('files', ['dir1', 'dir2', 'dir3']), ('rc', 0)] ) path = os.path.join('testdir', 'dir1') self.check_message_send_response( 'stat', {'path': path}, [('stat', (stat.S_IFDIR,)), ('rc', 0)] ) path = os.path.join('testdir', 'dir2') self.check_message_send_response( 'stat', {'path': path}, [('stat', (stat.S_IFDIR,)), ('rc', 0)] ) path = os.path.join('testdir', 'dir3') self.check_message_send_response( 'stat', {'path': path}, [('stat', (stat.S_IFDIR,)), ('rc', 0)] ) paths = [ os.path.join('testdir', 'dir1'), os.path.join('testdir', 'dir2'), os.path.join('testdir', 'dir3'), ] self.check_message_send_response('rmdir', {'paths': paths}, [('rc', 0)]) paths = [ os.path.join('testdir', 'info'), os.path.join('testdir', 'test_dir1'), os.path.join('testdir', 'test_dir2'), ] self.check_message_send_response('mkdir', {'paths': paths}, [('rc', 0)]) r = yield d self.assertEqual(r, ['builder1', 'builder2']) self.protocol.get_message_result.assert_not_called() @defer.inlineCallbacks def test_remote_set_builder_list_no_rmdir_leave_leftover_dirs(self): d = self.set_up_set_builder_list( [('builder1', 'test_dir1'), ('builder2', 'test_dir2')], delete_leftover_dirs=False ) self.check_message_set_worker_settings() self.check_message_send_response( 'listdir', {'path': 'testdir'}, [('files', ['dir1', 'dir2', 'dir3']), ('rc', 0)] ) paths = [ os.path.join('testdir', 'info'), os.path.join('testdir', 'test_dir1'), os.path.join('testdir', 'test_dir2'), ] self.check_message_send_response('mkdir', {'paths': paths}, [('rc', 0)]) r = yield d self.assertEqual(r, ['builder1', 'builder2']) self.protocol.get_message_result.assert_not_called() @defer.inlineCallbacks def test_remote_set_builder_list_no_mkdir_from_files(self): d = self.set_up_set_builder_list([('builder1', 'test_dir1'), ('builder2', 'test_dir2')]) self.check_message_set_worker_settings() self.check_message_send_response( 'listdir', {'path': 'testdir'}, [('files', ['dir1', 'test_dir2']), ('rc', 0)] ) path = os.path.join('testdir', 'dir1') self.check_message_send_response('stat', {'path': path}, [('stat', (1,)), ('rc', 0)]) paths = [os.path.join('testdir', 'info'), os.path.join('testdir', 'test_dir1')] self.check_message_send_response('mkdir', {'paths': paths}, [('rc', 0)]) r = yield d self.assertEqual(r, ['builder1', 'builder2']) self.protocol.get_message_result.assert_not_called() @defer.inlineCallbacks def test_remote_set_builder_list_no_mkdir(self): d = self.set_up_set_builder_list([('builder1', 'test_dir1'), ('builder2', 'test_dir2')]) self.check_message_set_worker_settings() self.check_message_send_response( 'listdir', {'path': 'testdir'}, [('files', ['test_dir1', 'test_dir2', 'info']), ('rc', 0)], ) r = yield d self.assertEqual(r, ['builder1', 'builder2']) self.protocol.get_message_result.assert_not_called() @defer.inlineCallbacks def test_remote_set_builder_list_key_is_missing(self): d = self.set_up_set_builder_list([('builder1', 'test_dir1'), ('builder2', 'test_dir2')]) self.check_message_set_worker_settings() self.check_message_send_response( 'listdir', {'path': 'testdir'}, [('no_key', []), ('rc', 0)] ) with self.assertRaisesRegex(Exception, "Key 'files' is missing."): yield d self.protocol.get_message_result.assert_not_called() @defer.inlineCallbacks def test_remote_set_builder_list_key_rc_not_zero(self): d = self.set_up_set_builder_list([('builder1', 'test_dir1'), ('builder2', 'test_dir2')]) self.check_message_set_worker_settings() self.check_message_send_response('listdir', {'path': 'testdir'}, [('rc', 123)]) with self.assertRaisesRegex(Exception, "Error number: 123"): yield d self.protocol.get_message_result.assert_not_called() @parameterized.expand([ ('want_stdout', 0, False), ('want_stdout', 1, True), ('want_stderr', 0, False), ('want_stderr', 1, True), (None, None, None), ]) @defer.inlineCallbacks def test_remote_start_command_args_update(self, arg_name, arg_value, expected_value): self.protocol.get_message_result.return_value = defer.succeed(None) rc_instance = base.RemoteCommandImpl() result_command_id_to_command_map = {1: rc_instance} self.protocol.command_id_to_command_map = {} args = {'args': 'args'} if arg_name is not None: args[arg_name] = arg_value yield self.conn.remoteStartCommand(rc_instance, 'builder', 1, 'command', args) expected_args = args.copy() if arg_name is not None: expected_args[arg_name] = expected_value self.assertEqual(result_command_id_to_command_map, self.protocol.command_id_to_command_map) self.protocol.get_message_result.assert_called_with({ 'op': 'start_command', 'builder_name': 'builder', 'command_id': 1, 'command_name': 'command', 'args': expected_args, }) @defer.inlineCallbacks def test_remote_shutdown(self): self.protocol.get_message_result.return_value = defer.succeed(None) yield self.conn.remoteShutdown() self.protocol.get_message_result.assert_called_once_with({'op': 'shutdown'}) @defer.inlineCallbacks def test_remote_interrupt_command(self): self.protocol.get_message_result.return_value = defer.succeed(None) yield self.conn.remoteInterruptCommand('builder', 1, 'test') self.protocol.get_message_result.assert_called_once_with({ 'op': 'interrupt_command', 'builder_name': 'builder', 'command_id': 1, 'why': 'test', }) def test_perspective_keepalive(self): self.conn.perspective_keepalive() self.conn.worker.messageReceivedFromWorker.assert_called_once_with() def test_perspective_shutdown(self): self.conn.perspective_shutdown() self.conn.worker.shutdownRequested.assert_called_once_with() self.conn.worker.messageReceivedFromWorker.assert_called_once_with()
17,498
Python
.py
362
39.790055
100
0.638641
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,515
test_protocols_manager_pbmanager.py
buildbot_buildbot/master/buildbot/test/unit/worker/test_protocols_manager_pbmanager.py
# This file is part of Buildbot. Buildbot is free software: you can # redistribute it and/or modify it under the terms of the GNU General Public # License as published by the Free Software Foundation, version 2. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more # details. # # You should have received a copy of the GNU General Public License along with # this program; if not, write to the Free Software Foundation, Inc., 51 # Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # Copyright Buildbot Team Members """ Test clean shutdown functionality of the master """ from unittest import mock from twisted.cred import credentials from twisted.internet import defer from twisted.spread import pb from twisted.trial import unittest from buildbot.worker.protocols.manager.pb import PBManager class FakeMaster: initLock = defer.DeferredLock() def addService(self, svc): pass @property def master(self): return self class TestPBManager(unittest.TestCase): @defer.inlineCallbacks def setUp(self): self.pbm = PBManager() yield self.pbm.setServiceParent(FakeMaster()) self.pbm.startService() self.connections = [] def tearDown(self): return self.pbm.stopService() def perspectiveFactory(self, mind, username): persp = mock.Mock() persp.is_my_persp = True persp.attached = lambda mind: defer.succeed(None) self.connections.append(username) return defer.succeed(persp) @defer.inlineCallbacks def test_register_unregister(self): portstr = "tcp:0:interface=127.0.0.1" reg = yield self.pbm.register(portstr, "boris", "pass", self.perspectiveFactory) # make sure things look right self.assertIn(portstr, self.pbm.dispatchers) disp = self.pbm.dispatchers[portstr] self.assertIn('boris', disp.users) # we can't actually connect to it, as that requires finding the # dynamically allocated port number which is buried out of reach; # however, we can try the requestAvatar and requestAvatarId methods. username = yield disp.requestAvatarId(credentials.UsernamePassword(b'boris', b'pass')) self.assertEqual(username, b'boris') avatar = yield disp.requestAvatar(b'boris', mock.Mock(), pb.IPerspective) _, persp, __ = avatar self.assertTrue(persp.is_my_persp) self.assertIn('boris', self.connections) yield reg.unregister() @defer.inlineCallbacks def test_register_no_user(self): portstr = "tcp:0:interface=127.0.0.1" reg = yield self.pbm.register(portstr, "boris", "pass", self.perspectiveFactory) # make sure things look right self.assertIn(portstr, self.pbm.dispatchers) disp = self.pbm.dispatchers[portstr] self.assertIn('boris', disp.users) # we can't actually connect to it, as that requires finding the # dynamically allocated port number which is buried out of reach; # however, we can try the requestAvatar and requestAvatarId methods. username = yield disp.requestAvatarId(credentials.UsernamePassword(b'boris', b'pass')) self.assertEqual(username, b'boris') with self.assertRaises(ValueError): yield disp.requestAvatar(b'notboris', mock.Mock(), pb.IPerspective) self.assertNotIn('boris', self.connections) yield reg.unregister() @defer.inlineCallbacks def test_requestAvatarId_noinitLock(self): portstr = "tcp:0:interface=127.0.0.1" reg = yield self.pbm.register(portstr, "boris", "pass", self.perspectiveFactory) disp = self.pbm.dispatchers[portstr] d = disp.requestAvatarId(credentials.UsernamePassword(b'boris', b'pass')) self.assertTrue(d.called, "requestAvatarId should have been called since the lock is free") yield reg.unregister() @defer.inlineCallbacks def test_requestAvatarId_initLock(self): portstr = "tcp:0:interface=127.0.0.1" reg = yield self.pbm.register(portstr, "boris", "pass", self.perspectiveFactory) disp = self.pbm.dispatchers[portstr] try: # simulate a reconfig/restart in progress yield self.pbm.master.initLock.acquire() # try to authenticate while the lock is locked d = disp.requestAvatarId(credentials.UsernamePassword(b'boris', b'pass')) self.assertFalse(d.called, "requestAvatarId should block until the lock is released") finally: # release the lock, it should allow for auth to proceed yield self.pbm.master.initLock.release() self.assertTrue( d.called, "requestAvatarId should have been called after the lock was released" ) yield reg.unregister()
5,019
Python
.py
106
40.188679
99
0.701434
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,516
test_base.py
buildbot_buildbot/master/buildbot/test/unit/worker/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 parameterized import parameterized from twisted.internet import defer from twisted.trial import unittest from buildbot import config from buildbot import locks from buildbot.machine.base import Machine from buildbot.plugins import util from buildbot.process import properties from buildbot.secrets.manager import SecretManager from buildbot.test import fakedb from buildbot.test.fake import bworkermanager from buildbot.test.fake import fakemaster from buildbot.test.fake import fakeprotocol from buildbot.test.fake import worker from buildbot.test.fake.secrets import FakeSecretStorage from buildbot.test.reactor import TestReactorMixin from buildbot.test.util import interfaces from buildbot.test.util import logging from buildbot.worker import AbstractLatentWorker from buildbot.worker import base class ConcreteWorker(base.AbstractWorker): pass class FakeBuilder: def getBuilderId(self): return defer.succeed(1) class WorkerInterfaceTests(interfaces.InterfaceTests): def test_attr_workername(self): self.assertTrue(hasattr(self.wrk, 'workername')) def test_attr_properties(self): self.assertTrue(hasattr(self.wrk, 'properties')) def test_attr_defaultProperties(self): self.assertTrue(hasattr(self.wrk, 'defaultProperties')) @defer.inlineCallbacks def test_attr_worker_basedir(self): yield self.callAttached() self.assertIsInstance(self.wrk.worker_basedir, str) @defer.inlineCallbacks def test_attr_path_module(self): yield self.callAttached() self.assertTrue(hasattr(self.wrk, 'path_module')) @defer.inlineCallbacks def test_attr_worker_system(self): yield self.callAttached() self.assertTrue(hasattr(self.wrk, 'worker_system')) def test_signature_acquireLocks(self): @self.assertArgSpecMatches(self.wrk.acquireLocks) def acquireLocks(self): pass def test_signature_releaseLocks(self): @self.assertArgSpecMatches(self.wrk.releaseLocks) def releaseLocks(self): pass def test_signature_attached(self): @self.assertArgSpecMatches(self.wrk.attached) def attached(self, conn): pass def test_signature_detached(self): @self.assertArgSpecMatches(self.wrk.detached) def detached(self): pass def test_signature_addWorkerForBuilder(self): @self.assertArgSpecMatches(self.wrk.addWorkerForBuilder) def addWorkerForBuilder(self, wfb): pass def test_signature_removeWorkerForBuilder(self): @self.assertArgSpecMatches(self.wrk.removeWorkerForBuilder) def removeWorkerForBuilder(self, wfb): pass def test_signature_buildFinished(self): @self.assertArgSpecMatches(self.wrk.buildFinished) def buildFinished(self, wfb): pass def test_signature_canStartBuild(self): @self.assertArgSpecMatches(self.wrk.canStartBuild) def canStartBuild(self): pass class RealWorkerItfc(TestReactorMixin, unittest.TestCase, WorkerInterfaceTests): def setUp(self): self.setup_test_reactor(auto_tear_down=False) self.wrk = ConcreteWorker('wrk', 'pa') @defer.inlineCallbacks def tearDown(self): yield self.tear_down_test_reactor() @defer.inlineCallbacks def callAttached(self): self.master = yield fakemaster.make_master(self, wantData=True) yield self.master.workers.disownServiceParent() self.workers = bworkermanager.FakeWorkerManager() yield self.workers.setServiceParent(self.master) self.master.workers = self.workers yield self.wrk.setServiceParent(self.master.workers) self.conn = fakeprotocol.FakeConnection(self.wrk) yield self.wrk.attached(self.conn) class FakeWorkerItfc(TestReactorMixin, unittest.TestCase, WorkerInterfaceTests): @defer.inlineCallbacks def setUp(self): self.setup_test_reactor(auto_tear_down=False) self.master = yield fakemaster.make_master(self) self.wrk = worker.FakeWorker(self.master) @defer.inlineCallbacks def tearDown(self): yield self.tear_down_test_reactor() def callAttached(self): self.conn = fakeprotocol.FakeConnection(self.wrk) return self.wrk.attached(self.conn) class TestAbstractWorker(logging.LoggingMixin, TestReactorMixin, unittest.TestCase): @defer.inlineCallbacks def setUp(self): self.setup_test_reactor(auto_tear_down=False) self.setUpLogging() self.master = yield fakemaster.make_master(self, wantDb=True, wantData=True) self.botmaster = self.master.botmaster yield self.master.workers.disownServiceParent() self.workers = self.master.workers = bworkermanager.FakeWorkerManager() yield self.workers.setServiceParent(self.master) @defer.inlineCallbacks def tearDown(self): yield self.tear_down_test_reactor() @defer.inlineCallbacks def createWorker(self, name='bot', password='pass', attached=False, configured=True, **kwargs): worker = ConcreteWorker(name, password, **kwargs) if configured: yield worker.setServiceParent(self.workers) if attached: worker.conn = fakeprotocol.FakeConnection(worker) return worker @defer.inlineCallbacks def createMachine(self, name, configured=True, **kwargs): machine = Machine(name) if configured: yield machine.setServiceParent(self.master.machine_manager) return machine @defer.inlineCallbacks def test_constructor_minimal(self): bs = yield self.createWorker('bot', 'pass') yield bs.startService() self.assertEqual(bs.workername, 'bot') self.assertEqual(bs.password, 'pass') self.assertEqual(bs.max_builds, None) self.assertEqual(bs.notify_on_missing, []) self.assertEqual(bs.missing_timeout, ConcreteWorker.DEFAULT_MISSING_TIMEOUT) self.assertEqual(bs.properties.getProperty('workername'), 'bot') self.assertEqual(bs.access, []) @defer.inlineCallbacks def test_constructor_secrets(self): fake_storage_service = FakeSecretStorage() secret_service = SecretManager() secret_service.services = [fake_storage_service] yield secret_service.setServiceParent(self.master) fake_storage_service.reconfigService(secretdict={"passkey": "1234"}) bs = yield self.createWorker('bot', util.Secret('passkey')) yield bs.startService() self.assertEqual(bs.password, '1234') @defer.inlineCallbacks def test_constructor_full(self): lock1 = locks.MasterLock('lock1') lock2 = locks.MasterLock('lock2') access1 = lock1.access('counting') access2 = lock2.access('counting') bs = yield self.createWorker( 'bot', 'pass', max_builds=2, notify_on_missing=['[email protected]'], missing_timeout=120, properties={'a': 'b'}, locks=[access1, access2], ) yield bs.startService() self.assertEqual(bs.max_builds, 2) self.assertEqual(bs.notify_on_missing, ['[email protected]']) self.assertEqual(bs.missing_timeout, 120) self.assertEqual(bs.properties.getProperty('a'), 'b') self.assertEqual(bs.access, [access1, access2]) @defer.inlineCallbacks def test_constructor_notify_on_missing_not_list(self): bs = yield self.createWorker('bot', 'pass', notify_on_missing='[email protected]') yield bs.startService() # turned into a list: self.assertEqual(bs.notify_on_missing, ['[email protected]']) def test_constructor_notify_on_missing_not_string(self): with self.assertRaises(config.ConfigErrors): ConcreteWorker('bot', 'pass', notify_on_missing=['[email protected]', 13]) @defer.inlineCallbacks def do_test_reconfigService(self, old, new, existingRegistration=True): old.parent = self.master if existingRegistration: old.registration = bworkermanager.FakeWorkerRegistration(old) old.missing_timer = mock.Mock(name='missing_timer') if not old.running: yield old.startService() yield old.reconfigServiceWithSibling(new) @defer.inlineCallbacks def test_reconfigService_attrs(self): old = yield self.createWorker( 'bot', 'pass', max_builds=2, notify_on_missing=['[email protected]'], missing_timeout=120, properties={'a': 'b'}, ) new = yield self.createWorker( 'bot', 'pass', configured=False, max_builds=3, notify_on_missing=['[email protected]'], missing_timeout=121, properties={'a': 'c'}, ) old.updateWorker = mock.Mock(side_effect=lambda: defer.succeed(None)) yield self.do_test_reconfigService(old, new) self.assertEqual(old.max_builds, 3) self.assertEqual(old.notify_on_missing, ['[email protected]']) self.assertEqual(old.missing_timeout, 121) self.assertEqual(old.properties.getProperty('a'), 'c') self.assertEqual(old.registration.updates, ['bot']) self.assertTrue(old.updateWorker.called) @defer.inlineCallbacks def test_reconfigService_has_properties(self): old = yield self.createWorker(name="bot", password="pass") yield self.do_test_reconfigService(old, old) self.assertTrue(old.properties.getProperty('workername'), 'bot') @defer.inlineCallbacks def test_setupProperties(self): props = properties.Properties() props.setProperty('foo', 1, 'Scheduler') props.setProperty('bar', 'bleh', 'Change') props.setProperty('omg', 'wtf', 'Builder') wrkr = yield self.createWorker( 'bot', 'passwd', defaultProperties={'bar': 'onoes', 'cuckoo': 42} ) wrkr.setupProperties(props) self.assertEqual(props.getProperty('bar'), 'bleh') self.assertEqual(props.getProperty('cuckoo'), 42) @defer.inlineCallbacks def test_reconfigService_initial_registration(self): old = yield self.createWorker('bot', 'pass') yield self.do_test_reconfigService(old, old, existingRegistration=False) self.assertIn('bot', self.master.workers.registrations) self.assertEqual(old.registration.updates, ['bot']) @defer.inlineCallbacks def test_reconfigService_builder(self): old = yield self.createWorker('bot', 'pass') yield self.do_test_reconfigService(old, old) # initial configuration, there is no builder configured self.assertEqual(old._configured_builderid_list, []) workers = yield self.master.data.get(('workers',)) self.assertEqual(len(workers[0]['configured_on']), 0) new = yield self.createWorker('bot', 'pass', configured=False) # we create a fake builder, and associate to the master self.botmaster.builders['bot'] = [FakeBuilder()] yield self.master.db.insert_test_data([ fakedb.Builder(id=1, name='builder'), fakedb.BuilderMaster(builderid=1, masterid=824), ]) # on reconfig, the db should see the builder configured for this worker yield old.reconfigServiceWithSibling(new) self.assertEqual(old._configured_builderid_list, [1]) workers = yield self.master.data.get(('workers',)) self.assertEqual(len(workers[0]['configured_on']), 1) self.assertEqual(workers[0]['configured_on'][0]['builderid'], 1) @defer.inlineCallbacks def test_reconfig_service_no_machine(self): old = yield self.createWorker('bot', 'pass') self.assertIsNone(old.machine) yield self.do_test_reconfigService(old, old) self.assertIsNone(old.machine) @defer.inlineCallbacks def test_reconfig_service_with_machine_initial(self): machine = yield self.createMachine('machine1') old = yield self.createWorker('bot', 'pass', machine_name='machine1') self.assertIsNone(old.machine) yield self.do_test_reconfigService(old, old) self.assertIs(old.machine, machine) @defer.inlineCallbacks def test_reconfig_service_with_unknown_machine(self): old = yield self.createWorker('bot', 'pass', machine_name='machine1') self.assertIsNone(old.machine) yield self.do_test_reconfigService(old, old) self.assertLogged('Unknown machine') @parameterized.expand([ ('None_to_machine_initial', False, None, None, 'machine1', 'machine1'), ('None_to_machine', True, None, None, 'machine1', 'machine1'), ('machine_to_None_initial', False, 'machine1', None, None, None), ('machine_to_None', True, 'machine1', 'machine1', None, None), ('machine_to_same_machine_initial', False, 'machine1', None, 'machine1', 'machine1'), ('machine_to_same_machine', True, 'machine1', 'machine1', 'machine1', 'machine1'), ('machine_to_another_machine_initial', False, 'machine1', None, 'machine2', 'machine2'), ('machine_to_another_machine', True, 'machine1', 'machine1', 'machine2', 'machine2'), ]) @defer.inlineCallbacks def test_reconfig_service_machine( self, test_name, do_initial_self_reconfig, old_machine_name, expected_old_machine_name, new_machine_name, expected_new_machine_name, ): machine1 = yield self.createMachine('machine1') machine2 = yield self.createMachine('machine2') name_to_machine = { None: None, machine1.name: machine1, machine2.name: machine2, } expected_old_machine = name_to_machine[expected_old_machine_name] expected_new_machine = name_to_machine[expected_new_machine_name] old = yield self.createWorker('bot', 'pass', machine_name=old_machine_name) new = yield self.createWorker( 'bot', 'pass', configured=False, machine_name=new_machine_name ) if do_initial_self_reconfig: yield self.do_test_reconfigService(old, old) self.assertIs(old.machine, expected_old_machine) yield self.do_test_reconfigService(old, new) self.assertIs(old.machine, expected_new_machine) @defer.inlineCallbacks def test_stopService(self): worker = yield self.createWorker() yield worker.startService() reg = worker.registration yield worker.stopService() self.assertTrue(reg.unregistered) self.assertEqual(worker.registration, None) # FIXME: Test that reconfig properly deals with # 1) locks # 2) telling worker about builder # 3) missing timer # in both the initial config and a reconfiguration. def test_startMissingTimer_no_parent(self): bs = ConcreteWorker('bot', 'pass', notify_on_missing=['abc'], missing_timeout=10) bs.startMissingTimer() self.assertEqual(bs.missing_timer, None) def test_startMissingTimer_no_timeout(self): bs = ConcreteWorker('bot', 'pass', notify_on_missing=['abc'], missing_timeout=0) bs.parent = mock.Mock() bs.startMissingTimer() self.assertEqual(bs.missing_timer, None) def test_startMissingTimer_no_notify(self): bs = ConcreteWorker('bot', 'pass', missing_timeout=3600) bs.parent = mock.Mock() bs.running = True bs.startMissingTimer() self.assertNotEqual(bs.missing_timer, None) def test_missing_timer(self): bs = ConcreteWorker('bot', 'pass', notify_on_missing=['abc'], missing_timeout=100) bs.parent = mock.Mock() bs.running = True bs.startMissingTimer() self.assertNotEqual(bs.missing_timer, None) bs.stopMissingTimer() self.assertEqual(bs.missing_timer, None) @defer.inlineCallbacks def test_setServiceParent_started(self): master = self.master bsmanager = master.workers yield master.startService() bs = ConcreteWorker('bot', 'pass') yield bs.setServiceParent(bsmanager) self.assertEqual(bs.manager, bsmanager) self.assertEqual(bs.parent, bsmanager) self.assertEqual(bsmanager.master, master) self.assertEqual(bs.master, master) @defer.inlineCallbacks def test_setServiceParent_masterLocks(self): """ http://trac.buildbot.net/ticket/2278 """ master = self.master bsmanager = master.workers yield master.startService() lock = locks.MasterLock('masterlock') bs = ConcreteWorker('bot', 'pass', locks=[lock.access("counting")]) yield bs.setServiceParent(bsmanager) @defer.inlineCallbacks def test_setServiceParent_workerLocks(self): """ http://trac.buildbot.net/ticket/2278 """ master = self.master bsmanager = master.workers yield master.startService() lock = locks.WorkerLock('lock') bs = ConcreteWorker('bot', 'pass', locks=[lock.access("counting")]) yield bs.setServiceParent(bsmanager) @defer.inlineCallbacks def test_startService_paused_true(self): """Test that paused state is restored on a buildbot restart""" yield self.master.db.insert_test_data([fakedb.Worker(id=9292, name='bot', paused=1)]) worker = yield self.createWorker() yield worker.startService() self.assertTrue(worker.isPaused()) self.assertFalse(worker._graceful) @defer.inlineCallbacks def test_startService_graceful_true(self): """Test that graceful state is NOT restored on a buildbot restart""" yield self.master.db.insert_test_data([fakedb.Worker(id=9292, name='bot', graceful=1)]) worker = yield self.createWorker() yield worker.startService() self.assertFalse(worker.isPaused()) self.assertFalse(worker._graceful) @defer.inlineCallbacks def test_startService_getWorkerInfo_empty(self): worker = yield self.createWorker() yield worker.startService() self.assertEqual(len(worker.info.asDict()), 0) # check that a new worker row was added for this worker bs = yield self.master.db.workers.getWorker(name='bot') self.assertEqual(bs.name, 'bot') @defer.inlineCallbacks def test_startService_getWorkerInfo_fromDb(self): yield self.master.db.insert_test_data([ fakedb.Worker( id=9292, name='bot', info={ 'admin': 'TheAdmin', 'host': 'TheHost', 'access_uri': 'TheURI', 'version': 'TheVersion', }, ) ]) worker = yield self.createWorker() yield worker.startService() self.assertEqual(worker.workerid, 9292) self.assertEqual( worker.info.asDict(), { 'version': ('TheVersion', 'Worker'), 'admin': ('TheAdmin', 'Worker'), 'host': ('TheHost', 'Worker'), 'access_uri': ('TheURI', 'Worker'), }, ) @defer.inlineCallbacks def test_attached_remoteGetWorkerInfo(self): worker = yield self.createWorker() yield worker.startService() ENVIRON = {} COMMANDS = {'cmd1': '1', 'cmd2': '1'} conn = fakeprotocol.FakeConnection(worker) conn.info = { 'admin': 'TheAdmin', 'host': 'TheHost', 'access_uri': 'TheURI', 'environ': ENVIRON, 'basedir': 'TheBaseDir', 'system': 'TheWorkerSystem', 'version': 'TheVersion', 'worker_commands': COMMANDS, } yield worker.attached(conn) self.assertEqual( worker.info.asDict(), { 'version': ('TheVersion', 'Worker'), 'admin': ('TheAdmin', 'Worker'), 'host': ('TheHost', 'Worker'), 'access_uri': ('TheURI', 'Worker'), 'basedir': ('TheBaseDir', 'Worker'), 'system': ('TheWorkerSystem', 'Worker'), }, ) self.assertEqual(worker.worker_environ, ENVIRON) self.assertEqual(worker.worker_basedir, 'TheBaseDir') self.assertEqual(worker.worker_system, 'TheWorkerSystem') self.assertEqual(worker.worker_commands, COMMANDS) @defer.inlineCallbacks def test_attached_callsMaybeStartBuildsForWorker(self): worker = yield self.createWorker() yield worker.startService() yield worker.reconfigServiceWithSibling(worker) conn = fakeprotocol.FakeConnection(worker) conn.info = {} yield worker.attached(conn) self.assertEqual(self.botmaster.buildsStartedForWorkers, ["bot"]) @defer.inlineCallbacks def test_attached_workerInfoUpdates(self): # put in stale info: yield self.master.db.insert_test_data([ fakedb.Worker( name='bot', info={ 'admin': 'WrongAdmin', 'host': 'WrongHost', 'access_uri': 'WrongURI', 'version': 'WrongVersion', }, ) ]) worker = yield self.createWorker() yield worker.startService() conn = fakeprotocol.FakeConnection(worker) conn.info = { 'admin': 'TheAdmin', 'host': 'TheHost', 'access_uri': 'TheURI', 'version': 'TheVersion', } yield worker.attached(conn) self.assertEqual( worker.info.asDict(), { 'version': ('TheVersion', 'Worker'), 'admin': ('TheAdmin', 'Worker'), 'host': ('TheHost', 'Worker'), 'access_uri': ('TheURI', 'Worker'), }, ) # and the db is updated too: db_worker = yield self.master.db.workers.getWorker(name="bot") self.assertEqual(db_worker.workerinfo['admin'], 'TheAdmin') self.assertEqual(db_worker.workerinfo['host'], 'TheHost') self.assertEqual(db_worker.workerinfo['access_uri'], 'TheURI') self.assertEqual(db_worker.workerinfo['version'], 'TheVersion') @defer.inlineCallbacks def test_double_attached(self): worker = yield self.createWorker() yield worker.startService() conn = fakeprotocol.FakeConnection(worker) yield worker.attached(conn) conn = fakeprotocol.FakeConnection(worker) with self.assertRaisesRegex( AssertionError, "bot: fake_peer connecting, but we are already connected to: fake_peer" ): yield worker.attached(conn) @defer.inlineCallbacks def test_worker_shutdown(self): worker = yield self.createWorker(attached=True) yield worker.startService() yield worker.shutdown() self.assertEqual( worker.conn.remoteCalls, [('remoteSetBuilderList', []), ('remoteShutdown',)] ) @defer.inlineCallbacks def test_worker_shutdown_not_connected(self): worker = yield self.createWorker(attached=False) yield worker.startService() # No exceptions should be raised here yield worker.shutdown() @defer.inlineCallbacks def test_shutdownRequested(self): worker = yield self.createWorker(attached=False) yield worker.startService() yield worker.shutdownRequested() self.assertEqual(worker._graceful, True) @defer.inlineCallbacks def test_missing_timer_missing(self): worker = yield self.createWorker(attached=False, missing_timeout=1) yield worker.startService() self.assertNotEqual(worker.missing_timer, None) yield self.reactor.advance(1) self.assertEqual(worker.missing_timer, None) self.assertEqual(len(self.master.data.updates.missingWorkers), 1) @defer.inlineCallbacks def test_missing_timer_stopped(self): worker = yield self.createWorker(attached=False, missing_timeout=1) yield worker.startService() self.assertNotEqual(worker.missing_timer, None) yield worker.stopService() self.assertEqual(worker.missing_timer, None) self.assertEqual(len(self.master.data.updates.missingWorkers), 0) @defer.inlineCallbacks def test_worker_actions_stop(self): worker = yield self.createWorker(attached=False) yield worker.startService() worker.controlWorker(("worker", 1, "stop"), {'reason': "none"}) self.assertEqual(worker._graceful, True) @defer.inlineCallbacks def test_worker_actions_kill(self): worker = yield self.createWorker(attached=False) yield worker.startService() worker.controlWorker(("worker", 1, "kill"), {'reason': "none"}) self.assertEqual(worker.conn, None) @defer.inlineCallbacks def test_worker_actions_pause(self): worker = yield self.createWorker(attached=False) yield worker.startService() self.assertTrue(worker.canStartBuild()) worker.controlWorker(("worker", 1, "pause"), {"reason": "none"}) self.assertEqual(worker._paused, True) self.assertFalse(worker.canStartBuild()) worker.controlWorker(("worker", 1, "unpause"), {"reason": "none"}) self.assertEqual(worker._paused, False) self.assertTrue(worker.canStartBuild()) @defer.inlineCallbacks def test_worker_quarantine_doesnt_affect_pause(self): worker = yield self.createWorker(attached=False) yield worker.startService() self.assertTrue(worker.canStartBuild()) self.assertIsNone(worker.quarantine_timer) self.assertFalse(worker._paused) # put worker into quarantine. # Check canStartBuild() is False, and paused state is not changed worker.putInQuarantine() self.assertFalse(worker._paused) self.assertFalse(worker.canStartBuild()) self.assertIsNotNone(worker.quarantine_timer) # human manually pauses the worker worker.controlWorker(("worker", 1, "pause"), {"reason": "none"}) self.assertTrue(worker._paused) self.assertFalse(worker.canStartBuild()) # simulate wait for quarantine to end # Check canStartBuild() is still False, and paused state is not changed self.master.reactor.advance(10) self.assertTrue(worker._paused) self.assertFalse(worker.canStartBuild()) self.assertIsNone(worker.quarantine_timer) @defer.inlineCallbacks def test_worker_quarantine_unpausing_exits_quarantine(self): worker = yield self.createWorker(attached=False) yield worker.startService() self.assertTrue(worker.canStartBuild()) self.assertIsNone(worker.quarantine_timer) # put worker into quarantine whilst unpaused. worker.putInQuarantine() self.assertFalse(worker._paused) self.assertFalse(worker.canStartBuild()) # pause and unpause the worker worker.controlWorker(("worker", 1, "pause"), {"reason": "none"}) self.assertFalse(worker.canStartBuild()) worker.controlWorker(("worker", 1, "unpause"), {"reason": "none"}) self.assertTrue(worker.canStartBuild()) # put worker into quarantine whilst paused. worker.controlWorker(("worker", 1, "pause"), {"reason": "none"}) worker.putInQuarantine() self.assertTrue(worker._paused) self.assertFalse(worker.canStartBuild()) # unpause worker should start the build worker.controlWorker(("worker", 1, "unpause"), {"reason": "none"}) self.assertFalse(worker._paused) self.assertTrue(worker.canStartBuild()) @defer.inlineCallbacks def test_worker_quarantine_unpausing_doesnt_reset_timeout(self): worker = yield self.createWorker(attached=False) yield worker.startService() self.assertTrue(worker.canStartBuild()) self.assertIsNone(worker.quarantine_timer) # pump up the quarantine wait time for quarantine_wait in (10, 20, 40, 80): worker.putInQuarantine() self.assertFalse(worker.canStartBuild()) self.assertIsNotNone(worker.quarantine_timer) self.master.reactor.advance(quarantine_wait) self.assertTrue(worker.canStartBuild()) self.assertIsNone(worker.quarantine_timer) # put worker into quarantine (160s) worker.putInQuarantine() self.assertFalse(worker._paused) self.assertFalse(worker.canStartBuild()) # pause and unpause the worker to exit quarantine worker.controlWorker(("worker", 1, "pause"), {"reason": "none"}) self.assertFalse(worker.canStartBuild()) worker.controlWorker(("worker", 1, "unpause"), {"reason": "none"}) self.assertFalse(worker._paused) self.assertTrue(worker.canStartBuild()) # next build fails. check timeout is 320s worker.putInQuarantine() self.master.reactor.advance(319) self.assertFalse(worker.canStartBuild()) self.assertIsNotNone(worker.quarantine_timer) self.master.reactor.advance(1) self.assertIsNone(worker.quarantine_timer) self.assertTrue(worker.canStartBuild()) @defer.inlineCallbacks def test_worker_quarantine_wait_times(self): worker = yield self.createWorker(attached=False) yield worker.startService() self.assertTrue(worker.canStartBuild()) self.assertIsNone(worker.quarantine_timer) for quarantine_wait in (10, 20, 40, 80, 160, 320, 640, 1280, 2560, 3600, 3600): # put worker into quarantine worker.putInQuarantine() self.assertFalse(worker.canStartBuild()) self.assertIsNotNone(worker.quarantine_timer) # simulate wait just before quarantine ends self.master.reactor.advance(quarantine_wait - 1) self.assertFalse(worker.canStartBuild()) self.assertIsNotNone(worker.quarantine_timer) # simulate wait to just after quarantine ends self.master.reactor.advance(1) self.assertTrue(worker.canStartBuild()) self.assertIsNone(worker.quarantine_timer) @defer.inlineCallbacks def test_worker_quarantine_reset(self): worker = yield self.createWorker(attached=False) yield worker.startService() self.assertTrue(worker.canStartBuild()) self.assertIsNone(worker.quarantine_timer) # pump up the quarantine wait time for quarantine_wait in (10, 20, 40, 80): worker.putInQuarantine() self.assertFalse(worker.canStartBuild()) self.assertIsNotNone(worker.quarantine_timer) self.master.reactor.advance(quarantine_wait) self.assertTrue(worker.canStartBuild()) self.assertIsNone(worker.quarantine_timer) # Now get a successful build worker.resetQuarantine() # the workers quarantine period should reset back to 10 worker.putInQuarantine() self.master.reactor.advance(10) self.assertTrue(worker.canStartBuild()) self.assertIsNone(worker.quarantine_timer) @defer.inlineCallbacks def test_worker_quarantine_whilst_quarantined(self): worker = yield self.createWorker(attached=False) yield worker.startService() self.assertTrue(worker.canStartBuild()) self.assertIsNone(worker.quarantine_timer) # put worker in quarantine worker.putInQuarantine() self.assertFalse(worker.canStartBuild()) self.assertIsNotNone(worker.quarantine_timer) # simulate wait for half the time, and put in quarantine again self.master.reactor.advance(5) worker.putInQuarantine() self.assertFalse(worker.canStartBuild()) self.assertIsNotNone(worker.quarantine_timer) # simulate wait for another 5 seconds, and we should leave quarantine self.master.reactor.advance(5) self.assertTrue(worker.canStartBuild()) self.assertIsNone(worker.quarantine_timer) # simulate wait for yet another 5 seconds, and ensure nothing changes self.master.reactor.advance(5) self.assertTrue(worker.canStartBuild()) self.assertIsNone(worker.quarantine_timer) @defer.inlineCallbacks def test_worker_quarantine_stop_timer(self): worker = yield self.createWorker(attached=False) yield worker.startService() self.assertTrue(worker.canStartBuild()) self.assertIsNone(worker.quarantine_timer) # Call stopQuarantineTimer whilst not quarantined worker.stopQuarantineTimer() self.assertTrue(worker.canStartBuild()) self.assertIsNone(worker.quarantine_timer) # Call stopQuarantineTimer whilst quarantined worker.putInQuarantine() self.assertFalse(worker.canStartBuild()) self.assertIsNotNone(worker.quarantine_timer) worker.stopQuarantineTimer() self.assertTrue(worker.canStartBuild()) self.assertIsNone(worker.quarantine_timer) class TestAbstractLatentWorker(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) self.botmaster = self.master.botmaster yield self.master.workers.disownServiceParent() self.workers = self.master.workers = bworkermanager.FakeWorkerManager() yield self.workers.setServiceParent(self.master) @defer.inlineCallbacks def tearDown(self): yield self.tear_down_test_reactor() @defer.inlineCallbacks def do_test_reconfigService(self, old, new, existingRegistration=True): old.parent = self.master if existingRegistration: old.registration = bworkermanager.FakeWorkerRegistration(old) old.missing_timer = mock.Mock(name='missing_timer') yield old.startService() yield old.reconfigServiceWithSibling(new) @defer.inlineCallbacks def test_reconfigService(self): old = AbstractLatentWorker("name", "password", build_wait_timeout=10) new = AbstractLatentWorker("name", "password", build_wait_timeout=30) yield self.do_test_reconfigService(old, new) self.assertEqual(old.build_wait_timeout, 30)
35,600
Python
.py
790
36.168354
99
0.666234
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,517
test_protocols_base.py
buildbot_buildbot/master/buildbot/test/unit/worker/test_protocols_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.test.fake import fakeprotocol from buildbot.test.reactor import TestReactorMixin from buildbot.test.util import protocols from buildbot.worker.protocols import base class TestFakeConnection(protocols.ConnectionInterfaceTest, TestReactorMixin, unittest.TestCase): def setUp(self): self.setup_test_reactor(auto_tear_down=False) self.worker = mock.Mock() self.conn = fakeprotocol.FakeConnection(self.worker) @defer.inlineCallbacks def tearDown(self): yield self.tear_down_test_reactor() class TestConnection(protocols.ConnectionInterfaceTest, TestReactorMixin, unittest.TestCase): def setUp(self): self.setup_test_reactor(auto_tear_down=False) self.worker = mock.Mock() self.conn = base.Connection(self.worker.workername) @defer.inlineCallbacks def tearDown(self): yield self.tear_down_test_reactor() def test_notify(self): cb = mock.Mock() self.conn.notifyOnDisconnect(cb) self.assertEqual(cb.call_args_list, []) self.conn.notifyDisconnected() self.assertNotEqual(cb.call_args_list, [])
1,943
Python
.py
43
40.860465
97
0.762308
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,518
test_protocols_pb.py
buildbot_buildbot/master/buildbot/test/unit/worker/test_protocols_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.internet.address import IPv4Address from twisted.spread import pb as twisted_pb from twisted.trial import unittest from buildbot.test.fake import fakemaster from buildbot.test.reactor import TestReactorMixin from buildbot.test.util import protocols as util_protocols from buildbot.worker.protocols import base from buildbot.worker.protocols import pb class TestListener(TestReactorMixin, unittest.TestCase): @defer.inlineCallbacks def setUp(self): self.setup_test_reactor(auto_tear_down=False) self.master = yield fakemaster.make_master(self) @defer.inlineCallbacks def tearDown(self): yield self.tear_down_test_reactor() def makeListener(self): listener = pb.Listener(self.master) return listener def test_constructor(self): listener = pb.Listener(self.master) self.assertEqual(listener.master, self.master) self.assertEqual(listener._registrations, {}) @defer.inlineCallbacks def test_updateRegistration_simple(self): listener = pb.Listener(self.master) reg = yield listener.updateRegistration('example', 'pass', 'tcp:1234') self.assertEqual(self.master.pbmanager._registrations, [('tcp:1234', 'example', 'pass')]) self.assertEqual(listener._registrations['example'], ('pass', 'tcp:1234', reg)) @defer.inlineCallbacks def test_updateRegistration_pass_changed(self): listener = pb.Listener(self.master) listener.updateRegistration('example', 'pass', 'tcp:1234') reg1 = yield listener.updateRegistration('example', 'pass1', 'tcp:1234') self.assertEqual(listener._registrations['example'], ('pass1', 'tcp:1234', reg1)) self.assertEqual(self.master.pbmanager._unregistrations, [('tcp:1234', 'example')]) @defer.inlineCallbacks def test_updateRegistration_port_changed(self): listener = pb.Listener(self.master) listener.updateRegistration('example', 'pass', 'tcp:1234') reg1 = yield listener.updateRegistration('example', 'pass', 'tcp:4321') self.assertEqual(listener._registrations['example'], ('pass', 'tcp:4321', reg1)) self.assertEqual(self.master.pbmanager._unregistrations, [('tcp:1234', 'example')]) @defer.inlineCallbacks def test_create_connection(self): listener = pb.Listener(self.master) worker = mock.Mock() worker.workername = 'test' mind = mock.Mock() listener.updateRegistration('example', 'pass', 'tcp:1234') self.master.workers.register(worker) conn = yield listener._create_connection(mind, worker.workername) mind.broker.transport.setTcpKeepAlive.assert_called_with(1) self.assertIsInstance(conn, pb.Connection) class TestConnectionApi( util_protocols.ConnectionInterfaceTest, TestReactorMixin, unittest.TestCase ): @defer.inlineCallbacks def setUp(self): self.setup_test_reactor(auto_tear_down=False) self.master = yield fakemaster.make_master(self) self.conn = pb.Connection(self.master, mock.Mock(), mock.Mock()) @defer.inlineCallbacks def tearDown(self): yield self.tear_down_test_reactor() class TestConnection(TestReactorMixin, unittest.TestCase): @defer.inlineCallbacks def setUp(self): self.setup_test_reactor(auto_tear_down=False) self.master = yield fakemaster.make_master(self) self.mind = mock.Mock() self.worker = mock.Mock() @defer.inlineCallbacks def tearDown(self): yield self.tear_down_test_reactor() def test_constructor(self): conn = pb.Connection(self.master, self.worker, self.mind) self.assertEqual(conn.mind, self.mind) self.assertEqual(conn.master, self.master) self.assertEqual(conn.worker, self.worker) @defer.inlineCallbacks def test_attached(self): conn = pb.Connection(self.master, self.worker, self.mind) att = yield conn.attached(self.mind) self.worker.attached.assert_called_with(conn) self.assertEqual(att, conn) self.reactor.pump([10] * 361) expected_call = [ mock.call('print', message="keepalive"), ] self.assertEqual(self.mind.callRemote.call_args_list, expected_call) conn.detached(self.mind) yield conn.waitShutdown() @defer.inlineCallbacks def test_detached(self): conn = pb.Connection(self.master, self.worker, self.mind) conn.attached(self.mind) conn.detached(self.mind) self.assertEqual(conn.keepalive_timer, None) self.assertEqual(conn.mind, None) yield conn.waitShutdown() def test_loseConnection(self): conn = pb.Connection(self.master, self.worker, self.mind) conn.loseConnection() self.assertEqual(conn.keepalive_timer, None) conn.mind.broker.transport.loseConnection.assert_called_with() def test_remotePrint(self): conn = pb.Connection(self.master, self.worker, self.mind) conn.remotePrint(message='test') conn.mind.callRemote.assert_called_with('print', message='test') @defer.inlineCallbacks def test_remoteGetWorkerInfo_slave(self): def side_effect(*args, **kwargs): if args[0] == 'getWorkerInfo': return defer.fail( twisted_pb.RemoteError('twisted.spread.flavors.NoSuchMethod', None, None) ) if args[0] == 'getSlaveInfo': return defer.succeed({'info': 'test'}) if args[0] == 'getCommands': return defer.succeed({'x': 1, 'y': 2}) if args[0] == 'getVersion': return defer.succeed('TheVersion') return None self.mind.callRemote.side_effect = side_effect conn = pb.Connection(self.master, self.worker, self.mind) info = yield conn.remoteGetWorkerInfo() r = {'info': 'test', 'worker_commands': {'y': 2, 'x': 1}, 'version': 'TheVersion'} self.assertEqual(info, r) expected_calls = [ mock.call('getWorkerInfo'), mock.call( 'print', message='buildbot-slave detected, failing back to deprecated buildslave API. ' '(Ignoring missing getWorkerInfo method.)', ), mock.call('getSlaveInfo'), mock.call('getCommands'), mock.call('getVersion'), ] self.assertEqual(self.mind.callRemote.call_args_list, expected_calls) @defer.inlineCallbacks def test_remoteGetWorkerInfo_slave_2_16(self): """In buildslave 2.16 all information about worker is retrieved in a single getSlaveInfo() call.""" def side_effect(*args, **kwargs): if args[0] == 'getWorkerInfo': return defer.fail( twisted_pb.RemoteError('twisted.spread.flavors.NoSuchMethod', None, None) ) if args[0] == 'getSlaveInfo': return defer.succeed({ 'info': 'test', 'slave_commands': {'x': 1, 'y': 2}, 'version': 'TheVersion', }) if args[0] == 'print': return None raise ValueError(f"Command unknown: {args}") self.mind.callRemote.side_effect = side_effect conn = pb.Connection(self.master, self.worker, self.mind) info = yield conn.remoteGetWorkerInfo() r = {'info': 'test', 'worker_commands': {'y': 2, 'x': 1}, 'version': 'TheVersion'} self.assertEqual(info, r) expected_calls = [ mock.call('getWorkerInfo'), mock.call( 'print', message='buildbot-slave detected, failing back to deprecated buildslave API. ' '(Ignoring missing getWorkerInfo method.)', ), mock.call('getSlaveInfo'), ] self.assertEqual(self.mind.callRemote.call_args_list, expected_calls) @defer.inlineCallbacks def test_remoteGetWorkerInfo_worker(self): def side_effect(*args, **kwargs): if args[0] == 'getWorkerInfo': return defer.succeed({ 'info': 'test', 'worker_commands': {'y': 2, 'x': 1}, 'version': 'TheVersion', }) raise ValueError(f"Command unknown: {args}") self.mind.callRemote.side_effect = side_effect conn = pb.Connection(self.master, self.worker, self.mind) info = yield conn.remoteGetWorkerInfo() r = {'info': 'test', 'worker_commands': {'y': 2, 'x': 1}, 'version': 'TheVersion'} self.assertEqual(info, r) expected_calls = [mock.call('getWorkerInfo')] self.assertEqual(self.mind.callRemote.call_args_list, expected_calls) @defer.inlineCallbacks def test_remoteGetWorkerInfo_getWorkerInfo_fails(self): def side_effect(*args, **kwargs): if args[0] == 'getWorkerInfo': return defer.fail( twisted_pb.RemoteError('twisted.spread.flavors.NoSuchMethod', None, None) ) if args[0] == 'getSlaveInfo': return defer.fail( twisted_pb.RemoteError('twisted.spread.flavors.NoSuchMethod', None, None) ) if args[0] == 'getCommands': return defer.succeed({'x': 1, 'y': 2}) if args[0] == 'getVersion': return defer.succeed('TheVersion') if args[0] == 'print': return None raise ValueError(f"Command unknown: {args}") self.mind.callRemote.side_effect = side_effect conn = pb.Connection(self.master, self.worker, self.mind) info = yield conn.remoteGetWorkerInfo() r = {'worker_commands': {'y': 2, 'x': 1}, 'version': 'TheVersion'} self.assertEqual(info, r) expected_calls = [ mock.call('getWorkerInfo'), mock.call( 'print', message='buildbot-slave detected, failing back to deprecated buildslave API. ' '(Ignoring missing getWorkerInfo method.)', ), mock.call('getSlaveInfo'), mock.call('getCommands'), mock.call('getVersion'), ] self.assertEqual(self.mind.callRemote.call_args_list, expected_calls) @defer.inlineCallbacks def test_remoteGetWorkerInfo_no_info(self): # All remote commands tried in remoteGetWorkerInfo are unavailable. # This should be real old worker... def side_effect(*args, **kwargs): if args[0] == 'print': return None return defer.fail( twisted_pb.RemoteError('twisted.spread.flavors.NoSuchMethod', None, None) ) self.mind.callRemote.side_effect = side_effect conn = pb.Connection(self.master, self.worker, self.mind) info = yield conn.remoteGetWorkerInfo() r = {} self.assertEqual(info, r) expected_calls = [ mock.call('getWorkerInfo'), mock.call( 'print', message='buildbot-slave detected, failing back to deprecated buildslave API. ' '(Ignoring missing getWorkerInfo method.)', ), mock.call('getSlaveInfo'), mock.call('getCommands'), mock.call('getVersion'), ] self.assertEqual(self.mind.callRemote.call_args_list, expected_calls) @defer.inlineCallbacks def test_remoteSetBuilderList(self): builders = ['builder1', 'builder2'] self.mind.callRemote.return_value = defer.succeed(builders) conn = pb.Connection(self.master, self.worker, self.mind) r = yield conn.remoteSetBuilderList(builders) self.assertEqual(r, builders) self.assertEqual(conn.builders, builders) self.mind.callRemote.assert_called_with('setBuilderList', builders) def test_remoteStartCommand(self): builders = ['builder'] ret_val = {'builder': mock.Mock()} self.mind.callRemote.return_value = defer.succeed(ret_val) conn = pb.Connection(self.master, self.worker, self.mind) conn.remoteSetBuilderList(builders) RCInstance = base.RemoteCommandImpl() builder_name = "builder" commandID = None remote_command = "command" args = {"args": 'args'} conn.remoteStartCommand(RCInstance, builder_name, commandID, remote_command, args) callargs = ret_val['builder'].callRemote.call_args_list[0][0] callargs_without_rc = (callargs[0], callargs[2], callargs[3], callargs[4]) self.assertEqual(callargs_without_rc, ('startCommand', commandID, remote_command, args)) self.assertIsInstance(callargs[1], pb.RemoteCommand) self.assertEqual(callargs[1].impl, RCInstance) @defer.inlineCallbacks def test_do_keepalive(self): conn = pb.Connection(self.master, self.worker, self.mind) yield conn._do_keepalive() self.mind.callRemote.assert_called_with('print', message="keepalive") def test_remoteShutdown(self): self.mind.callRemote.return_value = defer.succeed(None) conn = pb.Connection(self.master, self.worker, self.mind) # note that we do not test the "old way", as it is now *very* old. conn.remoteShutdown() self.mind.callRemote.assert_called_with('shutdown') def test_remoteStartBuild(self): conn = pb.Connection(self.master, self.worker, self.mind) builders = {'builder': mock.Mock()} self.mind.callRemote.return_value = defer.succeed(builders) conn = pb.Connection(self.master, self.worker, self.mind) conn.remoteSetBuilderList(builders) conn.remoteStartBuild('builder') builders['builder'].callRemote.assert_called_with('startBuild') @defer.inlineCallbacks def test_startStopKeepaliveTimer(self): conn = pb.Connection(self.master, self.worker, self.mind) conn.startKeepaliveTimer() self.mind.callRemote.assert_not_called() self.reactor.pump([10] * 361) expected_call = [ mock.call('print', message="keepalive"), ] self.assertEqual(self.mind.callRemote.call_args_list, expected_call) self.reactor.pump([10] * 361) expected_calls = [ mock.call('print', message="keepalive"), mock.call('print', message="keepalive"), ] self.assertEqual(self.mind.callRemote.call_args_list, expected_calls) conn.stopKeepaliveTimer() yield conn.waitShutdown() def test_perspective_shutdown(self): conn = pb.Connection(self.master, self.worker, self.mind) conn.perspective_shutdown() conn.worker.shutdownRequested.assert_called_with() conn.worker.messageReceivedFromWorker.assert_called_with() def test_perspective_keepalive(self): conn = pb.Connection(self.master, self.worker, self.mind) conn.perspective_keepalive() conn.worker.messageReceivedFromWorker.assert_called_with() def test_get_peer(self): conn = pb.Connection(self.master, self.worker, self.mind) conn.mind.broker.transport.getPeer.return_value = IPv4Address( "TCP", "ip", "port", ) self.assertEqual(conn.get_peer(), "ip:port") class Test_wrapRemoteException(unittest.TestCase): def test_raises_NoSuchMethod(self): def f(): with pb._wrapRemoteException(): raise twisted_pb.RemoteError('twisted.spread.flavors.NoSuchMethod', None, None) with self.assertRaises(pb._NoSuchMethod): f() def test_raises_unknown(self): class Error(Exception): pass def f(): with pb._wrapRemoteException(): raise Error() with self.assertRaises(Error): f() def test_raises_RemoteError(self): def f(): with pb._wrapRemoteException(): raise twisted_pb.RemoteError('twisted.spread.flavors.ProtocolError', None, None) with self.assertRaises(twisted_pb.RemoteError): f()
17,123
Python
.py
370
36.583784
97
0.638762
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,519
test_ec2.py
buildbot_buildbot/master/buildbot/test/unit/worker/test_ec2.py
# This file is part of Buildbot. Buildbot is free software: you can # redistribute it and/or modify it under the terms of the GNU General Public # License as published by the Free Software Foundation, version 2. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more # details. # # You should have received a copy of the GNU General Public License along with # this program; if not, write to the Free Software Foundation, Inc., 51 # Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # Portions Copyright Buildbot Team Members # Portions Copyright 2014 Longaccess private company import os from twisted.trial import unittest from buildbot.test.util.warnings import assertNotProducesWarnings from buildbot.warnings import DeprecatedApiWarning try: import boto3 from botocore.client import ClientError from moto import mock_aws except ImportError: boto3 = None ClientError = None if boto3 is not None: from buildbot.worker import ec2 else: ec2 = None # type: ignore[assignment] # Current moto (1.3.7) requires dummy credentials to work # https://github.com/spulec/moto/issues/1924 os.environ['AWS_SECRET_ACCESS_KEY'] = 'foobar_secret' os.environ['AWS_ACCESS_KEY_ID'] = 'foobar_key' os.environ['AWS_DEFAULT_REGION'] = 'us-east-1' # redefine the mock_aws decorator to skip the test if boto3 or moto # isn't installed def skip_ec2(f): f.skip = "boto3 or moto is not installed" return f if boto3 is None: mock_aws = skip_ec2 # type: ignore[assignment] def anyImageId(c): for image in c.describe_images()['Images']: return image['ImageId'] return 'foo' class TestEC2LatentWorker(unittest.TestCase): ec2_connection = None def setUp(self): super().setUp() if boto3 is None: raise unittest.SkipTest("moto not found") def botoSetup(self, name='latent_buildbot_worker'): # the proxy system is also not properly mocked, so we need to delete environment variables for env in ['http_proxy', 'https_proxy', 'HTTP_PROXY', 'HTTPS_PROXY']: if env in os.environ: del os.environ[env] # create key pair is not correctly mocked and need to have fake aws creds configured kw = { "region_name": 'us-east-1', "aws_access_key_id": 'ACCESS_KEY', "aws_secret_access_key": 'SECRET_KEY', "aws_session_token": 'SESSION_TOKEN', } c = boto3.client('ec2', **kw) r = boto3.resource('ec2', **kw) try: r.create_key_pair(KeyName=name) except NotImplementedError as e: raise unittest.SkipTest( "KeyPairs.create_key_pair not implemented" " in this version of moto, please update." ) from e r.create_security_group(GroupName=name, Description='the security group') instance = r.create_instances(ImageId=anyImageId(c), MinCount=1, MaxCount=1)[0] c.create_image(InstanceId=instance.id, Name="foo", Description="bar") c.terminate_instances(InstanceIds=[instance.id]) return c, r def _patch_moto_describe_spot_price_history(self, bs, instance_type, price): def fake_describe_price(*args, **kwargs): return {'SpotPriceHistory': [{'InstanceType': instance_type, 'SpotPrice': price}]} self.patch(bs.ec2.meta.client, "describe_spot_price_history", fake_describe_price) def _patch_moto_describe_spot_instance_requests(self, c, r, bs): this_call = [0] orig_describe_instance = bs.ec2.meta.client.describe_spot_instance_requests def fake_describe_spot_instance_requests(*args, **kwargs): curr_call = this_call[0] this_call[0] += 1 if curr_call == 0: raise ClientError( {'Error': {'Code': 'InvalidSpotInstanceRequestID.NotFound'}}, 'DescribeSpotInstanceRequests', ) if curr_call == 1: return orig_describe_instance(*args, **kwargs) response = orig_describe_instance(*args, **kwargs) instances = r.instances.filter( Filters=[{'Name': 'instance-state-name', 'Values': ['running']}] ) response['SpotInstanceRequests'][0]['Status']['Code'] = 'fulfilled' response['SpotInstanceRequests'][0]['InstanceId'] = next(iter(instances)).id return response self.patch( bs.ec2.meta.client, 'describe_spot_instance_requests', fake_describe_spot_instance_requests, ) @mock_aws def test_constructor_minimal(self): _, r = self.botoSetup('latent_buildbot_slave') amis = list(r.images.all()) bs = ec2.EC2LatentWorker( 'bot1', 'sekrit', 'm1.large', identifier='publickey', secret_identifier='privatekey', keypair_name='keypair_name', security_name='security_name', ami=amis[0].id, ) self.assertEqual(bs.workername, 'bot1') self.assertEqual(bs.password, 'sekrit') self.assertEqual(bs.instance_type, 'm1.large') self.assertEqual(bs.ami, amis[0].id) @mock_aws def test_constructor_tags(self): _, r = self.botoSetup('latent_buildbot_slave') amis = list(r.images.all()) tags = {'foo': 'bar'} bs = ec2.EC2LatentWorker( 'bot1', 'sekrit', 'm1.large', identifier='publickey', secret_identifier='privatekey', keypair_name='keypair_name', security_name='security_name', tags=tags, ami=amis[0].id, ) self.assertEqual(bs.tags, tags) @mock_aws def test_constructor_region(self): _, r = self.botoSetup() amis = list(r.images.all()) bs = ec2.EC2LatentWorker( 'bot1', 'sekrit', 'm1.large', identifier='publickey', secret_identifier='privatekey', keypair_name="latent_buildbot_worker", security_name='latent_buildbot_worker', ami=amis[0].id, region='us-west-1', ) self.assertEqual(bs.session.region_name, 'us-west-1') @mock_aws def test_fail_mixing_classic_and_vpc_ec2_settings(self): _, r = self.botoSetup() amis = list(r.images.all()) def create_worker(): ec2.EC2LatentWorker( 'bot1', 'sekrit', 'm1.large', keypair_name="test_key", identifier='publickey', secret_identifier='privatekey', ami=amis[0].id, security_name="classic", subnet_id="sn-1234", ) with self.assertRaises(ValueError): create_worker() @mock_aws def test_start_vpc_instance(self): _, r = self.botoSetup() vpc = r.create_vpc(CidrBlock="192.168.0.0/24") subnet = r.create_subnet(VpcId=vpc.id, CidrBlock="192.168.0.0/24") amis = list(r.images.all()) sg = r.create_security_group(GroupName="test_sg", Description="test_sg", VpcId=vpc.id) bs = ec2.EC2LatentWorker( 'bot1', 'sekrit', 'm1.large', identifier='publickey', secret_identifier='privatekey', keypair_name="latent_buildbot_worker", security_group_ids=[sg.id], subnet_id=subnet.id, ami=amis[0].id, ) bs._poll_resolution = 0 instance_id, _, _ = bs._start_instance() instances = r.instances.filter( Filters=[{'Name': 'instance-state-name', 'Values': ['running']}] ) instances = list(instances) self.assertEqual(len(instances), 1) self.assertEqual(instances[0].id, instance_id) self.assertEqual(instances[0].subnet_id, subnet.id) self.assertEqual(len(instances[0].security_groups), 1) self.assertEqual(instances[0].security_groups[0]['GroupId'], sg.id) self.assertEqual(instances[0].key_name, 'latent_buildbot_worker') @mock_aws def test_start_instance(self): _, r = self.botoSetup() amis = list(r.images.all()) bs = ec2.EC2LatentWorker( 'bot1', 'sekrit', 'm1.large', identifier='publickey', secret_identifier='privatekey', keypair_name='keypair_name', security_name='security_name', ami=amis[0].id, ) bs._poll_resolution = 1 instance_id, image_id, start_time = bs._start_instance() self.assertTrue(instance_id.startswith('i-')) self.assertTrue(image_id.startswith('ami-')) self.assertTrue(start_time > "00:00:00") instances = r.instances.filter( Filters=[{'Name': 'instance-state-name', 'Values': ['running']}] ) instances = list(instances) self.assertEqual(len(instances), 1) self.assertEqual(instances[0].id, instance_id) self.assertIsNone(instances[0].tags) self.assertEqual(instances[0].id, bs.properties.getProperty('instance')) @mock_aws def test_start_instance_volumes(self): _, r = self.botoSetup() block_device_map_arg = [ { 'DeviceName': "/dev/xvdb", 'Ebs': { "VolumeType": "io1", "Iops": 10, "VolumeSize": 20, }, }, { 'DeviceName': "/dev/xvdc", 'Ebs': { "VolumeType": "gp2", "VolumeSize": 30, "DeleteOnTermination": False, }, }, ] block_device_map_res = [ { 'DeviceName': "/dev/xvdb", 'Ebs': { "VolumeType": "io1", "Iops": 10, "VolumeSize": 20, "DeleteOnTermination": True, }, }, { 'DeviceName': "/dev/xvdc", 'Ebs': { "VolumeType": "gp2", "VolumeSize": 30, "DeleteOnTermination": False, }, }, ] amis = list(r.images.all()) bs = ec2.EC2LatentWorker( 'bot1', 'sekrit', 'm1.large', identifier='publickey', secret_identifier='privatekey', keypair_name="latent_buildbot_worker", security_name='latent_buildbot_worker', ami=amis[0].id, block_device_map=block_device_map_arg, ) # moto does not currently map volumes properly. below ensures # that my conversion code properly composes it, including # delete_on_termination default. self.assertEqual(block_device_map_res, bs.block_device_map) @mock_aws def test_start_instance_attach_volume(self): _, r = self.botoSetup() vol = r.create_volume(Size=10, AvailabilityZone='us-east-1a') amis = list(r.images.all()) ami = amis[0] bs = ec2.EC2LatentWorker( 'bot1', 'sekrit', 'm1.large', identifier='publickey', secret_identifier='privatekey', keypair_name="latent_buildbot_worker", security_name='latent_buildbot_worker', ami=ami.id, volumes=[(vol.id, "/dev/sdz")], ) bs._poll_resolution = 0 bs._start_instance() instances = r.instances.filter( Filters=[{'Name': 'instance-state-name', 'Values': ['running']}] ) instances = list(instances) instance = instances[0] sdz = next(bm for bm in instance.block_device_mappings if bm['DeviceName'] == '/dev/sdz') self.assertEqual(vol.id, sdz['Ebs']['VolumeId']) @mock_aws def test_start_instance_tags(self): _, r = self.botoSetup('latent_buildbot_slave') amis = list(r.images.all()) tags = {'foo': 'bar'} bs = ec2.EC2LatentWorker( 'bot1', 'sekrit', 'm1.large', identifier='publickey', secret_identifier='privatekey', keypair_name="latent_buildbot_worker", security_name='latent_buildbot_worker', tags=tags, ami=amis[0].id, ) bs._poll_resolution = 0 id, _, _ = bs._start_instance() instances = r.instances.filter( Filters=[{'Name': 'instance-state-name', 'Values': ['running']}] ) instances = list(instances) self.assertEqual(len(instances), 1) self.assertEqual(instances[0].id, id) self.assertEqual(instances[0].tags, [{'Value': 'bar', 'Key': 'foo'}]) @mock_aws def test_start_instance_ip(self): c, r = self.botoSetup('latent_buildbot_slave') amis = list(r.images.all()) eip = c.allocate_address(Domain='vpc') elastic_ip = eip['PublicIp'] bs = ec2.EC2LatentWorker( 'bot1', 'sekrit', 'm1.large', identifier='publickey', secret_identifier='privatekey', keypair_name="latent_buildbot_worker", security_name='latent_buildbot_worker', elastic_ip=elastic_ip, ami=amis[0].id, ) bs._poll_resolution = 0 bs._start_instance() instances = r.instances.filter( Filters=[{'Name': 'instance-state-name', 'Values': ['running']}] ) instances = list(instances) addresses = c.describe_addresses()['Addresses'] self.assertEqual(instances[0].id, addresses[0]['InstanceId']) @mock_aws def test_start_vpc_spot_instance(self): c, r = self.botoSetup() vpc = r.create_vpc(CidrBlock="192.168.0.0/24") subnet = r.create_subnet(VpcId=vpc.id, CidrBlock="192.168.0.0/24") amis = list(r.images.all()) sg = r.create_security_group(GroupName="test_sg", Description="test_sg", VpcId=vpc.id) bs = ec2.EC2LatentWorker( 'bot1', 'sekrit', 'm1.large', identifier='publickey', secret_identifier='privatekey', keypair_name="latent_buildbot_worker", ami=amis[0].id, spot_instance=True, max_spot_price=1.5, security_group_ids=[sg.id], subnet_id=subnet.id, ) bs._poll_resolution = 0 self._patch_moto_describe_spot_price_history(bs, 'm1.large', price=1.0) self._patch_moto_describe_spot_instance_requests(c, r, bs) instance_id, _, _ = bs._request_spot_instance() instances = r.instances.filter( Filters=[{'Name': 'instance-state-name', 'Values': ['running']}] ) instances = list(instances) self.assertTrue(bs.spot_instance) self.assertEqual(len(instances), 1) self.assertEqual(instances[0].id, instance_id) self.assertEqual(instances[0].subnet_id, subnet.id) self.assertEqual(len(instances[0].security_groups), 1) # TODO: As of moto 2.0.2 GroupId is not handled in spot requests # self.assertEqual(instances[0].security_groups[0]['GroupId'], sg.id) @mock_aws def test_start_spot_instance(self): c, r = self.botoSetup('latent_buildbot_slave') amis = list(r.images.all()) product_description = 'Linux/Unix' bs = ec2.EC2LatentWorker( 'bot1', 'sekrit', 'm1.large', identifier='publickey', secret_identifier='privatekey', keypair_name='keypair_name', security_name='security_name', ami=amis[0].id, spot_instance=True, max_spot_price=1.5, product_description=product_description, ) bs._poll_resolution = 0 self._patch_moto_describe_spot_price_history(bs, 'm1.large', price=1.0) self._patch_moto_describe_spot_instance_requests(c, r, bs) instance_id, _, _ = bs._request_spot_instance() instances = r.instances.filter( Filters=[{'Name': 'instance-state-name', 'Values': ['running']}] ) instances = list(instances) self.assertTrue(bs.spot_instance) self.assertEqual(bs.product_description, product_description) self.assertEqual(len(instances), 1) self.assertEqual(instances[0].id, instance_id) self.assertIsNone(instances[0].tags) @mock_aws def test_get_image_ami(self): _, r = self.botoSetup('latent_buildbot_slave') amis = list(r.images.all()) ami = amis[0] bs = ec2.EC2LatentWorker( 'bot1', 'sekrit', 'm1.large', identifier='publickey', secret_identifier='privatekey', keypair_name="latent_buildbot_worker", security_name='latent_buildbot_worker', ami=ami.id, ) image = bs.get_image() self.assertEqual(image.id, ami.id) @mock_aws def test_get_image_owners(self): _, r = self.botoSetup('latent_buildbot_slave') amis = list(r.images.all()) ami = amis[0] bs = ec2.EC2LatentWorker( 'bot1', 'sekrit', 'm1.large', identifier='publickey', secret_identifier='privatekey', keypair_name="latent_buildbot_worker", security_name='latent_buildbot_worker', valid_ami_owners=[int(ami.owner_id)], ) image = bs.get_image() self.assertEqual(image.owner_id, ami.owner_id) @mock_aws def test_get_image_location(self): self.botoSetup('latent_buildbot_slave') bs = ec2.EC2LatentWorker( 'bot1', 'sekrit', 'm1.large', identifier='publickey', secret_identifier='privatekey', keypair_name="latent_buildbot_worker", security_name='latent_buildbot_worker', valid_ami_location_regex='amazon/.*', ) image = bs.get_image() self.assertTrue(image.image_location.startswith("amazon/")) @mock_aws def test_get_image_location_not_found(self): def create_worker(): ec2.EC2LatentWorker( 'bot1', 'sekrit', 'm1.large', identifier='publickey', secret_identifier='privatekey', keypair_name="latent_buildbot_worker", security_name='latent_buildbot_worker', valid_ami_location_regex='foobar.*', ) with self.assertRaises(ValueError): create_worker() @mock_aws def test_fail_multiplier_and_max_are_none(self): """ price_multiplier and max_spot_price may not be None at the same time. """ _, r = self.botoSetup() amis = list(r.images.all()) def create_worker(): ec2.EC2LatentWorker( 'bot1', 'sekrit', 'm1.large', identifier='publickey', secret_identifier='privatekey', keypair_name="latent_buildbot_worker", security_name='latent_buildbot_worker', ami=amis[0].id, region='us-west-1', spot_instance=True, price_multiplier=None, max_spot_price=None, ) with self.assertRaises(ValueError): create_worker() class TestEC2LatentWorkerDefaultKeyairSecurityGroup(unittest.TestCase): ec2_connection = None def setUp(self): super().setUp() if boto3 is None: raise unittest.SkipTest("moto not found") def botoSetup(self): c = boto3.client('ec2', region_name='us-east-1') r = boto3.resource('ec2', region_name='us-east-1') try: r.create_key_pair(KeyName='latent_buildbot_slave') r.create_key_pair(KeyName='test_keypair') except NotImplementedError as e: raise unittest.SkipTest( "KeyPairs.create_key_pair not implemented" " in this version of moto, please update." ) from e r.create_security_group(GroupName='latent_buildbot_slave', Description='the security group') r.create_security_group(GroupName='test_security_group', Description='other security group') instance = r.create_instances(ImageId=anyImageId(c), MinCount=1, MaxCount=1)[0] c.create_image(InstanceId=instance.id, Name="foo", Description="bar") c.terminate_instances(InstanceIds=[instance.id]) return c, r @mock_aws def test_no_default_security_warning_when_security_group_ids(self): _, r = self.botoSetup() amis = list(r.images.all()) bs = ec2.EC2LatentWorker( 'bot1', 'sekrit', 'm1.large', identifier='publickey', secret_identifier='privatekey', ami=amis[0].id, keypair_name='test_keypair', subnet_id=["sn-1"], ) self.assertEqual(bs.security_name, None) @mock_aws def test_use_non_default_keypair_security(self): _, r = self.botoSetup() amis = list(r.images.all()) with assertNotProducesWarnings(DeprecatedApiWarning): bs = ec2.EC2LatentWorker( 'bot1', 'sekrit', 'm1.large', identifier='publickey', secret_identifier='privatekey', ami=amis[0].id, security_name='test_security_group', keypair_name='test_keypair', ) self.assertEqual(bs.keypair_name, 'test_keypair') self.assertEqual(bs.security_name, 'test_security_group')
22,426
Python
.py
574
28.41115
100
0.570248
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,520
test_protocols_manager_msgmanager.py
buildbot_buildbot/master/buildbot/test/unit/worker/test_protocols_manager_msgmanager.py
# This file is part of Buildbot. Buildbot is free software: you can # redistribute it and/or modify it under the terms of the GNU General Public # License as published by the Free Software Foundation, version 2. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more # details. # # You should have received a copy of the GNU General Public License along with # this program; if not, write to the Free Software Foundation, Inc., 51 # Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # Copyright Buildbot Team Members import base64 from unittest import mock import msgpack from autobahn.websocket.types import ConnectionDeny from parameterized import parameterized from twisted.internet import defer from twisted.trial import unittest from buildbot.worker.protocols.manager.msgpack import BuildbotWebSocketServerProtocol from buildbot.worker.protocols.manager.msgpack import ConnectioLostError from buildbot.worker.protocols.manager.msgpack import RemoteWorkerError from buildbot.worker.protocols.manager.msgpack import decode_http_authorization_header from buildbot.worker.protocols.manager.msgpack import encode_http_authorization_header class TestHttpAuthorization(unittest.TestCase): def test_encode(self): result = encode_http_authorization_header(b'name', b'pass') self.assertEqual(result, 'Basic bmFtZTpwYXNz') result = encode_http_authorization_header(b'name2', b'pass2') self.assertEqual(result, 'Basic bmFtZTI6cGFzczI=') def test_encode_username_contains_colon(self): with self.assertRaises(ValueError): encode_http_authorization_header(b'na:me', b'pass') def test_decode(self): result = decode_http_authorization_header( encode_http_authorization_header(b'name', b'pass') ) self.assertEqual(result, ('name', 'pass')) # password can contain a colon result = decode_http_authorization_header( encode_http_authorization_header(b'name', b'pa:ss') ) self.assertEqual(result, ('name', 'pa:ss')) def test_contains_no__basic(self): with self.assertRaises(ValueError): decode_http_authorization_header('Test bmFtZTpwYXNzOjI=') with self.assertRaises(ValueError): decode_http_authorization_header('TestTest bmFtZTpwYXNzOjI=') def test_contains_forbidden_character(self): with self.assertRaises(ValueError): decode_http_authorization_header('Basic test%test') def test_credentials_do_not_contain_colon(self): value = 'Basic ' + base64.b64encode(b'TestTestTest').decode() with self.assertRaises(ValueError): decode_http_authorization_header(value) class TestException(Exception): pass class TestBuildbotWebSocketServerProtocol(unittest.TestCase): def setUp(self): self.protocol = BuildbotWebSocketServerProtocol() self.protocol.sendMessage = mock.Mock() self.seq_number = 1 @defer.inlineCallbacks def send_msg_check_response(self, protocol, msg, expected): msg = msg.copy() msg['seq_number'] = self.seq_number expected = expected.copy() expected['seq_number'] = self.seq_number self.seq_number += 1 protocol.onMessage(msgpack.packb(msg), True) yield protocol._deferwaiter.wait() args_tuple, _ = protocol.sendMessage.call_args result = msgpack.unpackb(args_tuple[0], raw=False) self.assertEqual(result, expected) def send_msg_get_result(self, msg): msg = msg.copy() msg['seq_number'] = self.seq_number self.seq_number += 1 self.protocol.onMessage(msgpack.packb(msg), True) args_tuple, _ = self.protocol.sendMessage.call_args return msgpack.unpackb(args_tuple[0], raw=False)['result'] @defer.inlineCallbacks def connect_authenticated_worker(self): # worker has to be authenticated before opening the connection pfactory = mock.Mock() pfactory.connection = mock.Mock() self.setup_mock_users({'name': ('pass', pfactory)}) request = mock.Mock() request.headers = {"authorization": 'Basic bmFtZTpwYXNz'} request.peer = '' yield self.protocol.onConnect(request) yield self.protocol.onOpen() def setup_mock_users(self, users): self.protocol.factory = mock.Mock() self.protocol.factory.buildbot_dispatcher = mock.Mock() self.protocol.factory.buildbot_dispatcher.users = users @parameterized.expand([ ('update_op', {'seq_number': 1}), ('update_seq_number', {'op': 'update'}), ('complete_op', {'seq_number': 1}), ('complete_seq_number', {'op': 'complete'}), ('update_upload_file_write_op', {'seq_number': 1}), ('update_upload_file_write_seq_number', {'op': 'update_upload_file_write'}), ('update_upload_file_utime_op', {'seq_number': 1}), ('update_upload_file_utime_seq_number', {'op': 'update_upload_file_utime'}), ('update_upload_file_close_op', {'seq_number': 1}), ('update_upload_file_close_seq_number', {'op': 'update_upload_file_close'}), ('update_read_file_op', {'seq_number': 1}), ('update_read_file_seq_number', {'op': 'update_read_file'}), ('update_read_file_close_op', {'seq_number': 1}), ('update_read_file_close_seq_number', {'op': 'update_read_file_close'}), ('update_upload_directory_unpack_op', {'seq_number': 1}), ('update_upload_directory_unpack_seq_number', {'op': 'update_upload_directory_unpack'}), ('update_upload_directory_write_op', {'seq_number': 1}), ('update_upload_directory_write_seq_number', {'op': 'update_upload_directory_write'}), ]) def test_msg_missing_arg(self, name, msg): with mock.patch('twisted.python.log.msg') as mock_log: self.protocol.onMessage(msgpack.packb(msg), True) mock_log.assert_any_call(f'Invalid message from worker: {msg}') # if msg does not have 'sep_number' or 'op', response sendMessage should not be called self.protocol.sendMessage.assert_not_called() @parameterized.expand([ ('update', {'op': 'update', 'args': 'args'}), ('complete', {'op': 'complete', 'args': 'args'}), ('update_upload_file_write', {'op': 'update_upload_file_write', 'args': 'args'}), ( 'update_upload_file_utime', {'op': 'update_upload_file_utime', 'access_time': 1, 'modified_time': 2}, ), ('update_upload_file_close', {'op': 'update_upload_file_close'}), ('update_read_file', {'op': 'update_read_file', 'length': 1}), ('update_read_file_close', {'op': 'update_read_file_close'}), ('update_upload_directory_unpack', {'op': 'update_upload_directory_unpack'}), ('upload_directory_write', {'op': 'update_upload_directory_write', 'args': 'args'}), ]) @defer.inlineCallbacks def test_missing_command_id(self, command, msg): yield self.connect_authenticated_worker() expected = { 'op': 'response', 'result': '\'message did not contain obligatory "command_id" key\'', 'is_exception': True, } yield self.send_msg_check_response(self.protocol, msg, expected) @parameterized.expand([ ('update', {'op': 'update', 'args': 'args', 'command_id': 2}, {1: 'remoteCommand'}), ('complete', {'op': 'complete', 'args': 'args', 'command_id': 2}, {1: 'remoteCommand'}), ]) @defer.inlineCallbacks def test_unknown_command_id(self, command, msg, command_id_to_command_map): yield self.connect_authenticated_worker() self.protocol.command_id_to_command_map = command_id_to_command_map expected = {'op': 'response', 'result': '\'unknown "command_id"\'', 'is_exception': True} yield self.send_msg_check_response(self.protocol, msg, expected) @parameterized.expand([ ( 'update_upload_file_write', {'op': 'update_upload_file_write', 'args': 'args', 'command_id': 2}, ), ( 'update_upload_directory_unpack', {'op': 'update_upload_directory_unpack', 'command_id': 2}, ), ('update_upload_file_close', {'op': 'update_upload_file_close', 'command_id': 2}), ( 'update_upload_file_utime', { 'op': 'update_upload_file_utime', 'access_time': 1, 'modified_time': 2, 'command_id': 2, }, ), ( 'update_upload_directory_write', {'op': 'update_upload_directory_write', 'command_id': 2, 'args': 'args'}, ), ]) @defer.inlineCallbacks def test_unknown_command_id_writers(self, command, msg): yield self.connect_authenticated_worker() self.protocol.command_id_to_writer_map = {1: 'writer'} expected = {'op': 'response', 'result': '\'unknown "command_id"\'', 'is_exception': True} yield self.send_msg_check_response(self.protocol, msg, expected) @parameterized.expand([ ('update', {'op': 'update', 'command_id': 2}), ('complete', {'op': 'complete', 'command_id': 2}), ('update_upload_file_write', {'op': 'update_upload_file_write', 'command_id': 2}), ('update_upload_directory_write', {'op': 'update_upload_directory_write', 'command_id': 1}), ]) @defer.inlineCallbacks def test_missing_args(self, command, msg): yield self.connect_authenticated_worker() expected = { 'op': 'response', 'result': '\'message did not contain obligatory "args" key\'', 'is_exception': True, } yield self.send_msg_check_response(self.protocol, msg, expected) @parameterized.expand([ ('update_read_file', {'op': 'update_read_file', 'length': 1, 'command_id': 2}), ('update_read_file_close', {'op': 'update_read_file_close', 'command_id': 2}), ]) @defer.inlineCallbacks def test_unknown_command_id_readers(self, command, msg): yield self.connect_authenticated_worker() self.protocol.command_id_to_reader_map = {1: 'reader'} expected = {'op': 'response', 'result': '\'unknown "command_id"\'', 'is_exception': True} yield self.send_msg_check_response(self.protocol, msg, expected) @defer.inlineCallbacks def test_missing_authorization_header(self): request = mock.Mock() request.headers = {"authorization": ''} request.peer = '' with self.assertRaises(ConnectionDeny): yield self.protocol.onConnect(request) @defer.inlineCallbacks def test_auth_password_does_not_match(self): pfactory = mock.Mock() pfactory.connection = mock.Mock() self.setup_mock_users({'username': ('password', pfactory)}) request = mock.Mock() request.headers = { "authorization": encode_http_authorization_header(b'username', b'wrong_password') } request.peer = '' with self.assertRaises(ConnectionDeny): yield self.protocol.onConnect(request) @defer.inlineCallbacks def test_auth_username_unknown(self): pfactory = mock.Mock() pfactory.connection = mock.Mock() self.setup_mock_users({'username': ('pass', pfactory)}) request = mock.Mock() request.headers = { "authorization": encode_http_authorization_header(b'wrong_username', b'pass') } request.peer = '' with self.assertRaises(ConnectionDeny): yield self.protocol.onConnect(request) @defer.inlineCallbacks def test_update_success(self): yield self.connect_authenticated_worker() command_id = 1 command = mock.Mock() self.protocol.command_id_to_command_map = {command_id: command} msg = {'op': 'update', 'args': 'args', 'command_id': command_id} expected = {'op': 'response', 'result': None} yield self.send_msg_check_response(self.protocol, msg, expected) command.remote_update_msgpack.assert_called_once_with(msg['args']) @defer.inlineCallbacks def test_complete_success(self): yield self.connect_authenticated_worker() command_id = 1 command = mock.Mock() self.protocol.command_id_to_command_map = {command_id: command} self.protocol.command_id_to_reader_map = {} self.protocol.command_id_to_writer_map = {} msg = {'op': 'complete', 'args': 'args', 'command_id': command_id} expected = {'op': 'response', 'result': None} yield self.send_msg_check_response(self.protocol, msg, expected) command.remote_complete.assert_called_once() @defer.inlineCallbacks def test_complete_check_dict_removal(self): yield self.connect_authenticated_worker() command_id = 1 command = mock.Mock() self.protocol.command_id_to_command_map = {command_id: command, 2: 'test_command'} self.protocol.command_id_to_reader_map = {command_id: 'test_reader', 2: 'test_reader2'} self.protocol.command_id_to_writer_map = {command_id: 'test_writer', 2: 'test_writer2'} msg = {'op': 'complete', 'args': 'args', 'command_id': command_id} expected = {'op': 'response', 'result': None} yield self.send_msg_check_response(self.protocol, msg, expected) command.remote_complete.assert_called_once() self.assertEqual(self.protocol.command_id_to_command_map, {2: 'test_command'}) self.assertEqual(self.protocol.command_id_to_reader_map, {2: 'test_reader2'}) self.assertEqual(self.protocol.command_id_to_writer_map, {2: 'test_writer2'}) @defer.inlineCallbacks def test_update_upload_file_write_success(self): yield self.connect_authenticated_worker() command_id = 1 command = mock.Mock() self.protocol.command_id_to_writer_map = {command_id: command} msg = {'op': 'update_upload_file_write', 'args': 'args', 'command_id': command_id} expected = {'op': 'response', 'result': None} yield self.send_msg_check_response(self.protocol, msg, expected) command.remote_write.assert_called_once() @defer.inlineCallbacks def test_update_upload_file_utime_missing_access_time(self): yield self.connect_authenticated_worker() msg = {'op': 'update_upload_file_utime', 'modified_time': 2, 'command_id': 2} expected = { 'op': 'response', 'result': '\'message did not contain obligatory "access_time" key\'', 'is_exception': True, } yield self.send_msg_check_response(self.protocol, msg, expected) @defer.inlineCallbacks def test_update_upload_file_utime_missing_modified_time(self): yield self.connect_authenticated_worker() msg = {'op': 'update_upload_file_utime', 'access_time': 1, 'command_id': 2} expected = { 'op': 'response', 'result': '\'message did not contain obligatory "modified_time" key\'', 'is_exception': True, } yield self.send_msg_check_response(self.protocol, msg, expected) @defer.inlineCallbacks def test_update_upload_file_utime_success(self): yield self.connect_authenticated_worker() command_id = 1 command = mock.Mock() self.protocol.command_id_to_writer_map = {command_id: command} msg = { 'op': 'update_upload_file_utime', 'access_time': 1, 'modified_time': 2, 'command_id': command_id, } expected = {'op': 'response', 'result': None} yield self.send_msg_check_response(self.protocol, msg, expected) command.remote_utime.assert_called_once_with('access_time', 'modified_time') @defer.inlineCallbacks def test_update_upload_file_close_success(self): yield self.connect_authenticated_worker() command_id = 1 command = mock.Mock() self.protocol.command_id_to_writer_map = {command_id: command} msg = {'op': 'update_upload_file_close', 'command_id': command_id} expected = {'op': 'response', 'result': None} yield self.send_msg_check_response(self.protocol, msg, expected) command.remote_close.assert_called_once() @defer.inlineCallbacks def test_update_read_file_missing_length(self): yield self.connect_authenticated_worker() msg = {'op': 'update_read_file', 'command_id': 1} expected = { 'op': 'response', 'result': '\'message did not contain obligatory "length" key\'', 'is_exception': True, } yield self.send_msg_check_response(self.protocol, msg, expected) @defer.inlineCallbacks def test_update_read_file_success(self): yield self.connect_authenticated_worker() command_id = 1 command = mock.Mock() self.protocol.command_id_to_reader_map = {command_id: command} msg = {'op': 'update_read_file', 'length': 1, 'command_id': command_id} expected = {'op': 'response', 'result': None} yield self.send_msg_check_response(self.protocol, msg, expected) command.remote_read.assert_called_once_with(msg['length']) @defer.inlineCallbacks def test_update_read_file_close_success(self): yield self.connect_authenticated_worker() command_id = 1 command = mock.Mock() self.protocol.command_id_to_reader_map = {command_id: command} msg = {'op': 'update_read_file_close', 'command_id': command_id} expected = {'op': 'response', 'result': None} yield self.send_msg_check_response(self.protocol, msg, expected) command.remote_close.assert_called_once() @defer.inlineCallbacks def test_update_upload_directory_unpack_success(self): yield self.connect_authenticated_worker() command_id = 1 command = mock.Mock() self.protocol.command_id_to_writer_map = {command_id: command} msg = {'op': 'update_upload_directory_unpack', 'command_id': command_id} expected = {'op': 'response', 'result': None} yield self.send_msg_check_response(self.protocol, msg, expected) command.remote_unpack.assert_called_once() @defer.inlineCallbacks def test_update_upload_directory_write_success(self): yield self.connect_authenticated_worker() command_id = 1 command = mock.Mock() self.protocol.command_id_to_writer_map = {command_id: command} msg = {'op': 'update_upload_directory_write', 'command_id': command_id, 'args': 'args'} expected = {'op': 'response', 'result': None} yield self.send_msg_check_response(self.protocol, msg, expected) command.remote_write.assert_called_once_with(msg['args']) def test_onMessage_not_isBinary(self): # if isBinary is False, sendMessage should not be called msg = {} self.protocol.onMessage(msgpack.packb(msg), False) self.seq_number += 1 self.protocol.sendMessage.assert_not_called() @defer.inlineCallbacks def test_onMessage_worker_not_authenticated(self): msg = {'op': 'update', 'command_id': 1, 'args': 'test'} expected = { 'op': 'response', 'result': 'Worker not authenticated.', 'is_exception': True, } yield self.send_msg_check_response(self.protocol, msg, expected) @defer.inlineCallbacks def test_onMessage_command_does_not_exist(self): yield self.connect_authenticated_worker() msg = {'op': 'test'} expected = { 'op': 'response', 'result': 'Command test does not exist.', 'is_exception': True, } yield self.send_msg_check_response(self.protocol, msg, expected) @defer.inlineCallbacks def test_get_message_result_success(self): yield self.connect_authenticated_worker() msg = {'op': 'getWorkerInfo'} d = self.protocol.get_message_result(msg) seq_num = msg['seq_number'] self.assertEqual(d.called, False) self.protocol.sendMessage.assert_called() # master got an answer from worker through onMessage msg = {'seq_number': seq_num, 'op': 'response', 'result': 'test_result'} self.protocol.onMessage(msgpack.packb(msg), isBinary=True) self.assertEqual(d.called, True) res = yield d self.assertEqual(res, 'test_result') @defer.inlineCallbacks def test_get_message_result_failed(self): yield self.connect_authenticated_worker() msg = {'op': 'getWorkerInfo'} d = self.protocol.get_message_result(msg) seq_num = msg['seq_number'] self.assertEqual(d.called, False) # Master got an answer from worker through onMessage. # This time the message indicates failure msg_response = { 'seq_number': seq_num, 'op': 'response', 'is_exception': True, 'result': 'error_result', } self.protocol.onMessage(msgpack.packb(msg_response), isBinary=True) self.assertEqual(d.called, True) with self.assertRaises(RemoteWorkerError): yield d @defer.inlineCallbacks def test_get_message_result_no_worker_connection(self): # master can not send any messages if connection is not established with self.assertRaises(ConnectioLostError): yield self.protocol.get_message_result({'op': 'getWorkerInfo'}) @defer.inlineCallbacks def test_onClose_connection_lost_error(self): yield self.connect_authenticated_worker() # master sends messages for worker and waits for their response msg = {'op': 'getWorkerInfo'} d1 = self.protocol.get_message_result(msg) self.assertEqual(d1.called, False) msg = {'op': 'print', 'message': 'test'} d2 = self.protocol.get_message_result(msg) self.assertEqual(d2.called, False) # Worker disconnected, master will never get the response message. # Stop waiting and raise Exception self.protocol.onClose(True, None, 'worker is gone') self.assertEqual(d1.called, True) with self.assertRaises(ConnectioLostError): yield d1 self.assertEqual(d2.called, True) with self.assertRaises(ConnectioLostError): yield d2 self.protocol.connection.detached.assert_called() # contents of dict_def are deleted to stop waiting for the responses of all commands self.assertEqual(len(self.protocol.seq_num_to_waiters_map), 0)
22,985
Python
.py
470
40.33617
100
0.641513
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,521
test_protocols_manager_base.py
buildbot_buildbot/master/buildbot/test/unit/worker/test_protocols_manager_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 """ Test clean shutdown functionality of the master """ from unittest import mock from twisted.internet import defer from twisted.trial import unittest from buildbot.worker.protocols.manager.base import BaseDispatcher from buildbot.worker.protocols.manager.base import BaseManager class FakeMaster: initLock = defer.DeferredLock() def addService(self, svc): pass @property def master(self): return self class TestDispatcher(BaseDispatcher): def __init__(self, config_portstr, portstr): super().__init__(portstr) self.start_listening_count = 0 self.stop_listening_count = 0 def start_listening_port(self): def stopListening(): self.stop_listening_count += 1 self.start_listening_count += 1 port = mock.Mock() port.stopListening = stopListening return port class TestPort: def __init__(self, test): self.test = test def stopListening(self): self.test.stop_listening_count += 1 class TestManagerClass(BaseManager): dispatcher_class = TestDispatcher class TestBaseManager(unittest.TestCase): @defer.inlineCallbacks def setUp(self): self.manager = TestManagerClass('test_base_manager') yield self.manager.setServiceParent(FakeMaster()) def assert_equal_registration(self, result, expected): result_users = {key: result[key].users for key in result} self.assertEqual(result_users, expected) def assert_start_stop_listening_counts(self, disp, start_count, stop_count): self.assertEqual(disp.start_listening_count, start_count) self.assertEqual(disp.stop_listening_count, stop_count) @defer.inlineCallbacks def test_repr(self): reg = yield self.manager.register('tcp:port', 'x', 'y', 'pf') self.assertEqual( repr(self.manager.dispatchers['tcp:port']), '<base.BaseDispatcher for x on tcp:port>' ) self.assertEqual(repr(reg), '<base.Registration for x on tcp:port>') @defer.inlineCallbacks def test_register_before_start_service(self): yield self.manager.register('tcp:port', 'user', 'pass', 'pf') self.assert_equal_registration( self.manager.dispatchers, {'tcp:port': {'user': ('pass', 'pf')}} ) disp = self.manager.dispatchers['tcp:port'] self.assert_start_stop_listening_counts(disp, 0, 0) self.assertEqual(len(self.manager.services), 1) yield self.manager.startService() self.assert_start_stop_listening_counts(disp, 1, 0) yield self.manager.stopService() self.assert_start_stop_listening_counts(disp, 1, 1) @defer.inlineCallbacks def test_same_registration_two_times(self): yield self.manager.startService() yield self.manager.register('tcp:port', 'user', 'pass', 'pf') # one registration is ok self.assert_equal_registration( self.manager.dispatchers, {'tcp:port': {'user': ('pass', 'pf')}} ) self.assertEqual(len(self.manager.services), 1) disp = self.manager.dispatchers['tcp:port'] self.assert_start_stop_listening_counts(disp, 1, 0) # same user is not allowed to register with self.assertRaises(KeyError): yield self.manager.register('tcp:port', 'user', 'pass', 'pf') yield self.manager.stopService() self.assert_start_stop_listening_counts(disp, 1, 1) @defer.inlineCallbacks def test_register_unregister_register(self): yield self.manager.startService() reg = yield self.manager.register('tcp:port', 'user', 'pass', 'pf') self.assert_equal_registration( self.manager.dispatchers, {'tcp:port': {'user': ('pass', 'pf')}} ) disp = self.manager.dispatchers['tcp:port'] self.assert_start_stop_listening_counts(disp, 1, 0) reg.unregister() self.assert_equal_registration(self.manager.dispatchers, {}) # allow registering same user again yield self.manager.register('tcp:port', 'user', 'pass', 'pf') self.assert_equal_registration( self.manager.dispatchers, {'tcp:port': {'user': ('pass', 'pf')}} ) yield self.manager.stopService() self.assert_start_stop_listening_counts(disp, 1, 1) @defer.inlineCallbacks def test_register_unregister_empty_disp_users(self): yield self.manager.startService() reg = yield self.manager.register('tcp:port', 'user', 'pass', 'pf') self.assertEqual(len(self.manager.services), 1) expected = {'tcp:port': {'user': ('pass', 'pf')}} self.assert_equal_registration(self.manager.dispatchers, expected) disp = self.manager.dispatchers['tcp:port'] reg.unregister() self.assert_equal_registration(self.manager.dispatchers, {}) self.assertEqual(reg.username, None) self.assertEqual(len(self.manager.services), 0) yield self.manager.stopService() self.assert_start_stop_listening_counts(disp, 1, 1) @defer.inlineCallbacks def test_different_ports_same_users(self): yield self.manager.startService() # same registrations on different ports is ok reg1 = yield self.manager.register('tcp:port1', "user", "pass", 'pf') reg2 = yield self.manager.register('tcp:port2', "user", "pass", 'pf') reg3 = yield self.manager.register('tcp:port3', "user", "pass", 'pf') disp1 = self.manager.dispatchers['tcp:port1'] self.assert_start_stop_listening_counts(disp1, 1, 0) disp2 = self.manager.dispatchers['tcp:port2'] self.assert_start_stop_listening_counts(disp2, 1, 0) disp3 = self.manager.dispatchers['tcp:port3'] self.assert_start_stop_listening_counts(disp3, 1, 0) self.assert_equal_registration( self.manager.dispatchers, { 'tcp:port1': {'user': ('pass', 'pf')}, 'tcp:port2': {'user': ('pass', 'pf')}, 'tcp:port3': {'user': ('pass', 'pf')}, }, ) self.assertEqual(len(self.manager.services), 3) yield reg1.unregister() self.assert_equal_registration( self.manager.dispatchers, {'tcp:port2': {'user': ('pass', 'pf')}, 'tcp:port3': {'user': ('pass', 'pf')}}, ) self.assertEqual(reg1.username, None) self.assertEqual(len(self.manager.services), 2) self.assert_start_stop_listening_counts(disp1, 1, 1) yield reg2.unregister() self.assert_equal_registration( self.manager.dispatchers, {'tcp:port3': {'user': ('pass', 'pf')}} ) self.assertEqual(reg2.username, None) self.assertEqual(len(self.manager.services), 1) self.assert_start_stop_listening_counts(disp2, 1, 1) yield reg3.unregister() expected = {} self.assert_equal_registration(self.manager.dispatchers, expected) self.assertEqual(reg3.username, None) self.assertEqual(len(self.manager.services), 0) self.assert_start_stop_listening_counts(disp3, 1, 1) yield self.manager.stopService() self.assert_start_stop_listening_counts(disp1, 1, 1) self.assert_start_stop_listening_counts(disp2, 1, 1) self.assert_start_stop_listening_counts(disp3, 1, 1) @defer.inlineCallbacks def test_same_port_different_users(self): yield self.manager.startService() reg1 = yield self.manager.register('tcp:port', 'user1', 'pass1', 'pf1') reg2 = yield self.manager.register('tcp:port', 'user2', 'pass2', 'pf2') reg3 = yield self.manager.register('tcp:port', 'user3', 'pass3', 'pf3') disp = self.manager.dispatchers['tcp:port'] self.assertEqual(len(self.manager.services), 1) self.assert_equal_registration( self.manager.dispatchers, { 'tcp:port': { 'user1': ('pass1', 'pf1'), 'user2': ('pass2', 'pf2'), 'user3': ('pass3', 'pf3'), } }, ) self.assertEqual(len(self.manager.services), 1) yield reg1.unregister() self.assert_equal_registration( self.manager.dispatchers, {'tcp:port': {'user2': ('pass2', 'pf2'), 'user3': ('pass3', 'pf3')}}, ) self.assertEqual(reg1.username, None) self.assertEqual(len(self.manager.services), 1) yield reg2.unregister() self.assert_equal_registration( self.manager.dispatchers, {'tcp:port': {'user3': ('pass3', 'pf3')}} ) self.assertEqual(reg2.username, None) self.assertEqual(len(self.manager.services), 1) yield reg3.unregister() expected = {} self.assert_equal_registration(self.manager.dispatchers, expected) self.assertEqual(reg3.username, None) self.assertEqual(len(self.manager.services), 0) yield self.manager.stopService() self.assert_start_stop_listening_counts(disp, 1, 1)
9,837
Python
.py
213
37.723005
97
0.647016
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,522
test_local.py
buildbot_buildbot/master/buildbot/test/unit/worker/test_local.py
# This file is part of Buildbot. Buildbot is free software: you can # redistribute it and/or modify it under the terms of the GNU General Public # License as published by the Free Software Foundation, version 2. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more # details. # # You should have received a copy of the GNU General Public License along with # this program; if not, write to the Free Software Foundation, Inc., 51 # Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # Copyright Buildbot Team Members import os from unittest import mock from twisted.internet import defer from twisted.trial import unittest from buildbot.test.fake import fakemaster from buildbot.test.reactor import TestReactorMixin from buildbot.worker import local class TestLocalWorker(TestReactorMixin, unittest.TestCase): try: from buildbot_worker.bot import LocalWorker as _ except ImportError: skip = "buildbot-worker package is not installed" @defer.inlineCallbacks def setUp(self): self.setup_test_reactor(auto_tear_down=False) self.master = yield fakemaster.make_master(self, wantDb=True, wantData=True) self.botmaster = self.master.botmaster self.workers = self.master.workers @defer.inlineCallbacks def tearDown(self): yield self.tear_down_test_reactor() def createWorker(self, name='bot', attached=False, configured=True, **kwargs): worker = local.LocalWorker(name, **kwargs) if configured: worker.setServiceParent(self.workers) return worker @defer.inlineCallbacks def test_reconfigService_attrs(self): old = self.createWorker( 'bot', max_builds=2, notify_on_missing=['[email protected]'], missing_timeout=120, properties={'a': 'b'}, ) new = self.createWorker( 'bot', configured=False, max_builds=3, notify_on_missing=['[email protected]'], missing_timeout=121, workdir=os.path.abspath('custom'), properties={'a': 'c'}, ) old.updateWorker = mock.Mock(side_effect=lambda: defer.succeed(None)) yield old.startService() self.assertEqual(old.remote_worker.bot.basedir, os.path.abspath('basedir/workers/bot')) yield old.reconfigServiceWithSibling(new) self.assertEqual(old.max_builds, 3) self.assertEqual(old.notify_on_missing, ['[email protected]']) self.assertEqual(old.missing_timeout, 121) self.assertEqual(old.properties.getProperty('a'), 'c') self.assertEqual(old.registration.updates, ['bot']) self.assertTrue(old.updateWorker.called) # make sure that we can provide an absolute path self.assertEqual(old.remote_worker.bot.basedir, os.path.abspath('custom')) yield old.stopService() @defer.inlineCallbacks def test_workerinfo(self): wrk = self.createWorker( 'bot', max_builds=2, notify_on_missing=['[email protected]'], missing_timeout=120, properties={'a': 'b'}, ) yield wrk.startService() info = yield wrk.conn.remoteGetWorkerInfo() self.assertIn("worker_commands", info) yield wrk.stopService()
3,492
Python
.py
84
34.178571
95
0.678056
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,523
test_docker.py
buildbot_buildbot/master/buildbot/test/unit/worker/test_docker.py
# This file is part of Buildbot. Buildbot is free software: you can # redistribute it and/or modify it under the terms of the GNU General Public # License as published by the Free Software Foundation, version 2. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more # details. # # You should have received a copy of the GNU General Public License along with # this program; if not, write to the Free Software Foundation, Inc., 51 # Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # Copyright Buildbot Team Members from packaging.version import parse as parse_version from twisted.internet import defer from twisted.trial import unittest from buildbot import config from buildbot import interfaces from buildbot.process.properties import Interpolate from buildbot.process.properties import Properties from buildbot.process.properties import Property from buildbot.test.fake import docker from buildbot.test.fake import fakemaster from buildbot.test.reactor import TestReactorMixin from buildbot.test.util.config import ConfigErrorsMixin from buildbot.worker import docker as dockerworker class TestDockerLatentWorker(ConfigErrorsMixin, unittest.TestCase, TestReactorMixin): @defer.inlineCallbacks def setupWorker(self, *args, **kwargs): worker = dockerworker.DockerLatentWorker(*args, **kwargs) master = yield fakemaster.make_master(self, wantData=True) fakemaster.master = master worker.setServiceParent(master) yield master.startService() self.addCleanup(master.stopService) return worker def _create_client(self, *args, **kwargs): if self._client is None: self._client = docker.Client(*args, **kwargs) return self._client def setUp(self): self.setup_test_reactor(auto_tear_down=False) self.patch(dockerworker, 'docker', docker) # Patch factory function so that single test uses single client instance. self.patch(docker, "APIClient", self._create_client) self._client = None self.build = Properties(image='busybox:latest', builder='docker_worker', distro='wheezy') self.build2 = Properties(image='busybox:latest', builder='docker_worker2', distro='wheezy') docker.Client.containerCreated = False docker.Client.start_exception = None @defer.inlineCallbacks def tearDown(self): yield self.tear_down_test_reactor() @defer.inlineCallbacks def test_constructor_noimage_nodockerfile(self): with self.assertRaises(config.ConfigErrors): yield self.setupWorker('bot', 'pass', 'http://localhost:2375') @defer.inlineCallbacks def test_constructor_noimage_dockerfile(self): bs = yield self.setupWorker( 'bot', 'pass', 'http://localhost:2375', dockerfile="FROM ubuntu" ) self.assertEqual(bs.dockerfile, "FROM ubuntu") self.assertEqual(bs.image, None) @defer.inlineCallbacks def test_constructor_image_nodockerfile(self): bs = yield self.setupWorker('bot', 'pass', 'http://localhost:2375', image="myworker") self.assertEqual(bs.dockerfile, None) self.assertEqual(bs.image, 'myworker') @defer.inlineCallbacks def test_constructor_minimal(self): # Minimal set of parameters bs = yield self.setupWorker('bot', 'pass', 'tcp://1234:2375', 'worker') self.assertEqual(bs.workername, 'bot') self.assertEqual(bs.password, 'pass') self.assertEqual(bs.docker_host, 'tcp://1234:2375') self.assertEqual(bs.client_args, {}) self.assertEqual(bs.image, 'worker') self.assertEqual(bs.command, []) @defer.inlineCallbacks def test_builds_may_be_incompatible(self): # Minimal set of parameters bs = yield self.setupWorker('bot', 'pass', 'tcp://1234:2375', 'worker') self.assertEqual(bs.builds_may_be_incompatible, True) @defer.inlineCallbacks def test_contruction_too_old_docker(self): self.patch(dockerworker, 'docker_py_version', parse_version("3.2")) with self.assertRaisesConfigError("The python module 'docker>=4.0'"): yield self.setupWorker('bot', 'pass', 'tcp://1234:2375', 'worker') @defer.inlineCallbacks def test_contruction_minimal_docker(self): bs = yield self.setupWorker('bot', 'pass', 'tcp://1234:2375', 'worker') yield bs.start_instance(self.build) self.assertEqual( [c["Names"] for c in self._client._containers.values()], [["/buildbot-bot-87de7e"]] ) @defer.inlineCallbacks def test_constructor_nopassword(self): # when no password, it is created automatically bs = yield self.setupWorker('bot', None, 'tcp://1234:2375', 'worker') self.assertEqual(bs.workername, 'bot') self.assertEqual(len(bs.password), 20) @defer.inlineCallbacks def test_constructor_all_docker_parameters(self): # Volumes have their own tests bs = yield self.setupWorker( 'bot', 'pass', 'unix:///var/run/docker.sock', 'worker_img', ['/bin/sh'], dockerfile="FROM ubuntu", version='1.9', tls=True, hostconfig={'network_mode': 'fake', 'dns': ['1.1.1.1', '1.2.3.4']}, custom_context=False, buildargs=None, encoding='gzip', ) self.assertEqual(bs.workername, 'bot') self.assertEqual(bs.docker_host, 'unix:///var/run/docker.sock') self.assertEqual(bs.password, 'pass') self.assertEqual(bs.image, 'worker_img') self.assertEqual(bs.command, ['/bin/sh']) self.assertEqual(bs.dockerfile, "FROM ubuntu") self.assertEqual(bs.volumes, []) self.assertEqual(bs.client_args, {'version': '1.9', 'tls': True}) self.assertEqual(bs.hostconfig, {'network_mode': 'fake', 'dns': ['1.1.1.1', '1.2.3.4']}) self.assertFalse(bs.custom_context) self.assertEqual(bs.buildargs, None) self.assertEqual(bs.encoding, 'gzip') @defer.inlineCallbacks def test_constructor_host_config_build(self): # Volumes have their own tests bs = yield self.setupWorker( 'bot', 'pass', 'unix:///var/run/docker.sock', 'worker_img', ['/bin/sh'], dockerfile="FROM ubuntu", volumes=["/tmp:/tmp:ro"], hostconfig={'network_mode': 'fake', 'dns': ['1.1.1.1', '1.2.3.4']}, custom_context=False, buildargs=None, encoding='gzip', ) yield bs.start_instance(self.build) expected = { 'network_mode': 'fake', 'dns': ['1.1.1.1', '1.2.3.4'], 'binds': ['/tmp:/tmp:ro'], "init": True, } self.assertEqual(self._client.call_args_create_host_config, [expected]) @defer.inlineCallbacks def test_constructor_host_config_build_set_init(self): # Volumes have their own tests bs = yield self.setupWorker( 'bot', 'pass', 'unix:///var/run/docker.sock', 'worker_img', ['/bin/sh'], dockerfile="FROM ubuntu", volumes=["/tmp:/tmp:ro"], hostconfig={'network_mode': 'fake', 'dns': ['1.1.1.1', '1.2.3.4'], 'init': False}, custom_context=False, buildargs=None, encoding='gzip', ) yield bs.start_instance(self.build) self.assertEqual( self._client.call_args_create_host_config, [ { 'network_mode': 'fake', 'dns': ['1.1.1.1', '1.2.3.4'], 'init': False, 'binds': ['/tmp:/tmp:ro'], } ], ) @defer.inlineCallbacks def test_start_instance_docker_host_renderable(self): bs = yield self.setupWorker( 'bot', 'pass', docker_host=Interpolate('tcp://value-%(prop:builder)s'), image='worker' ) yield bs.start_instance(self.build) self.assertEqual(self._client.base_url, 'tcp://value-docker_worker') @defer.inlineCallbacks def test_start_instance_volume_renderable(self): bs = yield self.setupWorker( 'bot', 'pass', 'tcp://1234:2375', 'worker', ['bin/bash'], volumes=[ Interpolate('/data:/worker/%(kw:builder)s/build', builder=Property('builder')) ], ) yield bs.start_instance(self.build) self.assertEqual(len(self._client.call_args_create_container), 1) self.assertEqual( self._client.call_args_create_container[0]['volumes'], ['/worker/docker_worker/build'] ) @defer.inlineCallbacks def test_start_instance_hostconfig_renderable(self): bs = yield self.setupWorker( 'bot', 'pass', docker_host='tcp://1234:2375', image='worker', hostconfig={'prop': Interpolate('value-%(kw:builder)s', builder=Property('builder'))}, ) yield bs.start_instance(self.build) self.assertEqual(len(self._client.call_args_create_container), 1) expected = {'prop': 'value-docker_worker', 'binds': [], "init": True} self.assertEqual(self._client.call_args_create_host_config, [expected]) @defer.inlineCallbacks def test_interpolate_renderables_for_new_build(self): bs = yield self.setupWorker( 'bot', 'pass', 'tcp://1234:2375', 'worker', ['bin/bash'], volumes=[ Interpolate('/data:/worker/%(kw:builder)s/build', builder=Property('builder')) ], ) yield bs.start_instance(self.build) docker.Client.containerCreated = True # the worker recreates the (mock) client on every action, clearing the containers # but stop_instance only works if the there is a docker container running yield bs.stop_instance() self.assertTrue((yield bs.isCompatibleWithBuild(self.build2))) @defer.inlineCallbacks def test_reject_incompatible_build_while_running(self): bs = yield self.setupWorker( 'bot', 'pass', 'tcp://1234:2375', 'worker', ['bin/bash'], volumes=[ Interpolate('/data:/worker/%(kw:builder)s/build', builder=Property('builder')) ], ) yield bs.start_instance(self.build) self.assertFalse((yield bs.isCompatibleWithBuild(self.build2))) @defer.inlineCallbacks def test_volume_no_suffix(self): bs = yield self.setupWorker( 'bot', 'pass', 'tcp://1234:2375', 'worker', ['bin/bash'], volumes=['/src/webapp:/opt/webapp'], ) yield bs.start_instance(self.build) self.assertEqual(len(self._client.call_args_create_container), 1) self.assertEqual(len(self._client.call_args_create_host_config), 1) self.assertEqual(self._client.call_args_create_container[0]['volumes'], ['/opt/webapp']) self.assertEqual( self._client.call_args_create_host_config[0]['binds'], ["/src/webapp:/opt/webapp"] ) @defer.inlineCallbacks def test_volume_ro_rw(self): bs = yield self.setupWorker( 'bot', 'pass', 'tcp://1234:2375', 'worker', ['bin/bash'], volumes=['/src/webapp:/opt/webapp:ro', '~:/backup:rw'], ) yield bs.start_instance(self.build) self.assertEqual(len(self._client.call_args_create_container), 1) self.assertEqual(len(self._client.call_args_create_host_config), 1) self.assertEqual( self._client.call_args_create_container[0]['volumes'], ['/opt/webapp', '/backup'] ) self.assertEqual( self._client.call_args_create_host_config[0]['binds'], ['/src/webapp:/opt/webapp:ro', '~:/backup:rw'], ) @defer.inlineCallbacks def test_volume_bad_format(self): with self.assertRaises(config.ConfigErrors): yield self.setupWorker( 'bot', 'pass', 'http://localhost:2375', image="worker", volumes=['abcd=efgh'] ) @defer.inlineCallbacks def test_volume_bad_format_renderable(self): bs = yield self.setupWorker( 'bot', 'pass', 'http://localhost:2375', image="worker", volumes=[ Interpolate('/data==/worker/%(kw:builder)s/build', builder=Property('builder')) ], ) with self.assertRaises(config.ConfigErrors): yield bs.start_instance(self.build) @defer.inlineCallbacks def test_start_instance_image_no_version(self): bs = yield self.setupWorker('bot', 'pass', 'tcp://1234:2375', 'busybox', ['bin/bash']) _, name = yield bs.start_instance(self.build) self.assertEqual(name, 'busybox') @defer.inlineCallbacks def test_start_instance_image_right_version(self): bs = yield self.setupWorker( 'bot', 'pass', 'tcp://1234:2375', 'busybox:latest', ['bin/bash'] ) _, name = yield bs.start_instance(self.build) self.assertEqual(name, 'busybox:latest') @defer.inlineCallbacks def test_start_instance_image_wrong_version(self): bs = yield self.setupWorker('bot', 'pass', 'tcp://1234:2375', 'busybox:123', ['bin/bash']) with self.assertRaises(interfaces.LatentWorkerCannotSubstantiate): yield bs.start_instance(self.build) @defer.inlineCallbacks def test_start_instance_image_renderable(self): bs = yield self.setupWorker( 'bot', 'pass', 'tcp://1234:2375', Property('image'), ['bin/bash'] ) _, name = yield bs.start_instance(self.build) self.assertEqual(name, 'busybox:latest') @defer.inlineCallbacks def test_start_instance_noimage_nodockerfile(self): bs = yield self.setupWorker('bot', 'pass', 'tcp://1234:2375', 'customworker', ['bin/bash']) with self.assertRaises(interfaces.LatentWorkerCannotSubstantiate): yield bs.start_instance(self.build) @defer.inlineCallbacks def test_start_instance_image_and_dockefile(self): bs = yield self.setupWorker( 'bot', 'pass', 'tcp://1234:2375', 'customworker', dockerfile='BUG' ) with self.assertRaises(interfaces.LatentWorkerCannotSubstantiate): yield bs.start_instance(self.build) @defer.inlineCallbacks def test_start_instance_noimage_gooddockerfile(self): bs = yield self.setupWorker( 'bot', 'pass', 'tcp://1234:2375', 'customworker', dockerfile='FROM debian:wheezy' ) _, name = yield bs.start_instance(self.build) self.assertEqual(name, 'customworker') @defer.inlineCallbacks def test_start_instance_noimage_pull(self): bs = yield self.setupWorker( 'bot', 'pass', 'tcp://1234:2375', 'alpine:latest', autopull=True ) _, name = yield bs.start_instance(self.build) self.assertEqual(name, 'alpine:latest') @defer.inlineCallbacks def test_start_instance_image_pull(self): bs = yield self.setupWorker( 'bot', 'pass', 'tcp://1234:2375', 'tester:latest', autopull=True ) _, name = yield bs.start_instance(self.build) self.assertEqual(name, 'tester:latest') self.assertEqual(self._client._pullCount, 0) @defer.inlineCallbacks def test_start_instance_image_alwayspull(self): bs = yield self.setupWorker( 'bot', 'pass', 'tcp://1234:2375', 'tester:latest', autopull=True, alwaysPull=True ) _, name = yield bs.start_instance(self.build) self.assertEqual(name, 'tester:latest') self.assertEqual(self._client._pullCount, 1) @defer.inlineCallbacks def test_start_instance_image_noauto_alwayspull(self): bs = yield self.setupWorker( 'bot', 'pass', 'tcp://1234:2375', 'tester:latest', autopull=False, alwaysPull=True ) _, name = yield bs.start_instance(self.build) self.assertEqual(name, 'tester:latest') self.assertEqual(self._client._pullCount, 0) @defer.inlineCallbacks def test_start_instance_noimage_renderabledockerfile(self): bs = yield self.setupWorker( 'bot', 'pass', 'tcp://1234:2375', 'customworker', dockerfile=Interpolate('FROM debian:%(kw:distro)s', distro=Property('distro')), ) _, name = yield bs.start_instance(self.build) self.assertEqual(name, 'customworker') @defer.inlineCallbacks def test_start_instance_custom_context_and_buildargs(self): bs = yield self.setupWorker( 'bot', 'pass', 'tcp://1234:2375', 'tester:latest', dockerfile=Interpolate('FROM debian:latest'), custom_context=True, buildargs={'sample_arg1': 'test_val1'}, ) _, name = yield bs.start_instance(self.build) self.assertEqual(name, 'tester:latest') @defer.inlineCallbacks def test_start_instance_custom_context_no_buildargs(self): bs = yield self.setupWorker( 'bot', 'pass', 'tcp://1234:2375', 'tester:latest', dockerfile=Interpolate('FROM debian:latest'), custom_context=True, ) _, name = yield bs.start_instance(self.build) self.assertEqual(name, 'tester:latest') @defer.inlineCallbacks def test_start_instance_buildargs_no_custom_context(self): bs = yield self.setupWorker( 'bot', 'pass', 'tcp://1234:2375', 'tester:latest', dockerfile=Interpolate('FROM debian:latest'), buildargs={'sample_arg1': 'test_val1'}, ) _, name = yield bs.start_instance(self.build) self.assertEqual(name, 'tester:latest') @defer.inlineCallbacks def test_start_worker_but_already_created_with_same_name(self): bs = yield self.setupWorker( 'existing', 'pass', 'tcp://1234:2375', 'busybox:latest', ['bin/bash'] ) _, name = yield bs.start_instance(self.build) self.assertEqual(name, 'busybox:latest') @defer.inlineCallbacks def test_start_instance_client_start_exception(self): msg = 'The container operating system does not match the host operating system' docker.Client.start_exception = docker.errors.APIError(msg) bs = yield self.setupWorker( 'bot', 'pass', 'tcp://1234:2375', 'busybox:latest', ['bin/bash'] ) with self.assertRaises(interfaces.LatentWorkerCannotSubstantiate): yield bs.start_instance(self.build) @defer.inlineCallbacks def test_constructor_hostname(self): bs = yield self.setupWorker( 'bot', 'pass', 'http://localhost:2375', image="myworker_image", hostname="myworker_hostname", ) self.assertEqual(bs.hostname, 'myworker_hostname') @defer.inlineCallbacks def test_check_instance_running(self): bs = yield self.setupWorker('bot', 'pass', 'tcp://1234:2375', 'worker') yield bs.start_instance(self.build) self.assertEqual((yield bs.check_instance()), (True, "")) @defer.inlineCallbacks def test_check_instance_exited(self): bs = yield self.setupWorker('bot', 'pass', 'tcp://1234:2375', 'worker') yield bs.start_instance(self.build) for c in self._client._containers.values(): c["State"] = "exited" expected_logs = ( "logs: \n" "log for 8a61192da2b3bb2d922875585e29b74ec0dc4e0117fcbf84c962204e97564cd7\n" "1\n" "2\n" "3\n" "end\n" ) self.assertEqual((yield bs.check_instance()), (False, expected_logs)) class testDockerPyStreamLogs(unittest.TestCase): def compare(self, result, log): self.assertEqual(result, list(dockerworker._handle_stream_line(log))) def testEmpty(self): self.compare([], '{"stream":"\\n"}\r\n') def testOneLine(self): self.compare([" ---> Using cache"], '{"stream":" ---\\u003e Using cache\\n"}\r\n') def testMultipleLines(self): self.compare( ["Fetched 8298 kB in 3s (2096 kB/s)", "Reading package lists..."], '{"stream": "Fetched 8298 kB in 3s (2096 kB/s)\\nReading package lists..."}\r\n', ) def testError(self): self.compare( [ "ERROR: The command [/bin/sh -c apt-get update && apt-get install -y" " python-dev python-pip] returned a non-zero code: 127" ], '{"errorDetail": {"message": "The command [/bin/sh -c apt-get update && ' 'apt-get install -y python-dev python-pip] returned a ' 'non-zero code: 127"},' ' "error": "The command [/bin/sh -c apt-get update && apt-get install -y' ' python-dev python-pip] returned a non-zero code: 127"}\r\n', )
21,679
Python
.py
501
33.838323
99
0.611924
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,524
test_kubernetes.py
buildbot_buildbot/master/buildbot/test/unit/worker/test_kubernetes.py
# This file is part of Buildbot. Buildbot is free software: you can # redistribute it and/or modify it under the terms of the GNU General Public # License as published by the Free Software Foundation, version 2. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more # details. # # You should have received a copy of the GNU General Public License along with # this program; if not, write to the Free Software Foundation, Inc., 51 # Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # Copyright Buildbot Team Members import base64 from unittest import mock from twisted.internet import defer from twisted.trial import unittest from buildbot.interfaces import LatentWorkerFailedToSubstantiate from buildbot.process.properties import Interpolate from buildbot.process.properties import Properties from buildbot.test.fake import fakemaster from buildbot.test.fake import httpclientservice as fakehttpclientservice from buildbot.test.fake.fakebuild import FakeBuildForRendering as FakeBuild from buildbot.test.fake.fakeprotocol import FakeTrivialConnection as FakeBot from buildbot.test.reactor import TestReactorMixin from buildbot.util.kubeclientservice import KubeHardcodedConfig from buildbot.worker import kubernetes class FakeResult: code = 204 def mock_delete(*args): return defer.succeed(FakeResult()) KUBE_CTL_PROXY_FAKE = """ import time import sys print("Starting to serve on 127.0.0.1:" + sys.argv[2]) sys.stdout.flush() time.sleep(1000) """ KUBE_CTL_PROXY_FAKE_ERROR = """ import time import sys print("Issue with the config!", file=sys.stderr) sys.stderr.flush() sys.exit(1) """ class TestKubernetesWorker(TestReactorMixin, unittest.TestCase): worker = None def setUp(self): self.setup_test_reactor(auto_tear_down=False) @defer.inlineCallbacks def setupWorker(self, *args, config=None, **kwargs): self.patch(kubernetes.KubeLatentWorker, "_generate_random_password", lambda _: "random_pw") if config is None: config = KubeHardcodedConfig(master_url="https://kube.example.com") worker = kubernetes.KubeLatentWorker( *args, masterFQDN="buildbot-master", kube_config=config, **kwargs ) self.master = yield fakemaster.make_master(self, wantData=True) self._http = yield fakehttpclientservice.HTTPClientService.getService( self.master, self, "https://kube.example.com" ) yield worker.setServiceParent(self.master) yield self.master.startService() self.assertTrue(config.running) self.addCleanup(self.master.stopService) return worker @defer.inlineCallbacks def tearDown(self): yield self.tear_down_test_reactor() def get_expected_metadata(self): return {"name": "buildbot-worker-87de7e"} def get_expected_spec(self, image): return { "affinity": {}, "containers": [ { "name": "buildbot-worker-87de7e", "image": image, "env": [ {"name": "BUILDMASTER", "value": "buildbot-master"}, {"name": "WORKERNAME", "value": "worker"}, {"name": "WORKERPASS", "value": "random_pw"}, {"name": "BUILDMASTER_PORT", "value": "1234"}, ], "resources": {}, "volumeMounts": [], } ], "nodeSelector": {}, "restartPolicy": "Never", "volumes": [], } def test_instantiate(self): worker = kubernetes.KubeLatentWorker('worker') # class instantiation configures nothing self.assertEqual(getattr(worker, '_kube', None), None) @defer.inlineCallbacks def test_wrong_arg(self): with self.assertRaises(TypeError): yield self.setupWorker('worker', wrong_param='wrong_param') def test_service_arg(self): return self.setupWorker('worker') @defer.inlineCallbacks def test_builds_may_be_incompatible(self): worker = yield self.setupWorker('worker') # http is lazily created on worker substantiation self.assertEqual(worker.builds_may_be_incompatible, True) @defer.inlineCallbacks def test_start_service(self): worker = yield self.setupWorker('worker') # http is lazily created on worker substantiation self.assertNotEqual(worker._kube, None) def expect_pod_delete_nonexisting(self): self._http.expect( "delete", "/api/v1/namespaces/default/pods/buildbot-worker-87de7e", params={"graceperiod": 0}, code=404, content_json={"message": "Pod not found", "reason": "NotFound"}, ) def expect_pod_delete_existing(self, image): self._http.expect( "delete", "/api/v1/namespaces/default/pods/buildbot-worker-87de7e", params={"graceperiod": 0}, code=200, content_json={ "kind": "Pod", "metadata": self.get_expected_metadata(), "spec": self.get_expected_spec(image), }, ) def expect_pod_status_not_found(self): self._http.expect( "get", "/api/v1/namespaces/default/pods/buildbot-worker-87de7e/status", code=404, content_json={"kind": "Status", "reason": "NotFound"}, ) def expect_pod_status_exists(self, image): self._http.expect( "get", "/api/v1/namespaces/default/pods/buildbot-worker-87de7e/status", code=200, content_json={ "kind": "Pod", "metadata": self.get_expected_metadata(), "spec": self.get_expected_spec(image), }, ) def expect_pod_startup(self, image): self._http.expect( "post", "/api/v1/namespaces/default/pods", json={ "apiVersion": "v1", "kind": "Pod", "metadata": self.get_expected_metadata(), "spec": self.get_expected_spec(image), }, code=200, content_json={ "kind": "Pod", "metadata": self.get_expected_metadata(), "spec": self.get_expected_spec(image), }, ) def expect_pod_startup_error(self, image): self._http.expect( "post", "/api/v1/namespaces/default/pods", json={ "apiVersion": "v1", "kind": "Pod", "metadata": self.get_expected_metadata(), "spec": self.get_expected_spec(image), }, code=400, content_json={"kind": "Status", "reason": "MissingName", "message": "need name"}, ) @defer.inlineCallbacks def test_start_worker(self): worker = yield self.setupWorker('worker') self.expect_pod_delete_nonexisting() self.expect_pod_status_not_found() self.expect_pod_startup("rendered:buildbot/buildbot-worker") self.expect_pod_delete_existing("rendered:buildbot/buildbot-worker") self.expect_pod_status_not_found() d = worker.substantiate(None, FakeBuild()) worker.attached(FakeBot()) yield d @defer.inlineCallbacks def test_start_worker_but_error(self): worker = yield self.setupWorker('worker') self.expect_pod_delete_nonexisting() self.expect_pod_status_not_found() self.expect_pod_delete_nonexisting() self.expect_pod_status_not_found() def create_pod(namespace, spec): raise kubernetes.KubeJsonError(400, {'message': "yeah, but no"}) with mock.patch.object(worker, '_create_pod', create_pod): with self.assertRaises(LatentWorkerFailedToSubstantiate): yield worker.substantiate(None, FakeBuild()) self.assertEqual(worker.instance, None) @defer.inlineCallbacks def test_start_worker_but_error_spec(self): worker = yield self.setupWorker('worker') self.expect_pod_delete_nonexisting() self.expect_pod_status_not_found() self.expect_pod_startup_error("rendered:buildbot/buildbot-worker") self.expect_pod_delete_nonexisting() self.expect_pod_status_not_found() with self.assertRaises(LatentWorkerFailedToSubstantiate): yield worker.substantiate(None, FakeBuild()) self.assertEqual(worker.instance, None) @defer.inlineCallbacks def test_interpolate_renderables_for_new_build(self): build1 = Properties(img_prop="image1") build2 = Properties(img_prop="image2") worker = yield self.setupWorker('worker', image=Interpolate("%(prop:img_prop)s")) self.expect_pod_delete_nonexisting() self.expect_pod_status_not_found() self.expect_pod_startup("image1") self.expect_pod_delete_existing("image1") self.expect_pod_status_not_found() yield worker.start_instance(build1) yield worker.stop_instance() self.assertTrue((yield worker.isCompatibleWithBuild(build2))) @defer.inlineCallbacks def test_reject_incompatible_build_while_running(self): build1 = Properties(img_prop="image1") build2 = Properties(img_prop="image2") worker = yield self.setupWorker('worker', image=Interpolate("%(prop:img_prop)s")) self.expect_pod_delete_nonexisting() self.expect_pod_status_not_found() self.expect_pod_startup("image1") self.expect_pod_delete_existing("image1") self.expect_pod_status_not_found() yield worker.start_instance(build1) self.assertFalse((yield worker.isCompatibleWithBuild(build2))) yield worker.stop_instance() @defer.inlineCallbacks def test_start_worker_delete_non_json_response(self): worker = yield self.setupWorker('worker') self._http.expect( "delete", "/api/v1/namespaces/default/pods/buildbot-worker-87de7e", params={"graceperiod": 0}, code=404, content="not json", ) self.expect_pod_delete_nonexisting() self.expect_pod_status_not_found() with self.assertRaises(LatentWorkerFailedToSubstantiate) as e: yield worker.substantiate(None, FakeBuild()) self.assertIn("Failed to decode: not json", e.exception.args[0]) @defer.inlineCallbacks def test_start_worker_delete_timeout(self): worker = yield self.setupWorker('worker', missing_timeout=4) self.expect_pod_delete_existing("rendered:buildbot/buildbot-worker") self.expect_pod_status_exists("rendered:buildbot/buildbot-worker") self.expect_pod_status_exists("rendered:buildbot/buildbot-worker") self.expect_pod_status_exists("rendered:buildbot/buildbot-worker") self.expect_pod_status_exists("rendered:buildbot/buildbot-worker") self.expect_pod_status_exists("rendered:buildbot/buildbot-worker") d = worker.stop_instance() self.reactor.pump([0.5] * 20) with self.assertRaises(TimeoutError): yield d @defer.inlineCallbacks def test_start_worker_create_non_json_response(self): worker = yield self.setupWorker('worker') self.expect_pod_delete_nonexisting() self.expect_pod_status_not_found() expected_metadata = {"name": "buildbot-worker-87de7e"} expected_spec = { "affinity": {}, "containers": [ { "name": "buildbot-worker-87de7e", "image": "rendered:buildbot/buildbot-worker", "env": [ {"name": "BUILDMASTER", "value": "buildbot-master"}, {"name": "WORKERNAME", "value": "worker"}, {"name": "WORKERPASS", "value": "random_pw"}, {"name": "BUILDMASTER_PORT", "value": "1234"}, ], "resources": {}, "volumeMounts": [], } ], "nodeSelector": {}, "restartPolicy": "Never", "volumes": [], } self._http.expect( "post", "/api/v1/namespaces/default/pods", json={ "apiVersion": "v1", "kind": "Pod", "metadata": expected_metadata, "spec": expected_spec, }, code=200, content="not json", ) self.expect_pod_delete_nonexisting() self.expect_pod_status_not_found() with self.assertRaises(LatentWorkerFailedToSubstantiate) as e: yield worker.substantiate(None, FakeBuild()) self.assertIn("Failed to decode: not json", e.exception.args[0]) @defer.inlineCallbacks def test_hardcoded_config_verify_is_forwarded(self): config = KubeHardcodedConfig( master_url="https://kube.example.com", namespace="default", verify="/path/to/pem" ) worker = yield self.setupWorker('worker', config=config) self._http.expect( "delete", "/api/v1/namespaces/default/pods/buildbot-worker-87de7e", params={"graceperiod": 0}, verify="/path/to/pem", code=200, content_json={}, ) self._http.expect( "get", "/api/v1/namespaces/default/pods/buildbot-worker-87de7e/status", verify="/path/to/pem", code=404, content_json={"kind": "Status", "reason": "NotFound"}, ) yield worker.stop_instance() @defer.inlineCallbacks def test_hardcoded_config_verify_headers_is_forwarded(self): config = KubeHardcodedConfig( master_url="https://kube.example.com", namespace="default", verify="/path/to/pem", headers={"Test": "10"}, ) worker = yield self.setupWorker('worker', config=config) self._http.expect( "delete", "/api/v1/namespaces/default/pods/buildbot-worker-87de7e", params={"graceperiod": 0}, headers={'Test': '10'}, verify="/path/to/pem", code=200, content_json={}, ) self._http.expect( "get", "/api/v1/namespaces/default/pods/buildbot-worker-87de7e/status", headers={'Test': '10'}, verify="/path/to/pem", code=404, content_json={"kind": "Status", "reason": "NotFound"}, ) yield worker.stop_instance() @defer.inlineCallbacks def test_hardcoded_config_verify_bearer_token_is_rendered(self): config = KubeHardcodedConfig( master_url="https://kube.example.com", namespace="default", verify="/path/to/pem", bearerToken=Interpolate("%(kw:test)s", test=10), ) worker = yield self.setupWorker('worker', config=config) self._http.expect( "delete", "/api/v1/namespaces/default/pods/buildbot-worker-87de7e", params={"graceperiod": 0}, headers={"Authorization": "Bearer 10"}, verify="/path/to/pem", code=200, content_json={}, ) self._http.expect( "get", "/api/v1/namespaces/default/pods/buildbot-worker-87de7e/status", headers={"Authorization": "Bearer 10"}, verify="/path/to/pem", code=404, content_json={"kind": "Status", "reason": "NotFound"}, ) yield worker.stop_instance() @defer.inlineCallbacks def test_hardcoded_config_verify_basicAuth_is_expanded(self): config = KubeHardcodedConfig( master_url="https://kube.example.com", namespace="default", verify="/path/to/pem", basicAuth={'user': 'name', 'password': Interpolate("%(kw:test)s", test=10)}, ) worker = yield self.setupWorker('worker', config=config) self._http.expect( "delete", "/api/v1/namespaces/default/pods/buildbot-worker-87de7e", params={"graceperiod": 0}, headers={"Authorization": "Basic " + str(base64.b64encode(b"name:10"))}, verify="/path/to/pem", code=200, content_json={}, ) self._http.expect( "get", "/api/v1/namespaces/default/pods/buildbot-worker-87de7e/status", headers={"Authorization": "Basic " + str(base64.b64encode(b"name:10"))}, verify="/path/to/pem", code=404, content_json={"kind": "Status", "reason": "NotFound"}, ) yield worker.stop_instance()
17,218
Python
.py
416
31.151442
99
0.601877
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,525
test_interfaces.py
buildbot_buildbot/master/buildbot/test/unit/util/test_interfaces.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.test.util import interfaces class TestAssertArgSpecMatches(interfaces.InterfaceTests, unittest.TestCase): def test_simple_decorator(self): def myfunc(x, y=2, *args): pass @self.assertArgSpecMatches(myfunc) def myfunc2(x, y=2, *args): pass try: @self.assertArgSpecMatches(myfunc) def myfunc3(x, y=3, *args): pass except Exception as e: error = e else: error = None self.assertIdentical(type(error), unittest.FailTest) self.assertEqual(error.args, ('Expected: (x, y=3, *args); got: (x, y=2, *args)',)) def test_double_decorator(self): def myfunc(x, y): pass def myfunc2(x, y): pass def myfunc3(x, yy): pass @self.assertArgSpecMatches(myfunc, myfunc2) def myfunc4(x, y): pass try: @self.assertArgSpecMatches(myfunc, myfunc3) def myfunc5(x, y): pass except Exception as e: error = e else: error = None self.assertIdentical(type(error), unittest.FailTest) self.assertEqual(error.args, ('Expected: (x, y); got: (x, yy)',)) try: @self.assertArgSpecMatches(myfunc, myfunc3) def myfunc6(xx, yy): pass except Exception as e: error = e else: error = None self.assertIdentical(type(error), unittest.FailTest) self.assertEqual(error.args, ('Expected: (x, y); got: (x, yy)',)) def test_function_style(self): def myfunc(x, y=2, *args): pass def myfunc2(x, y=2, *args): pass def myfunc3(x, y=3, *args): pass self.assertArgSpecMatches(myfunc, myfunc2) try: self.assertArgSpecMatches(myfunc, myfunc3) except Exception as e: error = e else: error = None self.assertIdentical(type(error), unittest.FailTest) self.assertEqual(error.args, ('Expected: (x, y=2, *args); got: (x, y=3, *args)',))
2,956
Python
.py
79
28.43038
90
0.609474
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,526
test_ComparableMixin.py
buildbot_buildbot/master/buildbot/test/unit/util/test_ComparableMixin.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 typing import ClassVar from typing import Sequence from twisted.trial import unittest from buildbot import util class ComparableMixin(unittest.TestCase): class Foo(util.ComparableMixin): compare_attrs: ClassVar[Sequence[str]] = ("a", "b") def __init__(self, a, b, c): self.a, self.b, self.c = a, b, c class Bar(Foo, util.ComparableMixin): compare_attrs: ClassVar[Sequence[str]] = ("b", "c") def setUp(self): self.f123 = self.Foo(1, 2, 3) self.f124 = self.Foo(1, 2, 4) self.f134 = self.Foo(1, 3, 4) self.b123 = self.Bar(1, 2, 3) self.b223 = self.Bar(2, 2, 3) self.b213 = self.Bar(2, 1, 3) def test_equality_identity(self): self.assertEqual(self.f123, self.f123) def test_equality_same(self): another_f123 = self.Foo(1, 2, 3) self.assertEqual(self.f123, another_f123) def test_equality_unimportantDifferences(self): self.assertEqual(self.f123, self.f124) def test_inequality_unimportantDifferences_subclass(self): # verify that the parent class's compare_attrs does # affect the subclass self.assertNotEqual(self.b123, self.b223) def test_inequality_importantDifferences(self): self.assertNotEqual(self.f123, self.f134) def test_inequality_importantDifferences_subclass(self): self.assertNotEqual(self.b123, self.b213) def test_inequality_differentClasses(self): self.assertNotEqual(self.f123, self.b123) def test_instance_attribute_not_used(self): # setting compare_attrs as an instance method doesn't # affect the outcome of the comparison another_f123 = self.Foo(1, 2, 3) another_f123.compare_attrs = ("b", "a") # type: ignore self.assertEqual(self.f123, another_f123) def test_ne_importantDifferences(self): self.assertNotEqual(self.f123, self.f134) def test_ne_differentClasses(self): self.assertNotEqual(self.f123, self.b123) def test_compare(self): self.assertEqual(self.f123, self.f123) self.assertNotEqual(self.b223, self.b213) self.assertGreater(self.b223, self.b213) # Different classes self.assertFalse(self.b223 > self.f123) self.assertGreaterEqual(self.b223, self.b213) self.assertGreaterEqual(self.b223, self.b223) # Different classes self.assertFalse(self.f123 >= self.b123) self.assertLess(self.b213, self.b223) self.assertLessEqual(self.b213, self.b223) self.assertLessEqual(self.b213, self.b213) # Different classes self.assertFalse(self.f123 <= self.b123)
3,397
Python
.py
74
39.337838
79
0.696575
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,527
test_ssfilter.py
buildbot_buildbot/master/buildbot/test/unit/util/test_ssfilter.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 parameterized import parameterized from twisted.trial import unittest from buildbot.util.ssfilter import SourceStampFilter from buildbot.util.ssfilter import extract_filter_values from buildbot.util.ssfilter import extract_filter_values_branch from buildbot.util.ssfilter import extract_filter_values_regex class TestSourceStampFilter(unittest.TestCase): def test_extract_filter_values(self): self.assertEqual(extract_filter_values([], 'name'), []) self.assertEqual(extract_filter_values(['value'], 'name'), ['value']) self.assertEqual(extract_filter_values('value', 'name'), ['value']) with self.assertRaises(ValueError): extract_filter_values({'value'}, 'name') with self.assertRaises(ValueError): extract_filter_values(None, 'name') with self.assertRaises(ValueError): extract_filter_values([{'value'}], 'name') with self.assertRaises(ValueError): extract_filter_values([None], 'name') def test_extract_filter_values_branch(self): self.assertEqual(extract_filter_values_branch([], 'name'), []) self.assertEqual(extract_filter_values_branch(['value'], 'name'), ['value']) self.assertEqual(extract_filter_values_branch('value', 'name'), ['value']) self.assertEqual(extract_filter_values_branch([None], 'name'), [None]) self.assertEqual(extract_filter_values_branch(None, 'name'), [None]) with self.assertRaises(ValueError): extract_filter_values({'value'}, 'name') with self.assertRaises(ValueError): extract_filter_values([{'value'}], 'name') def test_extract_filter_values_regex(self): self.assertEqual(extract_filter_values_regex([], 'name'), []) self.assertEqual(extract_filter_values_regex(['value'], 'name'), ['value']) self.assertEqual(extract_filter_values_regex('value', 'name'), ['value']) self.assertEqual( extract_filter_values_regex([re.compile('test')], 'name'), [re.compile('test')] ) self.assertEqual( extract_filter_values_regex(re.compile('test'), 'name'), [re.compile('test')] ) with self.assertRaises(ValueError): extract_filter_values({'value'}, 'name') with self.assertRaises(ValueError): extract_filter_values([{'value'}], 'name') @parameterized.expand([ ('match', {'project': 'p', 'codebase': 'c', 'repository': 'r', 'branch': 'b'}, True), ('not_project', {'project': '0', 'codebase': 'c', 'repository': 'r', 'branch': 'b'}, False), ( 'not_codebase', {'project': 'p', 'codebase': '0', 'repository': 'r', 'branch': 'b'}, False, ), ( 'not_repository', {'project': 'p', 'codebase': 'c', 'repository': '0', 'branch': 'b'}, False, ), ('not_branch', {'project': 'p', 'codebase': 'c', 'repository': 'r', 'branch': '0'}, False), ( 'none_branch', {'project': 'p', 'codebase': 'c', 'repository': 'r', 'branch': None}, False, ), ]) def test_filter_is_matched_eq_or_re(self, name, ss, expected): filter = SourceStampFilter( project_eq='p', codebase_eq='c', repository_eq='r', branch_eq='b' ) self.assertEqual(filter.is_matched(ss), expected) filter = SourceStampFilter( project_re='^p$', codebase_re='^c$', repository_re='^r$', branch_re='^b$' ) self.assertEqual(filter.is_matched(ss), expected) filter = SourceStampFilter( project_re=re.compile('^p$'), codebase_re=re.compile('^c$'), repository_re=re.compile('^r$'), branch_re=re.compile('^b$'), ) self.assertEqual(filter.is_matched(ss), expected) @parameterized.expand([ ('match', {'project': 'p', 'codebase': 'c', 'repository': 'r', 'branch': 'b'}, True), ( 'not_project', {'project': 'p0', 'codebase': 'c', 'repository': 'r', 'branch': 'b'}, False, ), ( 'not_codebase', {'project': 'p', 'codebase': 'c0', 'repository': 'r', 'branch': 'b'}, False, ), ( 'not_repository', {'project': 'p', 'codebase': 'c', 'repository': 'r0', 'branch': 'b'}, False, ), ('not_branch', {'project': 'p', 'codebase': 'c', 'repository': 'r', 'branch': 'b0'}, False), ('none_branch', {'project': 'p', 'codebase': 'c', 'repository': 'r', 'branch': None}, True), ]) def test_filter_is_matched_not_eq_or_re(self, name, ss, expected): filter = SourceStampFilter( project_not_eq='p0', codebase_not_eq='c0', repository_not_eq='r0', branch_not_eq='b0' ) self.assertEqual(filter.is_matched(ss), expected) filter = SourceStampFilter( project_not_re='^p0$', codebase_not_re='^c0$', repository_not_re='^r0$', branch_not_re='^b0$', ) self.assertEqual(filter.is_matched(ss), expected) filter = SourceStampFilter( project_not_re=re.compile('^p0$'), codebase_not_re=re.compile('^c0$'), repository_not_re=re.compile('^r0$'), branch_not_re=re.compile('^b0$'), ) self.assertEqual(filter.is_matched(ss), expected) def test_filter_repr(self): filter = SourceStampFilter( project_eq='p', codebase_eq='c', repository_eq='r', branch_eq='b', project_re='^p$', codebase_re='^c$', repository_re='^r$', branch_re='^b$', project_not_eq='p0', codebase_not_eq='c0', repository_not_eq='r0', branch_not_eq='b0', project_not_re='^p0$', codebase_not_re='^c0$', repository_not_re='^r0$', branch_not_re='^b0$', ) self.assertEqual( repr(filter), "<SourceStampFilter on project in ['p'] and project not in ['p0'] " + "and project matches [re.compile('^p$')] " + "and project does not match [re.compile('^p0$')] " + "and codebase in ['c'] and codebase not in ['c0'] " + "and codebase matches [re.compile('^c$')] " + "and codebase does not match [re.compile('^c0$')] " + "and repository in ['r'] and repository not in ['r0'] " + "and repository matches [re.compile('^r$')] " + "and repository does not match [re.compile('^r0$')] " + "and branch in ['b'] and branch not in ['b0'] " + "and branch matches [re.compile('^b$')] " + "and branch does not match [re.compile('^b0$')]>", )
7,627
Python
.py
167
36.137725
100
0.572216
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,528
test_httpclientservice.py
buildbot_buildbot/master/buildbot/test/unit/util/test_httpclientservice.py
# This file is part of Buildbot. Buildbot is free software: you can # redistribute it and/or modify it under the terms of the GNU General Public # License as published by the Free Software Foundation, version 2. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more # details. # # You should have received a copy of the GNU General Public License along with # this program; if not, write to the Free Software Foundation, Inc., 51 # Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # Copyright Buildbot Team Members import datetime import json import os from unittest import mock from twisted.internet import defer from twisted.internet import reactor from twisted.python import components from twisted.trial import unittest from twisted.web import resource from buildbot import interfaces from buildbot.test.fake import httpclientservice as fakehttpclientservice from buildbot.test.util.site import SiteWithClose from buildbot.test.util.warnings import assertProducesWarning from buildbot.util import bytes2unicode from buildbot.util import httpclientservice from buildbot.util import service from buildbot.util import unicode2bytes try: from requests.auth import HTTPDigestAuth except ImportError: pass # There is no way to unregister an adapter, so we have no other option # than registering it as a module side effect :-( components.registerAdapter(lambda m: m, mock.Mock, interfaces.IHttpResponse) class HTTPClientServiceTestBase(unittest.TestCase): @defer.inlineCallbacks def setUp(self): if httpclientservice.txrequests is None or httpclientservice.treq is None: raise unittest.SkipTest('this test requires txrequests and treq') self.patch(httpclientservice, 'txrequests', mock.Mock()) self.patch(httpclientservice, 'treq', mock.Mock()) self.parent = service.MasterService() self.parent.reactor = reactor self.base_headers = {} yield self.parent.startService() class HTTPClientServiceTestTxRequest(HTTPClientServiceTestBase): @defer.inlineCallbacks def setUp(self): yield super().setUp() self._http = yield httpclientservice.HTTPClientService.getService( self.parent, 'http://foo', headers=self.base_headers ) @defer.inlineCallbacks def test_get(self): with assertProducesWarning(DeprecationWarning): yield self._http.get('/bar') self._http._txrequests_sessions[0].request.assert_called_once_with( 'get', 'http://foo/bar', headers={}, background_callback=mock.ANY ) @defer.inlineCallbacks def test_get_full_url(self): with assertProducesWarning(DeprecationWarning): yield self._http.get('http://other/bar') self._http._txrequests_sessions[0].request.assert_called_once_with( 'get', 'http://other/bar', headers={}, background_callback=mock.ANY ) @defer.inlineCallbacks def test_put(self): with assertProducesWarning(DeprecationWarning): yield self._http.put('/bar', json={'foo': 'bar'}) jsonStr = json.dumps({"foo": 'bar'}) jsonBytes = unicode2bytes(jsonStr) headers = {'Content-Type': 'application/json'} self._http._txrequests_sessions[0].request.assert_called_once_with( 'put', 'http://foo/bar', background_callback=mock.ANY, data=jsonBytes, headers=headers ) @defer.inlineCallbacks def test_post(self): with assertProducesWarning(DeprecationWarning): yield self._http.post('/bar', json={'foo': 'bar'}) jsonStr = json.dumps({"foo": 'bar'}) jsonBytes = unicode2bytes(jsonStr) headers = {'Content-Type': 'application/json'} self._http._txrequests_sessions[0].request.assert_called_once_with( 'post', 'http://foo/bar', background_callback=mock.ANY, data=jsonBytes, headers=headers ) @defer.inlineCallbacks def test_delete(self): with assertProducesWarning(DeprecationWarning): yield self._http.delete('/bar') self._http._txrequests_sessions[0].request.assert_called_once_with( 'delete', 'http://foo/bar', background_callback=mock.ANY, headers={} ) @defer.inlineCallbacks def test_post_headers(self): self.base_headers.update({'X-TOKEN': 'XXXYYY'}) with assertProducesWarning(DeprecationWarning): yield self._http.post('/bar', json={'foo': 'bar'}) jsonStr = json.dumps({"foo": 'bar'}) jsonBytes = unicode2bytes(jsonStr) self._http._txrequests_sessions[0].request.assert_called_once_with( 'post', 'http://foo/bar', background_callback=mock.ANY, data=jsonBytes, headers={'X-TOKEN': 'XXXYYY', 'Content-Type': 'application/json'}, ) @defer.inlineCallbacks def test_post_auth(self): self._http = yield httpclientservice.HTTPClientService.getService( self.parent, 'http://foo', auth=('user', 'pa$$') ) with assertProducesWarning(DeprecationWarning): yield self._http.post('/bar', json={'foo': 'bar'}) jsonStr = json.dumps({"foo": 'bar'}) jsonBytes = unicode2bytes(jsonStr) self._http._txrequests_sessions[0].request.assert_called_once_with( 'post', 'http://foo/bar', background_callback=mock.ANY, data=jsonBytes, auth=('user', 'pa$$'), headers={'Content-Type': 'application/json'}, ) class HTTPClientServiceTestTxRequestNoEncoding(HTTPClientServiceTestBase): @defer.inlineCallbacks def setUp(self): yield super().setUp() self._http = self.successResultOf( httpclientservice.HTTPClientService.getService( self.parent, 'http://foo', headers=self.base_headers, skipEncoding=True ) ) @defer.inlineCallbacks def test_post_raw(self): with assertProducesWarning(DeprecationWarning): yield self._http.post('/bar', json={'foo': 'bar'}) jsonStr = json.dumps({"foo": 'bar'}) headers = {'Content-Type': 'application/json'} self._http._txrequests_sessions[0].request.assert_called_once_with( 'post', 'http://foo/bar', background_callback=mock.ANY, data=jsonStr, headers=headers ) @defer.inlineCallbacks def test_post_rawlist(self): with assertProducesWarning(DeprecationWarning): yield self._http.post('/bar', json=[{'foo': 'bar'}]) jsonStr = json.dumps([{"foo": 'bar'}]) headers = {'Content-Type': 'application/json'} self._http._txrequests_sessions[0].request.assert_called_once_with( 'post', 'http://foo/bar', background_callback=mock.ANY, data=jsonStr, headers=headers ) class HTTPClientServiceTestTReq(HTTPClientServiceTestBase): @defer.inlineCallbacks def setUp(self): yield super().setUp() self.patch(httpclientservice.HTTPClientService, 'PREFER_TREQ', True) self._http = yield httpclientservice.HTTPClientService.getService( self.parent, 'http://foo', headers=self.base_headers ) @defer.inlineCallbacks def test_get(self): with assertProducesWarning(DeprecationWarning): yield self._http.get('/bar') httpclientservice.treq.get.assert_called_once_with( 'http://foo/bar', agent=mock.ANY, headers={} ) @defer.inlineCallbacks def test_put(self): with assertProducesWarning(DeprecationWarning): yield self._http.put('/bar', json={'foo': 'bar'}) headers = {'Content-Type': ['application/json']} httpclientservice.treq.put.assert_called_once_with( 'http://foo/bar', agent=mock.ANY, data=b'{"foo": "bar"}', headers=headers ) @defer.inlineCallbacks def test_post(self): with assertProducesWarning(DeprecationWarning): yield self._http.post('/bar', json={'foo': 'bar'}) headers = {'Content-Type': ['application/json']} httpclientservice.treq.post.assert_called_once_with( 'http://foo/bar', agent=mock.ANY, data=b'{"foo": "bar"}', headers=headers ) @defer.inlineCallbacks def test_delete(self): with assertProducesWarning(DeprecationWarning): yield self._http.delete('/bar') httpclientservice.treq.delete.assert_called_once_with( 'http://foo/bar', agent=mock.ANY, headers={} ) @defer.inlineCallbacks def test_post_headers(self): self.base_headers.update({'X-TOKEN': 'XXXYYY'}) with assertProducesWarning(DeprecationWarning): yield self._http.post('/bar', json={'foo': 'bar'}) headers = {'Content-Type': ['application/json'], 'X-TOKEN': ['XXXYYY']} httpclientservice.treq.post.assert_called_once_with( 'http://foo/bar', agent=mock.ANY, data=b'{"foo": "bar"}', headers=headers ) @defer.inlineCallbacks def test_post_auth(self): self._http = yield httpclientservice.HTTPClientService.getService( self.parent, 'http://foo', auth=('user', 'pa$$') ) with assertProducesWarning(DeprecationWarning): yield self._http.post('/bar', json={'foo': 'bar'}) headers = { 'Content-Type': ['application/json'], } httpclientservice.treq.post.assert_called_once_with( 'http://foo/bar', agent=mock.ANY, data=b'{"foo": "bar"}', auth=('user', 'pa$$'), headers=headers, ) @defer.inlineCallbacks def test_post_auth_digest(self): auth = HTTPDigestAuth('user', 'pa$$') self._http = yield httpclientservice.HTTPClientService.getService( self.parent, 'http://foo', auth=auth ) with assertProducesWarning(DeprecationWarning): yield self._http.post('/bar', data={'foo': 'bar'}) # if digest auth, we don't use treq! we use txrequests self._http._txrequests_sessions[0].request.assert_called_once_with( 'post', 'http://foo/bar', background_callback=mock.ANY, data={"foo": 'bar'}, auth=auth, headers={}, ) class HTTPClientServiceTestTReqNoEncoding(HTTPClientServiceTestBase): @defer.inlineCallbacks def setUp(self): yield super().setUp() self.patch(httpclientservice.HTTPClientService, 'PREFER_TREQ', True) self._http = self.successResultOf( httpclientservice.HTTPClientService.getService( self.parent, 'http://foo', headers=self.base_headers, skipEncoding=True ) ) @defer.inlineCallbacks def test_post_raw(self): with assertProducesWarning(DeprecationWarning): yield self._http.post('/bar', json={'foo': 'bar'}) json_str = json.dumps({"foo": 'bar'}) headers = {'Content-Type': ['application/json']} httpclientservice.treq.post.assert_called_once_with( 'http://foo/bar', agent=mock.ANY, data=json_str, headers=headers ) @defer.inlineCallbacks def test_post_rawlist(self): with assertProducesWarning(DeprecationWarning): yield self._http.post('/bar', json=[{'foo': 'bar'}]) json_str = json.dumps([{"foo": 'bar'}]) headers = {'Content-Type': ['application/json']} httpclientservice.treq.post.assert_called_once_with( 'http://foo/bar', agent=mock.ANY, data=json_str, headers=headers ) class MyResource(resource.Resource): isLeaf = True def render_GET(self, request): def decode(x): if isinstance(x, bytes): return bytes2unicode(x) elif isinstance(x, (list, tuple)): return [bytes2unicode(y) for y in x] elif isinstance(x, dict): newArgs = {} for a, b in x.items(): newArgs[decode(a)] = decode(b) return newArgs return x args = decode(request.args) content_type = request.getHeader(b'content-type') if content_type == b"application/json": jsonBytes = request.content.read() jsonStr = bytes2unicode(jsonBytes) args['json_received'] = json.loads(jsonStr) data = json.dumps(args) data = unicode2bytes(data) request.setHeader(b'content-type', b'application/json') request.setHeader(b'content-length', b"%d" % len(data)) if request.method == b'HEAD': return b'' return data render_HEAD = render_GET render_POST = render_GET class HTTPClientServiceTestTxRequestE2E(unittest.TestCase): """The e2e tests must be the same for txrequests and treq We just force treq in the other TestCase """ def httpFactory(self, parent): return httpclientservice.HTTPClientService.getService( parent, f'http://127.0.0.1:{self.port}' ) def expect(self, *arg, **kwargs): pass @defer.inlineCallbacks def setUp(self): # On slower machines with high CPU oversubscription this test may take longer to run than # the default timeout. self.timeout = 10 if httpclientservice.txrequests is None or httpclientservice.treq is None: raise unittest.SkipTest('this test requires txrequests and treq') self.site = SiteWithClose(MyResource()) self.listenport = reactor.listenTCP(0, self.site) self.port = self.listenport.getHost().port self.parent = parent = service.MasterService() self.parent.reactor = reactor yield parent.startService() self._http = yield self.httpFactory(parent) @defer.inlineCallbacks def tearDown(self): yield self.listenport.stopListening() yield self.site.stopFactory() yield self.site.close_connections() yield self.parent.stopService() @defer.inlineCallbacks def test_content(self): self.expect('get', '/', content_json={}) with assertProducesWarning(DeprecationWarning): res = yield self._http.get('/') content = yield res.content() self.assertEqual(content, b'{}') @defer.inlineCallbacks def test_content_with_params(self): self.expect('get', '/', params={"a": 'b'}, content_json={"a": ['b']}) with assertProducesWarning(DeprecationWarning): res = yield self._http.get('/', params={"a": 'b'}) content = yield res.content() self.assertEqual(content, b'{"a": ["b"]}') @defer.inlineCallbacks def test_post_content_with_params(self): self.expect('post', '/', params={"a": 'b'}, content_json={"a": ['b']}) with assertProducesWarning(DeprecationWarning): res = yield self._http.post('/', params={"a": 'b'}) content = yield res.content() self.assertEqual(content, b'{"a": ["b"]}') @defer.inlineCallbacks def test_put_content_with_data(self): self.expect('post', '/', data={"a": 'b'}, content_json={"a": ['b']}) with assertProducesWarning(DeprecationWarning): res = yield self._http.post('/', data={"a": 'b'}) content = yield res.content() self.assertEqual(content, b'{"a": ["b"]}') @defer.inlineCallbacks def test_put_content_with_json(self): exp_content_json = {"json_received": {"a": 'b'}} self.expect('post', '/', json={"a": 'b'}, content_json=exp_content_json) with assertProducesWarning(DeprecationWarning): res = yield self._http.post('/', json={"a": 'b'}) content = yield res.content() content = bytes2unicode(content) content = json.loads(content) self.assertEqual(content, exp_content_json) @defer.inlineCallbacks def test_put_content_with_json_datetime(self): exp_content_json = {"json_received": {"a": 'b', "ts": 12}} dt = datetime.datetime.fromtimestamp(12, datetime.timezone.utc) self.expect('post', '/', json={"a": 'b', "ts": dt}, content_json=exp_content_json) with assertProducesWarning(DeprecationWarning): res = yield self._http.post('/', json={"a": 'b', "ts": dt}) content = yield res.content() content = bytes2unicode(content) content = json.loads(content) self.assertEqual(content, exp_content_json) @defer.inlineCallbacks def test_json(self): self.expect('get', '/', content_json={}) with assertProducesWarning(DeprecationWarning): res = yield self._http.get('/') content = yield res.json() self.assertEqual(content, {}) self.assertEqual(res.code, 200) # note that freebsd workers will not like when there are too many parallel connections # we can change this test via environment variable NUM_PARALLEL = os.environ.get("BBTEST_NUM_PARALLEL", 5) @defer.inlineCallbacks def test_lots(self): for _ in range(self.NUM_PARALLEL): self.expect('get', '/', params={"a": 'b'}, content_json={"a": ['b']}) # use for benchmarking (txrequests: 3ms per request treq: 1ms per # request) for _ in range(self.NUM_PARALLEL): with assertProducesWarning(DeprecationWarning): res = yield self._http.get('/', params={"a": 'b'}) content = yield res.content() self.assertEqual(content, b'{"a": ["b"]}') @defer.inlineCallbacks def test_lots_parallel(self): for _ in range(self.NUM_PARALLEL): self.expect('get', '/', params={"a": 'b'}, content_json={"a": ['b']}) # use for benchmarking (txrequests: 3ms per request treq: 11ms per # request (!?)) def oneReq(): with assertProducesWarning(DeprecationWarning): d = self._http.get('/', params={"a": 'b'}) @d.addCallback def content(res): return res.content() return d dl = [oneReq() for i in range(self.NUM_PARALLEL)] yield defer.gatherResults(dl) class HTTPClientServiceTestTReqE2E(HTTPClientServiceTestTxRequestE2E): @defer.inlineCallbacks def setUp(self): self.patch(httpclientservice.HTTPClientService, 'PREFER_TREQ', True) yield super().setUp() class HTTPClientServiceTestFakeE2E(HTTPClientServiceTestTxRequestE2E): @defer.inlineCallbacks def httpFactory(self, parent): service = yield fakehttpclientservice.HTTPClientService.getService( parent, self, f'http://127.0.0.1:{self.port}' ) return service def expect(self, *arg, **kwargs): self._http.expect(*arg, **kwargs)
19,034
Python
.py
423
36.427896
99
0.640496
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,529
test_tuplematch.py
buildbot_buildbot/master/buildbot/test/unit/util/test_tuplematch.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.test.util import tuplematching from buildbot.util import tuplematch class MatchTuple(tuplematching.TupleMatchingMixin, unittest.TestCase): # called by the TupleMatchingMixin methods def do_test_match(self, routingKey, shouldMatch, filter): result = tuplematch.matchTuple(routingKey, filter) should_match_string = 'should match' if shouldMatch else "shouldn't match" msg = f"{routingKey!r} {should_match_string} {filter!r}" self.assertEqual(shouldMatch, result, msg)
1,265
Python
.py
24
49.833333
82
0.779126
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,530
test_eventual.py
buildbot_buildbot/master/buildbot/test/unit/util/test_eventual.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 twisted.python import log from twisted.trial import unittest from buildbot.util import eventual class Eventually(unittest.TestCase): def setUp(self): # reset the queue to its base state eventual._theSimpleQueue = eventual._SimpleCallQueue() self.old_log_err = log.err self.results = [] def tearDown(self): log.err = self.old_log_err return eventual.flushEventualQueue() # utility callback def cb(self, *args, **kwargs): r = args if kwargs: r = (*r, kwargs) self.results.append(r) # flush the queue and assert results @defer.inlineCallbacks def assertResults(self, exp): yield eventual.flushEventualQueue() self.assertEqual(self.results, exp) # tests def test_eventually_calls(self): eventual.eventually(self.cb) return self.assertResults([()]) def test_eventually_args(self): eventual.eventually(self.cb, 1, 2, a='a') return self.assertResults([(1, 2, {"a": 'a'})]) def test_eventually_err(self): # monkey-patch log.err; this is restored by tearDown def cb_err(): self.results.append("err") log.err = cb_err def cb_fails(): raise RuntimeError("should not cause test failure") eventual.eventually(cb_fails) return self.assertResults(['err']) def test_eventually_butNotNow(self): eventual.eventually(self.cb, 1) self.assertFalse(self.results) return self.assertResults([(1,)]) def test_eventually_order(self): eventual.eventually(self.cb, 1) eventual.eventually(self.cb, 2) eventual.eventually(self.cb, 3) return self.assertResults([(1,), (2,), (3,)]) def test_flush_waitForChainedEventuallies(self): def chain(n): self.results.append(n) if n <= 0: return eventual.eventually(chain, n - 1) chain(3) # (the flush this tests is implicit in assertResults) return self.assertResults([3, 2, 1, 0]) def test_flush_waitForTreeEventuallies(self): # a more complex set of eventualities def tree(n): self.results.append(n) if n <= 0: return eventual.eventually(tree, n - 1) eventual.eventually(tree, n - 1) tree(2) # (the flush this tests is implicit in assertResults) return self.assertResults([2, 1, 1, 0, 0, 0, 0]) def test_flush_duringTurn(self): testd = defer.Deferred() def cb(): d = eventual.flushEventualQueue() d.addCallback(testd.callback) eventual.eventually(cb) return testd def test_fireEventually_call(self): d = eventual.fireEventually(13) d.addCallback(self.cb) return self.assertResults([(13,)])
3,702
Python
.py
95
31.431579
79
0.652987
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,531
test_misc.py
buildbot_buildbot/master/buildbot/test/unit/util/test_misc.py
# This file is part of Buildbot. Buildbot is free software: you can # redistribute it and/or modify it under the terms of the GNU General Public # License as published by the Free Software Foundation, version 2. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more # details. # # You should have received a copy of the GNU General Public License along with # this program; if not, write to the Free Software Foundation, Inc., 51 # Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # Copyright Buildbot Team Members from twisted.internet import defer from twisted.trial import unittest from buildbot import util from buildbot.test.reactor import TestReactorMixin from buildbot.util import misc class deferredLocked(unittest.TestCase): def test_name(self): self.assertEqual(util.deferredLocked, misc.deferredLocked) @defer.inlineCallbacks def test_fn(self): lock = defer.DeferredLock() @util.deferredLocked(lock) def check_locked(arg1, arg2): self.assertEqual([lock.locked, arg1, arg2], [True, 1, 2]) return defer.succeed(None) yield check_locked(1, 2) self.assertFalse(lock.locked) @defer.inlineCallbacks def test_fn_fails(self): lock = defer.DeferredLock() @util.deferredLocked(lock) def do_fail(): return defer.fail(RuntimeError("oh noes")) try: yield do_fail() self.fail("didn't errback") except Exception: self.assertFalse(lock.locked) @defer.inlineCallbacks def test_fn_exception(self): lock = defer.DeferredLock() @util.deferredLocked(lock) def do_fail(): raise RuntimeError("oh noes") # using decorators confuses pylint and gives a false positive below try: yield do_fail() # pylint: disable=assignment-from-no-return self.fail("didn't errback") except Exception: self.assertFalse(lock.locked) @defer.inlineCallbacks def test_method(self): testcase = self class C: @util.deferredLocked('aLock') def check_locked(self, arg1, arg2): testcase.assertEqual([self.aLock.locked, arg1, arg2], [True, 1, 2]) return defer.succeed(None) obj = C() obj.aLock = defer.DeferredLock() yield obj.check_locked(1, 2) self.assertFalse(obj.aLock.locked) class TestCancelAfter(TestReactorMixin, unittest.TestCase): def setUp(self): self.setup_test_reactor(auto_tear_down=False) self.d = defer.Deferred() @defer.inlineCallbacks def tearDown(self): yield self.tear_down_test_reactor() def test_succeeds(self): d = misc.cancelAfter(10, self.d, self.reactor) self.assertIdentical(d, self.d) @d.addCallback def check(r): self.assertEqual(r, "result") self.assertFalse(d.called) self.d.callback("result") self.assertTrue(d.called) @defer.inlineCallbacks def test_fails(self): d = misc.cancelAfter(10, self.d, self.reactor) self.assertFalse(d.called) self.d.errback(RuntimeError("oh noes")) self.assertTrue(d.called) yield self.assertFailure(d, RuntimeError) @defer.inlineCallbacks def test_timeout_succeeds(self): d = misc.cancelAfter(10, self.d, self.reactor) self.assertFalse(d.called) self.reactor.advance(11) d.callback("result") # ignored self.assertTrue(d.called) yield self.assertFailure(d, defer.CancelledError) @defer.inlineCallbacks def test_timeout_fails(self): d = misc.cancelAfter(10, self.d, self.reactor) self.assertFalse(d.called) self.reactor.advance(11) self.d.errback(RuntimeError("oh noes")) # ignored self.assertTrue(d.called) yield self.assertFailure(d, defer.CancelledError) class TestChunkifyList(unittest.TestCase): def test_all(self): self.assertEqual(list(misc.chunkify_list([], 0)), []) self.assertEqual(list(misc.chunkify_list([], 1)), []) self.assertEqual(list(misc.chunkify_list([1], 0)), [[1]]) self.assertEqual(list(misc.chunkify_list([1], 1)), [[1]]) self.assertEqual(list(misc.chunkify_list([1], 2)), [[1]]) self.assertEqual(list(misc.chunkify_list([1, 2], 0)), [[1], [2]]) self.assertEqual(list(misc.chunkify_list([1, 2], 1)), [[1], [2]]) self.assertEqual(list(misc.chunkify_list([1, 2], 2)), [[1, 2]]) self.assertEqual(list(misc.chunkify_list([1, 2], 3)), [[1, 2]]) self.assertEqual(list(misc.chunkify_list([1, 2, 3], 0)), [[1], [2], [3]]) self.assertEqual(list(misc.chunkify_list([1, 2, 3], 1)), [[1], [2], [3]]) self.assertEqual(list(misc.chunkify_list([1, 2, 3], 2)), [[1, 2], [3]]) self.assertEqual(list(misc.chunkify_list([1, 2, 3], 3)), [[1, 2, 3]]) self.assertEqual(list(misc.chunkify_list([1, 2, 3], 4)), [[1, 2, 3]]) self.assertEqual( list(misc.chunkify_list([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 0)), [[1], [2], [3], [4], [5], [6], [7], [8], [9], [10]], ) self.assertEqual( list(misc.chunkify_list([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 1)), [[1], [2], [3], [4], [5], [6], [7], [8], [9], [10]], ) self.assertEqual( list(misc.chunkify_list([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 2)), [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]], ) self.assertEqual( list(misc.chunkify_list([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 3)), [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]], ) self.assertEqual( list(misc.chunkify_list([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 4)), [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10]], ) self.assertEqual( list(misc.chunkify_list([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 5)), [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]], ) self.assertEqual( list(misc.chunkify_list([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 6)), [[1, 2, 3, 4, 5, 6], [7, 8, 9, 10]], ) self.assertEqual( list(misc.chunkify_list([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 7)), [[1, 2, 3, 4, 5, 6, 7], [8, 9, 10]], ) self.assertEqual( list(misc.chunkify_list([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 8)), [[1, 2, 3, 4, 5, 6, 7, 8], [9, 10]], ) self.assertEqual( list(misc.chunkify_list([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 9)), [[1, 2, 3, 4, 5, 6, 7, 8, 9], [10]], ) self.assertEqual( list(misc.chunkify_list([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 10)), [[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]], )
7,036
Python
.py
165
34.066667
83
0.577109
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,532
test_patch_delay.py
buildbot_buildbot/master/buildbot/test/unit/util/test_patch_delay.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.unittest import SynchronousTestCase from buildbot.test.util.patch_delay import patchForDelay class TestException(Exception): pass def fun_to_patch(*args, **kwargs): return defer.succeed((args, kwargs)) def fun_to_patch_exception(): raise TestException() non_callable = 1 class Tests(SynchronousTestCase): def test_raises_not_found(self): with self.assertRaises(RuntimeError): with patchForDelay(__name__ + '.notfound'): pass def test_raises_not_callable(self): with self.assertRaises(RuntimeError): with patchForDelay(__name__ + '.non_callable'): pass def test_patches_within_context(self): d = fun_to_patch() self.assertTrue(d.called) with patchForDelay(__name__ + '.fun_to_patch') as delay: d = fun_to_patch() self.assertEqual(len(delay), 1) self.assertFalse(d.called) delay.fire() self.assertEqual(len(delay), 0) self.assertTrue(d.called) d = fun_to_patch() self.assertTrue(d.called) def test_auto_fires_unfired_delay(self): with patchForDelay(__name__ + '.fun_to_patch') as delay: d = fun_to_patch() self.assertEqual(len(delay), 1) self.assertFalse(d.called) self.assertTrue(d.called) def test_auto_fires_unfired_delay_exception(self): try: with patchForDelay(__name__ + '.fun_to_patch') as delay: d = fun_to_patch() self.assertEqual(len(delay), 1) self.assertFalse(d.called) raise TestException() except TestException: pass self.assertTrue(d.called) def test_passes_arguments(self): with patchForDelay(__name__ + '.fun_to_patch') as delay: d = fun_to_patch('arg', kw='kwarg') self.assertEqual(len(delay), 1) delay.fire() args = self.successResultOf(d) self.assertEqual(args, (('arg',), {'kw': 'kwarg'})) def test_passes_exception(self): with patchForDelay(__name__ + '.fun_to_patch_exception') as delay: d = fun_to_patch_exception() self.assertEqual(len(delay), 1) delay.fire() f = self.failureResultOf(d) f.check(TestException)
3,134
Python
.py
75
33.573333
79
0.642528
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,533
test_codebase.py
buildbot_buildbot/master/buildbot/test/unit/util/test_codebase.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.reactor import TestReactorMixin from buildbot.test.util import scheduler from buildbot.test.util.state import StateTestMixin from buildbot.util import codebase from buildbot.util import state class FakeObject(codebase.AbsoluteSourceStampsMixin, state.StateMixin): name = 'fake-name' def __init__(self, master, codebases): self.master = master self.codebases = codebases class TestAbsoluteSourceStampsMixin( unittest.TestCase, scheduler.SchedulerMixin, StateTestMixin, TestReactorMixin ): codebases = { 'a': {'repository': '', 'branch': 'master'}, 'b': {'repository': '', 'branch': 'master'}, } @defer.inlineCallbacks def setUp(self): self.setup_test_reactor(auto_tear_down=False) self.master = yield fakemaster.make_master(self, wantDb=True, wantData=True) self.db = self.master.db self.object = FakeObject(self.master, self.codebases) @defer.inlineCallbacks def tearDown(self): yield self.tear_down_test_reactor() @defer.inlineCallbacks def mkch(self, **kwargs): ch = self.makeFakeChange(**kwargs) ch = yield self.addFakeChange(ch) return ch @defer.inlineCallbacks def test_getCodebaseDict(self): cbd = yield self.object.getCodebaseDict('a') self.assertEqual(cbd, {'repository': '', 'branch': 'master'}) @defer.inlineCallbacks def test_getCodebaseDict_not_found(self): d = self.object.getCodebaseDict('c') yield self.assertFailure(d, KeyError) @defer.inlineCallbacks def test_getCodebaseDict_existing(self): yield self.set_fake_state( self.object, 'lastCodebases', { 'a': { 'repository': 'A', 'revision': '1234:abc', 'branch': 'master', 'lastChange': 10, } }, ) cbd = yield self.object.getCodebaseDict('a') self.assertEqual( cbd, {'repository': 'A', 'revision': '1234:abc', 'branch': 'master', 'lastChange': 10} ) cbd = yield self.object.getCodebaseDict('b') self.assertEqual(cbd, {'repository': '', 'branch': 'master'}) @defer.inlineCallbacks def test_recordChange(self): yield self.object.recordChange( ( yield self.mkch( codebase='a', repository='A', revision='1234:abc', branch='master', number=500 ) ) ) yield self.assert_state_by_class( 'fake-name', 'FakeObject', lastCodebases={ 'a': { 'repository': 'A', 'revision': '1234:abc', 'branch': 'master', 'lastChange': 500, } }, ) @defer.inlineCallbacks def test_recordChange_older(self): yield self.set_fake_state( self.object, 'lastCodebases', { 'a': { 'repository': 'A', 'revision': '2345:bcd', 'branch': 'master', 'lastChange': 510, } }, ) yield self.object.getCodebaseDict('a') yield self.object.recordChange( ( yield self.mkch( codebase='a', repository='A', revision='1234:abc', branch='master', number=500 ) ) ) yield self.assert_state_by_class( 'fake-name', 'FakeObject', lastCodebases={ 'a': { 'repository': 'A', 'revision': '2345:bcd', 'branch': 'master', 'lastChange': 510, } }, ) @defer.inlineCallbacks def test_recordChange_newer(self): yield self.set_fake_state( self.object, 'lastCodebases', { 'a': { 'repository': 'A', 'revision': '1234:abc', 'branch': 'master', 'lastChange': 490, } }, ) yield self.object.getCodebaseDict('a') yield self.object.recordChange( ( yield self.mkch( codebase='a', repository='A', revision='2345:bcd', branch='master', number=500 ) ) ) yield self.assert_state_by_class( 'fake-name', 'FakeObject', lastCodebases={ 'a': { 'repository': 'A', 'revision': '2345:bcd', 'branch': 'master', 'lastChange': 500, } }, )
5,778
Python
.py
165
24.09697
98
0.543066
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,534
test_netstrings.py
buildbot_buildbot/master/buildbot/test/unit/util/test_netstrings.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.protocols import basic from twisted.trial import unittest from buildbot.util import netstrings class NetstringParser(unittest.TestCase): def test_valid_netstrings(self): p = netstrings.NetstringParser() p.feed("5:hello,5:world,") self.assertEqual(p.strings, [b'hello', b'world']) def test_valid_netstrings_byte_by_byte(self): # (this is really testing twisted's support, but oh well) p = netstrings.NetstringParser() for c in "5:hello,5:world,": p.feed(c) self.assertEqual(p.strings, [b'hello', b'world']) def test_invalid_netstring(self): p = netstrings.NetstringParser() with self.assertRaises(basic.NetstringParseError): p.feed("5-hello!") def test_incomplete_netstring(self): p = netstrings.NetstringParser() p.feed("11:hello world,6:foob") # note that the incomplete 'foobar' does not appear here self.assertEqual(p.strings, [b'hello world'])
1,720
Python
.py
37
41.324324
79
0.720861
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,535
test_watchdog.py
buildbot_buildbot/master/buildbot/test/unit/util/test_watchdog.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.test.reactor import TestReactorMixin from buildbot.util.watchdog import Watchdog class TestWatchdog(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 test_not_started_no_calls(self): m = mock.Mock() w = Watchdog(self.reactor, m, 10) self.reactor.pump([1] * 100) self.assertEqual(m.call_count, 0) del w # to silence unused variable warnings def test_started_calls(self): m = mock.Mock() w = Watchdog(self.reactor, m, 10) w.start() self.reactor.advance(9.9) self.assertEqual(m.call_count, 0) self.reactor.advance(0.2) self.assertEqual(m.call_count, 1) self.reactor.advance(20) self.assertEqual(m.call_count, 1) def test_two_starts_single_call(self): m = mock.Mock() w = Watchdog(self.reactor, m, 10) w.start() w.start() self.reactor.advance(9.9) self.assertEqual(m.call_count, 0) self.reactor.advance(0.2) self.assertEqual(m.call_count, 1) self.reactor.advance(20) self.assertEqual(m.call_count, 1) def test_started_stopped_does_not_call(self): m = mock.Mock() w = Watchdog(self.reactor, m, 10) w.start() w.stop() self.reactor.pump([1] * 100) self.assertEqual(m.call_count, 0) def test_triggers_repeatedly(self): m = mock.Mock() w = Watchdog(self.reactor, m, 10) w.start() self.reactor.advance(9.9) self.assertEqual(m.call_count, 0) self.reactor.advance(0.2) self.assertEqual(m.call_count, 1) w.start() self.reactor.advance(9.9) self.assertEqual(m.call_count, 1) self.reactor.advance(0.2) self.assertEqual(m.call_count, 2) w.start() self.reactor.advance(9.9) self.assertEqual(m.call_count, 2) self.reactor.advance(0.2) self.assertEqual(m.call_count, 3) def test_notify_delays_trigger(self): m = mock.Mock() w = Watchdog(self.reactor, m, 10) w.start() self.reactor.advance(5) w.notify() self.reactor.advance(9.9) self.assertEqual(m.call_count, 0) self.reactor.advance(0.2) self.assertEqual(m.call_count, 1)
3,273
Python
.py
87
30.655172
79
0.658983
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,536
test_pathmatch.py
buildbot_buildbot/master/buildbot/test/unit/util/test_pathmatch.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.util import pathmatch class Matcher(unittest.TestCase): def setUp(self): self.m = pathmatch.Matcher() def test_dupe_path(self): def set(): self.m[('abc,')] = 1 set() with self.assertRaises(AssertionError): set() def test_empty(self): with self.assertRaises(KeyError): self.m[('abc',)] def test_diff_length(self): self.m[('abc', 'def')] = 2 self.m[('ab', 'cd', 'ef')] = 3 self.assertEqual(self.m[('abc', 'def')], (2, {})) def test_same_length(self): self.m[('abc', 'def')] = 2 self.m[('abc', 'efg')] = 3 self.assertEqual(self.m[('abc', 'efg')], (3, {})) def test_pattern_variables(self): self.m[('A', ':a', 'B', ':b')] = 'AB' self.assertEqual(self.m[('A', 'a', 'B', 'b')], ('AB', {"a": 'a', "b": 'b'})) def test_pattern_variables_underscore(self): self.m[('A', ':a_a_a')] = 'AB' self.assertEqual(self.m[('A', 'a')], ('AB', {"a_a_a": 'a'})) def test_pattern_variables_num(self): self.m[('A', 'n:a', 'B', 'n:b')] = 'AB' self.assertEqual(self.m[('A', '10', 'B', '-20')], ('AB', {"a": 10, "b": -20})) def test_pattern_variables_ident(self): self.m[('A', 'i:a', 'B', 'i:b')] = 'AB' self.assertEqual(self.m[('A', 'abc', 'B', 'x-z-B')], ('AB', {"a": 'abc', "b": 'x-z-B'})) def test_pattern_variables_string(self): self.m[('A', 's:a')] = 'A' self.assertEqual(self.m[('A', 'unicode \N{SNOWMAN}')], ('A', {"a": 'unicode \N{SNOWMAN}'})) def test_pattern_variables_num_invalid(self): self.m[('A', 'n:a')] = 'AB' with self.assertRaises(KeyError): self.m[('A', '1x0')] def test_pattern_variables_ident_invalid(self): self.m[('A', 'i:a')] = 'AB' with self.assertRaises(KeyError): self.m[('A', '10')] def test_pattern_variables_ident_num_distinguised(self): self.m[('A', 'n:a')] = 'num' self.m[('A', 'i:a')] = 'ident' self.assertEqual(self.m[('A', '123')], ('num', {"a": 123})) self.assertEqual(self.m[('A', 'abc')], ('ident', {"a": 'abc'})) def test_prefix_matching(self): self.m[('A', ':a')] = 'A' self.m[('A', ':a', 'B', ':b')] = 'AB' self.assertEqual( (self.m[('A', 'a1', 'B', 'b')], self.m['A', 'a2']), (('AB', {"a": 'a1', "b": 'b'}), ('A', {"a": 'a2'})), ) def test_dirty_again(self): self.m[('abc', 'def')] = 2 self.assertEqual(self.m[('abc', 'def')], (2, {})) self.m[('abc', 'efg')] = 3 self.assertEqual(self.m[('abc', 'def')], (2, {})) self.assertEqual(self.m[('abc', 'efg')], (3, {}))
3,499
Python
.py
77
38.376623
99
0.544813
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,537
test_identifiers.py
buildbot_buildbot/master/buildbot/test/unit/util/test_identifiers.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 locale from twisted.python import log from twisted.trial import unittest from buildbot.util import identifiers class Tests(unittest.TestCase): def test_isIdentifier(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 good = ["linux", "Linux", "abc123", "a" * 50, '\N{SNOWMAN}'] for g in good: log.msg(f'expect {g!r} to be good') self.assertTrue(identifiers.isIdentifier(50, g)) bad = [ None, '', b'linux', 'a/b', "a.b.c.d", "a-b_c.d9", 'spaces not allowed', "a" * 51, "123 no initial digits", '\N{SNOWMAN}.\N{SNOWMAN}', ] for b in bad: log.msg(f'expect {b!r} to be bad') self.assertFalse(identifiers.isIdentifier(50, b)) def assertEqualUnicode(self, got, exp): self.assertTrue(isinstance(exp, str)) self.assertEqual(got, exp) def test_forceIdentifier_already_is(self): self.assertEqualUnicode(identifiers.forceIdentifier(10, 'abc'), 'abc') def test_forceIdentifier_ascii(self): self.assertEqualUnicode(identifiers.forceIdentifier(10, 'abc'), 'abc') def test_forceIdentifier_too_long(self): self.assertEqualUnicode(identifiers.forceIdentifier(10, 'abcdefghijKL'), 'abcdefghij') def test_forceIdentifier_invalid_chars(self): self.assertEqualUnicode(identifiers.forceIdentifier(100, 'my log.html'), 'my_log_html') def test_forceIdentifier_leading_digit(self): self.assertEqualUnicode( identifiers.forceIdentifier(100, '9 pictures of cats.html'), '__pictures_of_cats_html' ) def test_forceIdentifier_digits(self): self.assertEqualUnicode( identifiers.forceIdentifier(100, 'warnings(2000)'), 'warnings_2000_' ) def test_incrementIdentifier_simple(self): self.assertEqualUnicode(identifiers.incrementIdentifier(100, 'aaa'), 'aaa_2') def test_incrementIdentifier_simple_way_too_long(self): self.assertEqualUnicode(identifiers.incrementIdentifier(3, 'aaa'), 'a_2') def test_incrementIdentifier_simple_too_long(self): self.assertEqualUnicode(identifiers.incrementIdentifier(4, 'aaa'), 'aa_2') def test_incrementIdentifier_single_digit(self): self.assertEqualUnicode(identifiers.incrementIdentifier(100, 'aaa_2'), 'aaa_3') def test_incrementIdentifier_add_digits(self): self.assertEqualUnicode(identifiers.incrementIdentifier(100, 'aaa_99'), 'aaa_100') def test_incrementIdentifier_add_digits_too_long(self): self.assertEqualUnicode(identifiers.incrementIdentifier(6, 'aaa_99'), 'aa_100') def test_incrementIdentifier_add_digits_out_of_space(self): with self.assertRaises(ValueError): identifiers.incrementIdentifier(6, '_99999')
3,951
Python
.py
82
40.353659
98
0.681995
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,538
test_deferwaiter.py
buildbot_buildbot/master/buildbot/test/unit/util/test_deferwaiter.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.test.reactor import TestReactorMixin from buildbot.util import asyncSleep from buildbot.util.deferwaiter import DeferWaiter from buildbot.util.deferwaiter import NonRepeatedActionHandler from buildbot.util.deferwaiter import RepeatedActionHandler class TestException(Exception): pass class WaiterTests(unittest.TestCase): def test_add_deferred_called(self): w = DeferWaiter() w.add(defer.succeed(None)) self.assertFalse(w.has_waited()) d = w.wait() self.assertTrue(d.called) def test_add_non_deferred(self): w = DeferWaiter() w.add(2) self.assertFalse(w.has_waited()) d = w.wait() self.assertTrue(d.called) def test_add_deferred_not_called_and_call_later(self): w = DeferWaiter() d1 = defer.Deferred() w.add(d1) self.assertTrue(w.has_waited()) d = w.wait() self.assertFalse(d.called) d1.callback(None) self.assertFalse(w.has_waited()) self.assertTrue(d.called) @defer.inlineCallbacks def test_passes_result(self): w = DeferWaiter() d1 = defer.Deferred() w.add(d1) d1.callback(123) res = yield d1 self.assertEqual(res, 123) d = w.wait() self.assertTrue(d.called) class RepeatedActionHandlerTests(unittest.TestCase, TestReactorMixin): 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_does_not_add_action_on_start(self): w = DeferWaiter() times = [] def action(): times.append(self.reactor.seconds()) h = RepeatedActionHandler(self.reactor, w, 1, action) self.reactor.advance(2) h.stop() self.assertEqual(len(times), 0) d = w.wait() self.assertTrue(d.called) yield d @parameterized.expand([ ('after_action', True), ('before_action', False), ]) @defer.inlineCallbacks def test_runs_action(self, name, timer_after_action): w = DeferWaiter() times = [] def action(): times.append(round(self.reactor.seconds(), 1)) h = RepeatedActionHandler( self.reactor, w, 1, action, start_timer_after_action_completes=timer_after_action ) h.start() self.reactor.pump([0.1] * 35) self.assertEqual(times, [1.1, 2.1, 3.1]) h.stop() d = w.wait() self.assertTrue(d.called) yield d @parameterized.expand([ ('after_action', True), ('before_action', False), ]) @defer.inlineCallbacks def test_runs_action_after_exception_with_timer(self, name, timer_after_action): w = DeferWaiter() times = [] def action(): times.append(round(self.reactor.seconds(), 1)) if len(times) == 2: raise TestException() h = RepeatedActionHandler( self.reactor, w, 1, action, start_timer_after_action_completes=timer_after_action ) h.start() self.reactor.pump([0.1] * 35) self.assertEqual(times, [1.1, 2.1, 3.1]) h.stop() d = w.wait() self.assertTrue(d.called) self.flushLoggedErrors(TestException) yield d @parameterized.expand([ ('after_action', True), ('before_action', False), ]) @defer.inlineCallbacks def test_runs_action_with_delay(self, name, timer_after_action): w = DeferWaiter() times = [] def action(): times.append(self.reactor.seconds()) h = RepeatedActionHandler( self.reactor, w, 10, action, start_timer_after_action_completes=timer_after_action ) h.start() self.reactor.pump([1] * 15) h.delay() self.reactor.pump([1] * 35) self.assertEqual(times, [10, 25, 35, 45]) h.stop() d = w.wait() self.assertTrue(d.called) yield d @parameterized.expand([ ('after_action', True), ('before_action', False), ]) @defer.inlineCallbacks def test_runs_action_with_force(self, name, timer_after_action): w = DeferWaiter() times = [] def action(): times.append(self.reactor.seconds()) h = RepeatedActionHandler( self.reactor, w, 10, action, start_timer_after_action_completes=timer_after_action ) h.start() self.reactor.pump([1] * 15) h.force() self.reactor.pump([1] * 35) self.assertEqual(times, [10, 15, 25, 35, 45]) h.stop() d = w.wait() self.assertTrue(d.called) yield d @defer.inlineCallbacks def test_ignores_duplicate_start_or_stop(self): w = DeferWaiter() times = [] def action(): times.append(round(self.reactor.seconds(), 1)) h = RepeatedActionHandler(self.reactor, w, 1, action) h.start() h.start() self.reactor.pump([0.1] * 35) self.assertEqual(times, [1.1, 2.1, 3.1]) h.stop() h.stop() d = w.wait() self.assertTrue(d.called) yield d @defer.inlineCallbacks def test_can_update_interval(self): w = DeferWaiter() times = [] def action(): times.append(round(self.reactor.seconds(), 1)) h = RepeatedActionHandler(self.reactor, w, 1, action) h.start() self.reactor.pump([0.1] * 15) h.set_interval(2) self.reactor.pump([0.1] * 50) self.assertEqual(times, [1.1, 2.1, 4.1, 6.2]) h.stop() d = w.wait() self.assertTrue(d.called) yield d @parameterized.expand([ ('after_action', True, [1.1, 2.6, 4.1]), ('before_action', False, [1.1, 2.1, 3.1, 4.1]), ]) @defer.inlineCallbacks def test_runs_long_action(self, name, timer_after_action, expected_times): w = DeferWaiter() times = [] @defer.inlineCallbacks def action(): times.append(round(self.reactor.seconds(), 1)) yield asyncSleep(0.5, reactor=self.reactor) h = RepeatedActionHandler( self.reactor, w, 1, action, start_timer_after_action_completes=timer_after_action ) h.start() self.reactor.pump([0.1] * 47) self.assertEqual(times, expected_times) h.stop() d = w.wait() self.assertTrue(d.called) yield d @parameterized.expand([ ('after_action', True, [10, 25, 47, 62]), ('before_action', False, [10, 20, 30, 47, 57, 67]), ]) @defer.inlineCallbacks def test_runs_long_action_with_delay(self, name, timer_after_action, expected_times): w = DeferWaiter() times = [] @defer.inlineCallbacks def action(): times.append(self.reactor.seconds()) yield asyncSleep(5, reactor=self.reactor) h = RepeatedActionHandler( self.reactor, w, 10, action, start_timer_after_action_completes=timer_after_action ) h.start() self.reactor.pump([1] * 37) h.delay() self.reactor.pump([1] * 39) self.assertEqual(times, expected_times) h.stop() d = w.wait() self.assertTrue(d.called) yield d @parameterized.expand([ ('after_action', True, [10, 25, 40]), ('before_action', False, [10, 22, 32, 42]), ]) @defer.inlineCallbacks def test_runs_long_action_with_delay_when_running( self, name, timer_after_action, expected_times ): w = DeferWaiter() times = [] @defer.inlineCallbacks def action(): times.append(self.reactor.seconds()) yield asyncSleep(5, reactor=self.reactor) h = RepeatedActionHandler( self.reactor, w, 10, action, start_timer_after_action_completes=timer_after_action ) h.start() self.reactor.pump([1] * 12) h.delay() self.reactor.pump([1] * 39) self.assertEqual(times, expected_times) h.stop() d = w.wait() self.assertTrue(d.called) yield d @parameterized.expand([ ('after_action', True, [10, 25, 37, 52, 67]), ('before_action', False, [10, 20, 30, 37, 47, 57, 67]), ]) @defer.inlineCallbacks def test_runs_long_action_with_force(self, name, timer_after_action, expected_times): w = DeferWaiter() times = [] @defer.inlineCallbacks def action(): times.append(self.reactor.seconds()) yield asyncSleep(5, reactor=self.reactor) h = RepeatedActionHandler( self.reactor, w, 10, action, start_timer_after_action_completes=timer_after_action ) h.start() self.reactor.pump([1] * 37) h.force() self.reactor.pump([1] * 39) self.assertEqual(times, expected_times) h.stop() d = w.wait() self.assertTrue(d.called) yield d @parameterized.expand([ ('after_action', True, [10, 25, 40]), ('before_action', False, [10, 20, 30, 40]), ]) @defer.inlineCallbacks def test_runs_long_action_with_force_when_running( self, name, timer_after_action, expected_times ): w = DeferWaiter() times = [] @defer.inlineCallbacks def action(): times.append(self.reactor.seconds()) yield asyncSleep(5, reactor=self.reactor) h = RepeatedActionHandler( self.reactor, w, 10, action, start_timer_after_action_completes=timer_after_action ) h.start() self.reactor.pump([1] * 12) h.force() self.reactor.pump([1] * 37) self.assertEqual(times, expected_times) h.stop() d = w.wait() self.assertTrue(d.called) yield d @parameterized.expand([ ('after_action', True), ('before_action', False), ]) @defer.inlineCallbacks def test_waiter_waits_for_action_timer_starts(self, name, timer_after_action): w = DeferWaiter() times = [] @defer.inlineCallbacks def action(): times.append(round(self.reactor.seconds(), 1)) yield asyncSleep(0.5, reactor=self.reactor) h = RepeatedActionHandler( self.reactor, w, 1, action, start_timer_after_action_completes=timer_after_action ) h.start() self.reactor.pump([0.1] * 12) self.assertEqual(times, [1.1]) d = w.wait() self.assertFalse(d.called) h.stop() self.assertFalse(d.called) self.reactor.pump([0.1] * 5) # action started on 1.1, will end at 1.6 self.assertTrue(d.called) yield d class NonRepeatedActionHandlerTests(unittest.TestCase, TestReactorMixin): 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_does_not_add_action_on_start(self): w = DeferWaiter() times = [] def action(): times.append(self.reactor.seconds()) h = NonRepeatedActionHandler(self.reactor, w, action) self.reactor.advance(20) h.stop() self.assertEqual(len(times), 0) d = w.wait() self.assertTrue(d.called) yield d @defer.inlineCallbacks def test_action(self): w = DeferWaiter() times = [] def action(): times.append(self.reactor.seconds()) h = NonRepeatedActionHandler(self.reactor, w, action) self.reactor.pump([1] * 10) h.schedule(10) self.reactor.pump([1] * 30) self.assertEqual(times, [20]) h.stop() d = w.wait() self.assertTrue(d.called) yield d @parameterized.expand([ ("invoke_again_if_running", True), ('dont_invoke_again_if_running', False), ]) @defer.inlineCallbacks def test_actions_when_multiple_schedule(self, name, invoke_again_if_running): w = DeferWaiter() times = [] def action(): times.append(self.reactor.seconds()) h = NonRepeatedActionHandler(self.reactor, w, action) self.reactor.pump([1] * 10) h.schedule(10, invoke_again_if_running=invoke_again_if_running) self.reactor.pump([1] * 2) h.schedule(10, invoke_again_if_running=invoke_again_if_running) self.reactor.pump([1] * 30) self.assertEqual(times, [20]) h.stop() d = w.wait() self.assertTrue(d.called) yield d @parameterized.expand([ ("invoke_again_if_running", True), ('dont_invoke_again_if_running', False), ]) @defer.inlineCallbacks def test_actions_when_schedule_and_force(self, name, invoke_again_if_running): w = DeferWaiter() times = [] def action(): times.append(self.reactor.seconds()) h = NonRepeatedActionHandler(self.reactor, w, action) self.reactor.pump([1] * 10) h.schedule(10, invoke_again_if_running=invoke_again_if_running) self.reactor.pump([1] * 2) h.force(invoke_again_if_running=invoke_again_if_running) self.reactor.pump([1] * 30) self.assertEqual(times, [12]) h.stop() d = w.wait() self.assertTrue(d.called) yield d @parameterized.expand([ ("invoke_again_if_running", True, [20, 32]), ('dont_invoke_again_if_running', False, [20]), ]) @defer.inlineCallbacks def test_long_actions_when_2_schedule(self, name, invoke_again_if_running, expected_times): w = DeferWaiter() times = [] @defer.inlineCallbacks def action(): times.append(self.reactor.seconds()) yield asyncSleep(5, reactor=self.reactor) h = NonRepeatedActionHandler(self.reactor, w, action) self.reactor.pump([1] * 10) h.schedule(10, invoke_again_if_running=invoke_again_if_running) self.reactor.pump([1] * 12) h.schedule(10, invoke_again_if_running=invoke_again_if_running) self.reactor.pump([1] * 30) self.assertEqual(times, expected_times) h.stop() d = w.wait() self.assertTrue(d.called) yield d @parameterized.expand([ ("invoke_again_if_running", True, [10, 15]), ('dont_invoke_again_if_running', False, [10]), ]) @defer.inlineCallbacks def test_long_actions_when_2_force(self, name, invoke_again_if_running, expected_times): w = DeferWaiter() times = [] @defer.inlineCallbacks def action(): times.append(self.reactor.seconds()) yield asyncSleep(5, reactor=self.reactor) h = NonRepeatedActionHandler(self.reactor, w, action) self.reactor.pump([1] * 10) h.force(invoke_again_if_running=invoke_again_if_running) self.reactor.pump([1] * 2) h.force(invoke_again_if_running=invoke_again_if_running) self.reactor.pump([1] * 30) self.assertEqual(times, expected_times) h.stop() d = w.wait() self.assertTrue(d.called) yield d @parameterized.expand([ ("invoke_again_if_running", True, [10, 15]), ('dont_invoke_again_if_running', False, [10]), ]) @defer.inlineCallbacks def test_long_actions_when_3_force(self, name, invoke_again_if_running, expected_times): w = DeferWaiter() times = [] @defer.inlineCallbacks def action(): times.append(self.reactor.seconds()) yield asyncSleep(5, reactor=self.reactor) h = NonRepeatedActionHandler(self.reactor, w, action) self.reactor.pump([1] * 10) h.force(invoke_again_if_running=invoke_again_if_running) self.reactor.pump([1] * 2) h.force(invoke_again_if_running=invoke_again_if_running) self.reactor.pump([1] * 2) h.force(invoke_again_if_running=invoke_again_if_running) self.reactor.pump([1] * 30) self.assertEqual(times, expected_times) h.stop() d = w.wait() self.assertTrue(d.called) yield d @parameterized.expand([ ("invoke_again_if_running", True, [20, 25]), ('dont_invoke_again_if_running', False, [20]), ]) @defer.inlineCallbacks def test_long_actions_when_schedule_and_force( self, name, invoke_again_if_running, expected_times ): w = DeferWaiter() times = [] @defer.inlineCallbacks def action(): times.append(self.reactor.seconds()) yield asyncSleep(5, reactor=self.reactor) h = NonRepeatedActionHandler(self.reactor, w, action) self.reactor.pump([1] * 10) h.schedule(10, invoke_again_if_running=invoke_again_if_running) self.reactor.pump([1] * 12) h.force(invoke_again_if_running=invoke_again_if_running) self.reactor.pump([1] * 30) self.assertEqual(times, expected_times) h.stop() d = w.wait() self.assertTrue(d.called) yield d @parameterized.expand([ ("invoke_again_if_running", True, [10, 22]), ('dont_invoke_again_if_running', False, [10]), ]) @defer.inlineCallbacks def test_long_actions_when_force_and_schedule( self, name, invoke_again_if_running, expected_times ): w = DeferWaiter() times = [] @defer.inlineCallbacks def action(): times.append(self.reactor.seconds()) yield asyncSleep(5, reactor=self.reactor) h = NonRepeatedActionHandler(self.reactor, w, action) self.reactor.pump([1] * 10) h.force(invoke_again_if_running=invoke_again_if_running) self.reactor.pump([1] * 2) h.schedule(10, invoke_again_if_running=invoke_again_if_running) self.reactor.pump([1] * 30) self.assertEqual(times, expected_times) h.stop() d = w.wait() self.assertTrue(d.called) yield d
19,244
Python
.py
539
27.19295
95
0.602456
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,539
test_ssl.py
buildbot_buildbot/master/buildbot/test/unit/util/test_ssl.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.config.errors import capture_config_errors from buildbot.test.util.config import ConfigErrorsMixin from buildbot.util import ssl class Tests(unittest.TestCase, ConfigErrorsMixin): @ssl.skipUnless def test_ClientContextFactory(self): from twisted.internet.ssl import ClientContextFactory self.assertEqual(ssl.ClientContextFactory, ClientContextFactory) @ssl.skipUnless def test_ConfigError(self): old_error = ssl.ssl_import_error old_has_ssl = ssl.has_ssl try: ssl.ssl_import_error = "lib xxx do not exist" ssl.has_ssl = False with capture_config_errors() as errors: ssl.ensureHasSSL("myplugin") self.assertConfigError( errors, "TLS dependencies required for myplugin are not installed : " "lib xxx do not exist\n pip install 'buildbot[tls]'", ) finally: ssl.ssl_import_error = old_error ssl.has_ssl = old_has_ssl
1,786
Python
.py
40
38.175
79
0.711328
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,540
test_db.py
buildbot_buildbot/master/buildbot/test/unit/util/test_db.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.unittest import TestCase from buildbot.test.util.db import get_trial_parallel_from_cwd class Tests(TestCase): def test_unknown(self): self.assertIsNone(get_trial_parallel_from_cwd("")) self.assertIsNone(get_trial_parallel_from_cwd("/")) self.assertIsNone(get_trial_parallel_from_cwd("/abc")) self.assertIsNone(get_trial_parallel_from_cwd("/abc/")) self.assertIsNone(get_trial_parallel_from_cwd("/abc/abc/1")) self.assertIsNone(get_trial_parallel_from_cwd("/abc/abc/1/")) self.assertIsNone(get_trial_parallel_from_cwd("/_trial_temp/abc/1")) self.assertIsNone(get_trial_parallel_from_cwd("/_trial_temp/abc/1/")) def test_single(self): self.assertIs(get_trial_parallel_from_cwd("_trial_temp"), False) self.assertIs(get_trial_parallel_from_cwd("_trial_temp/"), False) self.assertIs(get_trial_parallel_from_cwd("/_trial_temp"), False) self.assertIs(get_trial_parallel_from_cwd("/_trial_temp/"), False) self.assertIs(get_trial_parallel_from_cwd("/abc/_trial_temp"), False) self.assertIs(get_trial_parallel_from_cwd("/abc/_trial_temp/"), False) def test_index(self): self.assertEqual(get_trial_parallel_from_cwd("_trial_temp/0"), 0) self.assertEqual(get_trial_parallel_from_cwd("_trial_temp/0/"), 0) self.assertEqual(get_trial_parallel_from_cwd("_trial_temp/5"), 5) self.assertEqual(get_trial_parallel_from_cwd("_trial_temp/5/"), 5) self.assertEqual(get_trial_parallel_from_cwd("/_trial_temp/0"), 0) self.assertEqual(get_trial_parallel_from_cwd("/_trial_temp/0/"), 0) self.assertEqual(get_trial_parallel_from_cwd("/_trial_temp/5"), 5) self.assertEqual(get_trial_parallel_from_cwd("/_trial_temp/5/"), 5) self.assertEqual(get_trial_parallel_from_cwd("abc/_trial_temp/0"), 0) self.assertEqual(get_trial_parallel_from_cwd("abc/_trial_temp/0/"), 0) self.assertEqual(get_trial_parallel_from_cwd("abc/_trial_temp/5"), 5) self.assertEqual(get_trial_parallel_from_cwd("abc/_trial_temp/5/"), 5)
2,828
Python
.py
46
55.565217
79
0.706412
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,541
test_maildir.py
buildbot_buildbot/master/buildbot/test/unit/util/test_maildir.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.test.util import dirs from buildbot.util import maildir class TestMaildirService(dirs.DirsMixin, unittest.TestCase): def setUp(self): self.maildir = os.path.abspath("maildir") self.newdir = os.path.join(self.maildir, "new") self.curdir = os.path.join(self.maildir, "cur") self.tmpdir = os.path.join(self.maildir, "tmp") self.setUpDirs(self.maildir, self.newdir, self.curdir, self.tmpdir) self.svc = None def tearDown(self): if self.svc and self.svc.running: self.svc.stopService() self.tearDownDirs() # tests @defer.inlineCallbacks def test_start_stop_repeatedly(self): self.svc = maildir.MaildirService(self.maildir) self.svc.startService() yield self.svc.stopService() self.svc.startService() yield self.svc.stopService() self.assertEqual(len(list(self.svc)), 0) @defer.inlineCallbacks def test_messageReceived(self): self.svc = maildir.MaildirService(self.maildir) # add a fake messageReceived method messagesReceived = [] def messageReceived(filename): messagesReceived.append(filename) return defer.succeed(None) self.svc.messageReceived = messageReceived yield self.svc.startService() self.assertEqual(messagesReceived, []) tmpfile = os.path.join(self.tmpdir, "newmsg") newfile = os.path.join(self.newdir, "newmsg") with open(tmpfile, "w", encoding='utf-8'): pass os.rename(tmpfile, newfile) # TODO: can we wait for a dnotify somehow, if enabled? yield self.svc.poll() self.assertEqual(messagesReceived, ['newmsg']) def test_moveToCurDir(self): self.svc = maildir.MaildirService(self.maildir) tmpfile = os.path.join(self.tmpdir, "newmsg") newfile = os.path.join(self.newdir, "newmsg") with open(tmpfile, "w", encoding='utf-8'): pass os.rename(tmpfile, newfile) f = self.svc.moveToCurDir("newmsg") f.close() self.assertEqual( [ os.path.exists(os.path.join(d, "newmsg")) for d in (self.newdir, self.curdir, self.tmpdir) ], [False, True, False], )
3,125
Python
.py
75
34.333333
79
0.672385
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,542
test_debounce.py
buildbot_buildbot/master/buildbot/test/unit/util/test_debounce.py
# This file is part of Buildbot. Buildbot is free software: you can # redistribute it and/or modify it under the terms of the GNU General Public # License as published by the Free Software Foundation, version 2. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more # details. # # You should have received a copy of the GNU General Public License along with # this program; if not, write to the Free Software Foundation, Inc., 51 # Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # Copyright Buildbot Team Members from twisted.internet import defer from twisted.internet import task from twisted.python import failure from twisted.python import log from twisted.trial import unittest from buildbot.util import debounce class DebouncedClass: def __init__(self, reactor): self.callDeferred = None self.calls = 0 self.expCalls = 0 self.stopDeferreds = [] self.reactor = reactor @debounce.method(wait=4.0, get_reactor=lambda self: self.reactor) def maybe(self): assert not self.callDeferred self.calls += 1 log.msg('debounced function called') self.callDeferred = defer.Deferred() @self.callDeferred.addBoth def unset(x): log.msg('debounced function complete') self.callDeferred = None return x return self.callDeferred class DebounceTest(unittest.TestCase): def setUp(self): self.clock = task.Clock() def scenario(self, events): dbs = dict((k, DebouncedClass(self.clock)) for k in {n for n, _, _ in events}) while events: n, t, e = events.pop(0) db = dbs[n] log.msg(f'time={t}, event={e}') if t > self.clock.seconds(): self.clock.advance(t - self.clock.seconds()) if e == 'maybe': db.maybe() elif e == 'called': db.expCalls += 1 elif e == 'complete': db.callDeferred.callback(None) elif e == 'complete-and-called': db.callDeferred.callback(None) db.expCalls += 1 elif e == 'fail': db.callDeferred.errback(failure.Failure(RuntimeError())) elif e == 'failure_logged': self.assertEqual(len(self.flushLoggedErrors(RuntimeError)), 1) elif e == 'check': pass # just check the expCalls elif e == 'start': db.maybe.start() elif e in ('stop', 'stop-and-called'): db.stopDeferreds.append(db.maybe.stop()) if e == 'stop-and-called': db.expCalls += 1 elif e == 'stopNotComplete': self.assertFalse(db.stopDeferreds[-1].called) elif e == 'stopComplete': self.assertTrue(db.stopDeferreds[-1].called) db.stopDeferreds.pop() else: self.fail(f"unknown scenario event {e}") for db in dbs.values(): self.assertEqual(db.calls, db.expCalls) def test_called_once(self): """The debounced method is called only after 4 seconds""" self.scenario([ (1, 0.0, 'maybe'), (1, 2.0, 'check'), (1, 4.0, 'called'), (1, 5.0, 'check'), (1, 6.0, 'complete'), (1, 7.0, 'check'), ]) def test_coalesce_calls(self): """Multiple calls are coalesced during 4 seconds, but the function runs 4 seconds after the first call.""" self.scenario([ (1, 0.0, 'maybe'), (1, 1.0, 'maybe'), (1, 2.0, 'maybe'), (1, 3.0, 'maybe'), (1, 4.0, 'called'), (1, 5.0, 'check'), (1, 6.0, 'complete'), (1, 7.0, 'check'), ]) def test_second_call_during_first(self): """If the debounced method is called after an execution has begun, then a second execution will take place 4 seconds after the execution finishes, with intervening calls coalesced.""" self.scenario([ (1, 0.0, 'maybe'), (1, 4.0, 'called'), (1, 5.0, 'maybe'), (1, 6.0, 'complete'), (1, 7.0, 'maybe'), (1, 9.0, 'maybe'), (1, 10.0, 'called'), (1, 11.0, 'check'), ]) def test_failure_logged(self): """If the debounced method fails, the error is logged, but otherwise it behaves as if it had succeeded.""" self.scenario([ (1, 0.0, 'maybe'), (1, 4.0, 'called'), (1, 5.0, 'maybe'), (1, 6.0, 'fail'), (1, 6.0, 'failure_logged'), (1, 10.0, 'called'), (1, 11.0, 'check'), ]) def test_instance_independence(self): """The timers for two instances are independent.""" self.scenario([ (1, 0.0, 'maybe'), (2, 2.0, 'maybe'), (1, 4.0, 'called'), (2, 6.0, 'called'), (1, 6.0, 'complete'), (2, 6.0, 'complete'), (1, 7.0, 'check'), ]) def test_start_when_started(self): """Calling meth.start when already started has no effect""" self.scenario([ (1, 0.0, 'start'), (1, 1.0, 'start'), ]) def test_stop_while_idle(self): """If the debounced method is stopped while idle, subsequent calls do nothing.""" self.scenario([ (1, 0.0, 'stop'), (1, 0.0, 'stopComplete'), (1, 1.0, 'maybe'), (1, 6.0, 'check'), # not called ]) def test_stop_while_waiting(self): """If the debounced method is stopped while waiting, the waiting call occurs immediately, stop returns immediately, and subsequent calls do nothing.""" self.scenario([ (1, 0.0, 'maybe'), (1, 2.0, 'stop-and-called'), (1, 2.1, 'complete'), (1, 2.1, 'stopComplete'), (1, 3.0, 'maybe'), (1, 8.0, 'check'), # not called ]) def test_stop_while_running(self): """If the debounced method is stopped while running, the running call completes, stop returns only after the call completes, and subsequent calls do nothing.""" self.scenario([ (1, 0.0, 'maybe'), (1, 4.0, 'called'), (1, 5.0, 'stop'), (1, 5.0, 'stopNotComplete'), (1, 6.0, 'complete'), (1, 6.0, 'stopComplete'), (1, 6.0, 'maybe'), (1, 10.0, 'check'), # not called ]) def test_multiple_stops(self): """Multiple stop calls will return individually when the method completes.""" self.scenario([ (1, 0.0, 'maybe'), (1, 4.0, 'called'), (1, 5.0, 'stop'), (1, 5.0, 'stop'), (1, 5.0, 'stopNotComplete'), (1, 6.0, 'complete'), (1, 6.0, 'stopComplete'), (1, 6.0, 'stopComplete'), (1, 6.0, 'maybe'), (1, 10.0, 'check'), # not called ]) def test_stop_while_running_queued(self): """If the debounced method is stopped while running with another call queued, the running call completes, stop returns only after the call completes, the queued call still occurs, and subsequent calls do nothing.""" self.scenario([ (1, 0.0, 'maybe'), (1, 4.0, 'called'), (1, 4.5, 'maybe'), (1, 5.0, 'stop'), (1, 5.0, 'stopNotComplete'), (1, 6.0, 'complete-and-called'), (1, 6.5, 'complete'), (1, 6.5, 'stopComplete'), (1, 6.5, 'maybe'), (1, 10.0, 'check'), # not called ]) def test_start_after_stop(self): """After a stop and subsequent start, a call to the debounced method causes an invocation 4 seconds later.""" self.scenario([ (1, 0.0, 'stop'), (1, 1.0, 'maybe'), (1, 2.0, 'start'), (1, 2.0, 'maybe'), (1, 5.0, 'check'), # not called (1, 6.0, 'called'), ])
8,527
Python
.py
224
27.575893
86
0.521797
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,543
test_sautils.py
buildbot_buildbot/master/buildbot/test/unit/util/test_sautils.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 hashlib from twisted.trial import unittest from buildbot.util import sautils class TestSaUtils(unittest.TestCase): def _sha1(self, s): return hashlib.sha1(s).hexdigest() def test_hash_columns_single(self): self.assertEqual(sautils.hash_columns('master'), self._sha1(b'master')) def test_hash_columns_multiple(self): self.assertEqual(sautils.hash_columns('a', None, 'b', 1), self._sha1(b'a\0\xf5\x00b\x001')) def test_hash_columns_None(self): self.assertEqual(sautils.hash_columns(None), self._sha1(b'\xf5')) def test_hash_columns_integer(self): self.assertEqual(sautils.hash_columns(11), self._sha1(b'11'))
1,388
Python
.py
28
46.107143
99
0.749075
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,544
test_protocol.py
buildbot_buildbot/master/buildbot/test/unit/util/test_protocol.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.util.protocol import LineProcessProtocol class FakeLineProcessProtocol(LineProcessProtocol): def __init__(self): super().__init__() self.out_lines = [] self.err_lines = [] def outLineReceived(self, line): self.out_lines.append(line) def errLineReceived(self, line): self.err_lines.append(line) class TestLineProcessProtocol(unittest.TestCase): def test_stdout(self): p = FakeLineProcessProtocol() p.outReceived(b'\nline2\nline3\nli') p.outReceived(b'ne4\nli') self.assertEqual(p.out_lines, [b'', b'line2', b'line3', b'line4']) p.processEnded(0) self.assertEqual(p.out_lines, [b'', b'line2', b'line3', b'line4', b'li']) def test_stderr(self): p = FakeLineProcessProtocol() p.errReceived(b'\nline2\nline3\nli') p.errReceived(b'ne4\nli') self.assertEqual(p.err_lines, [b'', b'line2', b'line3', b'line4']) p.processEnded(0) self.assertEqual(p.err_lines, [b'', b'line2', b'line3', b'line4', b'li'])
1,813
Python
.py
40
40.2
81
0.701247
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,545
test_private_tempdir.py
buildbot_buildbot/master/buildbot/test/unit/util/test_private_tempdir.py
# This file is part of Buildbot. Buildbot is free software: you can # redistribute it and/or modify it under the terms of the GNU General Public # License as published by the Free Software Foundation, version 2. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more # details. # # You should have received a copy of the GNU General Public License along with # this program; if not, write to the Free Software Foundation, Inc., 51 # Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # Copyright Buildbot Team Members import os import shutil import tempfile from twisted.trial import unittest from buildbot.test.util.decorators import skipUnlessPlatformIs from buildbot.util.private_tempdir import PrivateTemporaryDirectory class TestTemporaryDirectory(unittest.TestCase): # In this test we want to also check potential platform differences, so # we don't mock the filesystem access def setUp(self): self.tempdir = tempfile.mkdtemp() def tearDown(self): shutil.rmtree(self.tempdir) def test_simple(self): with PrivateTemporaryDirectory(dir=self.tempdir) as dir: self.assertTrue(os.path.isdir(dir)) self.assertFalse(os.path.isdir(dir)) @skipUnlessPlatformIs('posix') def test_mode(self): with PrivateTemporaryDirectory(dir=self.tempdir, mode=0o700) as dir: self.assertEqual(0o40700, os.stat(dir).st_mode) def test_cleanup(self): ctx = PrivateTemporaryDirectory(dir=self.tempdir) self.assertTrue(os.path.isdir(ctx.name)) ctx.cleanup() self.assertFalse(os.path.isdir(ctx.name)) ctx.cleanup() # also check whether multiple calls don't throw ctx.cleanup()
1,893
Python
.py
42
40.404762
79
0.749593
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,546
test_kubeclientservice.py
buildbot_buildbot/master/buildbot/test/unit/util/test_kubeclientservice.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 sys from io import StringIO from unittest import mock from unittest.case import SkipTest from twisted.internet import defer from twisted.python import runtime 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.test.util import config from buildbot.util import kubeclientservice from buildbot.util import service class MockFileBase: file_mock_config: dict[str, str] = {} def setUp(self): self.patcher = mock.patch('buildbot.util.kubeclientservice.open', self.mock_open) self.patcher.start() def tearDown(self): self.patcher.stop() def mock_open(self, filename, mode=None, encoding='UTF-8'): filename_type = os.path.basename(filename) file_value = self.file_mock_config[filename_type] mock_open = mock.Mock( __enter__=mock.Mock(return_value=StringIO(file_value)), __exit__=mock.Mock() ) return mock_open class KubeClientServiceTestClusterConfig(MockFileBase, config.ConfigErrorsMixin, unittest.TestCase): file_mock_config = {'token': 'BASE64_TOKEN', 'namespace': 'buildbot_namespace'} def setUp(self): super().setUp() self.patch(kubeclientservice.os, 'environ', {'KUBERNETES_PORT': 'tcp://foo'}) def patchExist(self, val): self.patch(kubeclientservice.os.path, 'exists', lambda x: val) def test_not_exists(self): self.patchExist(False) with self.assertRaisesConfigError('kube_dir not found:'): kubeclientservice.KubeInClusterConfigLoader() @defer.inlineCallbacks def test_basic(self): self.patchExist(True) config = kubeclientservice.KubeInClusterConfigLoader() yield config.startService() self.assertEqual( config.getConfig(), { 'headers': {'Authorization': 'Bearer BASE64_TOKEN'}, 'master_url': 'https://foo', 'namespace': 'buildbot_namespace', 'verify': '/var/run/secrets/kubernetes.io/serviceaccount/ca.crt', }, ) KUBE_CTL_PROXY_FAKE = """ import time import sys print("Starting to serve on 127.0.0.1:" + sys.argv[2]) sys.stdout.flush() time.sleep(1000) """ KUBE_CTL_PROXY_FAKE_ERROR = """ import time import sys print("Issue with the config!", file=sys.stderr) sys.stderr.flush() sys.exit(1) """ class KubeClientServiceTestKubeHardcodedConfig( TestReactorMixin, config.ConfigErrorsMixin, 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:8001" ) yield self.master.startService() @defer.inlineCallbacks def tearDown(self): yield self.master.stopService() yield self.tear_down_test_reactor() def test_basic(self): self.config = kubeclientservice.KubeHardcodedConfig( master_url="http://localhost:8001", namespace="default" ) self.assertEqual( self.config.getConfig(), {'master_url': 'http://localhost:8001', 'namespace': 'default', 'headers': {}}, ) def test_cannot_pass_both_bearer_and_basic_auth(self): with self.assertRaises(RuntimeError): kubeclientservice.KubeHardcodedConfig( master_url="http://localhost:8001", namespace="default", verify="/path/to/pem", basicAuth="Bla", bearerToken="Bla", ) class KubeClientServiceTestKubeCtlProxyConfig(config.ConfigErrorsMixin, unittest.TestCase): def patchProxyCmd(self, cmd): if runtime.platformType != 'posix': self.config = None raise SkipTest('only posix platform is supported by this test') self.patch( kubeclientservice.KubeCtlProxyConfigLoader, 'kube_ctl_proxy_cmd', [sys.executable, "-c", cmd], ) def tearDown(self): if self.config is not None and self.config.running: return self.config.stopService() return None @defer.inlineCallbacks def test_basic(self): self.patchProxyCmd(KUBE_CTL_PROXY_FAKE) self.config = kubeclientservice.KubeCtlProxyConfigLoader() yield self.config.startService() self.assertEqual( self.config.getConfig(), {'master_url': 'http://localhost:8001', 'namespace': 'default'} ) @defer.inlineCallbacks def test_config_args(self): self.patchProxyCmd(KUBE_CTL_PROXY_FAKE) self.config = kubeclientservice.KubeCtlProxyConfigLoader( proxy_port=8002, namespace="system" ) yield self.config.startService() self.assertEqual(self.config.kube_proxy_output, b'Starting to serve on 127.0.0.1:8002') self.assertEqual( self.config.getConfig(), {'master_url': 'http://localhost:8002', 'namespace': 'system'} ) yield self.config.stopService() @defer.inlineCallbacks def test_reconfig(self): self.patchProxyCmd(KUBE_CTL_PROXY_FAKE) self.config = kubeclientservice.KubeCtlProxyConfigLoader( proxy_port=8002, namespace="system" ) yield self.config.startService() self.assertEqual(self.config.kube_proxy_output, b'Starting to serve on 127.0.0.1:8002') self.assertEqual( self.config.getConfig(), {'master_url': 'http://localhost:8002', 'namespace': 'system'} ) yield self.config.reconfigService(proxy_port=8003, namespace="system2") self.assertEqual(self.config.kube_proxy_output, b'Starting to serve on 127.0.0.1:8003') self.assertEqual( self.config.getConfig(), {'master_url': 'http://localhost:8003', 'namespace': 'system2'} ) yield self.config.stopService() @defer.inlineCallbacks def test_config_with_error(self): self.patchProxyCmd(KUBE_CTL_PROXY_FAKE_ERROR) self.config = kubeclientservice.KubeCtlProxyConfigLoader() with self.assertRaises(RuntimeError): yield self.config.startService() class KubeClientServiceTest(unittest.TestCase): @defer.inlineCallbacks def setUp(self): self.parent = service.BuildbotService(name="parent") self.client = kubeclientservice.KubeClientService() yield self.client.setServiceParent(self.parent) @defer.inlineCallbacks def tearDown(self): if self.parent.running: yield self.parent.stopService() @defer.inlineCallbacks def test_stopped(self): worker = mock.Mock(name="worker1") config = service.BuildbotService(name="config") yield self.client.register(worker, config) self.assertEqual(config.running, 0) yield self.client.unregister(worker) self.assertEqual(config.running, 0) @defer.inlineCallbacks def test_started(self): yield self.parent.startService() worker = mock.Mock(name="worker1") config = service.BuildbotService(name="config") yield self.client.register(worker, config) self.assertEqual(config.running, 1) yield self.client.unregister(worker) self.assertEqual(config.running, 0) @defer.inlineCallbacks def test_started_but_stop(self): yield self.parent.startService() worker = mock.Mock(name="worker1") config = service.BuildbotService(name="config") yield self.client.register(worker, config) self.assertEqual(config.running, 1) yield self.parent.stopService() self.assertEqual(config.running, 0) @defer.inlineCallbacks def test_stopped_but_start(self): worker = mock.Mock(name="worker1") config = service.BuildbotService(name="config") yield self.client.register(worker, config) self.assertEqual(config.running, 0) yield self.parent.startService() self.assertEqual(config.running, 1) yield self.parent.stopService() self.assertEqual(config.running, 0) @defer.inlineCallbacks def test_two_workers(self): yield self.parent.startService() worker1 = mock.Mock(name="worker1") worker2 = mock.Mock(name="worker2") config = service.BuildbotService(name="config") yield self.client.register(worker1, config) self.assertEqual(config.running, 1) yield self.client.register(worker2, config) self.assertEqual(config.running, 1) yield self.client.unregister(worker1) self.assertEqual(config.running, 1) yield self.client.unregister(worker2) self.assertEqual(config.running, 0)
9,723
Python
.py
231
34.536797
100
0.683224
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,547
test_backoff.py
buildbot_buildbot/master/buildbot/test/unit/util/test_backoff.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 time from twisted.internet import defer from twisted.trial import unittest from buildbot.test.reactor import TestReactorMixin from buildbot.util import backoff class TestException(Exception): pass class ExponentialBackoffEngineAsyncTests(unittest.TestCase, TestReactorMixin): def setUp(self): self.setup_test_reactor(auto_tear_down=False) @defer.inlineCallbacks def tearDown(self): yield self.tear_down_test_reactor() def test_construct_asserts(self): with self.assertRaises(ValueError): backoff.ExponentialBackoffEngine(-1, 1, 1) with self.assertRaises(ValueError): backoff.ExponentialBackoffEngine(1, -1, 1) with self.assertRaises(ValueError): backoff.ExponentialBackoffEngine(1, 1, -1) @defer.inlineCallbacks def assert_called_after_time(self, d, time): self.assertFalse(d.called) self.reactor.advance(time * 0.99) self.assertFalse(d.called) self.reactor.advance(time * 0.010001) # avoid rounding errors by overshooting a little self.assertTrue(d.called) yield d # throw exceptions stored in d, if any @defer.inlineCallbacks def assert_called_immediately(self, d): self.assertTrue(d.called) yield d @defer.inlineCallbacks def test_wait_times(self): engine = backoff.ExponentialBackoffEngineAsync( self.reactor, start_seconds=10, multiplier=2, max_wait_seconds=1000 ) yield self.assert_called_after_time(engine.wait_on_failure(), 10) yield self.assert_called_after_time(engine.wait_on_failure(), 20) engine.on_success() yield self.assert_called_after_time(engine.wait_on_failure(), 10) yield self.assert_called_after_time(engine.wait_on_failure(), 20) yield self.assert_called_after_time(engine.wait_on_failure(), 40) engine.on_success() engine.on_success() yield self.assert_called_after_time(engine.wait_on_failure(), 10) @defer.inlineCallbacks def test_max_wait_seconds(self): engine = backoff.ExponentialBackoffEngineAsync( self.reactor, start_seconds=10, multiplier=2, max_wait_seconds=100 ) yield self.assert_called_after_time(engine.wait_on_failure(), 10) yield self.assert_called_after_time(engine.wait_on_failure(), 20) yield self.assert_called_after_time(engine.wait_on_failure(), 40) yield self.assert_called_after_time(engine.wait_on_failure(), 30) with self.assertRaises(backoff.BackoffTimeoutExceededError): yield self.assert_called_immediately(engine.wait_on_failure()) with self.assertRaises(backoff.BackoffTimeoutExceededError): yield self.assert_called_immediately(engine.wait_on_failure()) engine.on_success() yield self.assert_called_after_time(engine.wait_on_failure(), 10) yield self.assert_called_after_time(engine.wait_on_failure(), 20) yield self.assert_called_after_time(engine.wait_on_failure(), 40) yield self.assert_called_after_time(engine.wait_on_failure(), 30) with self.assertRaises(backoff.BackoffTimeoutExceededError): yield self.assert_called_immediately(engine.wait_on_failure()) class ExponentialBackoffEngineSyncTests(unittest.TestCase): # All the complex cases are tested in ExponentialBackoffEngineAsyncTests where we can fake # the clock. For the synchronous engine we just need to test that waiting works. def test_wait_on_failure(self): engine = backoff.ExponentialBackoffEngineSync( start_seconds=0.05, multiplier=2, max_wait_seconds=1 ) begin = time.monotonic() engine.wait_on_failure() end = time.monotonic() # Note that if time is adjusted back even a little bit during the test it will fail. # So we add a little bit of wiggle room. self.assertGreater(end - begin, 0.04)
4,700
Python
.py
93
43.473118
95
0.717216
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,548
test_bbcollections.py
buildbot_buildbot/master/buildbot/test/unit/util/test_bbcollections.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.util import bbcollections class KeyedSets(unittest.TestCase): def setUp(self): self.ks = bbcollections.KeyedSets() def test_getitem_default(self): self.assertEqual(self.ks['x'], set()) # remaining tests effectively cover __getitem__ def test_add(self): self.ks.add('y', 2) self.assertEqual(self.ks['y'], set([2])) def test_add_twice(self): self.ks.add('z', 2) self.ks.add('z', 4) self.assertEqual(self.ks['z'], set([2, 4])) def test_discard_noError(self): self.ks.add('full', 12) self.ks.discard('empty', 13) # should not fail self.ks.discard('full', 13) # nor this self.assertEqual(self.ks['full'], set([12])) def test_discard_existing(self): self.ks.add('yarn', 'red') self.ks.discard('yarn', 'red') self.assertEqual(self.ks['yarn'], set([])) def test_contains_true(self): self.ks.add('yarn', 'red') self.assertTrue('yarn' in self.ks) def test_contains_false(self): self.assertFalse('yarn' in self.ks) def test_contains_setNamesNotContents(self): self.ks.add('yarn', 'red') self.assertFalse('red' in self.ks) def test_pop_exists(self): self.ks.add('names', 'pop') self.ks.add('names', 'coke') self.ks.add('names', 'soda') popped = self.ks.pop('names') remaining = self.ks['names'] self.assertEqual((popped, remaining), (set(['pop', 'coke', 'soda']), set())) def test_pop_missing(self): self.assertEqual(self.ks.pop('flavors'), set())
2,366
Python
.py
55
37.036364
84
0.659991
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,549
test_async_sort.py
buildbot_buildbot/master/buildbot/test/unit/util/test_async_sort.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.util.logging import LoggingMixin from buildbot.util.async_sort import async_sort class AsyncSort(unittest.TestCase, LoggingMixin): def setUp(self) -> None: self.setUpLogging() return super().setUp() @defer.inlineCallbacks def test_sync_call(self): l = ["b", "c", "a"] yield async_sort(l, lambda x: x) return self.assertEqual(l, ["a", "b", "c"]) @defer.inlineCallbacks def test_async_call(self): l = ["b", "c", "a"] yield async_sort(l, defer.succeed) self.assertEqual(l, ["a", "b", "c"]) @defer.inlineCallbacks def test_async_fail(self): l = ["b", "c", "a"] class SortFail(Exception): pass with self.assertRaises(SortFail): yield async_sort( l, lambda x: defer.succeed(x) if x != "a" else defer.fail(SortFail("ono")) ) self.assertEqual(l, ["b", "c", "a"])
1,736
Python
.py
42
35.880952
90
0.677956
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,550
test_runprocess.py
buildbot_buildbot/master/buildbot/test/unit/util/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 import os from unittest import mock from parameterized import parameterized from twisted.internet import defer from twisted.python import runtime from twisted.trial import unittest from buildbot.test.reactor import TestReactorMixin from buildbot.test.util.logging import LoggingMixin from buildbot.util.runprocess import RunProcess # windows returns rc 1, because exit status cannot indicate "signalled"; # posix returns rc -1 for "signalled" FATAL_RC = -1 if runtime.platformType == 'win32': FATAL_RC = 1 class TestRunProcess(TestReactorMixin, LoggingMixin, unittest.TestCase): FAKE_PID = 1234 def setUp(self): self.setup_test_reactor(auto_tear_down=False) self.setUpLogging() self.process = None self.reactor.spawnProcess = self.fake_spawn_process @defer.inlineCallbacks def tearDown(self): yield self.tear_down_test_reactor() def fake_spawn_process(self, pp, command, args, env, workdir, usePTY=False): self.assertIsNone(self.process) self.pp = pp self.pp.transport = mock.Mock() self.process = mock.Mock() self.process.pid = self.FAKE_PID self.process_spawned_args = (command, args, env, workdir) return self.process def run_process(self, command, override_kill_success=True, override_is_dead=True, **kwargs): self.run_process_obj = RunProcess(self.reactor, command, '/workdir', **kwargs) self.run_process_obj.get_os_env = lambda: {'OS_ENV': 'value'} self.run_process_obj.send_signal = mock.Mock(side_effect=lambda sig: override_kill_success) self.run_process_obj.is_dead = mock.Mock(side_effect=lambda: override_is_dead) return self.run_process_obj.start() def end_process(self, signal=None, rc=0): reason = mock.Mock() reason.value.signal = signal reason.value.exitCode = rc self.pp.processEnded(reason) @defer.inlineCallbacks def test_no_output(self): d = self.run_process(['cmd'], collect_stdout=True, collect_stderr=False) self.assertEqual( self.process_spawned_args, ('cmd', ['cmd'], {'OS_ENV': 'value', 'PWD': os.path.abspath('/workdir')}, '/workdir'), ) self.pp.connectionMade() self.assertFalse(d.called) self.end_process() self.assertTrue(d.called) res = yield d self.assertEqual(res, (0, b'')) @defer.inlineCallbacks def test_env_new_kv(self): d = self.run_process( ['cmd'], collect_stdout=False, collect_stderr=False, env={'custom': 'custom-value'} ) self.assertEqual( self.process_spawned_args, ( 'cmd', ['cmd'], {'OS_ENV': 'value', 'PWD': os.path.abspath('/workdir'), 'custom': 'custom-value'}, '/workdir', ), ) self.pp.connectionMade() self.end_process() res = yield d self.assertEqual(res, 0) @defer.inlineCallbacks def test_env_overwrite_os_kv(self): d = self.run_process( ['cmd'], collect_stdout=True, collect_stderr=False, env={'OS_ENV': 'custom-value'} ) self.assertEqual( self.process_spawned_args, ( 'cmd', ['cmd'], {'OS_ENV': 'custom-value', 'PWD': os.path.abspath('/workdir')}, '/workdir', ), ) self.pp.connectionMade() self.end_process() res = yield d self.assertEqual(res, (0, b'')) @defer.inlineCallbacks def test_env_remove_os_kv(self): d = self.run_process( ['cmd'], collect_stdout=True, collect_stderr=False, env={'OS_ENV': None} ) self.assertEqual( self.process_spawned_args, ('cmd', ['cmd'], {'PWD': os.path.abspath('/workdir')}, '/workdir'), ) self.pp.connectionMade() self.end_process() res = yield d self.assertEqual(res, (0, b'')) @defer.inlineCallbacks def test_collect_nothing(self): d = self.run_process(['cmd'], collect_stdout=False, collect_stderr=False) self.pp.connectionMade() self.pp.transport.write.assert_not_called() self.pp.transport.closeStdin.assert_called() self.pp.outReceived(b'stdout_data') self.pp.errReceived(b'stderr_data') self.assertFalse(d.called) self.end_process() self.assertTrue(d.called) res = yield d self.assertEqual(res, 0) @defer.inlineCallbacks def test_collect_stdout_no_stderr(self): d = self.run_process(['cmd'], collect_stdout=True, collect_stderr=False) self.pp.connectionMade() self.pp.transport.write.assert_not_called() self.pp.transport.closeStdin.assert_called() self.pp.outReceived(b'stdout_data') self.pp.errReceived(b'stderr_data') self.assertFalse(d.called) self.end_process() self.assertTrue(d.called) res = yield d self.assertEqual(res, (0, b'stdout_data')) @defer.inlineCallbacks def test_collect_stdout_with_stdin(self): d = self.run_process( ['cmd'], collect_stdout=True, collect_stderr=False, initial_stdin=b'stdin' ) self.pp.connectionMade() self.pp.transport.write.assert_called_with(b'stdin') self.pp.transport.closeStdin.assert_called() self.pp.outReceived(b'stdout_data') self.pp.errReceived(b'stderr_data') self.end_process() res = yield d self.assertEqual(res, (0, b'stdout_data')) @defer.inlineCallbacks def test_collect_stdout_and_stderr(self): d = self.run_process(['cmd'], collect_stdout=True, collect_stderr=True) self.pp.connectionMade() self.pp.transport.write.assert_not_called() self.pp.transport.closeStdin.assert_called() self.pp.outReceived(b'stdout_data') self.pp.errReceived(b'stderr_data') self.end_process() res = yield d self.assertEqual(res, (0, b'stdout_data', b'stderr_data')) @defer.inlineCallbacks def test_process_failed_with_rc(self): d = self.run_process(['cmd'], collect_stdout=True, collect_stderr=True) self.pp.connectionMade() self.pp.outReceived(b'stdout_data') self.pp.errReceived(b'stderr_data') self.end_process(rc=1) res = yield d self.assertEqual(res, (1, b'stdout_data', b'stderr_data')) @defer.inlineCallbacks def test_process_failed_with_signal(self): d = self.run_process(['cmd'], collect_stdout=True, collect_stderr=True) self.pp.connectionMade() self.pp.outReceived(b'stdout_data') self.pp.errReceived(b'stderr_data') self.end_process(signal='SIGILL') res = yield d self.assertEqual(res, (-1, b'stdout_data', b'stderr_data')) @parameterized.expand([ ('too_short_time_no_output', 0, 4.9, False, False, False), ('too_short_time_with_output', 0, 4.9, False, True, True), ('timed_out_no_output', 0, 5.1, True, False, False), ('timed_out_with_output', 0, 5.1, True, True, True), ('stdout_prevented_timeout', 1.0, 4.9, False, True, False), ('stderr_prevented_timeout', 1.0, 4.9, False, False, True), ('timed_out_after_extra_output', 1.0, 5.1, True, True, True), ]) @defer.inlineCallbacks def test_io_timeout(self, name, wait1, wait2, timed_out, had_stdout, had_stderr): d = self.run_process(['cmd'], collect_stdout=True, collect_stderr=True, io_timeout=5) self.pp.connectionMade() self.reactor.advance(wait1) if had_stdout: self.pp.outReceived(b'stdout_data') if had_stderr: self.pp.errReceived(b'stderr_data') self.reactor.advance(wait2) self.assertFalse(d.called) self.end_process() self.assertTrue(d.called) if timed_out: self.run_process_obj.send_signal.assert_called_with('TERM') else: self.run_process_obj.send_signal.assert_not_called() res = yield d self.assertEqual( res, ( FATAL_RC if timed_out else 0, b'stdout_data' if had_stdout else b'', b'stderr_data' if had_stderr else b'', ), ) @parameterized.expand([ ('too_short_time', 4.9, False), ('timed_out', 5.1, True), ]) @defer.inlineCallbacks def test_runtime_timeout(self, name, wait, timed_out): d = self.run_process(['cmd'], collect_stdout=True, collect_stderr=True, runtime_timeout=5) self.pp.connectionMade() self.reactor.advance(wait) self.assertFalse(d.called) self.end_process() self.assertTrue(d.called) if timed_out: self.run_process_obj.send_signal.assert_called_with('TERM') else: self.run_process_obj.send_signal.assert_not_called() res = yield d self.assertEqual(res, (FATAL_RC if timed_out else 0, b'', b'')) @defer.inlineCallbacks def test_runtime_timeout_failing_to_kill(self): d = self.run_process( ['cmd'], collect_stdout=True, collect_stderr=True, runtime_timeout=5, sigterm_timeout=5, override_is_dead=False, ) self.pp.connectionMade() self.reactor.advance(5.1) self.run_process_obj.send_signal.assert_called_with('TERM') self.reactor.advance(5.1) self.run_process_obj.send_signal.assert_called_with('KILL') self.reactor.advance(5.1) self.assertTrue(d.called) self.end_process() with self.assertRaises(RuntimeError): yield d self.assertLogged("attempted to kill process, but it wouldn't die")
10,700
Python
.py
261
32.398467
99
0.627313
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,551
test_test_result_submitter.py
buildbot_buildbot/master/buildbot/test/unit/util/test_test_result_submitter.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.fake import fakemaster from buildbot.test.reactor import TestReactorMixin from buildbot.util.test_result_submitter import TestResultSubmitter class TestTestResultSubmitter(TestReactorMixin, unittest.TestCase): @defer.inlineCallbacks def setUp(self): self.setup_test_reactor(auto_tear_down=False) self.master = yield fakemaster.make_master(self, wantData=True, wantDb=True) yield self.master.startService() yield self.master.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), ]) @defer.inlineCallbacks def tearDown(self): yield self.master.stopService() yield self.tear_down_test_reactor() @defer.inlineCallbacks def test_complete_empty(self): sub = TestResultSubmitter() yield sub.setup_by_ids(self.master, 88, 30, 131, 'desc', 'cat', 'unit') setid = sub.get_test_result_set_id() sets = yield self.master.data.get(('builds', 30, 'test_result_sets')) self.assertEqual( list(sets), [ { 'test_result_setid': setid, 'builderid': 88, 'buildid': 30, 'stepid': 131, 'description': 'desc', 'category': 'cat', 'value_unit': 'unit', 'tests_passed': None, 'tests_failed': None, 'complete': False, } ], ) yield sub.finish() sets = yield self.master.data.get(('builds', 30, 'test_result_sets')) self.assertEqual( list(sets), [ { 'test_result_setid': setid, 'builderid': 88, 'buildid': 30, 'stepid': 131, 'description': 'desc', 'category': 'cat', 'value_unit': 'unit', 'tests_passed': None, 'tests_failed': None, 'complete': True, } ], ) @defer.inlineCallbacks def test_submit_result(self): sub = TestResultSubmitter(batch_n=3) yield sub.setup_by_ids(self.master, 88, 30, 131, 'desc', 'cat', 'unit') sub.add_test_result('1', 'name1') yield sub.finish() setid = sub.get_test_result_set_id() sets = yield self.master.data.get(('builds', 30, 'test_result_sets')) self.assertEqual( list(sets), [ { 'test_result_setid': setid, 'builderid': 88, 'buildid': 30, 'stepid': 131, 'description': 'desc', 'category': 'cat', 'value_unit': 'unit', 'tests_passed': None, 'tests_failed': None, 'complete': True, } ], ) results = yield self.master.data.get(('test_result_sets', setid, 'results')) self.assertEqual( list(results), [ { 'test_resultid': 1, 'builderid': 88, 'test_result_setid': setid, 'test_name': 'name1', 'test_code_path': None, 'duration_ns': None, 'line': None, 'value': '1', } ], ) def filter_results_value_name(self, results): return [{'test_name': r['test_name'], 'value': r['value']} for r in results] @defer.inlineCallbacks def test_submit_result_wrong_argument_types(self): sub = TestResultSubmitter() yield sub.setup_by_ids(self.master, 88, 30, 131, 'desc', 'cat', 'unit') with self.assertRaises(TypeError): sub.add_test_result(1, 'name1') with self.assertRaises(TypeError): sub.add_test_result('1', test_name=123) with self.assertRaises(TypeError): sub.add_test_result('1', 'name1', test_code_path=123) with self.assertRaises(TypeError): sub.add_test_result('1', 'name1', line='123') with self.assertRaises(TypeError): sub.add_test_result('1', 'name1', duration_ns='123') @defer.inlineCallbacks def test_batchs_last_batch_full(self): sub = TestResultSubmitter(batch_n=3) yield sub.setup_by_ids(self.master, 88, 30, 131, 'desc', 'cat', 'unit') sub.add_test_result('1', 'name1') sub.add_test_result('2', 'name2') sub.add_test_result('3', 'name3') sub.add_test_result('4', 'name4') sub.add_test_result('5', 'name5') sub.add_test_result('6', 'name6') yield sub.finish() setid = sub.get_test_result_set_id() results = yield self.master.data.get(('test_result_sets', setid, 'results')) results = self.filter_results_value_name(results) self.assertEqual( results, [ {'test_name': 'name1', 'value': '1'}, {'test_name': 'name2', 'value': '2'}, {'test_name': 'name3', 'value': '3'}, {'test_name': 'name4', 'value': '4'}, {'test_name': 'name5', 'value': '5'}, {'test_name': 'name6', 'value': '6'}, ], ) @defer.inlineCallbacks def test_batchs_last_batch_not_full(self): sub = TestResultSubmitter(batch_n=3) yield sub.setup_by_ids(self.master, 88, 30, 131, 'desc', 'cat', 'unit') sub.add_test_result('1', 'name1') sub.add_test_result('2', 'name2') sub.add_test_result('3', 'name3') sub.add_test_result('4', 'name4') sub.add_test_result('5', 'name5') yield sub.finish() setid = sub.get_test_result_set_id() results = yield self.master.data.get(('test_result_sets', setid, 'results')) results = self.filter_results_value_name(results) self.assertEqual( results, [ {'test_name': 'name1', 'value': '1'}, {'test_name': 'name2', 'value': '2'}, {'test_name': 'name3', 'value': '3'}, {'test_name': 'name4', 'value': '4'}, {'test_name': 'name5', 'value': '5'}, ], ) @defer.inlineCallbacks def test_counts_pass_fail(self): sub = TestResultSubmitter(batch_n=3) yield sub.setup_by_ids(self.master, 88, 30, 131, 'desc', 'pass_fail', 'boolean') sub.add_test_result('0', 'name1') sub.add_test_result('0', 'name2') sub.add_test_result('1', 'name3') sub.add_test_result('1', 'name4') sub.add_test_result('0', 'name5') yield sub.finish() setid = sub.get_test_result_set_id() sets = yield self.master.data.get(('builds', 30, 'test_result_sets')) self.assertEqual( list(sets), [ { 'test_result_setid': setid, 'builderid': 88, 'buildid': 30, 'stepid': 131, 'description': 'desc', 'category': 'pass_fail', 'value_unit': 'boolean', 'tests_passed': 2, 'tests_failed': 3, 'complete': True, } ], ) @defer.inlineCallbacks def test_counts_pass_fail_invalid_values(self): sub = TestResultSubmitter(batch_n=3) yield sub.setup_by_ids(self.master, 88, 30, 131, 'desc', 'pass_fail', 'boolean') sub.add_test_result('0', 'name1') sub.add_test_result('0', 'name2') sub.add_test_result('1', 'name3') sub.add_test_result('1', 'name4') sub.add_test_result('invalid', 'name5') yield sub.finish() setid = sub.get_test_result_set_id() sets = yield self.master.data.get(('builds', 30, 'test_result_sets')) self.assertEqual( list(sets), [ { 'test_result_setid': setid, 'builderid': 88, 'buildid': 30, 'stepid': 131, 'description': 'desc', 'category': 'pass_fail', 'value_unit': 'boolean', 'tests_passed': 2, 'tests_failed': 2, 'complete': True, } ], ) # also check whether we preserve the "invalid" values in the database. results = yield self.master.data.get(('test_result_sets', setid, 'results')) results = self.filter_results_value_name(results) self.assertEqual( results, [ {'test_name': 'name1', 'value': '0'}, {'test_name': 'name2', 'value': '0'}, {'test_name': 'name3', 'value': '1'}, {'test_name': 'name4', 'value': '1'}, {'test_name': 'name5', 'value': 'invalid'}, ], ) self.flushLoggedErrors(ValueError) @defer.inlineCallbacks def test_counts_pass_only(self): sub = TestResultSubmitter(batch_n=3) yield sub.setup_by_ids(self.master, 88, 30, 131, 'desc', 'pass_only', 'some_unit') sub.add_test_result('string1', 'name1') sub.add_test_result('string2', 'name2') sub.add_test_result('string3', 'name3') sub.add_test_result('string4', 'name4') sub.add_test_result('string5', 'name5') yield sub.finish() setid = sub.get_test_result_set_id() sets = yield self.master.data.get(('builds', 30, 'test_result_sets')) self.assertEqual( list(sets), [ { 'test_result_setid': setid, 'builderid': 88, 'buildid': 30, 'stepid': 131, 'description': 'desc', 'category': 'pass_only', 'value_unit': 'some_unit', 'tests_passed': 5, 'tests_failed': 0, 'complete': True, } ], ) results = yield self.master.data.get(('test_result_sets', setid, 'results')) results = self.filter_results_value_name(results) self.assertEqual( results, [ {'test_name': 'name1', 'value': 'string1'}, {'test_name': 'name2', 'value': 'string2'}, {'test_name': 'name3', 'value': 'string3'}, {'test_name': 'name4', 'value': 'string4'}, {'test_name': 'name5', 'value': 'string5'}, ], ) self.flushLoggedErrors(ValueError) @defer.inlineCallbacks def test_counts_fail_only(self): sub = TestResultSubmitter(batch_n=3) yield sub.setup_by_ids(self.master, 88, 30, 131, 'desc', 'fail_only', 'some_unit') sub.add_test_result('string1', 'name1') sub.add_test_result('string2', 'name2') sub.add_test_result('string3', 'name3') sub.add_test_result('string4', 'name4') sub.add_test_result('string5', 'name5') yield sub.finish() setid = sub.get_test_result_set_id() sets = yield self.master.data.get(('builds', 30, 'test_result_sets')) self.assertEqual( list(sets), [ { 'test_result_setid': setid, 'builderid': 88, 'buildid': 30, 'stepid': 131, 'description': 'desc', 'category': 'fail_only', 'value_unit': 'some_unit', 'tests_passed': 0, 'tests_failed': 5, 'complete': True, } ], ) results = yield self.master.data.get(('test_result_sets', setid, 'results')) results = self.filter_results_value_name(results) self.assertEqual( results, [ {'test_name': 'name1', 'value': 'string1'}, {'test_name': 'name2', 'value': 'string2'}, {'test_name': 'name3', 'value': 'string3'}, {'test_name': 'name4', 'value': 'string4'}, {'test_name': 'name5', 'value': 'string5'}, ], ) self.flushLoggedErrors(ValueError)
13,923
Python
.py
344
27.796512
90
0.505981
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,552
test_giturlparse.py
buildbot_buildbot/master/buildbot/test/unit/util/test_giturlparse.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.util import giturlparse class Tests(unittest.TestCase): def test_github(self): for u in [ "https://github.com/buildbot/buildbot", "https://github.com/buildbot/buildbot.git", "ssh://[email protected]:buildbot/buildbot.git", "git://github.com/buildbot/buildbot.git", ]: u = giturlparse(u) self.assertIn(u.user, (None, "git")) self.assertEqual(u.domain, "github.com") self.assertEqual(u.owner, "buildbot") self.assertEqual(u.repo, "buildbot") self.assertIsNone(u.port) def test_gitlab(self): for u in [ "ssh://[email protected]/group/subgrouptest/testproject.git", "https://mygitlab.com/group/subgrouptest/testproject.git", "[email protected]:group/subgrouptest/testproject.git", "git://mygitlab.com/group/subgrouptest/testproject.git", ]: u = giturlparse(u) self.assertIsNone(u.port) self.assertIn(u.user, (None, "git")) self.assertEqual(u.domain, "mygitlab.com") self.assertEqual(u.owner, "group/subgrouptest") self.assertEqual(u.repo, "testproject") def test_gitlab_subsubgroup(self): for u in [ "ssh://[email protected]/group/subgrouptest/subsubgroup/testproject.git", "https://mygitlab.com/group/subgrouptest/subsubgroup/testproject.git", "git://mygitlab.com/group/subgrouptest/subsubgroup/testproject.git", ]: u = giturlparse(u) self.assertIn(u.user, (None, "git")) self.assertIsNone(u.port) self.assertEqual(u.domain, "mygitlab.com") self.assertEqual(u.owner, "group/subgrouptest/subsubgroup") self.assertEqual(u.repo, "testproject") def test_gitlab_user(self): for u in [ "ssh://[email protected]:group/subgrouptest/testproject.git", "https://[email protected]/group/subgrouptest/testproject.git", ]: u = giturlparse(u) self.assertEqual(u.domain, "mygitlab.com") self.assertIsNone(u.port) self.assertEqual(u.user, "buildbot") self.assertEqual(u.owner, "group/subgrouptest") self.assertEqual(u.repo, "testproject") def test_gitlab_port(self): for u in ["ssh://[email protected]:1234/group/subgrouptest/testproject.git"]: u = giturlparse(u) self.assertEqual(u.domain, "mygitlab.com") self.assertEqual(u.port, 1234) self.assertEqual(u.user, "buildbot") self.assertEqual(u.owner, "group/subgrouptest") self.assertEqual(u.repo, "testproject") def test_bitbucket(self): for u in [ "https://bitbucket.org/org/repo.git", "ssh://[email protected]:org/repo.git", "[email protected]:org/repo.git", ]: u = giturlparse(u) self.assertIn(u.user, (None, "git")) self.assertEqual(u.domain, "bitbucket.org") self.assertEqual(u.owner, "org") self.assertEqual(u.repo, "repo") def test_no_owner(self): for u in [ "https://example.org/repo.git", "ssh://example.org:repo.git", "ssh://[email protected]:repo.git", "[email protected]:repo.git", ]: u = giturlparse(u) self.assertIn(u.user, (None, "git")) self.assertEqual(u.domain, "example.org") self.assertIsNone(u.owner) self.assertEqual(u.repo, "repo") def test_protos(self): self.assertEqual(giturlparse("https://bitbucket.org/org/repo.git").proto, "https") self.assertEqual(giturlparse("git://bitbucket.org/org/repo.git").proto, "git") self.assertEqual(giturlparse("ssh://[email protected]:org/repo.git").proto, "ssh") self.assertEqual(giturlparse("[email protected]:org/repo.git").proto, "ssh") def test_user_password(self): for u, expected_user, expected_password in [ ("https://[email protected]/buildbot/buildbot", "user", None), ("https://user:[email protected]/buildbot/buildbot", "user", "password"), ]: u = giturlparse(u) self.assertEqual(u.user, expected_user) self.assertEqual(u.password, expected_password) self.assertEqual(u.domain, "github.com") self.assertEqual(u.owner, "buildbot") self.assertEqual(u.repo, "buildbot") self.assertIsNone(u.port)
5,379
Python
.py
114
37.166667
90
0.624976
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,553
test_notifier.py
buildbot_buildbot/master/buildbot/test/unit/util/test_notifier.py
# Copyright Buildbot Team Members # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. from twisted.internet import defer from twisted.python.failure import Failure from twisted.trial import unittest from buildbot.util import Notifier class TestException(Exception): """ An exception thrown in tests. """ class Tests(unittest.TestCase): def test_wait(self): """ Calling `Notifier.wait` returns a deferred that hasn't fired. """ n = Notifier() self.assertNoResult(n.wait()) def test_notify_no_waiters(self): """ Calling `Notifier.notify` when there are no waiters does not raise. """ n = Notifier() n.notify(object()) # Does not raise. @defer.inlineCallbacks def test_notify_multiple_waiters(self): """ If there all multiple waiters, `Notifier.notify` fires all the deferreds with the same value. """ value = object() n = Notifier() ds = [n.wait(), n.wait()] n.notify(value) self.assertEqual((yield ds[0]), value) self.assertEqual((yield ds[1]), value) @defer.inlineCallbacks def test_new_waiters_not_notified(self): """ If a new waiter is added while notifying, it won't be notified until the next notification. """ value = object() n = Notifier() box = [] def add_new_waiter(_): box.append(n.wait()) n.wait().addCallback(add_new_waiter) n.notify(object()) self.assertNoResult(box[0]) n.notify(value) self.assertEqual( (yield box[0]), value, ) @defer.inlineCallbacks def test_notify_failure(self): """ If a failure is passed to `Notifier.notify` then the waiters are errback'd. """ n = Notifier() d = n.wait() n.notify(Failure(TestException())) with self.assertRaises(TestException): yield d def test_nonzero_waiters(self): """ If there are waiters, ``Notifier`` evaluates as `True`. """ n = Notifier() n.wait() self.assertTrue(n) def test_nonzero_no_waiters(self): """ If there no waiters, ``Notifier`` evaluates as `False`. """ n = Notifier() self.assertFalse(n) def test_nonzero_cleared_waiters(self): """ After notifying waiters, ``Notifier`` evaluates as `False`. """ n = Notifier() n.wait() n.notify(object()) self.assertFalse(n)
3,658
Python
.py
106
27.698113
72
0.640837
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,554
test_test_util_runprocess.py
buildbot_buildbot/master/buildbot/test/unit/util/test_test_util_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 twisted.internet import defer from twisted.trial import reporter from twisted.trial import unittest from buildbot.test.runprocess import ExpectMasterShell from buildbot.test.runprocess import MasterRunProcessMixin from buildbot.util import runprocess class TestRunprocessMixin(unittest.TestCase): def run_test_method(self, method): class TestCase(MasterRunProcessMixin, unittest.TestCase): def setUp(self): self.setup_master_run_process() def runTest(self): return method(self) self.testcase = TestCase() result = reporter.TestResult() self.testcase.run(result) # This blocks return result def assert_test_failure(self, result, expected_failure): self.assertEqual(result.errors, []) self.assertEqual(len(result.failures), 1) self.assertTrue(result.failures[0][1].check(unittest.FailTest)) if expected_failure: self.assertSubstring(expected_failure, result.failures[0][1].getErrorMessage()) def assert_successful(self, result): if not result.wasSuccessful(): output = 'expected success' if result.failures: output += f'\ntest failed: {result.failures[0][1].getErrorMessage()}' if result.errors: output += f'\nerrors: {[error[1].value for error in result.errors]}' raise self.failureException(output) self.assertTrue(result.wasSuccessful()) def test_patch(self): original_run_process = runprocess.run_process def method(testcase): testcase.expect_commands() self.assertEqual(runprocess.run_process, testcase.patched_run_process) result = self.run_test_method(method) self.assert_successful(result) self.assertEqual(runprocess.run_process, original_run_process) def test_method_chaining(self): expect = ExpectMasterShell('command') self.assertEqual(expect, expect.exit(0)) self.assertEqual(expect, expect.stdout(b"output")) self.assertEqual(expect, expect.stderr(b"error")) def test_run_process_one_command_only_rc(self): @defer.inlineCallbacks def method(testcase): testcase.expect_commands( ExpectMasterShell(["command"]).stdout(b'stdout').stderr(b'stderr') ) res = yield runprocess.run_process( None, ["command"], collect_stdout=False, collect_stderr=False ) self.assertEqual(res, 0) testcase.assert_all_commands_ran() result = self.run_test_method(method) self.assert_successful(result) def test_run_process_one_command_only_rc_stdout(self): @defer.inlineCallbacks def method(testcase): testcase.expect_commands( ExpectMasterShell(["command"]).stdout(b'stdout').stderr(b'stderr') ) res = yield runprocess.run_process( None, ["command"], collect_stdout=True, collect_stderr=False ) self.assertEqual(res, (0, b'stdout')) testcase.assert_all_commands_ran() result = self.run_test_method(method) self.assert_successful(result) def test_run_process_one_command_with_rc_stderr(self): @defer.inlineCallbacks def method(testcase): testcase.expect_commands( ExpectMasterShell(["command"]).stdout(b'stdout').stderr(b'stderr') ) res = yield runprocess.run_process( None, ["command"], collect_stdout=False, collect_stderr=True ) self.assertEqual(res, (0, b'stderr')) testcase.assert_all_commands_ran() result = self.run_test_method(method) self.assert_successful(result) def test_run_process_one_command_with_rc_stdout_stderr(self): @defer.inlineCallbacks def method(testcase): testcase.expect_commands( ExpectMasterShell(["command"]).stdout(b'stdout').stderr(b'stderr') ) res = yield runprocess.run_process(None, ["command"]) self.assertEqual(res, (0, b'stdout', b'stderr')) testcase.assert_all_commands_ran() result = self.run_test_method(method) self.assert_successful(result) def test_run_process_expect_two_run_one(self): @defer.inlineCallbacks def method(testcase): testcase.expect_commands(ExpectMasterShell(["command"])) testcase.expect_commands(ExpectMasterShell(["command2"])) res = yield runprocess.run_process(None, ["command"]) self.assertEqual(res, (0, b'', b'')) testcase.assert_all_commands_ran() result = self.run_test_method(method) self.assert_test_failure(result, "assert all expected commands were run") def test_run_process_wrong_command(self): @defer.inlineCallbacks def method(testcase): testcase.expect_commands(ExpectMasterShell(["command2"])) yield runprocess.run_process(None, ["command"]) result = self.run_test_method(method) self.assert_test_failure(result, "unexpected command run") # assert we have a meaningful message self.assert_test_failure(result, "command2") def test_run_process_wrong_args(self): @defer.inlineCallbacks def method(testcase): testcase.expect_commands(ExpectMasterShell(["command", "arg"])) yield runprocess.run_process(None, ["command", "otherarg"]) testcase.assert_all_commands_ran() result = self.run_test_method(method) self.assert_test_failure(result, "unexpected command run") def test_run_process_missing_path(self): @defer.inlineCallbacks def method(testcase): testcase.expect_commands(ExpectMasterShell(["command"]).workdir("/home")) yield runprocess.run_process(None, ["command"]) testcase.assert_all_commands_ran() result = self.run_test_method(method) self.assert_test_failure(result, "unexpected command run") def test_run_process_wrong_path(self): @defer.inlineCallbacks def method(testcase): testcase.expect_commands(ExpectMasterShell(["command", "arg"]).workdir("/home")) yield runprocess.run_process(None, ["command"], workdir="/path") testcase.assert_all_commands_ran() result = self.run_test_method(method) self.assert_test_failure(result, "unexpected command run") def test_run_process_not_current_path(self): @defer.inlineCallbacks def method(testcase): testcase.expect_commands(ExpectMasterShell(["command", "arg"])) yield runprocess.run_process(None, ["command"], workdir="/path") testcase.assert_all_commands_ran() result = self.run_test_method(method) self.assert_test_failure(result, "unexpected command run") def test_run_process_error_output(self): @defer.inlineCallbacks def method(testcase): testcase.expect_commands(ExpectMasterShell(["command"]).stderr(b"some test")) res = yield runprocess.run_process( None, ["command"], collect_stderr=False, stderr_is_error=True ) self.assertEqual(res, (-1, b'')) testcase.assert_all_commands_ran() result = self.run_test_method(method) self.assert_successful(result) def test_run_process_nonzero_exit(self): @defer.inlineCallbacks def method(testcase): testcase.expect_commands(ExpectMasterShell(["command"]).exit(1)) res = yield runprocess.run_process(None, ["command"]) self.assertEqual(res, (1, b'', b'')) testcase.assert_all_commands_ran() result = self.run_test_method(method) self.assert_successful(result) def test_run_process_environ_success(self): @defer.inlineCallbacks def method(testcase): testcase.expect_commands(ExpectMasterShell(["command"])) testcase.add_run_process_expect_env({'key': 'value'}) res = yield runprocess.run_process(None, ["command"], env={'key': 'value'}) self.assertEqual(res, (0, b'', b'')) testcase.assert_all_commands_ran() result = self.run_test_method(method) self.assert_successful(result) def test_run_process_environ_wrong_value(self): @defer.inlineCallbacks def method(testcase): testcase.expect_commands(ExpectMasterShell(["command"])) testcase.add_run_process_expect_env({'key': 'value'}) yield runprocess.run_process(None, ["command"], env={'key': 'wrongvalue'}) testcase.assert_all_commands_ran() result = self.run_test_method(method) self.assert_test_failure(result, "Expected environment to have key = 'value'") def test_run_process_environ_missing(self): @defer.inlineCallbacks def method(testcase): testcase.expect_commands(ExpectMasterShell(["command"])) testcase.add_run_process_expect_env({'key': 'value'}) d = runprocess.run_process(None, ["command"]) return d result = self.run_test_method(method) self.assert_test_failure(result, "Expected environment to have key = 'value'")
10,205
Python
.py
208
39.182692
92
0.651195
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,555
test_lineboundaries.py
buildbot_buildbot/master/buildbot/test/unit/util/test_lineboundaries.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.python import log from twisted.trial import unittest from buildbot.util import lineboundaries class TestLineBoundaryFinder(unittest.TestCase): def setUp(self): self.lbf = lineboundaries.LineBoundaryFinder() def test_already_terminated(self): res = self.lbf.append('abcd\ndefg\n') self.assertEqual(res, 'abcd\ndefg\n') res = self.lbf.append('xyz\n') self.assertEqual(res, 'xyz\n') res = self.lbf.flush() self.assertEqual(res, None) def test_partial_line(self): res = self.lbf.append('hello\nworld') self.assertEqual(res, 'hello\n') res = self.lbf.flush() self.assertEqual(res, 'world\n') def test_empty_appends(self): res = self.lbf.append('hello ') self.assertEqual(res, None) res = self.lbf.append('') self.assertEqual(res, None) res = self.lbf.append('world\n') self.assertEqual(res, 'hello world\n') res = self.lbf.append('') self.assertEqual(res, None) def test_embedded_newlines(self): res = self.lbf.append('hello, ') self.assertEqual(res, None) res = self.lbf.append('cruel\nworld') self.assertEqual(res, 'hello, cruel\n') res = self.lbf.flush() self.assertEqual(res, 'world\n') def test_windows_newlines_folded(self): r"Windows' \r\n is treated as and converted to a newline" res = self.lbf.append('hello, ') self.assertEqual(res, None) res = self.lbf.append('cruel\r\n\r\nworld') self.assertEqual(res, 'hello, cruel\n\n') res = self.lbf.flush() self.assertEqual(res, 'world\n') def test_bare_cr_folded(self): r"a bare \r is treated as and converted to a newline" self.lbf.append('1%\r5%\r15%\r100%\nfinished') res = self.lbf.flush() self.assertEqual(res, 'finished\n') def test_backspace_folded(self): r"a lot of \b is treated as and converted to a newline" self.lbf.append('1%\b\b5%\b\b15%\b\b\b100%\nfinished') res = self.lbf.flush() self.assertEqual(res, 'finished\n') def test_mixed_consecutive_newlines(self): r"mixing newline styles back-to-back doesn't collapse them" res = self.lbf.append('1\r\n\n\r') self.assertEqual(res, '1\n\n') res = self.lbf.append('2\n\r\n') self.assertEqual(res, '\n2\n\n') def test_split_newlines(self): r"multi-character newlines, split across chunks, are converted" input = 'a\nb\r\nc\rd\n\re' result = [] for splitpoint in range(1, len(input) - 1): a, b = input[:splitpoint], input[splitpoint:] result.append(self.lbf.append(a)) result.append(self.lbf.append(b)) result.append(self.lbf.flush()) result = [e for e in result if e is not None] res = ''.join(result) log.msg(f'feeding {a!r}, {b!r} gives {res!r}') self.assertEqual(res, 'a\nb\nc\nd\n\ne\n') result.clear() def test_split_terminal_control(self): """terminal control characters are converted""" res = self.lbf.append('1234\033[u4321') self.assertEqual(res, '1234\n') res = self.lbf.flush() self.assertEqual(res, '4321\n') res = self.lbf.append('1234\033[1;2H4321') self.assertEqual(res, '1234\n') res = self.lbf.flush() self.assertEqual(res, '4321\n') res = self.lbf.append('1234\033[1;2f4321') self.assertEqual(res, '1234\n') res = self.lbf.flush() self.assertEqual(res, '4321\n') def test_long_lines(self): """long lines are split""" res = [] for _ in range(4): res.append(self.lbf.append('12' * 1000)) res = [e for e in res if e is not None] res = ''.join(res) # a split at 4096 + the remaining chars self.assertEqual(res, '12' * 2048 + '\n' + '12' * 952 + '\n') def test_huge_lines(self): """huge lines are split""" res = [] res.append(self.lbf.append('12' * 32768)) res.append(self.lbf.flush()) res = [e for e in res if e is not None] self.assertEqual(res, [('12' * 2048 + '\n') * 16]) def test_empty_flush(self): res = self.lbf.flush() self.assertEqual(res, None)
5,119
Python
.py
119
35.084034
79
0.621703
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,556
test_lru.py
buildbot_buildbot/master/buildbot/test/unit/util/test_lru.py
# This file is part of Buildbot. Buildbot is free software: you can # redistribute it and/or modify it under the terms of the GNU General Public # License as published by the Free Software Foundation, version 2. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more # details. # # You should have received a copy of the GNU General Public License along with # this program; if not, write to the Free Software Foundation, Inc., 51 # Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # Copyright Buildbot Team Members import gc import platform import random import string from twisted.internet import defer from twisted.internet import reactor from twisted.python import failure from twisted.trial import unittest from buildbot.util import lru # construct weakref-able objects for particular keys def short(k): return set([k.upper() * 3]) def long(k): return set([k.upper() * 6]) class LRUCacheTest(unittest.TestCase): def setUp(self): lru.inv_failed = False self.lru = lru.LRUCache(short, 3) def tearDown(self): self.assertFalse(lru.inv_failed, "invariant failed; see logs") def check_result(self, r, exp, exp_hits=None, exp_misses=None, exp_refhits=None): self.assertEqual(r, exp) if exp_hits is not None: self.assertEqual(self.lru.hits, exp_hits) if exp_misses is not None: self.assertEqual(self.lru.misses, exp_misses) if exp_refhits is not None: self.assertEqual(self.lru.refhits, exp_refhits) def test_single_key(self): # just get an item val = self.lru.get('a') self.check_result(val, short('a'), 0, 1) # second time, it should be cached.. self.lru.miss_fn = long val = self.lru.get('a') self.check_result(val, short('a'), 1, 1) def test_simple_lru_expulsion(self): val = self.lru.get('a') self.check_result(val, short('a'), 0, 1) val = self.lru.get('b') self.check_result(val, short('b'), 0, 2) val = self.lru.get('c') self.check_result(val, short('c'), 0, 3) val = self.lru.get('d') self.check_result(val, short('d'), 0, 4) del val gc.collect() # now try 'a' again - it should be a miss self.lru.miss_fn = long val = self.lru.get('a') self.check_result(val, long('a'), 0, 5) # ..and that expelled B, but C is still in the cache val = self.lru.get('c') self.check_result(val, short('c'), 1, 5) @defer.inlineCallbacks def test_simple_lru_expulsion_maxsize_1(self): self.lru = lru.LRUCache(short, 1) val = yield self.lru.get('a') self.check_result(val, short('a'), 0, 1) val = yield self.lru.get('a') self.check_result(val, short('a'), 1, 1) val = yield self.lru.get('b') self.check_result(val, short('b'), 1, 2) del val gc.collect() # now try 'a' again - it should be a miss self.lru.miss_fn = long val = yield self.lru.get('a') self.check_result(val, long('a'), 1, 3) del val gc.collect() # ..and that expelled B val = yield self.lru.get('b') self.check_result(val, long('b'), 1, 4) def test_simple_lru_expulsion_maxsize_1_null_result(self): # a regression test for #2011 def miss_fn(k): if k == 'b': return None return short(k) self.lru = lru.LRUCache(miss_fn, 1) val = self.lru.get('a') self.check_result(val, short('a'), 0, 1) val = self.lru.get('b') self.check_result(val, None, 0, 2) del val # 'a' was not expelled since 'b' was None self.lru.miss_fn = long val = self.lru.get('a') self.check_result(val, short('a'), 1, 2) def test_queue_collapsing(self): # just to check that we're practicing with the right queue size (so # QUEUE_SIZE_FACTOR is 10) self.assertEqual(self.lru.max_queue, 30) for c in 'a' + 'x' * 27 + 'ab': res = self.lru.get(c) self.check_result(res, short('b'), 27, 3) # at this point, we should have 'x', 'a', and 'b' in the cache, and # 'axx..xxab' in the queue. self.assertEqual(len(self.lru.queue), 30) # This 'get' operation for an existing key should cause compaction res = self.lru.get('b') self.check_result(res, short('b'), 28, 3) self.assertEqual(len(self.lru.queue), 3) # expect a cached short('a') self.lru.miss_fn = long res = self.lru.get('a') self.check_result(res, short('a'), 29, 3) def test_all_misses(self): for i, c in enumerate(string.ascii_lowercase + string.ascii_uppercase): res = self.lru.get(c) self.check_result(res, short(c), 0, i + 1) def test_get_exception(self): def fail_miss_fn(k): raise RuntimeError("oh noes") self.lru.miss_fn = fail_miss_fn got_exc = False try: self.lru.get('abc') except RuntimeError: got_exc = True self.assertEqual(got_exc, True) def test_all_hits(self): res = self.lru.get('a') self.check_result(res, short('a'), 0, 1) self.lru.miss_fn = long for i in range(100): res = self.lru.get('a') self.check_result(res, short('a'), i + 1, 1) def test_weakrefs(self): if platform.python_implementation() == 'PyPy': raise unittest.SkipTest('PyPy has different behavior with regards to weakref dicts') res_a = self.lru.get('a') self.check_result(res_a, short('a')) # note that res_a keeps a reference to this value res_b = self.lru.get('b') self.check_result(res_b, short('b')) del res_b # discard reference to b # blow out the cache and the queue self.lru.miss_fn = long for c in string.ascii_lowercase[2:] * 5: self.lru.get(c) # and fetch a again, expecting the cached value res = self.lru.get('a') self.check_result(res, res_a, exp_refhits=1) # but 'b' should give us a new value res = self.lru.get('b') self.check_result(res, long('b'), exp_refhits=1) def test_fuzz(self): chars = list(string.ascii_lowercase * 40) random.shuffle(chars) for c in chars: res = self.lru.get(c) self.check_result(res, short(c)) def test_set_max_size(self): # load up the cache with three items for c in 'abc': res = self.lru.get(c) self.check_result(res, short(c)) del res # reset the size to 1 self.lru.set_max_size(1) gc.collect() # and then expect that 'b' is no longer in the cache self.lru.miss_fn = long res = self.lru.get('b') self.check_result(res, long('b')) def test_miss_fn_kwargs(self): def keep_kwargs_miss_fn(k, **kwargs): return set(kwargs.keys()) self.lru.miss_fn = keep_kwargs_miss_fn val = self.lru.get('a', a=1, b=2) self.check_result(val, set(['a', 'b']), 0, 1) def test_miss_fn_returns_none(self): calls = [] def none_miss_fn(k): calls.append(k) return None self.lru.miss_fn = none_miss_fn for _ in range(2): self.assertEqual(self.lru.get('a'), None) # check that the miss_fn was called twice self.assertEqual(calls, ['a', 'a']) def test_put(self): self.assertEqual(self.lru.get('p'), short('p')) self.lru.put('p', set(['P2P2'])) self.assertEqual(self.lru.get('p'), set(['P2P2'])) def test_put_nonexistent_key(self): self.assertEqual(self.lru.get('p'), short('p')) self.lru.put('q', set(['new-q'])) self.assertEqual(self.lru.get('p'), set(['PPP'])) self.assertEqual(self.lru.get('q'), set(['new-q'])) # updated class AsyncLRUCacheTest(unittest.TestCase): def setUp(self): lru.inv_failed = False self.lru = lru.AsyncLRUCache(self.short_miss_fn, 3) def tearDown(self): self.assertFalse(lru.inv_failed, "invariant failed; see logs") def short_miss_fn(self, key): return defer.succeed(short(key)) def long_miss_fn(self, key): return defer.succeed(long(key)) def failure_miss_fn(self, key): return defer.succeed(None) def check_result(self, r, exp, exp_hits=None, exp_misses=None, exp_refhits=None): self.assertEqual(r, exp) if exp_hits is not None: self.assertEqual(self.lru.hits, exp_hits) if exp_misses is not None: self.assertEqual(self.lru.misses, exp_misses) if exp_refhits is not None: self.assertEqual(self.lru.refhits, exp_refhits) # tests @defer.inlineCallbacks def test_single_key(self): # just get an item res = yield self.lru.get('a') self.check_result(res, short('a'), 0, 1) # second time, it should be cached.. self.lru.miss_fn = self.long_miss_fn res = yield self.lru.get('a') self.check_result(res, short('a'), 1, 1) @defer.inlineCallbacks def test_simple_lru_expulsion(self): res = yield self.lru.get('a') self.check_result(res, short('a'), 0, 1) res = yield self.lru.get('b') self.check_result(res, short('b'), 0, 2) res = yield self.lru.get('c') self.check_result(res, short('c'), 0, 3) res = yield self.lru.get('d') self.check_result(res, short('d'), 0, 4) gc.collect() # now try 'a' again - it should be a miss self.lru.miss_fn = self.long_miss_fn res = yield self.lru.get('a') self.check_result(res, long('a'), 0, 5) # ..and that expelled B, but C is still in the cache res = yield self.lru.get('c') self.check_result(res, short('c'), 1, 5) @defer.inlineCallbacks def test_simple_lru_expulsion_maxsize_1(self): self.lru = lru.AsyncLRUCache(self.short_miss_fn, 1) res = yield self.lru.get('a') self.check_result(res, short('a'), 0, 1) res = yield self.lru.get('a') self.check_result(res, short('a'), 1, 1) res = yield self.lru.get('b') self.check_result(res, short('b'), 1, 2) gc.collect() # now try 'a' again - it should be a miss self.lru.miss_fn = self.long_miss_fn res = yield self.lru.get('a') self.check_result(res, long('a'), 1, 3) gc.collect() # ..and that expelled B res = yield self.lru.get('b') self.check_result(res, long('b'), 1, 4) @defer.inlineCallbacks def test_simple_lru_expulsion_maxsize_1_null_result(self): # a regression test for #2011 def miss_fn(k): if k == 'b': return defer.succeed(None) return defer.succeed(short(k)) self.lru = lru.AsyncLRUCache(miss_fn, 1) res = yield self.lru.get('a') self.check_result(res, short('a'), 0, 1) res = yield self.lru.get('b') self.check_result(res, None, 0, 2) # 'a' was not expelled since 'b' was None self.lru.miss_fn = self.long_miss_fn res = yield self.lru.get('a') self.check_result(res, short('a'), 1, 2) @defer.inlineCallbacks def test_queue_collapsing(self): # just to check that we're practicing with the right queue size (so # QUEUE_SIZE_FACTOR is 10) self.assertEqual(self.lru.max_queue, 30) for c in 'a' + 'x' * 27 + 'ab': res = yield self.lru.get(c) self.check_result(res, short('b'), 27, 3) # at this point, we should have 'x', 'a', and 'b' in the cache, and # 'axx..xxab' in the queue. self.assertEqual(len(self.lru.queue), 30) # This 'get' operation for an existing key should cause compaction res = yield self.lru.get('b') self.check_result(res, short('b'), 28, 3) self.assertEqual(len(self.lru.queue), 3) # expect a cached short('a') self.lru.miss_fn = self.long_miss_fn res = yield self.lru.get('a') self.check_result(res, short('a'), 29, 3) @defer.inlineCallbacks def test_all_misses(self): for i, c in enumerate(string.ascii_lowercase + string.ascii_uppercase): res = yield self.lru.get(c) self.check_result(res, short(c), 0, i + 1) @defer.inlineCallbacks def test_get_exception(self): def fail_miss_fn(k): return defer.fail(RuntimeError("oh noes")) self.lru.miss_fn = fail_miss_fn got_exc = False try: yield self.lru.get('abc') except RuntimeError: got_exc = True self.assertEqual(got_exc, True) @defer.inlineCallbacks def test_all_hits(self): res = yield self.lru.get('a') self.check_result(res, short('a'), 0, 1) self.lru.miss_fn = self.long_miss_fn for i in range(100): res = yield self.lru.get('a') self.check_result(res, short('a'), i + 1, 1) @defer.inlineCallbacks def test_weakrefs(self): if platform.python_implementation() == 'PyPy': raise unittest.SkipTest('PyPy has different behavior with regards to weakref dicts') res_a = yield self.lru.get('a') self.check_result(res_a, short('a')) # note that res_a keeps a reference to this value res_b = yield self.lru.get('b') self.check_result(res_b, short('b')) del res_b # discard reference to b # blow out the cache and the queue self.lru.miss_fn = self.long_miss_fn for c in string.ascii_lowercase[2:] * 5: yield self.lru.get(c) # and fetch a again, expecting the cached value res = yield self.lru.get('a') self.check_result(res, res_a, exp_refhits=1) # but 'b' should give us a new value res = yield self.lru.get('b') self.check_result(res, long('b'), exp_refhits=1) @defer.inlineCallbacks def test_fuzz(self): chars = list(string.ascii_lowercase * 40) random.shuffle(chars) for c in chars: res = yield self.lru.get(c) self.check_result(res, short(c)) @defer.inlineCallbacks def test_massively_parallel(self): chars = list(string.ascii_lowercase * 5) misses = [0] def slow_short_miss_fn(key): d = defer.Deferred() misses[0] += 1 reactor.callLater(0, lambda: d.callback(short(key))) return d self.lru.miss_fn = slow_short_miss_fn def check(c, d): d.addCallback(self.check_result, short(c)) return d yield defer.gatherResults([check(c, self.lru.get(c)) for c in chars]) self.assertEqual(misses[0], 26) self.assertEqual(self.lru.misses, 26) self.assertEqual(self.lru.hits, 4 * 26) @defer.inlineCallbacks def test_slow_fetch(self): def slower_miss_fn(k): d = defer.Deferred() reactor.callLater(0.05, lambda: d.callback(short(k))) return d self.lru.miss_fn = slower_miss_fn def do_get(test_d, k): d = self.lru.get(k) d.addCallback(self.check_result, short(k)) d.addCallbacks(test_d.callback, test_d.errback) ds = [] for i in range(8): d = defer.Deferred() reactor.callLater(0.02 * i, do_get, d, 'x') ds.append(d) yield defer.gatherResults(ds) self.assertEqual((self.lru.hits, self.lru.misses), (7, 1)) def test_slow_failure(self): def slow_fail_miss_fn(k): d = defer.Deferred() reactor.callLater(0.05, lambda: d.errback(failure.Failure(RuntimeError("oh noes")))) return d self.lru.miss_fn = slow_fail_miss_fn @defer.inlineCallbacks def do_get(test_d, k): d = self.lru.get(k) yield self.assertFailure(d, RuntimeError) d.addCallbacks(test_d.callback, test_d.errback) ds = [] for i in range(8): d = defer.Deferred() reactor.callLater(0.02 * i, do_get, d, 'x') ds.append(d) d = defer.gatherResults(ds) return d @defer.inlineCallbacks def test_set_max_size(self): # load up the cache with three items for c in 'abc': res = yield self.lru.get(c) self.check_result(res, short(c)) # reset the size to 1 self.lru.set_max_size(1) gc.collect() # and then expect that 'b' is no longer in the cache self.lru.miss_fn = self.long_miss_fn res = yield self.lru.get('b') self.check_result(res, long('b')) @defer.inlineCallbacks def test_miss_fn_kwargs(self): def keep_kwargs_miss_fn(k, **kwargs): return defer.succeed(set(kwargs.keys())) self.lru.miss_fn = keep_kwargs_miss_fn res = yield self.lru.get('a', a=1, b=2) self.check_result(res, set(['a', 'b']), 0, 1) @defer.inlineCallbacks def test_miss_fn_returns_none(self): calls = [] def none_miss_fn(k): calls.append(k) return defer.succeed(None) self.lru.miss_fn = none_miss_fn for _ in range(2): self.assertEqual((yield self.lru.get('a')), None) # check that the miss_fn was called twice self.assertEqual(calls, ['a', 'a']) @defer.inlineCallbacks def test_put(self): self.assertEqual((yield self.lru.get('p')), short('p')) self.lru.put('p', set(['P2P2'])) self.assertEqual((yield self.lru.get('p')), set(['P2P2']))
18,210
Python
.py
447
31.829978
96
0.586944
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,557
test_path_expand_user.py
buildbot_buildbot/master/buildbot/test/unit/util/test_path_expand_user.py
# This file is part of Buildbot. Buildbot is free software: you can # redistribute it and/or modify it under the terms of the GNU General Public # License as published by the Free Software Foundation, version 2. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more # details. # # You should have received a copy of the GNU General Public License along with # this program; if not, write to the Free Software Foundation, Inc., 51 # Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # Copyright Buildbot Team Members import os from parameterized import parameterized from twisted.trial import unittest from buildbot.test.util.decorators import skipUnlessPlatformIs from buildbot.util import path_expand_user class TestExpanduser(unittest.TestCase): @parameterized.expand([ ('no_tilde', 'test_path', {}, 'test_path'), ('no_env_tilde', '~test_path', {}, '~test_path'), ( 'homedrive_tilde', '~test_path', {'HOMEDRIVE': 'C:\\', 'HOMEPATH': 'Users\\eric', 'USERNAME': 'eric'}, 'C:\\Users\\test_path', ), ( 'homedrive_tilde_only', '~', {'HOMEDRIVE': 'C:\\', 'HOMEPATH': 'Users\\eric', 'USERNAME': 'eric'}, 'C:\\Users\\eric', ), ( 'no_homedrive_tilde', '~test_path', {'HOMEPATH': 'Users\\eric', 'USERNAME': 'eric'}, 'Users\\test_path', ), ( 'no_homedrive_tilde_only', '~', {'HOMEPATH': 'Users\\eric', 'USERNAME': 'eric'}, 'Users\\eric', ), ( 'userprofile_tilde', '~test_path', {'USERPROFILE': 'C:\\Users\\eric', 'USERNAME': 'eric'}, 'C:\\Users\\test_path', ), ( 'userprofile_tilde_only', '~', {'USERPROFILE': 'C:\\Users\\eric', 'USERNAME': 'eric'}, 'C:\\Users\\eric', ), ( 'userprofile_backslash', '~test_path\\foo\\bar', {'USERPROFILE': 'C:\\Users\\eric', 'USERNAME': 'eric'}, 'C:\\Users\\test_path\\foo\\bar', ), ( 'userprofile_slash', '~test_path/foo/bar', {'USERPROFILE': 'C:\\Users\\eric', 'USERNAME': 'eric'}, 'C:\\Users\\test_path/foo/bar', ), ( 'userprofile_not_separate_tilde_backslash', '~\\foo\\bar', {'USERPROFILE': 'C:\\Users\\eric', 'USERNAME': 'eric'}, 'C:\\Users\\eric\\foo\\bar', ), ( 'userprofile_separate_tilde_slash', '~/foo/bar', {'USERPROFILE': 'C:\\Users\\eric', 'USERNAME': 'eric'}, 'C:\\Users\\eric/foo/bar', ), # bpo-36264: ignore `HOME` when set on windows ( 'ignore_home_on_windows', '~test_path', {'HOME': 'F:\\', 'USERPROFILE': 'C:\\Users\\eric', 'USERNAME': 'eric'}, 'C:\\Users\\test_path', ), ( 'ignore_home_on_windows_tilde_only', '~', {'HOME': 'F:\\', 'USERPROFILE': 'C:\\Users\\eric', 'USERNAME': 'eric'}, 'C:\\Users\\eric', ), # bpo-39899: don't guess another user's home directory if # `%USERNAME% != basename(%USERPROFILE%)` ( 'dont_guess_home_dir', '~test_path', {'USERPROFILE': 'C:\\Users\\eric', 'USERNAME': 'idle'}, '~test_path', ), ( 'dont_guess_home_dir_tilde_only', '~', {'USERPROFILE': 'C:\\Users\\eric', 'USERNAME': 'idle'}, 'C:\\Users\\eric', ), ]) def test_nt(self, name, path, env, result): self.assertEqual(path_expand_user.nt_expanduser(path, env), result) @parameterized.expand([ ('no_home', 'test_path', {}, 'test_path'), ('home_tilde_only', '~', {'HOME': '/home/victor'}, '/home/victor'), ('home_tilde_only_trailing_slash', '~', {'HOME': '/home/victor/'}, '/home/victor'), ('home_slash_tilde_only', '~', {'HOME': '/'}, '/'), ('home_slash_tilde_slash', '~/', {'HOME': '/'}, '/'), ('home_slash_tilde_slash_name', '~/test_path', {'HOME': '/'}, '/test_path'), ('home_empty_tilde_only', '~', {'HOME': ''}, '/'), ('home_empty_tilde_slash', '~/', {'HOME': ''}, '/'), ('home_empty_tilde_slash_name', '~/test_path', {'HOME': ''}, '/test_path'), ('home_double_slash_tilde_only', '~', {'HOME': '//'}, '/'), ('home_double_slash_tilde_slash', '~/', {'HOME': '//'}, '/'), ('home_double_slash_tilde_slash_name', '~/test_path', {'HOME': '//'}, '/test_path'), ('home_triple_slash_tilde_only', '~', {'HOME': '///'}, '/'), ('home_triple_slash_tilde_slash', '~/', {'HOME': '///'}, '/'), ('home_triple_slash_tilde_slash_name', '~/test_path', {'HOME': '///'}, '/test_path'), ]) def test_posix(self, name, path, env, result): self.assertEqual(path_expand_user.posix_expanduser(path, env), result) @skipUnlessPlatformIs('posix') def test_posix_no_home(self): import pwd home = pwd.getpwuid(os.getuid()).pw_dir # $HOME can end with a trailing /, so strip it (see cpython #17809) home = home.rstrip("/") or '/' self.assertEqual(path_expand_user.posix_expanduser("~", {}), home)
5,640
Python
.py
139
31.28777
93
0.516476
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,558
test_render_description.py
buildbot_buildbot/master/buildbot/test/unit/util/test_render_description.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.util.render_description import render_description class TestRaml(unittest.TestCase): def test_plain(self): self.assertIsNone(render_description("description", None)) def test_unknown(self): with self.assertRaises(RuntimeError): render_description("description", "unknown") def test_markdown(self): self.assertEqual( render_description("# description\ntext", "markdown"), "<h1>description</h1>\n<p>text</p>", )
1,250
Python
.py
27
42.111111
79
0.744454
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,559
test_poll.py
buildbot_buildbot/master/buildbot/test/unit/util/test_poll.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.test.reactor import TestReactorMixin from buildbot.util import poll class TestPollerSync(TestReactorMixin, unittest.TestCase): @poll.method def poll(self): self.calls += 1 if self.fail_after_running: raise RuntimeError('oh noes') def setUp(self): self.setup_test_reactor(auto_tear_down=False) self.master = mock.Mock() self.master.reactor = self.reactor poll.track_poll_methods() self.calls = 0 self.fail_after_running = False @defer.inlineCallbacks def tearDown(self): poll.reset_poll_methods() self.assertEqual(self.reactor.getDelayedCalls(), []) yield self.tear_down_test_reactor() def test_call_not_started_does_nothing(self): self.reactor.advance(100) self.assertEqual(self.calls, 0) def test_call_when_stopped_does_nothing(self): self.poll() self.assertEqual(self.calls, 0) @defer.inlineCallbacks def test_call_when_started_forces_run(self): self.poll.start(interval=100, now=False) self.poll() self.reactor.advance(0) self.assertEqual(self.calls, 1) yield self.poll.stop() @defer.inlineCallbacks def test_start_with_now_forces_run_immediately(self): self.poll.start(interval=10, now=True) self.reactor.advance(0) self.assertEqual(self.calls, 1) yield self.poll.stop() @defer.inlineCallbacks def test_start_with_now_false_does_not_run(self): self.poll.start(interval=10, now=False) self.assertEqual(self.calls, 0) yield self.poll.stop() def test_stop_on_stopped_does_nothing(self): self.poll.start(interval=1) d = self.poll.stop() self.assertTrue(d.called) d = self.poll.stop() self.assertTrue(d.called) @defer.inlineCallbacks def test_start_twice_error(self): self.poll.start(interval=1) with self.assertRaises(AssertionError): self.poll.start(interval=2) yield self.poll.stop() def test_repeats_and_stops(self): """Polling repeats until stopped, and stop returns a Deferred""" self.poll.start(interval=10, now=True) self.reactor.advance(0) while self.reactor.seconds() <= 200: self.assertEqual(self.calls, (self.reactor.seconds() // 10) + 1) self.reactor.advance(1) d = self.poll.stop() self.assertTrue(d.called) self.assertEqual(self.calls, 21) self.reactor.advance(10) self.assertEqual(self.calls, 21) @defer.inlineCallbacks def test_fail_reschedules_and_logs_exceptions(self): self.fail_after_running = True self.poll.start(interval=1, now=True) self.reactor.advance(0) self.assertEqual(self.calls, 1) self.reactor.advance(1) self.assertEqual(self.calls, 2) self.assertEqual(len(self.flushLoggedErrors(RuntimeError)), 2) yield self.poll.stop() @parameterized.expand([ ('shorter_than_interval_now_True', 5, True), ('longer_than_interval_now_True', 15, True), ('shorter_than_interval_now_False', 5, False), ('longer_than_interval_now_False', 15, False), ]) @defer.inlineCallbacks def test_run_with_random_delay(self, name, random_delay_max, now): interval = 10 with mock.patch("buildbot.util.poll.randint", return_value=random_delay_max): self.poll.start(interval=interval, now=now, random_delay_max=random_delay_max) self.reactor.advance(0) if not now: i = 0 while i < interval: self.assertEqual(self.calls, 0) self.reactor.advance(1) i += 1 i = 0 while i < random_delay_max: self.assertEqual(self.calls, 0) self.reactor.advance(1) i += 1 self.assertEqual(self.calls, 1) yield self.poll.stop() @parameterized.expand([ ('now_True', True), ('now_False', False), ]) @defer.inlineCallbacks def test_run_with_random_delay_zero_interval_still_delays(self, name, now): random_delay_max = 5 with mock.patch("buildbot.util.poll.randint", return_value=random_delay_max): self.poll.start(interval=0, now=now, random_delay_max=random_delay_max) self.reactor.advance(0) self.assertEqual(self.calls, 0) i = 0 while i < random_delay_max: self.assertEqual(self.calls, 0) self.reactor.advance(1) i += 1 self.assertEqual(self.calls, 1) yield self.poll.stop() @defer.inlineCallbacks def test_run_with_random_delay_stops_immediately_during_delay_phase(self): random_delay_max = 5 with mock.patch("buildbot.util.poll.randint", return_value=random_delay_max): self.poll.start(interval=10, now=True, random_delay_max=random_delay_max) self.reactor.advance(1) self.assertEqual(self.calls, 0) yield self.poll.stop() class TestPollerAsync(TestReactorMixin, unittest.TestCase): @poll.method @defer.inlineCallbacks def poll(self): assert not self.running, "overlapping call" self.running = True d = defer.Deferred() self.reactor.callLater(self.duration, d.callback, None) yield d self.calls += 1 self.running = False if self.fail_after_running: raise RuntimeError('oh noes') def setUp(self): self.setup_test_reactor(auto_tear_down=False) self.master = mock.Mock() self.master.reactor = self.reactor poll.track_poll_methods() self.calls = 0 self.running = False self.duration = 1 self.fail_after_running = False @defer.inlineCallbacks def tearDown(self): poll.reset_poll_methods() yield self.tear_down_test_reactor() @defer.inlineCallbacks def test_call_when_started_forces_run(self): self.poll.start(interval=10, now=True) self.reactor.advance(0) self.assertEqual(self.calls, 0) self.assertTrue(self.running) self.reactor.advance(self.duration) self.assertEqual(self.calls, 1) self.assertFalse(self.running) yield self.poll.stop() def test_repeats_and_stops(self): """Polling repeats until stopped, and stop returns a Deferred. The duration of the function's execution does not affect the execution interval: executions occur every 10 seconds.""" self.poll.start(interval=10, now=True) self.reactor.advance(0) while self.reactor.seconds() <= 200: self.assertEqual(self.calls, (self.reactor.seconds() + 9) // 10) self.assertEqual(self.running, self.reactor.seconds() % 10 == 0) self.reactor.advance(1) d = self.poll.stop() self.assertTrue(d.called) self.assertEqual(self.calls, 21) self.reactor.advance(10) self.assertEqual(self.calls, 21) @parameterized.expand([ ('now_True', True), ('now_False', False), ]) @defer.inlineCallbacks def test_zero_interval_starts_immediately(self, name, now): self.poll.start(interval=0, now=now) self.reactor.advance(0) self.assertEqual(self.calls, 0) self.assertTrue(self.running) self.reactor.advance(1) self.assertEqual(self.calls, 1) self.assertTrue(self.running) self.reactor.pump([1] * 10) self.assertEqual(self.calls, 11) self.assertTrue(self.running) d = self.poll.stop() self.assertTrue(self.running) self.reactor.advance(1) self.assertFalse(self.running) yield d @defer.inlineCallbacks def test_fail_reschedules_and_logs_exceptions(self): self.fail_after_running = True self.poll.start(interval=10, now=True) self.reactor.advance(0) self.assertTrue(self.running) self.reactor.advance(1) self.assertEqual(self.calls, 1) self.reactor.advance(10) self.assertTrue(self.running) self.reactor.advance(1) self.assertEqual(self.calls, 2) self.assertEqual(len(self.flushLoggedErrors(RuntimeError)), 2) yield self.poll.stop() def test_stop_while_running_waits_for_completion(self): self.duration = 2 self.poll.start(interval=10) self.reactor.advance(0) self.assertFalse(self.running) self.reactor.advance(10) self.assertTrue(self.running) d = self.poll.stop() self.assertFalse(d.called) # not stopped yet self.reactor.advance(1) self.assertFalse(d.called) self.reactor.advance(1) self.assertTrue(d.called) def test_call_while_waiting_schedules_immediately(self): self.poll.start(interval=10) self.reactor.advance(0) self.reactor.advance(5) self.poll() self.reactor.advance(0) self.assertTrue(self.running) self.reactor.advance(1) self.assertEqual(self.calls, 1) self.assertFalse(self.running) self.reactor.advance(4) self.assertTrue(self.running) self.reactor.advance(1) self.assertEqual(self.calls, 2) def test_call_while_running_reschedules_immediately_after(self): self.duration = 5 self.poll.start(interval=10, now=True) self.reactor.advance(0) self.assertTrue(self.running) self.reactor.advance(3) self.poll() self.reactor.advance(2) self.assertEqual(self.calls, 1) self.reactor.advance(5) self.assertEqual(self.calls, 2) def test_call_while_running_then_stop(self): """Calling the poll method while the decorated method is running, then calling stop will not wait for both invocations to complete.""" self.duration = 5 self.poll.start(interval=10, now=True) self.reactor.advance(0) self.assertTrue(self.running) self.reactor.advance(3) self.assertTrue(self.running) self.poll() d = self.poll.stop() self.reactor.advance(2) self.assertEqual(self.calls, 1) self.assertTrue(d.called) self.reactor.advance(5) self.assertEqual(self.calls, 1) def test_stop_twice_while_running(self): """If stop is called *twice* while the poll function is running, then neither Deferred fires until the run is complete.""" self.duration = 2 self.poll.start(interval=10) self.reactor.advance(0) self.assertFalse(self.running) self.reactor.advance(10) self.assertTrue(self.running) d1 = self.poll.stop() self.assertFalse(d1.called) # not stopped yet self.reactor.advance(1) d2 = self.poll.stop() self.assertFalse(d2.called) self.reactor.advance(1) self.assertTrue(d1.called) self.assertTrue(d2.called) @defer.inlineCallbacks def test_stop_and_restart(self): """If the method is immediately restarted from a callback on a stop Deferred, the polling continues with the new start time.""" self.duration = 6 self.poll.start(interval=10) self.reactor.advance(0) self.assertFalse(self.running) self.reactor.advance(10) self.assertTrue(self.running) d = self.poll.stop() self.assertFalse(d.called) # not stopped yet self.reactor.advance(6) self.assertFalse(self.running) self.assertTrue(d.called) yield d self.poll.start(interval=10) self.reactor.advance(10) self.assertEqual(self.reactor.seconds(), 26) self.assertTrue(self.running) self.reactor.advance(6) yield self.poll.stop() def test_method_longer_than_interval_invoked_at_interval_multiples(self): self.duration = 4 self.poll.start(interval=3, now=True) self.reactor.advance(0) exp = [ (0, True, 0), (1, True, 0), (2, True, 0), (3, True, 0), (4, False, 1), (5, False, 1), (6, True, 1), # next multiple of 3 (10, False, 2), (12, True, 2), (16, False, 3), ] for secs, running, calls in exp: while self.reactor.seconds() < secs: self.reactor.advance(1) self.assertEqual(self.running, running) self.assertEqual(self.calls, calls) @parameterized.expand([ ('shorter_than_interval_now_True', 5, True), ('longer_than_interval_now_True', 15, True), ('shorter_than_interval_now_False', 5, False), ('longer_than_interval_now_False', 15, False), ]) @defer.inlineCallbacks def test_run_with_random_delay(self, name, random_delay_max, now): interval = 10 with mock.patch("buildbot.util.poll.randint", return_value=random_delay_max): self.poll.start(interval=interval, now=now, random_delay_max=random_delay_max) self.reactor.advance(0) if not now: i = 0 while i < interval: self.assertFalse(self.running) self.assertEqual(self.calls, 0) self.reactor.advance(1) i += 1 i = 0 while i < random_delay_max: self.assertFalse(self.running) self.assertEqual(self.calls, 0) self.reactor.advance(1) i += 1 self.assertEqual(self.calls, 0) self.assertTrue(self.running) self.reactor.advance(self.duration) self.assertEqual(self.calls, 1) self.assertFalse(self.running) yield self.poll.stop() @parameterized.expand([ ('now_True', True), ('now_False', False), ]) @defer.inlineCallbacks def test_run_with_random_delay_zero_interval_still_delays(self, name, now): random_delay_max = 5 with mock.patch("buildbot.util.poll.randint", return_value=random_delay_max): self.poll.start(interval=0, now=now, random_delay_max=random_delay_max) self.reactor.advance(0) self.assertFalse(self.running) self.assertEqual(self.calls, 0) i = 0 while i < random_delay_max: self.assertFalse(self.running) self.assertEqual(self.calls, 0) self.reactor.advance(1) i += 1 self.assertTrue(self.running) self.reactor.advance(1) self.assertEqual(self.calls, 1) self.assertFalse(self.running) yield self.poll.stop() @defer.inlineCallbacks def test_run_with_random_delay_stops_immediately_during_delay_phase(self): random_delay_max = 5 with mock.patch("buildbot.util.poll.randint", return_value=random_delay_max): self.poll.start(interval=10, now=True, random_delay_max=random_delay_max) self.reactor.advance(1) self.assertFalse(self.running) self.assertEqual(self.calls, 0) yield self.poll.stop()
16,342
Python
.py
410
30.578049
90
0.628773
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,560
test_state.py
buildbot_buildbot/master/buildbot/test/unit/util/test_state.py
# This file is part of Buildbot. Buildbot is free software: you can # redistribute it and/or modify it under the terms of the GNU General Public # License as published by the Free Software Foundation, version 2. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more # details. # # You should have received a copy of the GNU General Public License along with # this program; if not, write to the Free Software Foundation, Inc., 51 # Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # Copyright Buildbot Team Members from twisted.internet import defer from twisted.trial import unittest from buildbot.test.fake import fakemaster from buildbot.test.reactor import TestReactorMixin from buildbot.test.util.state import StateTestMixin from buildbot.util import state class FakeObject(state.StateMixin): name = "fake-name" def __init__(self, master): self.master = master class TestStateMixin(TestReactorMixin, StateTestMixin, unittest.TestCase): OBJECTID = 19 @defer.inlineCallbacks def setUp(self): self.setup_test_reactor(auto_tear_down=False) self.master = yield fakemaster.make_master(self, wantDb=True) self.object = FakeObject(self.master) @defer.inlineCallbacks def tearDown(self): yield self.tear_down_test_reactor() @defer.inlineCallbacks def test_getState(self): yield self.set_fake_state(self.object, 'fav_color', ['red', 'purple']) res = yield self.object.getState('fav_color') self.assertEqual(res, ['red', 'purple']) @defer.inlineCallbacks def test_getState_default(self): res = yield self.object.getState('fav_color', 'black') self.assertEqual(res, 'black') @defer.inlineCallbacks def test_getState_KeyError(self): yield self.set_fake_state(self.object, 'fav_color', ['red', 'purple']) with self.assertRaises(KeyError): yield self.object.getState('fav_book') self.flushLoggedErrors(KeyError) @defer.inlineCallbacks def test_setState(self): yield self.object.setState('y', 14) yield self.assert_state_by_class('fake-name', 'FakeObject', y=14) @defer.inlineCallbacks def test_setState_existing(self): yield self.set_fake_state(self.object, 'x', 13) yield self.object.setState('x', 14) yield self.assert_state_by_class('fake-name', 'FakeObject', x=14)
2,591
Python
.py
58
39.5
79
0.725646
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,561
test_service.py
buildbot_buildbot/master/buildbot/test/unit/util/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 from unittest import mock from twisted.internet import defer from twisted.trial import unittest from buildbot import config from buildbot.process.properties import Interpolate from buildbot.test.fake import fakemaster from buildbot.test.reactor import TestReactorMixin from buildbot.util import service from buildbot.util.twisted import async_to_deferred class DeferredStartStop(service.AsyncService): def startService(self): self.d = defer.Deferred() return self.d def stopService(self): self.d = defer.Deferred() return self.d class AsyncMultiService(unittest.TestCase): def setUp(self): self.svc = service.AsyncMultiService() @defer.inlineCallbacks def test_empty(self): yield self.svc.startService() yield self.svc.stopService() @defer.inlineCallbacks def test_waits_for_child_services(self): child = DeferredStartStop() yield child.setServiceParent(self.svc) d = self.svc.startService() self.assertFalse(d.called) child.d.callback(None) self.assertTrue(d.called) d = self.svc.stopService() self.assertFalse(d.called) child.d.callback(None) self.assertTrue(d.called) @defer.inlineCallbacks def test_child_fails(self): child = DeferredStartStop() yield child.setServiceParent(self.svc) d = self.svc.startService() self.assertFalse(d.called) child.d.errback(RuntimeError('oh noes')) self.assertTrue(d.called) @d.addErrback def check(f): f.check(RuntimeError) d = self.svc.stopService() self.assertFalse(d.called) child.d.errback(RuntimeError('oh noes')) self.assertTrue(d.called) @d.addErrback def check_again(f): f.check(RuntimeError) def test_child_starts_on_sSP(self): d = self.svc.startService() self.assertTrue(d.called) child = DeferredStartStop() d = child.setServiceParent(self.svc) self.assertFalse(d.called) child.d.callback(None) self.assertTrue(d.called) class ClusteredBuildbotService(unittest.TestCase, TestReactorMixin): SVC_NAME = 'myName' SVC_ID = 20 class DummyService(service.ClusteredBuildbotService): pass @defer.inlineCallbacks def setUp(self): self.setup_test_reactor(auto_tear_down=False) self.master = yield fakemaster.make_master(self, wantDb=True, wantData=True) self.svc = self.makeService() @defer.inlineCallbacks def tearDown(self): yield self.tear_down_test_reactor() def makeService(self, attach_to_master=True, name=SVC_NAME, serviceid=SVC_ID): svc = self.DummyService(name=name) if attach_to_master: svc.setServiceParent(self.master) self.setServiceClaimable(svc, defer.succeed(False)) self.setActivateToReturn(svc, defer.succeed(None)) self.setDeactivateToReturn(svc, defer.succeed(None)) self.setGetServiceIdToReturn(svc, defer.succeed(serviceid)) self.setUnclaimToReturn(svc, defer.succeed(None)) return svc def makeMock(self, value): mockObj = mock.Mock() if isinstance(value, Exception): mockObj.side_effect = value else: mockObj.return_value = value return mockObj def setServiceClaimable(self, svc, claimable): svc._claimService = self.makeMock(claimable) def setGetServiceIdToReturn(self, svc, serviceid): svc._getServiceId = self.makeMock(serviceid) def setUnclaimToReturn(self, svc, unclaim): svc._unclaimService = self.makeMock(unclaim) def setActivateToReturn(self, svc, activate): svc.activate = self.makeMock(activate) def setDeactivateToReturn(self, svc, deactivate): svc.deactivate = self.makeMock(deactivate) def test_name_PreservesUnicodePromotion(self): svc = self.makeService(name='n') self.assertIsInstance(svc.name, str) self.assertEqual(svc.name, 'n') def test_name_GetsUnicodePromotion(self): svc = self.makeService(name='n') self.assertIsInstance(svc.name, str) self.assertEqual(svc.name, 'n') def test_compare(self): a = self.makeService(attach_to_master=False, name='a', serviceid=20) b1 = self.makeService(attach_to_master=False, name='b', serviceid=21) b2 = self.makeService(attach_to_master=False, name='b', serviceid=21) # same args as 'b1' b3 = self.makeService(attach_to_master=False, name='b', serviceid=20) # same id as 'a' self.assertTrue(a == a) # noqa: PLR0124 self.assertTrue(a != b1) self.assertTrue(a != b2) self.assertTrue(a != b3) self.assertTrue(b1 != a) self.assertTrue(b1 == b1) # noqa: PLR0124 self.assertTrue(b1 == b2) self.assertTrue(b1 == b3) def test_create_NothingCalled(self): # None of the member functions get called until startService happens self.assertFalse(self.svc.activate.called) self.assertFalse(self.svc.deactivate.called) self.assertFalse(self.svc._getServiceId.called) self.assertFalse(self.svc._claimService.called) self.assertFalse(self.svc._unclaimService.called) def test_create_IsInactive(self): # starts in inactive state self.assertFalse(self.svc.isActive()) def test_create_HasNoServiceIdYet(self): # has no service id at first self.assertIdentical(self.svc.serviceid, None) def test_start_UnclaimableSoNotActiveYet(self): self.svc.startService() self.assertFalse(self.svc.isActive()) def test_start_GetsServiceIdAssigned(self): self.svc.startService() self.assertEqual(1, self.svc._getServiceId.call_count) self.assertEqual(1, self.svc._claimService.call_count) self.assertEqual(self.SVC_ID, self.svc.serviceid) def test_start_WontPollYet(self): self.svc.startService() # right before the poll interval, nothing has tried again yet self.reactor.advance(self.svc.POLL_INTERVAL_SEC * 0.95) self.assertEqual(0, self.svc.activate.call_count) self.assertEqual(1, self.svc._getServiceId.call_count) self.assertEqual(1, self.svc._claimService.call_count) self.assertEqual(0, self.svc.deactivate.call_count) self.assertEqual(0, self.svc._unclaimService.call_count) self.assertFalse(self.svc.isActive()) @defer.inlineCallbacks def test_start_PollButClaimFails(self): yield self.svc.startService() # at the POLL time, it gets called again, but we're still inactive... self.reactor.advance(self.svc.POLL_INTERVAL_SEC * 1.05) self.assertEqual(0, self.svc.activate.call_count) self.assertEqual(1, self.svc._getServiceId.call_count) self.assertEqual(2, self.svc._claimService.call_count) self.assertEqual(0, self.svc.deactivate.call_count) self.assertEqual(0, self.svc._unclaimService.call_count) self.assertEqual(False, self.svc.isActive()) def test_start_PollsPeriodically(self): NUMBER_OF_POLLS = 15 self.svc.startService() for _ in range(NUMBER_OF_POLLS): self.reactor.advance(self.svc.POLL_INTERVAL_SEC) self.assertEqual(1, self.svc._getServiceId.call_count) self.assertEqual(1 + NUMBER_OF_POLLS, self.svc._claimService.call_count) def test_start_ClaimSucceeds(self): self.setServiceClaimable(self.svc, defer.succeed(True)) self.svc.startService() self.assertEqual(1, self.svc.activate.call_count) self.assertEqual(1, self.svc._getServiceId.call_count) self.assertEqual(1, self.svc._claimService.call_count) self.assertEqual(0, self.svc.deactivate.call_count) self.assertEqual(0, self.svc._unclaimService.call_count) self.assertEqual(True, self.svc.isActive()) def test_start_PollingAfterClaimSucceedsDoesNothing(self): self.setServiceClaimable(self.svc, defer.succeed(True)) self.svc.startService() # another epoch shouldn't do anything further... self.reactor.advance(self.svc.POLL_INTERVAL_SEC * 2) self.assertEqual(1, self.svc.activate.call_count) self.assertEqual(1, self.svc._getServiceId.call_count) self.assertEqual(1, self.svc._claimService.call_count) self.assertEqual(0, self.svc.deactivate.call_count) self.assertEqual(0, self.svc._unclaimService.call_count) self.assertEqual(True, self.svc.isActive()) def test_stopWhileStarting_NeverActive(self): self.svc.startService() # .. claim fails stopDeferred = self.svc.stopService() # a stop at this point unwinds things immediately self.successResultOf(stopDeferred) # advance the clock, and nothing should happen self.reactor.advance(self.svc.POLL_INTERVAL_SEC * 2) self.assertEqual(1, self.svc._claimService.call_count) self.assertEqual(0, self.svc._unclaimService.call_count) self.assertEqual(0, self.svc.deactivate.call_count) self.assertFalse(self.svc.isActive()) def test_stop_AfterActivated(self): self.setServiceClaimable(self.svc, defer.succeed(True)) self.svc.startService() # now deactivate: stopDeferred = self.svc.stopService() # immediately stops self.successResultOf(stopDeferred) self.assertEqual(1, self.svc.activate.call_count) self.assertEqual(1, self.svc._getServiceId.call_count) self.assertEqual(1, self.svc._claimService.call_count) self.assertEqual(1, self.svc._unclaimService.call_count) self.assertEqual(1, self.svc.deactivate.call_count) self.assertEqual(False, self.svc.isActive()) def test_stop_AfterActivated_NoDeferred(self): # set all the child-class functions to return non-deferreds, # just to check we can handle both: self.setServiceClaimable(self.svc, True) self.setActivateToReturn(self.svc, None) self.setDeactivateToReturn(self.svc, None) self.setGetServiceIdToReturn(self.svc, self.SVC_ID) self.setUnclaimToReturn(self.svc, None) self.svc.startService() # now deactivate: stopDeferred = self.svc.stopService() # immediately stops self.successResultOf(stopDeferred) self.assertEqual(1, self.svc.activate.call_count) self.assertEqual(1, self.svc._getServiceId.call_count) self.assertEqual(1, self.svc._claimService.call_count) self.assertEqual(1, self.svc._unclaimService.call_count) self.assertEqual(1, self.svc.deactivate.call_count) self.assertEqual(False, self.svc.isActive()) def test_stopWhileStarting_getServiceIdTakesForever(self): # create a deferred that will take a while... svcIdDeferred = defer.Deferred() self.setGetServiceIdToReturn(self.svc, svcIdDeferred) self.setServiceClaimable(self.svc, defer.succeed(True)) self.svc.startService() # stop before it has the service id (the svcIdDeferred is stuck) stopDeferred = self.svc.stopService() self.assertNoResult(stopDeferred) # .. no deactivates yet.... self.assertEqual(0, self.svc.deactivate.call_count) self.assertEqual(0, self.svc.activate.call_count) self.assertEqual(0, self.svc._claimService.call_count) self.assertEqual(False, self.svc.isActive()) # then let service id part finish svcIdDeferred.callback(None) # ... which will cause the stop to also finish self.successResultOf(stopDeferred) # and everything else should unwind too: self.assertEqual(1, self.svc.activate.call_count) self.assertEqual(1, self.svc._getServiceId.call_count) self.assertEqual(1, self.svc._claimService.call_count) self.assertEqual(1, self.svc.deactivate.call_count) self.assertEqual(1, self.svc._unclaimService.call_count) self.assertEqual(False, self.svc.isActive()) def test_stopWhileStarting_claimServiceTakesForever(self): # create a deferred that will take a while... claimDeferred = defer.Deferred() self.setServiceClaimable(self.svc, claimDeferred) self.svc.startService() # .. claim is still pending here # stop before it's done activating stopDeferred = self.svc.stopService() self.assertNoResult(stopDeferred) # .. no deactivates yet.... self.assertEqual(0, self.svc.activate.call_count) self.assertEqual(1, self.svc._getServiceId.call_count) self.assertEqual(1, self.svc._claimService.call_count) self.assertEqual(0, self.svc.deactivate.call_count) self.assertEqual(0, self.svc._unclaimService.call_count) self.assertEqual(False, self.svc.isActive()) # then let claim succeed, but we should see things unwind claimDeferred.callback(True) # ... which will cause the stop to also finish self.successResultOf(stopDeferred) # and everything else should unwind too: self.assertEqual(1, self.svc.activate.call_count) self.assertEqual(1, self.svc._getServiceId.call_count) self.assertEqual(1, self.svc._claimService.call_count) self.assertEqual(1, self.svc.deactivate.call_count) self.assertEqual(1, self.svc._unclaimService.call_count) self.assertEqual(False, self.svc.isActive()) def test_stopWhileStarting_activateTakesForever(self): """If activate takes forever, things acquiesce nicely""" # create a deferreds that will take a while... activateDeferred = defer.Deferred() self.setActivateToReturn(self.svc, activateDeferred) self.setServiceClaimable(self.svc, defer.succeed(True)) self.svc.startService() # stop before it's done activating stopDeferred = self.svc.stopService() self.assertNoResult(stopDeferred) # .. no deactivates yet.... self.assertEqual(1, self.svc.activate.call_count) self.assertEqual(1, self.svc._getServiceId.call_count) self.assertEqual(1, self.svc._claimService.call_count) self.assertEqual(0, self.svc.deactivate.call_count) self.assertEqual(0, self.svc._unclaimService.call_count) self.assertEqual(True, self.svc.isActive()) # then let activate finish activateDeferred.callback(None) # ... which will cause the stop to also finish self.successResultOf(stopDeferred) # and everything else should unwind too: self.assertEqual(1, self.svc.activate.call_count) self.assertEqual(1, self.svc._getServiceId.call_count) self.assertEqual(1, self.svc._claimService.call_count) self.assertEqual(1, self.svc.deactivate.call_count) self.assertEqual(1, self.svc._unclaimService.call_count) self.assertEqual(False, self.svc.isActive()) def test_stop_unclaimTakesForever(self): # create a deferred that will take a while... unclaimDeferred = defer.Deferred() self.setUnclaimToReturn(self.svc, unclaimDeferred) self.setServiceClaimable(self.svc, defer.succeed(True)) self.svc.startService() # stop before it's done activating stopDeferred = self.svc.stopService() self.assertNoResult(stopDeferred) # .. no deactivates yet.... self.assertEqual(1, self.svc.deactivate.call_count) self.assertEqual(1, self.svc._unclaimService.call_count) self.assertEqual(False, self.svc.isActive()) # then let unclaim part finish unclaimDeferred.callback(None) # ... which will cause the stop to finish self.successResultOf(stopDeferred) # and everything should unwind: self.assertEqual(1, self.svc.deactivate.call_count) self.assertEqual(1, self.svc._unclaimService.call_count) self.assertEqual(False, self.svc.isActive()) def test_stop_deactivateTakesForever(self): # create a deferred that will take a while... deactivateDeferred = defer.Deferred() self.setDeactivateToReturn(self.svc, deactivateDeferred) self.setServiceClaimable(self.svc, defer.succeed(True)) self.svc.startService() # stop before it's done activating stopDeferred = self.svc.stopService() self.assertNoResult(stopDeferred) self.assertEqual(1, self.svc.deactivate.call_count) self.assertEqual(0, self.svc._unclaimService.call_count) self.assertEqual(False, self.svc.isActive()) # then let deactivate finish deactivateDeferred.callback(None) # ... which will cause the stop to finish self.successResultOf(stopDeferred) # and everything else should unwind too: self.assertEqual(1, self.svc.deactivate.call_count) self.assertEqual(1, self.svc._unclaimService.call_count) self.assertEqual(False, self.svc.isActive()) def test_claim_raises(self): self.setServiceClaimable(self.svc, RuntimeError()) self.svc.startService() self.assertEqual(1, len(self.flushLoggedErrors(RuntimeError))) self.assertEqual(False, self.svc.isActive()) @defer.inlineCallbacks def test_activate_raises(self): self.setServiceClaimable(self.svc, defer.succeed(True)) self.setActivateToReturn(self.svc, RuntimeError()) yield self.svc.startService() self.assertEqual(1, len(self.flushLoggedErrors(RuntimeError))) # half-active: we actually return True in this case: self.assertEqual(True, self.svc.isActive()) def test_deactivate_raises(self): self.setServiceClaimable(self.svc, defer.succeed(True)) self.setDeactivateToReturn(self.svc, RuntimeError()) self.svc.startService() self.svc.stopService() self.assertEqual(1, len(self.flushLoggedErrors(RuntimeError))) self.assertEqual(False, self.svc.isActive()) def test_unclaim_raises(self): self.setServiceClaimable(self.svc, defer.succeed(True)) self.setUnclaimToReturn(self.svc, RuntimeError()) self.svc.startService() self.svc.stopService() self.assertEqual(1, len(self.flushLoggedErrors(RuntimeError))) self.assertEqual(False, self.svc.isActive()) class MyService(service.BuildbotService): def checkConfig(self, foo, a=None): if a is None: config.error("a must be specified") return defer.succeed(True) def reconfigService(self, *argv, **kwargs): self.config = argv, kwargs return defer.succeed(None) class fakeConfig: pass class fakeMaster(service.MasterService, service.ReconfigurableServiceMixin): pass def makeFakeMaster(): m = fakeMaster() m.db = mock.Mock() return m class BuildbotService(unittest.TestCase): def setUp(self): self.master = makeFakeMaster() @defer.inlineCallbacks def prepareService(self): self.master.config = fakeConfig() serv = MyService(1, a=2, name="basic") yield serv.setServiceParent(self.master) yield self.master.startService() yield serv.reconfigServiceWithSibling(serv) return serv @defer.inlineCallbacks def testNominal(self): yield self.prepareService() self.assertEqual(self.master.namedServices["basic"].config, ((1,), {"a": 2})) @defer.inlineCallbacks def testConfigDict(self): serv = yield self.prepareService() self.assertEqual( serv.getConfigDict(), { 'args': (1,), 'class': 'buildbot.test.unit.util.test_service.MyService', 'kwargs': {'a': 2}, 'name': 'basic', }, ) def testNoName(self): with self.assertRaises(ValueError): MyService(1, a=2) def testChecksDone(self): with self.assertRaises(config.ConfigErrors): MyService(1, name="foo") class BuildbotServiceManager(unittest.TestCase): def setUp(self): self.master = makeFakeMaster() @defer.inlineCallbacks def prepareService(self): self.master.config = fakeConfig() serv = MyService(1, a=2, name="basic") self.master.config.services = {"basic": serv} self.manager = service.BuildbotServiceManager() yield self.manager.setServiceParent(self.master) yield self.master.startService() yield self.master.reconfigServiceWithBuildbotConfig(self.master.config) return serv @defer.inlineCallbacks def testNominal(self): yield self.prepareService() self.assertEqual(self.manager.namedServices["basic"].config, ((1,), {"a": 2})) @defer.inlineCallbacks def testReconfigNoChange(self): serv = yield self.prepareService() serv.config = None # 'de-configure' the service # reconfigure with the same config serv2 = MyService(1, a=2, name="basic") self.master.config.services = {"basic": serv2} # reconfigure the master yield self.master.reconfigServiceWithBuildbotConfig(self.master.config) # the first service is still used self.assertIdentical(self.manager.namedServices["basic"], serv) # the second service is not used self.assertNotIdentical(self.manager.namedServices["basic"], serv2) # reconfigServiceWithConstructorArgs was not called self.assertEqual(serv.config, None) @defer.inlineCallbacks def testReconfigWithChanges(self): serv = yield self.prepareService() serv.config = None # 'de-configure' the service # reconfigure with the different config serv2 = MyService(1, a=4, name="basic") self.master.config.services = {"basic": serv2} # reconfigure the master yield self.master.reconfigServiceWithBuildbotConfig(self.master.config) # the first service is still used self.assertIdentical(self.manager.namedServices["basic"], serv) # the second service is not used self.assertNotIdentical(self.manager.namedServices["basic"], serv2) # reconfigServiceWithConstructorArgs was called with new config self.assertEqual(serv.config, ((1,), {"a": 4})) def testNoName(self): with self.assertRaises(ValueError): MyService(1, a=2) def testChecksDone(self): with self.assertRaises(config.ConfigErrors): MyService(1, name="foo") @defer.inlineCallbacks def testReconfigWithNew(self): serv = yield self.prepareService() # reconfigure with the new service serv2 = MyService(1, a=4, name="basic2") self.master.config.services['basic2'] = serv2 # the second service is not there yet self.assertIdentical(self.manager.namedServices.get("basic2"), None) # reconfigure the master yield self.master.reconfigServiceWithBuildbotConfig(self.master.config) # the first service is still used self.assertIdentical(self.manager.namedServices["basic"], serv) # the second service is created self.assertIdentical(self.manager.namedServices["basic2"], serv2) # reconfigServiceWithConstructorArgs was called with new config self.assertEqual(serv2.config, ((1,), {"a": 4})) @defer.inlineCallbacks def testReconfigWithDeleted(self): serv = yield self.prepareService() self.assertEqual(serv.running, True) # remove all self.master.config.services = {} # reconfigure the master yield self.master.reconfigServiceWithBuildbotConfig(self.master.config) # the first service is still used self.assertIdentical(self.manager.namedServices.get("basic"), None) self.assertEqual(serv.running, False) @defer.inlineCallbacks def testConfigDict(self): yield self.prepareService() self.assertEqual( self.manager.getConfigDict(), { 'childs': [ { 'args': (1,), 'class': 'buildbot.test.unit.util.test_service.MyService', 'kwargs': {'a': 2}, 'name': 'basic', } ], 'name': 'services', }, ) @defer.inlineCallbacks def testRenderSecrets(self): yield self.prepareService() service = self.manager.namedServices['basic'] test = yield service.renderSecrets(Interpolate('test_string')) self.assertEqual(test, 'test_string') @defer.inlineCallbacks def testRenderSecrets2Args(self): yield self.prepareService() service = self.manager.namedServices['basic'] test, test2 = yield service.renderSecrets( Interpolate('test_string'), 'ok_for_non_renderable' ) self.assertEqual(test, 'test_string') self.assertEqual(test2, 'ok_for_non_renderable') @defer.inlineCallbacks def testRenderSecretsWithTuple(self): yield self.prepareService() service = self.manager.namedServices['basic'] test = yield service.renderSecrets(('user', Interpolate('test_string'))) self.assertEqual(test, ('user', 'test_string')) @async_to_deferred async def test_service_name_collision(self): with self.assertRaises(config.ConfigErrors): self.master.config = fakeConfig() service = MyService(1, name="service") self.master.config.services = [service, service] self.manager = service.BuildbotServiceManager() await self.manager.setServiceParent(self.master) await self.master.startService() await self.master.reconfigServiceWithBuildbotConfig(self.master.config) class UnderTestSharedService(service.SharedService): def __init__(self, arg1=None): super().__init__() class UnderTestDependentService(service.AsyncService): @defer.inlineCallbacks def startService(self): self.dependent = yield UnderTestSharedService.getService(self.parent) def stopService(self): assert self.dependent.running class SharedService(unittest.TestCase): @defer.inlineCallbacks def test_bad_constructor(self): parent = service.AsyncMultiService() with self.assertRaises(TypeError): yield UnderTestSharedService.getService(parent, arg2="foo") @defer.inlineCallbacks def test_creation(self): parent = service.AsyncMultiService() r = yield UnderTestSharedService.getService(parent) r2 = yield UnderTestSharedService.getService(parent) r3 = yield UnderTestSharedService.getService(parent, "arg1") r4 = yield UnderTestSharedService.getService(parent, "arg1") self.assertIdentical(r, r2) self.assertNotIdentical(r, r3) self.assertIdentical(r3, r4) self.assertEqual(len(list(iter(parent))), 2) @defer.inlineCallbacks def test_startup(self): """the service starts when parent starts and stop""" parent = service.AsyncMultiService() r = yield UnderTestSharedService.getService(parent) self.assertEqual(r.running, 0) yield parent.startService() self.assertEqual(r.running, 1) yield parent.stopService() self.assertEqual(r.running, 0) @defer.inlineCallbacks def test_already_started(self): """the service starts during the getService if parent already started""" parent = service.AsyncMultiService() yield parent.startService() r = yield UnderTestSharedService.getService(parent) self.assertEqual(r.running, 1) # then we stop the parent, and the shared service stops yield parent.stopService() self.assertEqual(r.running, 0) @defer.inlineCallbacks def test_already_stopped_last(self): parent = service.AsyncMultiService() o = UnderTestDependentService() yield o.setServiceParent(parent) yield parent.startService() yield parent.stopService()
29,215
Python
.py
627
38.00319
98
0.683599
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,562
test_raml.py
buildbot_buildbot/master/buildbot/test/unit/util/test_raml.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.trial import unittest from buildbot.util import raml class TestRaml(unittest.TestCase): def setUp(self): self.api = raml.RamlSpec() def test_api(self): self.assertTrue(self.api.api is not None) def test_endpoints(self): self.assertIn( "/masters/{masterid}/builders/{builderid}/workers/{workerid}", self.api.endpoints.keys() ) def test_endpoints_uri_parameters(self): # comparison of OrderedDict do not take in account order :( # this is why we compare str repr, to make sure the endpoints are in # the right order self.assertEqual( str( self.api.endpoints["/masters/{masterid}/builders/{builderid}/workers/{workerid}"][ 'uriParameters' ] ), str( raml.OrderedDict([ ( 'masterid', raml.OrderedDict([ ('type', 'number'), ('description', 'the id of the master'), ]), ), ( 'builderid', raml.OrderedDict([ ('type', 'number'), ('description', 'the id of the builder'), ]), ), ( 'workerid', raml.OrderedDict([ ('type', 'number'), ('description', 'the id of the worker'), ]), ), ]) ), ) def test_types(self): self.assertIn("log", self.api.types.keys()) def test_json_example(self): self.assertEqual( textwrap.dedent(self.api.format_json(self.api.types["build"]['example'], 0)), textwrap.dedent(""" { "builderid": 10, "buildid": 100, "buildrequestid": 13, "workerid": 20, "complete": false, "complete_at": null, "masterid": 824, "number": 1, "results": null, "started_at": 1451001600, "state_string": "created", "properties": {} }""").strip(), ) def test_endpoints_by_type(self): self.assertIn( "/masters/{masterid}/builders/{builderid}/workers/{workerid}", self.api.endpoints_by_type['worker'].keys(), ) def test_iter_actions(self): build = self.api.endpoints_by_type['build'] actions = dict(self.api.iter_actions(build['/builds/{buildid}'])) self.assertEqual(sorted(actions.keys()), sorted(['rebuild', 'stop'])) def test_rawendpoints(self): self.assertIn("/steps/{stepid}/logs/{log_slug}/raw", self.api.rawendpoints.keys())
3,756
Python
.py
94
27.191489
100
0.525768
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,563
test_subscriptions.py
buildbot_buildbot/master/buildbot/test/unit/util/test_subscriptions.py
# This file is part of Buildbot. Buildbot is free software: you can # redistribute it and/or modify it under the terms of the GNU General Public # License as published by the Free Software Foundation, version 2. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more # details. # # You should have received a copy of the GNU General Public License along with # this program; if not, write to the Free Software Foundation, Inc., 51 # Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # Copyright Buildbot Team Members from twisted.internet import defer from twisted.python import failure from twisted.trial import unittest from buildbot.util import subscription class TestException(Exception): pass class subscriptions(unittest.TestCase): def setUp(self): self.subpt = subscription.SubscriptionPoint('test_sub') def test_str(self): self.assertIn('test_sub', str(self.subpt)) def test_subscribe_unsubscribe(self): state = [] def cb(*args, **kwargs): state.append((args, kwargs)) # subscribe sub = self.subpt.subscribe(cb) self.assertTrue(isinstance(sub, subscription.Subscription)) self.assertEqual(state, []) # deliver self.subpt.deliver(1, 2, a=3, b=4) self.assertEqual(state, [((1, 2), {"a": 3, "b": 4})]) state.pop() # unsubscribe sub.unsubscribe() # don't receive events anymore self.subpt.deliver(3, 4) self.assertEqual(state, []) def test_exception(self): def cb(*args, **kwargs): raise RuntimeError('mah bucket!') self.subpt.subscribe(cb) self.subpt.deliver() # should not raise exceptions = self.subpt.pop_exceptions() self.assertEqual(len(exceptions), 1) self.assertIsInstance(exceptions[0], RuntimeError) # log.err will cause Trial to complain about this error anyway, unless # we clean it up self.assertEqual(1, len(self.flushLoggedErrors(RuntimeError))) def test_deferred_exception(self): d = defer.Deferred() @defer.inlineCallbacks def cb_deferred(*args, **kwargs): yield d raise RuntimeError('msg') self.subpt.subscribe(cb_deferred) self.subpt.deliver() d.callback(None) exceptions = self.subpt.pop_exceptions() self.assertEqual(len(exceptions), 1) self.assertIsInstance(exceptions[0], failure.Failure) self.assertEqual(1, len(self.flushLoggedErrors(RuntimeError))) def test_deferred_exception_after_pop_exceptions(self): # waitForDeliveriesToFinish is forgotten to be called and exception happens after # pop_exceptions. d = defer.Deferred() @defer.inlineCallbacks def cb_deferred(*args, **kwargs): yield d raise TestException('msg') self.subpt.subscribe(cb_deferred) self.subpt.deliver() exceptions = self.subpt.pop_exceptions() d.callback(None) self.assertEqual(len(exceptions), 0) self.assertEqual(2, len(self.flushLoggedErrors(TestException))) def test_multiple_exceptions(self): d = defer.Deferred() @defer.inlineCallbacks def cb_deferred(*args, **kwargs): yield d raise RuntimeError('msg') def cb(*args, **kwargs): raise RuntimeError('msg') self.subpt.subscribe(cb_deferred) self.subpt.subscribe(cb) self.subpt.deliver() d.callback(None) exceptions = self.subpt.pop_exceptions() self.assertEqual(len(exceptions), 2) self.assertIsInstance(exceptions[0], RuntimeError) self.assertIsInstance(exceptions[1], failure.Failure) self.assertEqual(2, len(self.flushLoggedErrors(RuntimeError))) def test_deliveries_finished(self): state = [] def create_cb(d): def cb(*args): state.append(args) return d return cb d1 = defer.Deferred() d2 = defer.Deferred() self.subpt.subscribe(create_cb(d1)) self.subpt.subscribe(create_cb(d2)) self.assertEqual(state, []) self.subpt.deliver(1, 2) self.assertEqual(state, [(1, 2), (1, 2)]) d = self.subpt.waitForDeliveriesToFinish() self.assertFalse(d.called) d1.callback(None) self.assertFalse(d.called) d2.callback(None) self.assertTrue(d.called) # when there are no waiting deliveries, should call the callback immediately d = self.subpt.waitForDeliveriesToFinish() self.assertTrue(d.called) def test_deliveries_not_finished_within_callback(self): state = [] def cb(*args): state.append(args) d = self.subpt.waitForDeliveriesToFinish() self.assertFalse(d.called) self.subpt.subscribe(cb) self.assertEqual(state, []) self.subpt.deliver(1, 2) self.assertEqual(state, [(1, 2)])
5,271
Python
.py
130
32.153846
89
0.652396
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,564
test_git_credential.py
buildbot_buildbot/master/buildbot/test/unit/util/test_git_credential.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.properties import Properties from buildbot.process.properties import Property from buildbot.test.fake.fakebuild import FakeBuild from buildbot.util.git_credential import GitCredentialInputRenderer class TestGitCredentialInputRenderer(unittest.TestCase): def setUp(self): self.props = Properties() self.build = FakeBuild(props=self.props) @defer.inlineCallbacks def test_render(self): self.props.setProperty("password", "property_password", "test") renderer = GitCredentialInputRenderer( username="user", password=Property("password"), url="https://example.com/repo.git", ) rendered = yield self.build.render(renderer) self.assertEqual( rendered, "url=https://example.com/repo.git\nusername=user\npassword=property_password\n", )
1,667
Python
.py
37
40.243243
92
0.747692
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,565
test_git.py
buildbot_buildbot/master/buildbot/test/unit/util/test_git.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.trial import unittest from buildbot.test.util import config from buildbot.util.git import GitMixin from buildbot.util.git import check_ssh_config from buildbot.util.git import ensureSshKeyNewline from buildbot.util.git import escapeShellArgIfNeeded from buildbot.util.git import getSshKnownHostsContents class TestEscapeShellArgIfNeeded(unittest.TestCase): def assert_escapes(self, arg): escaped = f'"{arg}"' self.assertEqual(escapeShellArgIfNeeded(arg), escaped) def assert_does_not_escape(self, arg): self.assertEqual(escapeShellArgIfNeeded(arg), arg) def test_empty(self): self.assert_escapes('') def test_spaces(self): self.assert_escapes(' ') self.assert_escapes('a ') self.assert_escapes(' a') self.assert_escapes('a b') def test_special(self): self.assert_escapes('a=b') self.assert_escapes('a%b') self.assert_escapes('a(b') self.assert_escapes('a[b') def test_no_escape(self): self.assert_does_not_escape('abc') self.assert_does_not_escape('a_b') self.assert_does_not_escape('-opt') self.assert_does_not_escape('--opt') class TestSetUpGit(unittest.TestCase, config.ConfigErrorsMixin): @parameterized.expand([ ('no_keys', None, None, None, None), ('only_private_key', 'key', None, None, None), ('private_key_host_key', 'key', 'host', None, None), ('private_key_known_hosts', 'key', None, 'hosts', None), ( 'no_private_key_host_key', None, 'host', None, 'sshPrivateKey must be provided in order use sshHostKey', ), ( 'no_private_key_known_hosts', None, None, 'hosts', 'sshPrivateKey must be provided in order use sshKnownHosts', ), ( 'both_host_key_known_hosts', 'key', 'host', 'hosts', 'only one of sshKnownHosts and sshHostKey can be provided', ), ]) def test_config(self, name, private_key, host_key, known_hosts, config_error): if config_error is None: check_ssh_config( 'TestSetUpGit', private_key, host_key, known_hosts, ) else: with self.assertRaisesConfigError(config_error): check_ssh_config( 'TestSetUpGit', private_key, host_key, known_hosts, ) class TestParseGitFeatures(GitMixin, unittest.TestCase): def setUp(self): self.setupGit() def test_no_output(self): self.parseGitFeatures('') self.assertFalse(self.gitInstalled) self.assertFalse(self.supportsBranch) self.assertFalse(self.supportsSubmoduleForce) self.assertFalse(self.supportsSubmoduleCheckout) self.assertFalse(self.supportsSshPrivateKeyAsEnvOption) self.assertFalse(self.supportsSshPrivateKeyAsConfigOption) self.assertFalse(self.supports_lsremote_symref) self.assertFalse(self.supports_credential_store) def test_git_noversion(self): self.parseGitFeatures('git') self.assertFalse(self.gitInstalled) self.assertFalse(self.supportsBranch) self.assertFalse(self.supportsSubmoduleForce) self.assertFalse(self.supportsSubmoduleCheckout) self.assertFalse(self.supportsSshPrivateKeyAsEnvOption) self.assertFalse(self.supportsSshPrivateKeyAsConfigOption) self.assertFalse(self.supports_lsremote_symref) self.assertFalse(self.supports_credential_store) def test_git_zero_version(self): self.parseGitFeatures('git version 0.0.0') self.assertTrue(self.gitInstalled) self.assertFalse(self.supportsBranch) self.assertFalse(self.supportsSubmoduleForce) self.assertFalse(self.supportsSubmoduleCheckout) self.assertFalse(self.supportsSshPrivateKeyAsEnvOption) self.assertFalse(self.supportsSshPrivateKeyAsConfigOption) self.assertFalse(self.supports_lsremote_symref) self.assertFalse(self.supports_credential_store) def test_git_2_10_0(self): self.parseGitFeatures('git version 2.10.0') self.assertTrue(self.gitInstalled) self.assertTrue(self.supportsBranch) self.assertTrue(self.supportsSubmoduleForce) self.assertTrue(self.supportsSubmoduleCheckout) self.assertTrue(self.supportsSshPrivateKeyAsEnvOption) self.assertTrue(self.supportsSshPrivateKeyAsConfigOption) self.assertTrue(self.supports_lsremote_symref) self.assertTrue(self.supports_credential_store) class TestAdjustCommandParamsForSshPrivateKey(GitMixin, unittest.TestCase): def test_throws_when_wrapper_not_given(self): self.gitInstalled = True command = [] env = {} with self.assertRaises(RuntimeError): self.setupGit() self.adjustCommandParamsForSshPrivateKey(command, env, 'path/to/key') class TestGetSshKnownHostsContents(unittest.TestCase): def test(self): key = 'ssh-rsa AAAA<...>WsHQ==' expected = '* ssh-rsa AAAA<...>WsHQ==' self.assertEqual(expected, getSshKnownHostsContents(key)) class TestensureSshKeyNewline(unittest.TestCase): def setUp(self): self.sshGoodPrivateKey = """-----BEGIN SSH PRIVATE KEY----- base64encodedkeydata -----END SSH PRIVATE KEY----- """ self.sshMissingNewlinePrivateKey = """-----BEGIN SSH PRIVATE KEY----- base64encodedkeydata -----END SSH PRIVATE KEY-----""" def test_good_key(self): """Don't break good keys""" self.assertEqual(self.sshGoodPrivateKey, ensureSshKeyNewline(self.sshGoodPrivateKey)) def test_missing_newline(self): """Add missing newline to stripped keys""" self.assertEqual( self.sshGoodPrivateKey, ensureSshKeyNewline(self.sshMissingNewlinePrivateKey) )
6,857
Python
.py
162
34.148148
93
0.678164
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,566
test_logwatcher.py
buildbot_buildbot/master/buildbot/test/unit/scripts/test_logwatcher.py
# This file is part of Buildbot. Buildbot is free software: you can # redistribute it and/or modify it under the terms of the GNU General Public # License as published by the Free Software Foundation, version 2. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more # details. # # You should have received a copy of the GNU General Public License along with # this program; if not, write to the Free Software Foundation, Inc., 51 # Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # Copyright Buildbot Team Members import os from unittest import mock from twisted.internet import defer from twisted.trial import unittest from buildbot.scripts.logwatcher import BuildmasterStartupError from buildbot.scripts.logwatcher import BuildmasterTimeoutError from buildbot.scripts.logwatcher import LogWatcher from buildbot.scripts.logwatcher import ReconfigError from buildbot.test.reactor import TestReactorMixin from buildbot.test.util import dirs from buildbot.util import unicode2bytes class MockedLogWatcher(LogWatcher): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.printed_output = [] self.created_paths = [] def create_logfile(self, path): self.created_paths.append(path) def print_output(self, output): self.printed_output.append(output) class TestLogWatcher(unittest.TestCase, dirs.DirsMixin, TestReactorMixin): delimiter = unicode2bytes(os.linesep) def setUp(self): self.setUpDirs('workdir') self.addCleanup(self.tearDownDirs) self.setup_test_reactor(auto_tear_down=False) self.spawned_process = mock.Mock() self.reactor.spawnProcess = mock.Mock(return_value=self.spawned_process) @defer.inlineCallbacks def tearDown(self): yield self.tear_down_test_reactor() def test_start(self): lw = MockedLogWatcher('workdir/test.log', _reactor=self.reactor) lw._start = mock.Mock() lw.start() self.reactor.spawnProcess.assert_called() self.assertEqual(lw.created_paths, ['workdir/test.log']) self.assertTrue(lw.running) @defer.inlineCallbacks def test_success_before_timeout(self): lw = MockedLogWatcher('workdir/test.log', timeout=5, _reactor=self.reactor) d = lw.start() self.reactor.advance(4.9) lw.lineReceived(b'BuildMaster is running') res = yield d self.assertEqual(res, 'buildmaster') @defer.inlineCallbacks def test_failure_after_timeout(self): lw = MockedLogWatcher('workdir/test.log', timeout=5, _reactor=self.reactor) d = lw.start() self.reactor.advance(5.1) lw.lineReceived(b'BuildMaster is running') with self.assertRaises(BuildmasterTimeoutError): yield d @defer.inlineCallbacks def test_progress_restarts_timeout(self): lw = MockedLogWatcher('workdir/test.log', timeout=5, _reactor=self.reactor) d = lw.start() self.reactor.advance(4.9) lw.lineReceived(b'added builder') self.reactor.advance(4.9) lw.lineReceived(b'BuildMaster is running') res = yield d self.assertEqual(res, 'buildmaster') @defer.inlineCallbacks def test_handles_very_long_lines(self): lw = MockedLogWatcher('workdir/test.log', timeout=5, _reactor=self.reactor) d = lw.start() lw.dataReceived( b't' * lw.MAX_LENGTH * 2 + self.delimiter + b'BuildMaster is running' + self.delimiter ) res = yield d self.assertEqual( lw.printed_output, ['Got an a very long line in the log (length 32768 bytes), ignoring'] ) self.assertEqual(res, 'buildmaster') @defer.inlineCallbacks def test_handles_very_long_lines_separate_packet(self): lw = MockedLogWatcher('workdir/test.log', timeout=5, _reactor=self.reactor) d = lw.start() lw.dataReceived(b't' * lw.MAX_LENGTH * 2) lw.dataReceived(self.delimiter + b'BuildMaster is running' + self.delimiter) res = yield d self.assertEqual( lw.printed_output, ['Got an a very long line in the log (length 32768 bytes), ignoring'] ) self.assertEqual(res, 'buildmaster') @defer.inlineCallbacks def test_handles_very_long_lines_separate_packet_with_newline(self): lw = MockedLogWatcher('workdir/test.log', timeout=5, _reactor=self.reactor) d = lw.start() lw.dataReceived(b't' * lw.MAX_LENGTH * 2 + self.delimiter) lw.dataReceived(b'BuildMaster is running' + self.delimiter) res = yield d self.assertEqual( lw.printed_output, ['Got an a very long line in the log (length 32768 bytes), ignoring'] ) self.assertEqual(res, 'buildmaster') @defer.inlineCallbacks def test_matches_lines(self): lines_and_expected = [ (b'configuration update aborted without making any changes', ReconfigError()), ( b'WARNING: configuration update partially applied; master may malfunction', ReconfigError(), ), (b'Server Shut Down', ReconfigError()), (b'BuildMaster startup failed', BuildmasterStartupError()), (b'message from master: attached', 'worker'), (b'configuration update complete', 'buildmaster'), (b'BuildMaster is running', 'buildmaster'), ] for line, expected in lines_and_expected: lw = MockedLogWatcher('workdir/test.log', timeout=5, _reactor=self.reactor) d = lw.start() lw.lineReceived(line) if isinstance(expected, Exception): with self.assertRaises(type(expected)): yield d else: res = yield d self.assertEqual(res, expected)
6,067
Python
.py
136
36.764706
100
0.673663
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,567
test_checkconfig.py
buildbot_buildbot/master/buildbot/test/unit/scripts/test_checkconfig.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 import textwrap from io import StringIO from unittest import mock from twisted.trial import unittest from buildbot.scripts import base from buildbot.scripts import checkconfig from buildbot.test.util import dirs class TestConfigLoader(dirs.DirsMixin, unittest.TestCase): def setUp(self): # config dir must be unique so that the python runtime does not optimize its list of module self.configdir = self.mktemp() return self.setUpDirs(self.configdir) def tearDown(self): return self.tearDownDirs() # tests def do_test_load(self, config='', other_files=None, stdout_re=None, stderr_re=None): if other_files is None: other_files = {} configFile = os.path.join(self.configdir, 'master.cfg') with open(configFile, "w", encoding='utf-8') as f: f.write(config) for filename, contents in other_files.items(): if isinstance(filename, type(())): fn = os.path.join(self.configdir, *filename) dn = os.path.dirname(fn) if not os.path.isdir(dn): os.makedirs(dn) else: fn = os.path.join(self.configdir, filename) with open(fn, "w", encoding='utf-8') as f: f.write(contents) old_stdout = sys.stdout old_stderr = sys.stderr stdout = sys.stdout = StringIO() stderr = sys.stderr = StringIO() try: checkconfig._loadConfig(basedir=self.configdir, configFile="master.cfg", quiet=False) finally: sys.stdout = old_stdout sys.stderr = old_stderr if stdout_re: stdout = stdout.getvalue() self.assertTrue(stdout_re.search(stdout), stdout) if stderr_re: stderr = stderr.getvalue() self.assertTrue(stderr_re.search(stderr), stderr) def test_success(self): len_sys_path = len(sys.path) config = textwrap.dedent("""\ c = BuildmasterConfig = {} c['multiMaster'] = True c['schedulers'] = [] from buildbot.config import BuilderConfig from buildbot.process.factory import BuildFactory c['builders'] = [ BuilderConfig('testbuilder', factory=BuildFactory(), workername='worker'), ] from buildbot.worker import Worker c['workers'] = [ Worker('worker', 'pass'), ] c['protocols'] = {'pb': {'port': 9989}} """) self.do_test_load(config=config, stdout_re=re.compile('Config file is good!')) # (regression) check that sys.path hasn't changed self.assertEqual(len(sys.path), len_sys_path) def test_failure_ImportError(self): config = textwrap.dedent("""\ import test_scripts_checkconfig_does_not_exist """) # Python 3 displays this error: # No module named 'test_scripts_checkconfig_does_not_exist' # # Python 2 displays this error: # No module named test_scripts_checkconfig_does_not_exist # # We need a regexp that matches both. self.do_test_load( config=config, stderr_re=re.compile("No module named '?test_scripts_checkconfig_does_not_exist'?"), ) self.flushLoggedErrors() def test_failure_no_workers(self): config = textwrap.dedent("""\ BuildmasterConfig={} """) self.do_test_load(config=config, stderr_re=re.compile('no workers')) self.flushLoggedErrors() def test_success_imports(self): config = textwrap.dedent("""\ from othermodule import port c = BuildmasterConfig = {} c['schedulers'] = [] c['builders'] = [] c['workers'] = [] c['protocols'] = {'pb': {'port': port}} """) other_files = {'othermodule.py': 'port = 9989'} self.do_test_load(config=config, other_files=other_files) def test_success_import_package(self): config = textwrap.dedent("""\ from otherpackage.othermodule import port c = BuildmasterConfig = {} c['schedulers'] = [] c['builders'] = [] c['workers'] = [] c['protocols'] = {'pb': {'port': 9989}} """) other_files = { ('otherpackage', '__init__.py'): '', ('otherpackage', 'othermodule.py'): 'port = 9989', } self.do_test_load(config=config, other_files=other_files) class TestCheckconfig(unittest.TestCase): def setUp(self): self.loadConfig = mock.Mock(spec=checkconfig._loadConfig, return_value=3) # checkconfig is decorated with @in_reactor, so strip that decoration # since the reactor is already running self.patch(checkconfig, 'checkconfig', checkconfig.checkconfig._orig) self.patch(checkconfig, '_loadConfig', self.loadConfig) def test_checkconfig_default(self): self.assertEqual(checkconfig.checkconfig({}), 3) self.loadConfig.assert_called_with(basedir=os.getcwd(), configFile='master.cfg', quiet=None) def test_checkconfig_given_dir(self): self.assertEqual(checkconfig.checkconfig({"configFile": '.'}), 3) self.loadConfig.assert_called_with(basedir='.', configFile='master.cfg', quiet=None) def test_checkconfig_given_file(self): config = {"configFile": 'master.cfg'} self.assertEqual(checkconfig.checkconfig(config), 3) self.loadConfig.assert_called_with(basedir=os.getcwd(), configFile='master.cfg', quiet=None) def test_checkconfig_quiet(self): config = {"configFile": 'master.cfg', "quiet": True} self.assertEqual(checkconfig.checkconfig(config), 3) self.loadConfig.assert_called_with(basedir=os.getcwd(), configFile='master.cfg', quiet=True) def test_checkconfig_syntaxError_quiet(self): """ When C{base.getConfigFileFromTac} raises L{SyntaxError}, C{checkconfig.checkconfig} return an error. """ mockGetConfig = mock.Mock(spec=base.getConfigFileFromTac, side_effect=SyntaxError) self.patch(checkconfig, 'getConfigFileFromTac', mockGetConfig) config = {"configFile": '.', "quiet": True} self.assertEqual(checkconfig.checkconfig(config), 1)
7,326
Python
.py
161
35.509317
100
0.615428
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,568
test_user.py
buildbot_buildbot/master/buildbot/test/unit/scripts/test_user.py
# This file is part of Buildbot. Buildbot is free software: you can # redistribute it and/or modify it under the terms of the GNU General Public # License as published by the Free Software Foundation, version 2. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more # details. # # You should have received a copy of the GNU General Public License along with # this program; if not, write to the Free Software Foundation, Inc., 51 # Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # Copyright Buildbot Team Members from twisted.internet import defer from twisted.internet import reactor from twisted.trial import unittest from buildbot.clients import usersclient from buildbot.process.users import users from buildbot.scripts import user class TestUsersClient(unittest.TestCase): class FakeUsersClient: def __init__(self, master, username="user", passwd="userpw", port=0): self.master = master self.port = port self.username = username self.passwd = passwd self.fail = False def send(self, op, bb_username, bb_password, ids, info): self.op = op self.bb_username = bb_username self.bb_password = bb_password self.ids = ids self.info = info d = defer.Deferred() if self.fail: reactor.callLater(0, d.errback, RuntimeError("oh noes")) else: reactor.callLater(0, d.callback, None) return d def setUp(self): def fake_UsersClient(*args): self.usersclient = self.FakeUsersClient(*args) return self.usersclient self.patch(usersclient, 'UsersClient', fake_UsersClient) # un-do the effects of @in_reactor self.patch(user, 'user', user.user._orig) @defer.inlineCallbacks def test_usersclient_send_ids(self): yield user.user({ "master": 'a:9990', "username": "x", "passwd": "y", "op": 'get', "bb_username": None, "bb_password": None, "ids": ['me', 'you'], "info": None, }) c = self.usersclient self.assertEqual( (c.master, c.port, c.username, c.passwd, c.op, c.ids, c.info), ('a', 9990, "x", "y", 'get', ['me', 'you'], None), ) @defer.inlineCallbacks def test_usersclient_send_update_info(self): def _fake_encrypt(passwd): assert passwd == 'day' return 'ENCRY' self.patch(users, 'encrypt', _fake_encrypt) yield user.user({ "master": 'a:9990', "username": "x", "passwd": "y", "op": 'update', "bb_username": 'bud', "bb_password": 'day', "ids": None, "info": [{'identifier': 'x', 'svn': 'x'}], }) c = self.usersclient self.assertEqual( ( c.master, c.port, c.username, c.passwd, c.op, c.bb_username, c.bb_password, c.ids, c.info, ), ( 'a', 9990, "x", "y", 'update', 'bud', 'ENCRY', None, [{'identifier': 'x', 'svn': 'x'}], ), ) @defer.inlineCallbacks def test_usersclient_send_add_info(self): yield user.user({ "master": 'a:9990', "username": "x", "passwd": "y", "op": 'add', "bb_username": None, "bb_password": None, "ids": None, "info": [{'git': 'x <h@c>', 'irc': 'aaa'}], }) c = self.usersclient self.assertEqual( ( c.master, c.port, c.username, c.passwd, c.op, c.bb_username, c.bb_password, c.ids, c.info, ), ( 'a', 9990, "x", "y", 'add', None, None, None, [{'identifier': 'aaa', 'git': 'x <h@c>', 'irc': 'aaa'}], ), )
4,661
Python
.py
142
21.507042
79
0.492892
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,569
test_sendchange.py
buildbot_buildbot/master/buildbot/test/unit/scripts/test_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 twisted.internet import defer from twisted.internet import reactor from twisted.trial import unittest from buildbot.clients import sendchange as sendchange_client from buildbot.scripts import sendchange from buildbot.test.util import misc class TestSendChange(misc.StdoutAssertionsMixin, unittest.TestCase): class FakeSender: def __init__(self, testcase, master, auth, encoding=None): self.master = master self.auth = auth self.encoding = encoding self.testcase = testcase def send(self, branch, revision, comments, files, **kwargs): kwargs['branch'] = branch kwargs['revision'] = revision kwargs['comments'] = comments kwargs['files'] = files self.send_kwargs = kwargs d = defer.Deferred() if self.testcase.fail: reactor.callLater(0, d.errback, RuntimeError("oh noes")) else: reactor.callLater(0, d.callback, None) return d def setUp(self): self.fail = False # set to true to get Sender.send to fail def Sender_constr(*args, **kwargs): self.sender = self.FakeSender(self, *args, **kwargs) return self.sender self.patch(sendchange_client, 'Sender', Sender_constr) # undo the effects of @in_reactor self.patch(sendchange, 'sendchange', sendchange.sendchange._orig) self.setUpStdoutAssertions() @defer.inlineCallbacks def test_sendchange_config(self): rc = yield sendchange.sendchange({ "encoding": 'utf16', "who": 'me', "auth": ['a', 'b'], "master": 'm', "branch": 'br', "category": 'cat', "revision": 'rr', "properties": {'a': 'b'}, "repository": 'rep', "project": 'prj', "vc": 'git', "revlink": 'rl', "when": 1234.0, "comments": 'comm', "files": ('a', 'b'), "codebase": 'cb', }) self.assertEqual( ( self.sender.master, self.sender.auth, self.sender.encoding, self.sender.send_kwargs, self.getStdout(), rc, ), ( 'm', ['a', 'b'], 'utf16', { 'branch': 'br', 'category': 'cat', 'codebase': 'cb', 'comments': 'comm', 'files': ('a', 'b'), 'project': 'prj', 'properties': {'a': 'b'}, 'repository': 'rep', 'revision': 'rr', 'revlink': 'rl', 'when': 1234.0, 'who': 'me', 'vc': 'git', }, 'change sent successfully', 0, ), ) @defer.inlineCallbacks def test_sendchange_config_no_codebase(self): rc = yield sendchange.sendchange({ "encoding": 'utf16', "who": 'me', "auth": ['a', 'b'], "master": 'm', "branch": 'br', "category": 'cat', "revision": 'rr', "properties": {'a': 'b'}, "repository": 'rep', "project": 'prj', "vc": 'git', "revlink": 'rl', "when": 1234.0, "comments": 'comm', "files": ('a', 'b'), }) self.assertEqual( ( self.sender.master, self.sender.auth, self.sender.encoding, self.sender.send_kwargs, self.getStdout(), rc, ), ( 'm', ['a', 'b'], 'utf16', { 'branch': 'br', 'category': 'cat', 'codebase': None, 'comments': 'comm', 'files': ('a', 'b'), 'project': 'prj', 'properties': {'a': 'b'}, 'repository': 'rep', 'revision': 'rr', 'revlink': 'rl', 'when': 1234.0, 'who': 'me', 'vc': 'git', }, 'change sent successfully', 0, ), ) @defer.inlineCallbacks def test_sendchange_fail(self): self.fail = True rc = yield sendchange.sendchange({}) self.assertEqual((self.getStdout().split('\n')[0], rc), ('change not sent:', 1))
5,548
Python
.py
156
22.923077
88
0.475446
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,570
test_start.py
buildbot_buildbot/master/buildbot/test/unit/scripts/test_start.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 sys import time from unittest import mock from twisted.internet import defer from twisted.internet.utils import getProcessOutputAndValue from twisted.trial import unittest from buildbot.scripts import start from buildbot.test.util import dirs from buildbot.test.util import misc from buildbot.test.util.decorators import skipUnlessPlatformIs def mkconfig(**kwargs): config = { 'quiet': False, 'basedir': os.path.abspath('basedir'), 'nodaemon': False, } config.update(kwargs) return config fake_master_tac = """\ from twisted.application import service from twisted.internet import reactor from twisted.python import log application = service.Application('highscore') class App(service.Service): def startService(self): super().startService() log.msg("BuildMaster is running") # heh heh heh reactor.callLater(0, reactor.stop) app = App() app.setServiceParent(application) # isBuildmasterDir wants to see this -> Application('buildmaster') """ class TestStart(misc.StdoutAssertionsMixin, dirs.DirsMixin, unittest.TestCase): def setUp(self): # On slower machines with high CPU oversubscription this test may take longer to run than # the default timeout. self.timeout = 20 self.setUpDirs('basedir') with open(os.path.join('basedir', 'buildbot.tac'), "w", encoding='utf-8') as f: f.write(fake_master_tac) self.setUpStdoutAssertions() def tearDown(self): self.tearDownDirs() # tests def test_start_not_basedir(self): self.assertEqual(start.start(mkconfig(basedir='doesntexist')), 1) self.assertInStdout('invalid buildmaster directory') def runStart(self, **config): args = [ '-c', 'from buildbot.scripts.start import start; import sys; ' f'sys.exit(start({mkconfig(**config)!r}))', ] env = os.environ.copy() env['PYTHONPATH'] = os.pathsep.join(sys.path) return getProcessOutputAndValue(sys.executable, args=args, env=env) def assert_stderr_ok(self, err): lines = err.split(b'\n') good_warning_parts = [b'32-bit Python on a 64-bit', b'cryptography.hazmat.bindings'] for line in lines: is_line_good = False if line == b'': is_line_good = True else: for part in good_warning_parts: if part in line: is_line_good = True break if not is_line_good: self.assertEqual(err, b'') # not valid warning @defer.inlineCallbacks def test_start_no_daemon(self): (_, err, rc) = yield self.runStart(nodaemon=True) self.assert_stderr_ok(err) self.assertEqual(rc, 0) @defer.inlineCallbacks def test_start_quiet(self): res = yield self.runStart(quiet=True) self.assertEqual(res[0], b'') self.assert_stderr_ok(res[1]) self.assertEqual(res[2], 0) @skipUnlessPlatformIs('posix') @defer.inlineCallbacks def test_start_timeout_nonnumber(self): (out, err, rc) = yield self.runStart(start_timeout='a') self.assertEqual((rc, err), (1, b'')) self.assertSubstring(b'Start timeout must be a number\n', out) @skipUnlessPlatformIs('posix') @defer.inlineCallbacks def test_start_timeout_number_string(self): # integer values from command-line options come in as strings res = yield self.runStart(start_timeout='10') self.assertEqual(res, (mock.ANY, b'', 0)) @skipUnlessPlatformIs('posix') @defer.inlineCallbacks def test_start(self): try: (out, err, rc) = yield self.runStart() self.assertEqual((rc, err), (0, b'')) self.assertSubstring(b'buildmaster appears to have (re)started correctly', out) finally: # wait for the pidfile to go away after the reactor.stop # in buildbot.tac takes effect pidfile = os.path.join('basedir', 'twistd.pid') while os.path.exists(pidfile): time.sleep(0.01) # the remainder of this script does obscene things: # - forks # - shells out to tail # - starts and stops the reactor # so testing it will be *far* more pain than is worthwhile
5,108
Python
.py
126
33.531746
97
0.667339
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,571
test_trycmd.py
buildbot_buildbot/master/buildbot/test/unit/scripts/test_trycmd.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.trial import unittest from buildbot.clients import tryclient from buildbot.scripts import trycmd class TestStatusLog(unittest.TestCase): def test_trycmd(self): Try = mock.Mock() self.patch(tryclient, 'Try', Try) inst = Try.return_value = mock.Mock(name='Try-instance') rc = trycmd.trycmd({"cfg": 1}) Try.assert_called_with({"cfg": 1}) inst.run.assert_called_with() self.assertEqual(rc, 0)
1,200
Python
.py
27
40.962963
79
0.746998
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,572
test_cleanupdb.py
buildbot_buildbot/master/buildbot/test/unit/scripts/test_cleanupdb.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 textwrap import sqlalchemy as sa from twisted.internet import defer from twisted.trial import unittest from buildbot.scripts import cleanupdb from buildbot.test.fake import fakemaster from buildbot.test.reactor import TestReactorMixin from buildbot.test.unit.db import test_logs from buildbot.test.util import db from buildbot.test.util import dirs from buildbot.test.util import misc from buildbot.util.twisted import async_to_deferred try: import lz4 _ = lz4 hasLz4 = True except ImportError: hasLz4 = False try: import zstandard _ = zstandard HAS_ZSTD = True except ImportError: HAS_ZSTD = False try: import brotli _ = brotli HAS_BROTLI = True except ImportError: HAS_BROTLI = False def mkconfig(**kwargs): config = {"quiet": False, "basedir": os.path.abspath('basedir'), "force": True} config.update(kwargs) return config def patch_environ(case, key, value): """ Add an environment variable for the duration of a test. """ old_environ = os.environ.copy() def cleanup(): os.environ.clear() os.environ.update(old_environ) os.environ[key] = value case.addCleanup(cleanup) class TestCleanupDb( misc.StdoutAssertionsMixin, dirs.DirsMixin, TestReactorMixin, unittest.TestCase ): def setUp(self): self.setup_test_reactor(auto_tear_down=False) self.setUpDirs('basedir') with open(os.path.join('basedir', 'buildbot.tac'), "w", encoding='utf-8') as f: f.write( textwrap.dedent(""" from twisted.application import service application = service.Application('buildmaster') """) ) self.setUpStdoutAssertions() self.ensureNoSqliteMemory() @defer.inlineCallbacks def tearDown(self): self.tearDownDirs() yield self.tear_down_test_reactor() def ensureNoSqliteMemory(self): # test may use mysql or pg if configured in env envkey = "BUILDBOT_TEST_DB_URL" if envkey not in os.environ or os.environ[envkey] == 'sqlite://': patch_environ( self, envkey, "sqlite:///" + os.path.abspath(os.path.join("basedir", "state.sqlite")), ) def createMasterCfg(self, extraconfig=""): db_url = db.resolve_test_index_in_db_url(os.environ["BUILDBOT_TEST_DB_URL"]) with open(os.path.join('basedir', 'master.cfg'), "w", encoding='utf-8') as f: f.write( textwrap.dedent(f""" from buildbot.plugins import * c = BuildmasterConfig = dict() c['db_url'] = {db_url!r} c['buildbotNetUsageData'] = None c['multiMaster'] = True # don't complain for no builders {extraconfig} """) ) @async_to_deferred async def test_cleanup_not_basedir(self): res = await cleanupdb._cleanupDatabase(mkconfig(basedir='doesntexist')) self.assertEqual(res, 1) self.assertInStdout('invalid buildmaster directory') @async_to_deferred async def test_cleanup_bad_config(self): res = await cleanupdb._cleanupDatabase(mkconfig(basedir='basedir')) self.assertEqual(res, 1) self.assertInStdout("master.cfg' does not exist") @async_to_deferred async def test_cleanup_bad_config2(self): self.createMasterCfg(extraconfig="++++ # syntaxerror") res = await cleanupdb._cleanupDatabase(mkconfig(basedir='basedir')) self.assertEqual(res, 1) self.assertInStdout("encountered a SyntaxError while parsing config file:") # config logs an error via log.err, we must eat it or trial will # complain self.flushLoggedErrors() def assertDictAlmostEqual(self, d1, d2): # The test shows each methods return different size # but we still make a fuzzy comparison to resist if underlying libraries # improve efficiency self.assertEqual(len(d1), len(d2)) for k in d2.keys(): self.assertApproximates(d1[k], d2[k], 10) class TestCleanupDbRealDb(db.RealDatabaseWithConnectorMixin, TestCleanupDb): @defer.inlineCallbacks def setUp(self): yield super().setUp() table_names = [ 'logs', 'logchunks', 'steps', 'builds', 'projects', 'builders', 'masters', 'buildrequests', 'buildsets', 'workers', ] self.master = yield fakemaster.make_master(self, wantRealReactor=True) yield self.setUpRealDatabaseWithConnector(self.master, table_names=table_names) @defer.inlineCallbacks def tearDown(self): yield self.tearDownRealDatabaseWithConnector() @async_to_deferred async def test_cleanup(self): # we reuse the fake db background data from db.logs unit tests await self.insert_test_data(test_logs.Tests.backgroundData) # insert a log with lots of redundancy LOGDATA = "xx\n" * 2000 logid = await self.master.db.logs.addLog(102, "x", "x", "s") await self.master.db.logs.appendLog(logid, LOGDATA) # test all methods lengths = {} for mode in self.master.db.logs.COMPRESSION_MODE: if mode == "lz4" and not hasLz4: # ok.. lz4 is not installed, don't fail lengths["lz4"] = 40 continue if mode == "zstd" and not HAS_ZSTD: # zstandard is not installed, don't fail lengths["zstd"] = 20 continue if mode == "br" and not HAS_BROTLI: # brotli is not installed, don't fail lengths["br"] = 14 continue # create a master.cfg with different compression method self.createMasterCfg(f"c['logCompressionMethod'] = '{mode}'") res = await cleanupdb._cleanupDatabase(mkconfig(basedir='basedir')) self.assertEqual(res, 0) # make sure the compression don't change the data we can retrieve # via api res = await self.master.db.logs.getLogLines(logid, 0, 2000) self.assertEqual(res, LOGDATA) # retrieve the actual data size in db using raw sqlalchemy def thd(conn): tbl = self.master.db.model.logchunks q = sa.select(sa.func.sum(sa.func.length(tbl.c.content))) q = q.where(tbl.c.logid == logid) return conn.execute(q).fetchone()[0] lengths[mode] = await self.master.db.pool.do(thd) self.assertDictAlmostEqual( lengths, { 'raw': 5999, 'bz2': 44, 'lz4': 40, 'gz': 31, 'zstd': 20, 'br': 14, }, )
7,713
Python
.py
196
30.510204
88
0.625668
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,573
test_stop.py
buildbot_buildbot/master/buildbot/test/unit/scripts/test_stop.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 import time from twisted.trial import unittest from buildbot.scripts import stop from buildbot.test.util import dirs from buildbot.test.util import misc from buildbot.test.util.decorators import skipUnlessPlatformIs def mkconfig(**kwargs): config = {"quiet": False, "clean": False, "basedir": os.path.abspath('basedir')} config['no-wait'] = kwargs.pop('no_wait', False) config.update(kwargs) return config class TestStop(misc.StdoutAssertionsMixin, dirs.DirsMixin, unittest.TestCase): def setUp(self): self.setUpDirs('basedir') self.setUpStdoutAssertions() def tearDown(self): self.tearDownDirs() # tests def do_test_stop(self, config, kill_sequence, is_running=True, **kwargs): with open(os.path.join('basedir', 'buildbot.tac'), "w", encoding='utf-8') as f: f.write("Application('buildmaster')") if is_running: with open("basedir/twistd.pid", "w", encoding='utf-8') as f: f.write('1234') def sleep(t): self.assertTrue(kill_sequence, f"unexpected sleep: {t}") what, exp_t = kill_sequence.pop(0) self.assertEqual((what, exp_t), ('sleep', t)) self.patch(time, 'sleep', sleep) def kill(pid, signal): self.assertTrue(kill_sequence, f"unexpected signal: {signal}") exp_sig, result = kill_sequence.pop(0) self.assertEqual((pid, signal), (1234, exp_sig)) if isinstance(result, Exception): raise result return result self.patch(os, 'kill', kill) rv = stop.stop(config, **kwargs) self.assertEqual(kill_sequence, []) return rv @skipUnlessPlatformIs('posix') def test_stop_not_running(self): rv = self.do_test_stop(mkconfig(no_wait=True), [], is_running=False) self.assertInStdout('not running') self.assertEqual(rv, 0) @skipUnlessPlatformIs('posix') def test_stop_dead_but_pidfile_remains(self): rv = self.do_test_stop( mkconfig(no_wait=True), [(signal.SIGTERM, OSError(3, 'No such process'))] ) self.assertEqual(rv, 0) self.assertFalse(os.path.exists(os.path.join('basedir', 'twistd.pid'))) self.assertInStdout('not running') @skipUnlessPlatformIs('posix') def test_stop_dead_but_pidfile_remains_quiet(self): rv = self.do_test_stop( mkconfig(quiet=True, no_wait=True), [(signal.SIGTERM, OSError(3, 'No such process'))], ) self.assertEqual(rv, 0) self.assertFalse(os.path.exists(os.path.join('basedir', 'twistd.pid'))) self.assertWasQuiet() @skipUnlessPlatformIs('posix') def test_stop_dead_but_pidfile_remains_wait(self): rv = self.do_test_stop( mkconfig(no_wait=True), [(signal.SIGTERM, OSError(3, 'No such process'))], wait=True ) self.assertEqual(rv, 0) self.assertFalse(os.path.exists(os.path.join('basedir', 'twistd.pid'))) @skipUnlessPlatformIs('posix') def test_stop_slow_death_wait(self): rv = self.do_test_stop( mkconfig(no_wait=True), [ (signal.SIGTERM, None), ('sleep', 0.1), (0, None), # polling.. ('sleep', 1), (0, None), ('sleep', 1), (0, None), ('sleep', 1), (0, OSError(3, 'No such process')), ], wait=True, ) self.assertInStdout('is dead') self.assertEqual(rv, 0) @skipUnlessPlatformIs('posix') def test_stop_slow_death_wait_timeout(self): rv = self.do_test_stop( mkconfig(no_wait=True), [ (signal.SIGTERM, None), ('sleep', 0.1), ] + [ (0, None), ('sleep', 1), ] * 10, wait=True, ) self.assertInStdout('never saw process') self.assertEqual(rv, 1) @skipUnlessPlatformIs('posix') def test_stop_slow_death_config_wait_timeout(self): rv = self.do_test_stop( mkconfig(), [ (signal.SIGTERM, None), ('sleep', 0.1), ] + [ (0, None), ('sleep', 1), ] * 10, ) self.assertInStdout('never saw process') self.assertEqual(rv, 1) @skipUnlessPlatformIs('posix') def test_stop_clean(self): rv = self.do_test_stop( mkconfig(clean=True, no_wait=True), [ (signal.SIGUSR1, None), ], wait=False, ) self.assertInStdout('sent SIGUSR1 to process') self.assertEqual(rv, 0)
5,602
Python
.py
148
28.621622
96
0.588181
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,574
test_tryserver.py
buildbot_buildbot/master/buildbot/test/unit/scripts/test_tryserver.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 sys from io import StringIO from twisted.trial import unittest from buildbot.scripts import tryserver from buildbot.test.util import dirs class TestStatusLog(dirs.DirsMixin, unittest.TestCase): def setUp(self): self.newdir = os.path.join('jobdir', 'new') self.tmpdir = os.path.join('jobdir', 'tmp') self.setUpDirs("jobdir", self.newdir, self.tmpdir) def test_trycmd(self): config = {"jobdir": 'jobdir'} inputfile = StringIO('this is my try job') self.patch(sys, 'stdin', inputfile) rc = tryserver.tryserver(config) self.assertEqual(rc, 0) newfiles = os.listdir(self.newdir) tmpfiles = os.listdir(self.tmpdir) self.assertEqual((len(newfiles), len(tmpfiles)), (1, 0)) with open(os.path.join(self.newdir, newfiles[0]), encoding='utf-8') as f: self.assertEqual(f.read(), 'this is my try job')
1,636
Python
.py
36
40.972222
81
0.72093
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,575
test_upgrade_master.py
buildbot_buildbot/master/buildbot/test/unit/scripts/test_upgrade_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 sys from io import StringIO from unittest import mock from twisted.internet import defer from twisted.trial import unittest from buildbot.config import master as config_master from buildbot.db import connector from buildbot.db import masters from buildbot.db import model from buildbot.scripts import base from buildbot.scripts import upgrade_master from buildbot.test.reactor import TestReactorMixin from buildbot.test.util import dirs from buildbot.test.util import misc from buildbot.test.util import www def mkconfig(**kwargs): config = {"quiet": False, "replace": False, "basedir": 'test'} config.update(kwargs) return config class TestUpgradeMaster(dirs.DirsMixin, misc.StdoutAssertionsMixin, unittest.TestCase): def setUp(self): # createMaster is decorated with @in_reactor, so strip that decoration # since the master is already running self.patch(upgrade_master, 'upgradeMaster', upgrade_master.upgradeMaster._orig) self.setUpDirs('test') self.setUpStdoutAssertions() def patchFunctions(self, basedirOk=True, configOk=True): self.calls = [] def checkBasedir(config): self.calls.append('checkBasedir') return basedirOk self.patch(base, 'checkBasedir', checkBasedir) def loadConfig(config, configFileName='master.cfg'): self.calls.append('loadConfig') return config_master.MasterConfig() if configOk else False self.patch(base, 'loadConfig', loadConfig) def upgradeFiles(config): self.calls.append('upgradeFiles') self.patch(upgrade_master, 'upgradeFiles', upgradeFiles) def upgradeDatabase(config, master_cfg): self.assertIsInstance(master_cfg, config_master.MasterConfig) self.calls.append('upgradeDatabase') self.patch(upgrade_master, 'upgradeDatabase', upgradeDatabase) # tests @defer.inlineCallbacks def test_upgradeMaster_success(self): self.patchFunctions() rv = yield upgrade_master.upgradeMaster(mkconfig()) self.assertEqual(rv, 0) self.assertInStdout('upgrade complete') @defer.inlineCallbacks def test_upgradeMaster_quiet(self): self.patchFunctions() rv = yield upgrade_master.upgradeMaster(mkconfig(quiet=True)) self.assertEqual(rv, 0) self.assertWasQuiet() @defer.inlineCallbacks def test_upgradeMaster_bad_basedir(self): self.patchFunctions(basedirOk=False) rv = yield upgrade_master.upgradeMaster(mkconfig()) self.assertEqual(rv, 1) @defer.inlineCallbacks def test_upgradeMaster_bad_config(self): self.patchFunctions(configOk=False) rv = yield upgrade_master.upgradeMaster(mkconfig()) self.assertEqual(rv, 1) class TestUpgradeMasterFunctions( www.WwwTestMixin, dirs.DirsMixin, misc.StdoutAssertionsMixin, TestReactorMixin, unittest.TestCase, ): def setUp(self): self.setup_test_reactor(auto_tear_down=False) self.setUpDirs('test') self.basedir = os.path.abspath(os.path.join('test', 'basedir')) self.setUpStdoutAssertions() @defer.inlineCallbacks def tearDown(self): self.tearDownDirs() yield self.tear_down_test_reactor() def writeFile(self, path, contents): with open(path, "w", encoding='utf-8') as f: f.write(contents) def readFile(self, path): with open(path, encoding='utf-8') as f: return f.read() # tests def test_installFile(self): self.writeFile('test/srcfile', 'source data') upgrade_master.installFile(mkconfig(), 'test/destfile', 'test/srcfile') self.assertEqual(self.readFile('test/destfile'), 'source data') self.assertInStdout('creating test/destfile') def test_installFile_existing_differing(self): self.writeFile('test/srcfile', 'source data') self.writeFile('test/destfile', 'dest data') upgrade_master.installFile(mkconfig(), 'test/destfile', 'test/srcfile') self.assertEqual(self.readFile('test/destfile'), 'dest data') self.assertEqual(self.readFile('test/destfile.new'), 'source data') self.assertInStdout('writing new contents to') def test_installFile_existing_differing_overwrite(self): self.writeFile('test/srcfile', 'source data') self.writeFile('test/destfile', 'dest data') upgrade_master.installFile(mkconfig(), 'test/destfile', 'test/srcfile', overwrite=True) self.assertEqual(self.readFile('test/destfile'), 'source data') self.assertFalse(os.path.exists('test/destfile.new')) self.assertInStdout('overwriting') def test_installFile_existing_same(self): self.writeFile('test/srcfile', 'source data') self.writeFile('test/destfile', 'source data') upgrade_master.installFile(mkconfig(), 'test/destfile', 'test/srcfile') self.assertEqual(self.readFile('test/destfile'), 'source data') self.assertFalse(os.path.exists('test/destfile.new')) self.assertWasQuiet() def test_installFile_quiet(self): self.writeFile('test/srcfile', 'source data') upgrade_master.installFile(mkconfig(quiet=True), 'test/destfile', 'test/srcfile') self.assertWasQuiet() def test_upgradeFiles(self): upgrade_master.upgradeFiles(mkconfig()) for f in [ 'test/master.cfg.sample', ]: self.assertTrue(os.path.exists(f), f"{f} not found") self.assertInStdout('upgrading basedir') def test_upgradeFiles_notice_about_unused_public_html(self): os.mkdir('test/public_html') self.writeFile('test/public_html/index.html', 'INDEX') upgrade_master.upgradeFiles(mkconfig()) self.assertInStdout('public_html is not used') @defer.inlineCallbacks def test_upgradeDatabase(self): setup = mock.Mock(side_effect=lambda **kwargs: defer.succeed(None)) self.patch(connector.DBConnector, 'setup', setup) upgrade = mock.Mock(side_effect=lambda **kwargs: defer.succeed(None)) self.patch(model.Model, 'upgrade', upgrade) setAllMastersActiveLongTimeAgo = mock.Mock(side_effect=lambda **kwargs: defer.succeed(None)) self.patch( masters.MastersConnectorComponent, 'setAllMastersActiveLongTimeAgo', setAllMastersActiveLongTimeAgo, ) yield upgrade_master.upgradeDatabase( mkconfig(basedir='test', quiet=True), config_master.MasterConfig() ) setup.asset_called_with(check_version=False, verbose=False) upgrade.assert_called_with() self.assertWasQuiet() @defer.inlineCallbacks def test_upgradeDatabaseFail(self): setup = mock.Mock(side_effect=lambda **kwargs: defer.succeed(None)) self.patch(connector.DBConnector, 'setup', setup) self.patch(sys, 'stderr', StringIO()) upgrade = mock.Mock(side_effect=lambda **kwargs: defer.fail(Exception("o noz"))) self.patch(model.Model, 'upgrade', upgrade) ret = yield upgrade_master._upgradeMaster( mkconfig(basedir='test', quiet=True), config_master.MasterConfig() ) self.assertEqual(ret, 1) self.assertIn( "problem while upgrading!:\nTraceback (most recent call last):\n", sys.stderr.getvalue() ) self.assertIn("o noz", sys.stderr.getvalue())
8,221
Python
.py
179
38.648045
100
0.698075
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,576
test_base.py
buildbot_buildbot/master/buildbot/test/unit/scripts/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 import errno import os import string import textwrap from io import StringIO from twisted.python import runtime from twisted.python import usage from twisted.trial import unittest from buildbot.config import master as config_master from buildbot.scripts import base from buildbot.test.util import dirs from buildbot.test.util import misc from buildbot.test.util.decorators import skipUnlessPlatformIs class TestIBD(dirs.DirsMixin, misc.StdoutAssertionsMixin, unittest.TestCase): def setUp(self): self.setUpDirs('test') self.stdout = StringIO() self.setUpStdoutAssertions() def test_isBuildmasterDir_no_dir(self): self.assertFalse(base.isBuildmasterDir(os.path.abspath('test/nosuch'))) self.assertInStdout('error reading') self.assertInStdout('invalid buildmaster directory') def test_isBuildmasterDir_no_file(self): self.assertFalse(base.isBuildmasterDir(os.path.abspath('test'))) self.assertInStdout('error reading') self.assertInStdout('invalid buildmaster directory') def test_isBuildmasterDir_no_Application(self): # Loading of pre-0.9.0 buildbot.tac file should fail. with open(os.path.join('test', 'buildbot.tac'), 'w', encoding='utf-8') as f: f.write("foo\nx = Application('buildslave')\nbar") self.assertFalse(base.isBuildmasterDir(os.path.abspath('test'))) self.assertInStdout('unexpected content') self.assertInStdout('invalid buildmaster directory') def test_isBuildmasterDir_matches(self): with open(os.path.join('test', 'buildbot.tac'), 'w', encoding='utf-8') as f: f.write("foo\nx = Application('buildmaster')\nbar") self.assertTrue(base.isBuildmasterDir(os.path.abspath('test'))) self.assertWasQuiet() class TestTacFallback(dirs.DirsMixin, unittest.TestCase): """ Tests for L{base.getConfigFileFromTac}. """ def setUp(self): """ Create a base directory. """ self.basedir = os.path.abspath('basedir') return self.setUpDirs('basedir') def _createBuildbotTac(self, contents=None): """ Create a C{buildbot.tac} that points to a given C{configfile} and create that file. @param configfile: Config file to point at and create. @type configfile: L{str} """ if contents is None: contents = '#dummy' tacfile = os.path.join(self.basedir, "buildbot.tac") with open(tacfile, "w", encoding='utf-8') as f: f.write(contents) return tacfile def test_getConfigFileFromTac(self): """ When L{getConfigFileFromTac} is passed a C{basedir} containing a C{buildbot.tac}, it reads the location of the config file from there. """ self._createBuildbotTac("configfile='other.cfg'") foundConfigFile = base.getConfigFileFromTac(basedir=self.basedir) self.assertEqual(foundConfigFile, "other.cfg") def test_getConfigFileFromTac_fallback(self): """ When L{getConfigFileFromTac} is passed a C{basedir} which doesn't contain a C{buildbot.tac}, it returns C{master.cfg} """ foundConfigFile = base.getConfigFileFromTac(basedir=self.basedir) self.assertEqual(foundConfigFile, 'master.cfg') def test_getConfigFileFromTac_tacWithoutConfigFile(self): """ When L{getConfigFileFromTac} is passed a C{basedir} containing a C{buildbot.tac}, but C{buildbot.tac} doesn't define C{configfile}, L{getConfigFileFromTac} returns C{master.cfg} """ self._createBuildbotTac() foundConfigFile = base.getConfigFileFromTac(basedir=self.basedir) self.assertEqual(foundConfigFile, 'master.cfg') def test_getConfigFileFromTac_usingFile(self): """ When L{getConfigFileFromTac} is passed a C{basedir} containing a C{buildbot.tac} which references C{__file__}, that reference points to C{buildbot.tac}. """ self._createBuildbotTac( textwrap.dedent(""" from twisted.python.util import sibpath configfile = sibpath(__file__, "relative.cfg") """) ) foundConfigFile = base.getConfigFileFromTac(basedir=self.basedir) self.assertEqual(foundConfigFile, os.path.join(self.basedir, "relative.cfg")) class TestSubcommandOptions(unittest.TestCase): def fakeOptionsFile(self, **kwargs): self.patch(base.SubcommandOptions, 'loadOptionsFile', lambda self: kwargs.copy()) def parse(self, cls, *args): self.opts = cls() self.opts.parseOptions(args) return self.opts class Bare(base.SubcommandOptions): optFlags = [['foo', 'f', 'Foo!']] def test_bare_subclass(self): self.fakeOptionsFile() opts = self.parse(self.Bare, '-f') self.assertTrue(opts['foo']) class ParamsAndOptions(base.SubcommandOptions): optParameters = [['volume', 'v', '5', 'How Loud?']] buildbotOptions = [['volcfg', 'volume']] def test_buildbotOptions(self): self.fakeOptionsFile() opts = self.parse(self.ParamsAndOptions) self.assertEqual(opts['volume'], '5') def test_buildbotOptions_options(self): self.fakeOptionsFile(volcfg='3') opts = self.parse(self.ParamsAndOptions) self.assertEqual(opts['volume'], '3') def test_buildbotOptions_override(self): self.fakeOptionsFile(volcfg='3') opts = self.parse(self.ParamsAndOptions, '--volume', '7') self.assertEqual(opts['volume'], '7') class RequiredOptions(base.SubcommandOptions): optParameters = [['volume', 'v', None, 'How Loud?']] requiredOptions = ['volume'] def test_requiredOptions(self): self.fakeOptionsFile() with self.assertRaises(usage.UsageError): self.parse(self.RequiredOptions) class TestLoadOptionsFile(dirs.DirsMixin, misc.StdoutAssertionsMixin, unittest.TestCase): def setUp(self): self.setUpDirs('test', 'home') self.opts = base.SubcommandOptions() self.dir = os.path.abspath('test') self.home = os.path.abspath('home') self.setUpStdoutAssertions() def tearDown(self): self.tearDownDirs() def do_loadOptionsFile(self, _here, exp): # only patch these os.path functions briefly, to # avoid breaking other parts of the test system patches = [] if runtime.platformType == 'win32': from win32com.shell import shell patches.append(self.patch(shell, 'SHGetFolderPath', lambda *args: self.home)) else: def expanduser(p): return p.replace('~/', self.home + '/') patches.append(self.patch(os.path, 'expanduser', expanduser)) old_dirname = os.path.dirname def dirname(p): # bottom out at self.dir, rather than / if p == self.dir: return p return old_dirname(p) patches.append(self.patch(os.path, 'dirname', dirname)) try: self.assertEqual(self.opts.loadOptionsFile(_here=_here), exp) finally: for p in patches: p.restore() def writeOptionsFile(self, dir, content, bbdir='.buildbot'): os.makedirs(os.path.join(dir, bbdir)) with open(os.path.join(dir, bbdir, 'options'), 'w', encoding='utf-8') as f: f.write(content) def test_loadOptionsFile_subdirs_not_found(self): subdir = os.path.join(self.dir, 'a', 'b') os.makedirs(subdir) self.do_loadOptionsFile(_here=subdir, exp={}) def test_loadOptionsFile_subdirs_at_root(self): subdir = os.path.join(self.dir, 'a', 'b') os.makedirs(subdir) self.writeOptionsFile(self.dir, 'abc="def"') self.writeOptionsFile(self.home, 'abc=123') # not seen self.do_loadOptionsFile(_here=subdir, exp={'abc': 'def'}) def test_loadOptionsFile_subdirs_at_tip(self): subdir = os.path.join(self.dir, 'a', 'b') os.makedirs(subdir) self.writeOptionsFile(os.path.join(self.dir, 'a', 'b'), 'abc="def"') self.writeOptionsFile(self.dir, 'abc=123') # not seen self.do_loadOptionsFile(_here=subdir, exp={'abc': 'def'}) def test_loadOptionsFile_subdirs_at_homedir(self): subdir = os.path.join(self.dir, 'a', 'b') os.makedirs(subdir) # on windows, the subdir of the home (well, appdata) dir # is 'buildbot', not '.buildbot' self.writeOptionsFile( self.home, 'abc=123', 'buildbot' if runtime.platformType == 'win32' else '.buildbot' ) self.do_loadOptionsFile(_here=subdir, exp={'abc': 123}) def test_loadOptionsFile_syntax_error(self): self.writeOptionsFile(self.dir, 'abc=abc') with self.assertRaises(NameError): self.do_loadOptionsFile(_here=self.dir, exp={}) self.assertInStdout('error while reading') def test_loadOptionsFile_toomany(self): subdir = os.path.join(self.dir, *tuple(string.ascii_lowercase)) os.makedirs(subdir) self.do_loadOptionsFile(_here=subdir, exp={}) self.assertInStdout('infinite glories') # NOTE: testing the ownership check requires patching os.stat, which causes # other problems since it is so heavily used. def mkconfig(**kwargs): config = {"quiet": False, "replace": False, "basedir": 'test'} config.update(kwargs) return config class TestLoadConfig(dirs.DirsMixin, misc.StdoutAssertionsMixin, unittest.TestCase): def setUp(self): self.setUpDirs('test') self.setUpStdoutAssertions() def tearDown(self): self.tearDownDirs() def activeBasedir(self, extra_lines=()): with open(os.path.join('test', 'buildbot.tac'), "w", encoding='utf-8') as f: f.write("from twisted.application import service\n") f.write("service.Application('buildmaster')\n") f.write("\n".join(extra_lines)) def test_checkBasedir(self): self.activeBasedir() rv = base.checkBasedir(mkconfig()) self.assertTrue(rv) self.assertInStdout('checking basedir') def test_checkBasedir_quiet(self): self.activeBasedir() rv = base.checkBasedir(mkconfig(quiet=True)) self.assertTrue(rv) self.assertWasQuiet() def test_checkBasedir_no_dir(self): rv = base.checkBasedir(mkconfig(basedir='doesntexist')) self.assertFalse(rv) self.assertInStdout('invalid buildmaster directory') @skipUnlessPlatformIs('posix') def test_checkBasedir_active_pidfile(self): """ active PID file is giving error. """ self.activeBasedir() # write our own pid in the file with open(os.path.join('test', 'twistd.pid'), 'w', encoding='utf-8') as f: f.write(str(os.getpid())) rv = base.checkBasedir(mkconfig()) self.assertFalse(rv) self.assertInStdout('still running') @skipUnlessPlatformIs('posix') def test_checkBasedir_bad_pidfile(self): """ corrupted PID file is giving error. """ self.activeBasedir() with open(os.path.join('test', 'twistd.pid'), 'w', encoding='utf-8') as f: f.write("xxx") rv = base.checkBasedir(mkconfig()) self.assertFalse(rv) self.assertInStdout('twistd.pid contains non-numeric value') @skipUnlessPlatformIs('posix') def test_checkBasedir_stale_pidfile(self): """ Stale PID file is removed without causing a system exit. """ self.activeBasedir() pidfile = os.path.join('test', 'twistd.pid') with open(pidfile, 'w', encoding='utf-8') as f: f.write(str(os.getpid() + 1)) def kill(pid, sig): raise OSError(errno.ESRCH, "fake") self.patch(os, "kill", kill) rv = base.checkBasedir(mkconfig()) self.assertTrue(rv) self.assertInStdout('Removing stale pidfile test') self.assertFalse(os.path.exists(pidfile)) @skipUnlessPlatformIs('posix') def test_checkBasedir_pidfile_kill_error(self): """ if ping-killing the PID file does not work, we should error out. """ self.activeBasedir() # write our own pid in the file pidfile = os.path.join('test', 'twistd.pid') with open(pidfile, 'w', encoding='utf-8') as f: f.write(str(os.getpid() + 1)) def kill(pid, sig): raise OSError(errno.EPERM, "fake") self.patch(os, "kill", kill) rv = base.checkBasedir(mkconfig()) self.assertFalse(rv) self.assertInStdout('Can\'t check status of PID') self.assertTrue(os.path.exists(pidfile)) def test_checkBasedir_invalid_rotateLength(self): self.activeBasedir(extra_lines=['rotateLength="32"']) rv = base.checkBasedir(mkconfig()) self.assertFalse(rv) self.assertInStdout('ERROR') self.assertInStdout('rotateLength') def test_checkBasedir_invalid_maxRotatedFiles(self): self.activeBasedir(extra_lines=['maxRotatedFiles="64"']) rv = base.checkBasedir(mkconfig()) self.assertFalse(rv) self.assertInStdout('ERROR') self.assertInStdout('maxRotatedFiles') def test_loadConfig(self): @classmethod def loadConfig(cls): return config_master.MasterConfig() self.patch(config_master.FileLoader, 'loadConfig', loadConfig) cfg = base.loadConfig(mkconfig()) self.assertIsInstance(cfg, config_master.MasterConfig) self.assertInStdout('checking') def test_loadConfig_ConfigErrors(self): @classmethod def loadConfig(cls): raise config_master.ConfigErrors(['oh noes']) self.patch(config_master.FileLoader, 'loadConfig', loadConfig) cfg = base.loadConfig(mkconfig()) self.assertIdentical(cfg, None) self.assertInStdout('oh noes') def test_loadConfig_exception(self): @classmethod def loadConfig(cls): raise RuntimeError() self.patch(config_master.FileLoader, 'loadConfig', loadConfig) cfg = base.loadConfig(mkconfig()) self.assertIdentical(cfg, None) self.assertInStdout('RuntimeError')
15,181
Python
.py
344
35.90407
96
0.656303
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,577
test_restart.py
buildbot_buildbot/master/buildbot/test/unit/scripts/test_restart.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.trial import unittest from buildbot.scripts import restart from buildbot.scripts import start from buildbot.scripts import stop from buildbot.test.util import dirs from buildbot.test.util import misc def mkconfig(**kwargs): config = {"quiet": False, "basedir": os.path.abspath('basedir')} config.update(kwargs) return config class TestStop(misc.StdoutAssertionsMixin, dirs.DirsMixin, unittest.TestCase): def setUp(self): self.setUpDirs('basedir') with open(os.path.join('basedir', 'buildbot.tac'), "w", encoding='utf-8') as f: f.write("Application('buildmaster')") self.setUpStdoutAssertions() def tearDown(self): self.tearDownDirs() # tests def test_restart_not_basedir(self): self.assertEqual(restart.restart(mkconfig(basedir='doesntexist')), 1) self.assertInStdout('invalid buildmaster directory') def test_restart_stop_fails(self): self.patch(stop, 'stop', lambda config, wait: 1) self.assertEqual(restart.restart(mkconfig()), 1) def test_restart_stop_succeeds_start_fails(self): self.patch(stop, 'stop', lambda config, wait: 0) self.patch(start, 'start', lambda config: 1) self.assertEqual(restart.restart(mkconfig()), 1) def test_restart_succeeds(self): self.patch(stop, 'stop', lambda config, wait: 0) self.patch(start, 'start', lambda config: 0) self.assertEqual(restart.restart(mkconfig()), 0) self.assertInStdout('now restarting') def test_restart_succeeds_quiet(self): self.patch(stop, 'stop', lambda config, wait: 0) self.patch(start, 'start', lambda config: 0) self.assertEqual(restart.restart(mkconfig(quiet=True)), 0) self.assertWasQuiet() def test_restart_clean(self): self.patch(stop, 'stop', lambda config, wait: 0) self.patch(start, 'start', lambda config: 0) self.assertEqual(restart.restart(mkconfig(quiet=True, clean=True)), 0) self.assertWasQuiet()
2,759
Python
.py
59
41.372881
87
0.715829
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,578
test_create_master.py
buildbot_buildbot/master/buildbot/test/unit/scripts/test_create_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 from unittest import mock from twisted.internet import defer from twisted.trial import unittest from buildbot.db import connector from buildbot.db import model from buildbot.scripts import create_master from buildbot.test.reactor import TestReactorMixin from buildbot.test.util import dirs from buildbot.test.util import misc from buildbot.test.util import www def mkconfig(**kwargs): config = { "force": False, "relocatable": False, "config": 'master.cfg', "db": 'sqlite:///state.sqlite', "basedir": os.path.abspath('basedir'), "quiet": False, **{'no-logrotate': False, 'log-size': 10000000, 'log-count': 10}, } config.update(kwargs) return config class TestCreateMaster(misc.StdoutAssertionsMixin, unittest.TestCase): def setUp(self): # createMaster is decorated with @in_reactor, so strip that decoration # since the master is already running self.patch(create_master, 'createMaster', create_master.createMaster._orig) self.setUpStdoutAssertions() # tests @defer.inlineCallbacks def do_test_createMaster(self, config): # mock out everything that createMaster calls, then check that # they are called, in order functions = ['makeBasedir', 'makeTAC', 'makeSampleConfig', 'createDB'] repls = {} calls = [] for fn in functions: repl = repls[fn] = mock.Mock(name=fn) repl.side_effect = lambda config, fn=fn: calls.append(fn) self.patch(create_master, fn, repl) repls['createDB'].side_effect = lambda config: calls.append(fn) or defer.succeed(None) rc = yield create_master.createMaster(config) self.assertEqual(rc, 0) self.assertEqual(calls, functions) for repl in repls.values(): repl.assert_called_with(config) @defer.inlineCallbacks def test_createMaster_quiet(self): yield self.do_test_createMaster(mkconfig(quiet=True)) self.assertWasQuiet() @defer.inlineCallbacks def test_createMaster_loud(self): yield self.do_test_createMaster(mkconfig(quiet=False)) self.assertInStdout('buildmaster configured in') class TestCreateMasterFunctions( www.WwwTestMixin, dirs.DirsMixin, misc.StdoutAssertionsMixin, TestReactorMixin, unittest.TestCase, ): def setUp(self): self.setup_test_reactor(auto_tear_down=False) self.setUpDirs('test') self.basedir = os.path.abspath(os.path.join('test', 'basedir')) self.setUpStdoutAssertions() @defer.inlineCallbacks def tearDown(self): self.tearDownDirs() yield self.tear_down_test_reactor() def assertInTacFile(self, str): with open(os.path.join('test', 'buildbot.tac'), encoding='utf-8') as f: content = f.read() self.assertIn(str, content) def assertNotInTacFile(self, str): with open(os.path.join('test', 'buildbot.tac'), encoding='utf-8') as f: content = f.read() self.assertNotIn(str, content) def assertDBSetup(self, basedir=None, db_url='sqlite:///state.sqlite', verbose=True): # mock out the database setup self.db = mock.Mock() self.db.setup.side_effect = lambda *a, **k: defer.succeed(None) self.DBConnector = mock.Mock() self.DBConnector.return_value = self.db self.patch(connector, 'DBConnector', self.DBConnector) basedir = basedir or self.basedir # pylint: disable=unsubscriptable-object self.assertEqual( { "basedir": self.DBConnector.call_args[0][1], "db_url": self.DBConnector.call_args[0][0].mkconfig.db['db_url'], "verbose": self.db.setup.call_args[1]['verbose'], "check_version": self.db.setup.call_args[1]['check_version'], }, {"basedir": self.basedir, "db_url": db_url, "verbose": True, "check_version": False}, ) # tests def test_makeBasedir(self): self.assertFalse(os.path.exists(self.basedir)) create_master.makeBasedir(mkconfig(basedir=self.basedir)) self.assertTrue(os.path.exists(self.basedir)) self.assertInStdout(f'mkdir {self.basedir}') def test_makeBasedir_quiet(self): self.assertFalse(os.path.exists(self.basedir)) create_master.makeBasedir(mkconfig(basedir=self.basedir, quiet=True)) self.assertTrue(os.path.exists(self.basedir)) self.assertWasQuiet() def test_makeBasedir_existing(self): os.mkdir(self.basedir) create_master.makeBasedir(mkconfig(basedir=self.basedir)) self.assertInStdout('updating existing installation') def test_makeTAC(self): create_master.makeTAC(mkconfig(basedir='test')) self.assertInTacFile("Application('buildmaster')") self.assertWasQuiet() def test_makeTAC_relocatable(self): create_master.makeTAC(mkconfig(basedir='test', relocatable=True)) self.assertInTacFile("basedir = '.'") # repr() prefers '' self.assertWasQuiet() def test_makeTAC_no_logrotate(self): create_master.makeTAC(mkconfig(basedir='test', **{'no-logrotate': True})) self.assertNotInTacFile("import Log") self.assertWasQuiet() def test_makeTAC_int_log_count(self): create_master.makeTAC(mkconfig(basedir='test', **{'log-count': 30})) self.assertInTacFile("\nmaxRotatedFiles = 30\n") self.assertWasQuiet() def test_makeTAC_str_log_count(self): with self.assertRaises(TypeError): create_master.makeTAC(mkconfig(basedir='test', **{'log-count': '30'})) def test_makeTAC_none_log_count(self): create_master.makeTAC(mkconfig(basedir='test', **{'log-count': None})) self.assertInTacFile("\nmaxRotatedFiles = None\n") self.assertWasQuiet() def test_makeTAC_int_log_size(self): create_master.makeTAC(mkconfig(basedir='test', **{'log-size': 3000})) self.assertInTacFile("\nrotateLength = 3000\n") self.assertWasQuiet() def test_makeTAC_str_log_size(self): with self.assertRaises(TypeError): create_master.makeTAC(mkconfig(basedir='test', **{'log-size': '3000'})) def test_makeTAC_existing_incorrect(self): with open(os.path.join('test', 'buildbot.tac'), "w", encoding='utf-8') as f: f.write('WRONG') create_master.makeTAC(mkconfig(basedir='test')) self.assertInTacFile("WRONG") self.assertTrue(os.path.exists(os.path.join('test', 'buildbot.tac.new'))) self.assertInStdout('not touching existing buildbot.tac') def test_makeTAC_existing_incorrect_quiet(self): with open(os.path.join('test', 'buildbot.tac'), "w", encoding='utf-8') as f: f.write('WRONG') create_master.makeTAC(mkconfig(basedir='test', quiet=True)) self.assertInTacFile("WRONG") self.assertWasQuiet() def test_makeTAC_existing_correct(self): create_master.makeTAC(mkconfig(basedir='test', quiet=True)) create_master.makeTAC(mkconfig(basedir='test')) self.assertFalse(os.path.exists(os.path.join('test', 'buildbot.tac.new'))) self.assertInStdout('and is correct') def test_makeSampleConfig(self): create_master.makeSampleConfig(mkconfig(basedir='test')) self.assertTrue(os.path.exists(os.path.join('test', 'master.cfg.sample'))) self.assertInStdout('creating ') def test_makeSampleConfig_db(self): create_master.makeSampleConfig(mkconfig(basedir='test', db='XXYYZZ', quiet=True)) with open(os.path.join('test', 'master.cfg.sample'), encoding='utf-8') as f: self.assertIn("XXYYZZ", f.read()) self.assertWasQuiet() @defer.inlineCallbacks def test_createDB(self): setup = mock.Mock(side_effect=lambda **kwargs: defer.succeed(None)) self.patch(connector.DBConnector, 'setup', setup) upgrade = mock.Mock(side_effect=lambda **kwargs: defer.succeed(None)) self.patch(model.Model, 'upgrade', upgrade) yield create_master.createDB(mkconfig(basedir='test', quiet=True)) setup.asset_called_with(check_version=False, verbose=False) upgrade.assert_called_with() self.assertWasQuiet()
9,069
Python
.py
193
39.404145
97
0.675908
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,579
test_runner.py
buildbot_buildbot/master/buildbot/test/unit/scripts/test_runner.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 getpass import os import sys from io import StringIO from unittest import mock from twisted.python import log from twisted.python import runtime from twisted.python import usage from twisted.trial import unittest from buildbot.scripts import base from buildbot.scripts import runner from buildbot.test.util import misc class OptionsMixin: def setUpOptions(self): self.options_file = {} self.patch(base.SubcommandOptions, 'loadOptionsFile', lambda other_self: self.options_file) def assertOptions(self, opts, exp): got = {k: opts[k] for k in exp} if got != exp: msg = [] for k in exp: if opts[k] != exp[k]: msg.append(f" {k}: expected {exp[k]!r}, got {opts[k]!r}") self.fail("did not get expected options\n" + ("\n".join(msg))) class TestUpgradeMasterOptions(OptionsMixin, unittest.TestCase): def setUp(self): self.setUpOptions() def parse(self, *args): self.opts = runner.UpgradeMasterOptions() self.opts.parseOptions(args) return self.opts def test_synopsis(self): opts = runner.UpgradeMasterOptions() self.assertIn('buildbot upgrade-master', opts.getSynopsis()) def test_defaults(self): opts = self.parse() exp = {"quiet": False, "replace": False} self.assertOptions(opts, exp) def test_short(self): opts = self.parse('-q', '-r') exp = {"quiet": True, "replace": True} self.assertOptions(opts, exp) def test_long(self): opts = self.parse('--quiet', '--replace') exp = {"quiet": True, "replace": True} self.assertOptions(opts, exp) class TestCreateMasterOptions(OptionsMixin, unittest.TestCase): def setUp(self): self.setUpOptions() def parse(self, *args): self.opts = runner.CreateMasterOptions() self.opts.parseOptions(args) return self.opts def defaults_and(self, **kwargs): defaults = { "force": False, "relocatable": False, "config": 'master.cfg', "db": 'sqlite:///state.sqlite', "basedir": os.getcwd(), "quiet": False, **{'no-logrotate': False, 'log-size': 10000000, 'log-count': 10}, } unk_keys = set(kwargs.keys()) - set(defaults.keys()) assert not unk_keys, f"invalid keys {unk_keys}" opts = defaults.copy() opts.update(kwargs) return opts def test_synopsis(self): opts = runner.CreateMasterOptions() self.assertIn('buildbot create-master', opts.getSynopsis()) def test_defaults(self): opts = self.parse() exp = self.defaults_and() self.assertOptions(opts, exp) def test_db_quiet(self): opts = self.parse('-q') exp = self.defaults_and(quiet=True) self.assertOptions(opts, exp) def test_db_quiet_long(self): opts = self.parse('--quiet') exp = self.defaults_and(quiet=True) self.assertOptions(opts, exp) def test_force(self): opts = self.parse('-f') exp = self.defaults_and(force=True) self.assertOptions(opts, exp) def test_force_long(self): opts = self.parse('--force') exp = self.defaults_and(force=True) self.assertOptions(opts, exp) def test_relocatable(self): opts = self.parse('-r') exp = self.defaults_and(relocatable=True) self.assertOptions(opts, exp) def test_relocatable_long(self): opts = self.parse('--relocatable') exp = self.defaults_and(relocatable=True) self.assertOptions(opts, exp) def test_no_logrotate(self): opts = self.parse('-n') exp = self.defaults_and(**{'no-logrotate': True}) self.assertOptions(opts, exp) def test_no_logrotate_long(self): opts = self.parse('--no-logrotate') exp = self.defaults_and(**{'no-logrotate': True}) self.assertOptions(opts, exp) def test_config(self): opts = self.parse('-cxyz') exp = self.defaults_and(config='xyz') self.assertOptions(opts, exp) def test_config_long(self): opts = self.parse('--config=xyz') exp = self.defaults_and(config='xyz') self.assertOptions(opts, exp) def test_log_size(self): opts = self.parse('-s124') exp = self.defaults_and(**{'log-size': 124}) self.assertOptions(opts, exp) def test_log_size_long(self): opts = self.parse('--log-size=124') exp = self.defaults_and(**{'log-size': 124}) self.assertOptions(opts, exp) def test_log_size_noninteger(self): with self.assertRaises(usage.UsageError): self.parse('--log-size=1M') def test_log_count(self): opts = self.parse('-l124') exp = self.defaults_and(**{'log-count': 124}) self.assertOptions(opts, exp) def test_log_count_long(self): opts = self.parse('--log-count=124') exp = self.defaults_and(**{'log-count': 124}) self.assertOptions(opts, exp) def test_log_count_none(self): opts = self.parse('--log-count=None') exp = self.defaults_and(**{'log-count': None}) self.assertOptions(opts, exp) def test_log_count_noninteger(self): with self.assertRaises(usage.UsageError): self.parse('--log-count=M') def test_db_long(self): opts = self.parse('--db=foo://bar') exp = self.defaults_and(db='foo://bar') self.assertOptions(opts, exp) def test_db_invalid(self): with self.assertRaisesRegex(usage.UsageError, "could not parse database URL 'inv_db_url'"): self.parse("--db=inv_db_url") def test_db_basedir(self): path = r'c:\foo\bar' if runtime.platformType == "win32" else '/foo/bar' opts = self.parse('-f', path) exp = self.defaults_and(force=True, basedir=path) self.assertOptions(opts, exp) class BaseTestSimpleOptions(OptionsMixin): # tests for options with just --quiet and a usage message commandName: str | None = None optionsClass: type[usage.Options] | None = None def setUp(self): self.setUpOptions() def parse(self, *args): self.opts = self.optionsClass() self.opts.parseOptions(args) return self.opts def test_synopsis(self): opts = self.optionsClass() self.assertIn(f'buildbot {self.commandName}', opts.getSynopsis()) def test_defaults(self): opts = self.parse() exp = {"quiet": False} self.assertOptions(opts, exp) def test_quiet(self): opts = self.parse('--quiet') exp = {"quiet": True} self.assertOptions(opts, exp) class TestStopOptions(BaseTestSimpleOptions, unittest.TestCase): commandName = 'stop' optionsClass = runner.StopOptions class TestResetartOptions(BaseTestSimpleOptions, unittest.TestCase): commandName = 'restart' optionsClass = runner.RestartOptions def test_nodaemon(self): opts = self.parse('--nodaemon') exp = {"nodaemon": True} self.assertOptions(opts, exp) class TestStartOptions(BaseTestSimpleOptions, unittest.TestCase): commandName = 'start' optionsClass = runner.StartOptions def test_nodaemon(self): opts = self.parse('--nodaemon') exp = {"nodaemon": True} self.assertOptions(opts, exp) class TestReconfigOptions(BaseTestSimpleOptions, unittest.TestCase): commandName = 'reconfig' optionsClass = runner.ReconfigOptions class TestTryOptions(OptionsMixin, unittest.TestCase): def setUp(self): self.setUpOptions() def parse(self, *args): self.opts = runner.TryOptions() self.opts.parseOptions(args) return self.opts def defaults_and(self, **kwargs): defaults = { "connect": None, "host": None, "jobdir": None, "username": None, "master": None, "passwd": None, "who": None, "comment": None, "diff": None, "patchlevel": 0, "baserev": None, "vc": None, "branch": None, "repository": None, "topfile": None, "topdir": None, "wait": False, "dryrun": False, "quiet": False, "builders": [], "properties": {}, "buildbotbin": 'buildbot', } # dashes make python syntax hard.. defaults['get-builder-names'] = False if 'get_builder_names' in kwargs: kwargs['get-builder-names'] = kwargs['get_builder_names'] del kwargs['get_builder_names'] assert set(kwargs.keys()) <= set(defaults.keys()), "invalid keys" opts = defaults.copy() opts.update(kwargs) return opts def test_synopsis(self): opts = runner.TryOptions() self.assertIn('buildbot try', opts.getSynopsis()) def test_defaults(self): opts = self.parse() exp = self.defaults_and() self.assertOptions(opts, exp) def test_properties(self): opts = self.parse('--properties=a=b') exp = self.defaults_and(properties={"a": 'b'}) self.assertOptions(opts, exp) def test_properties_multiple_opts(self): opts = self.parse('--properties=X=1', '--properties=Y=2') exp = self.defaults_and(properties={"X": '1', "Y": '2'}) self.assertOptions(opts, exp) def test_properties_equals(self): opts = self.parse('--properties=X=2+2=4') exp = self.defaults_and(properties={"X": '2+2=4'}) self.assertOptions(opts, exp) def test_properties_commas(self): opts = self.parse('--properties=a=b,c=d') exp = self.defaults_and(properties={"a": 'b', "c": 'd'}) self.assertOptions(opts, exp) def test_property(self): opts = self.parse('--property=a=b') exp = self.defaults_and(properties={"a": 'b'}) self.assertOptions(opts, exp) def test_property_multiple_opts(self): opts = self.parse('--property=X=1', '--property=Y=2') exp = self.defaults_and(properties={"X": '1', "Y": '2'}) self.assertOptions(opts, exp) def test_property_equals(self): opts = self.parse('--property=X=2+2=4') exp = self.defaults_and(properties={"X": '2+2=4'}) self.assertOptions(opts, exp) def test_property_commas(self): opts = self.parse('--property=a=b,c=d') exp = self.defaults_and(properties={"a": 'b,c=d'}) self.assertOptions(opts, exp) def test_property_and_properties(self): opts = self.parse('--property=X=1', '--properties=Y=2') exp = self.defaults_and(properties={"X": '1', "Y": '2'}) self.assertOptions(opts, exp) def test_properties_builders_multiple(self): opts = self.parse('--builder=aa', '--builder=bb') exp = self.defaults_and(builders=['aa', 'bb']) self.assertOptions(opts, exp) def test_options_short(self): opts = self.parse(*'-n -q -c pb -u me -m mr:7 -w you -C comm -p 2 -b bb'.split()) exp = self.defaults_and( dryrun=True, quiet=True, connect='pb', username='me', master='mr:7', who='you', comment='comm', patchlevel=2, builders=['bb'], ) self.assertOptions(opts, exp) def test_options_long(self): opts = self.parse( *"""--wait --dryrun --get-builder-names --quiet --connect=pb --host=h --jobdir=j --username=u --master=m:1234 --passwd=p --who=w --comment=comm --diff=d --patchlevel=7 --baserev=br --vc=cvs --branch=br --repository=rep --builder=bl --properties=a=b --topfile=Makefile --topdir=. --buildbotbin=.virtualenvs/buildbot/bin/buildbot""".split() ) exp = self.defaults_and( wait=True, dryrun=True, get_builder_names=True, quiet=True, connect='pb', host='h', jobdir='j', username='u', master='m:1234', passwd='p', who='w', comment='comm', diff='d', patchlevel=7, baserev='br', vc='cvs', branch='br', repository='rep', builders=['bl'], properties={"a": 'b'}, topfile='Makefile', topdir='.', buildbotbin='.virtualenvs/buildbot/bin/buildbot', ) self.assertOptions(opts, exp) def test_patchlevel_inval(self): with self.assertRaises(ValueError): self.parse('-p', 'a') def test_config_builders(self): self.options_file['try_builders'] = ['a', 'b'] opts = self.parse() self.assertOptions(opts, {"builders": ['a', 'b']}) def test_config_builders_override(self): self.options_file['try_builders'] = ['a', 'b'] opts = self.parse('-b', 'd') # overrides a, b self.assertOptions(opts, {"builders": ['d']}) def test_config_old_names(self): self.options_file['try_masterstatus'] = 'ms' self.options_file['try_dir'] = 'td' self.options_file['try_password'] = 'pw' opts = self.parse() self.assertOptions(opts, {"master": 'ms', "jobdir": 'td', "passwd": 'pw'}) def test_config_masterstatus(self): self.options_file['masterstatus'] = 'ms' opts = self.parse() self.assertOptions(opts, {"master": 'ms'}) def test_config_masterstatus_override(self): self.options_file['masterstatus'] = 'ms' opts = self.parse('-m', 'mm') self.assertOptions(opts, {"master": 'mm'}) def test_config_options(self): self.options_file.update({ "try_connect": 'pb', "try_vc": 'cvs', "try_branch": 'br', "try_repository": 'rep', "try_topdir": '.', "try_topfile": 'Makefile', "try_host": 'h', "try_username": 'u', "try_jobdir": 'j', "try_password": 'p', "try_master": 'm:8', "try_who": 'w', "try_comment": 'comm', "try_quiet": 'y', "try_wait": 'y', "try_buildbotbin": '.virtualenvs/buildbot/bin/buildbot', }) opts = self.parse() exp = self.defaults_and( wait=True, quiet=True, connect='pb', host='h', jobdir='j', username='u', master='m:8', passwd='p', who='w', comment='comm', vc='cvs', branch='br', repository='rep', topfile='Makefile', topdir='.', buildbotbin='.virtualenvs/buildbot/bin/buildbot', ) self.assertOptions(opts, exp) def test_pb_withNoMaster(self): """ When 'builbot try' is asked to connect via pb, but no master is specified, a usage error is raised. """ with self.assertRaises(usage.UsageError): self.parse('--connect=pb') def test_pb_withInvalidMaster(self): """ When 'buildbot try' is asked to connect via pb, but an invalid master is specified, a usage error is raised. """ with self.assertRaises(usage.UsageError): self.parse('--connect=pb', '--master=foo') class TestSendChangeOptions(OptionsMixin, unittest.TestCase): master_and_who = ['-m', 'm:1', '-W', 'w'] def setUp(self): self.setUpOptions() self.getpass_response = 'typed-password' self.patch(getpass, 'getpass', lambda prompt: self.getpass_response) def parse(self, *args): self.opts = runner.SendChangeOptions() self.opts.parseOptions(args) return self.opts def test_synopsis(self): opts = runner.SendChangeOptions() self.assertIn('buildbot sendchange', opts.getSynopsis()) def test_defaults(self): opts = self.parse('-m', 'm:1', '-W', 'me') exp = { "master": 'm:1', "auth": ('change', 'changepw'), "who": 'me', "vc": None, "repository": '', "project": '', "branch": None, "category": None, "revision": None, "revision_file": None, "property": None, "comments": '', "logfile": None, "when": None, "revlink": '', "encoding": 'utf8', "files": (), } self.assertOptions(opts, exp) def test_files(self): opts = self.parse(*[*self.master_and_who, 'a', 'b', 'c']) self.assertEqual(opts['files'], ('a', 'b', 'c')) def test_properties(self): opts = self.parse('--property', 'x:y', '--property', 'a:b', *self.master_and_who) self.assertEqual(opts['properties'], {"x": 'y', "a": 'b'}) def test_properties_with_colon(self): opts = self.parse('--property', 'x:http://foo', *self.master_and_who) self.assertEqual(opts['properties'], {"x": 'http://foo'}) def test_config_file(self): self.options_file['master'] = 'MMM:123' self.options_file['who'] = 'WWW' self.options_file['branch'] = 'BBB' self.options_file['category'] = 'CCC' self.options_file['vc'] = 'svn' opts = self.parse() exp = {"master": 'MMM:123', "who": 'WWW', "branch": 'BBB', "category": 'CCC', "vc": 'svn'} self.assertOptions(opts, exp) def test_short_args(self): opts = self.parse( *( '-m m:1 -a a:b -W W -R r -P p -b b -s git ' + '-C c -r r -p pn:pv -c c -F f -w 123 -l l -e e' ).split() ) exp = { "master": 'm:1', "auth": ('a', 'b'), "who": 'W', "repository": 'r', "project": 'p', "branch": 'b', "category": 'c', "revision": 'r', "vc": 'git', "properties": {"pn": 'pv'}, "comments": 'c', "logfile": 'f', "when": 123.0, "revlink": 'l', "encoding": 'e', } self.assertOptions(opts, exp) def test_long_args(self): opts = self.parse( *( '--master m:1 --auth a:b --who w --repository r ' + '--project p --branch b --category c --revision r --vc git ' + '--property pn:pv --comments c --logfile f ' + '--when 123 --revlink l --encoding e' ).split() ) exp = { "master": 'm:1', "auth": ('a', 'b'), "who": 'w', "repository": 'r', "project": 'p', "branch": 'b', "category": 'c', "revision": 'r', "vc": 'git', "properties": {"pn": 'pv'}, "comments": 'c', "logfile": 'f', "when": 123.0, "revlink": 'l', "encoding": 'e', } self.assertOptions(opts, exp) def test_revision_file(self): with open('revfile', "w", encoding='utf-8') as f: f.write('my-rev') self.addCleanup(lambda: os.unlink('revfile')) opts = self.parse('--revision_file', 'revfile', *self.master_and_who) self.assertOptions(opts, {"revision": 'my-rev'}) def test_invalid_when(self): with self.assertRaises(usage.UsageError): self.parse('--when=foo', *self.master_and_who) def test_comments_overrides_logfile(self): opts = self.parse('--logfile', 'logs', '--comments', 'foo', *self.master_and_who) self.assertOptions(opts, {"comments": 'foo'}) def test_logfile(self): with open('comments', "w", encoding='utf-8') as f: f.write('hi') self.addCleanup(lambda: os.unlink('comments')) opts = self.parse('--logfile', 'comments', *self.master_and_who) self.assertOptions(opts, {"comments": 'hi'}) def test_logfile_stdin(self): stdin = mock.Mock() stdin.read = lambda: 'hi' self.patch(sys, 'stdin', stdin) opts = self.parse('--logfile', '-', *self.master_and_who) self.assertOptions(opts, {"comments": 'hi'}) def test_auth_getpass(self): opts = self.parse('--auth=dustin', *self.master_and_who) self.assertOptions(opts, {"auth": ('dustin', 'typed-password')}) def test_invalid_vcs(self): with self.assertRaises(usage.UsageError): self.parse('--vc=foo', *self.master_and_who) def test_invalid_master(self): with self.assertRaises(usage.UsageError): self.parse("--who=test", "-m foo") class TestTryServerOptions(OptionsMixin, unittest.TestCase): def setUp(self): self.setUpOptions() def parse(self, *args): self.opts = runner.TryServerOptions() self.opts.parseOptions(args) return self.opts def test_synopsis(self): opts = runner.TryServerOptions() self.assertIn('buildbot tryserver', opts.getSynopsis()) def test_defaults(self): with self.assertRaises(usage.UsageError): self.parse() def test_with_jobdir(self): opts = self.parse('--jobdir', 'xyz') exp = {"jobdir": 'xyz'} self.assertOptions(opts, exp) class TestCheckConfigOptions(OptionsMixin, unittest.TestCase): def setUp(self): self.setUpOptions() def parse(self, *args): self.opts = runner.CheckConfigOptions() self.opts.parseOptions(args) return self.opts def test_synopsis(self): opts = runner.CheckConfigOptions() self.assertIn('buildbot checkconfig', opts.getSynopsis()) def test_defaults(self): opts = self.parse() exp = {"quiet": False} self.assertOptions(opts, exp) def test_configfile(self): opts = self.parse('foo.cfg') exp = {"quiet": False, "configFile": 'foo.cfg'} self.assertOptions(opts, exp) def test_quiet(self): opts = self.parse('-q') exp = {"quiet": True} self.assertOptions(opts, exp) class TestUserOptions(OptionsMixin, unittest.TestCase): # mandatory arguments extra_args = ['--master', 'a:1', '--username', 'u', '--passwd', 'p'] def setUp(self): self.setUpOptions() def parse(self, *args): self.opts = runner.UserOptions() self.opts.parseOptions(args) return self.opts def test_defaults(self): with self.assertRaises(usage.UsageError): self.parse() def test_synopsis(self): opts = runner.UserOptions() self.assertIn('buildbot user', opts.getSynopsis()) def test_master(self): opts = self.parse( "--master", "abcd:1234", '--op=get', '--ids=x', '--username=u', '--passwd=p' ) self.assertOptions(opts, {"master": 'abcd:1234'}) def test_ids(self): opts = self.parse("--ids", "id1,id2,id3", '--op', 'get', *self.extra_args) self.assertEqual(opts['ids'], ['id1', 'id2', 'id3']) def test_info(self): opts = self.parse( "--info", "git=Tyler Durden <[email protected]>", '--op', 'add', *self.extra_args ) self.assertEqual(opts['info'], [{"git": 'Tyler Durden <[email protected]>'}]) def test_info_only_id(self): opts = self.parse("--info", "tdurden", '--op', 'update', *self.extra_args) self.assertEqual(opts['info'], [{"identifier": 'tdurden'}]) def test_info_with_id(self): opts = self.parse("--info", "tdurden:svn=marla", '--op', 'update', *self.extra_args) self.assertEqual(opts['info'], [{"identifier": 'tdurden', "svn": 'marla'}]) def test_info_multiple(self): opts = self.parse( "--info", "git=Tyler Durden <[email protected]>", "--info", "git=Narrator <[email protected]>", '--op', 'add', *self.extra_args, ) self.assertEqual( opts['info'], [{"git": 'Tyler Durden <[email protected]>'}, {"git": 'Narrator <[email protected]>'}], ) def test_config_user_params(self): self.options_file['user_master'] = 'mm:99' self.options_file['user_username'] = 'un' self.options_file['user_passwd'] = 'pw' opts = self.parse('--op', 'get', '--ids', 'x') self.assertOptions(opts, {"master": 'mm:99', "username": 'un', "passwd": 'pw'}) def test_config_master(self): self.options_file['master'] = 'mm:99' opts = self.parse('--op', 'get', '--ids', 'x', '--username=u', '--passwd=p') self.assertOptions(opts, {"master": 'mm:99'}) def test_config_master_override(self): self.options_file['master'] = 'not seen' self.options_file['user_master'] = 'mm:99' opts = self.parse('--op', 'get', '--ids', 'x', '--username=u', '--passwd=p') self.assertOptions(opts, {"master": 'mm:99'}) def test_invalid_info(self): with self.assertRaises(usage.UsageError): self.parse("--info", "foo=bar", '--op', 'add', *self.extra_args) def test_no_master(self): with self.assertRaises(usage.UsageError): self.parse('-op=foo') def test_invalid_master(self): with self.assertRaises(usage.UsageError): self.parse('-m', 'foo') def test_no_operation(self): with self.assertRaises(usage.UsageError): self.parse('-m', 'a:1') def test_bad_operation(self): with self.assertRaises(usage.UsageError): self.parse('-m', 'a:1', '--op=mayhem') def test_no_username(self): with self.assertRaises(usage.UsageError): self.parse('-m', 'a:1', '--op=add') def test_no_password(self): with self.assertRaises(usage.UsageError): self.parse('--op=add', '-m', 'a:1', '-u', 'tdurden') def test_invalid_bb_username(self): with self.assertRaises(usage.UsageError): self.parse('--op=add', '--bb_username=tdurden', *self.extra_args) def test_invalid_bb_password(self): with self.assertRaises(usage.UsageError): self.parse('--op=add', '--bb_password=marla', *self.extra_args) def test_update_no_bb_username(self): with self.assertRaises(usage.UsageError): self.parse('--op=update', '--bb_password=marla', *self.extra_args) def test_update_no_bb_password(self): with self.assertRaises(usage.UsageError): self.parse('--op=update', '--bb_username=tdurden', *self.extra_args) def test_no_ids_info(self): with self.assertRaises(usage.UsageError): self.parse('--op=add', *self.extra_args) def test_ids_with_add(self): with self.assertRaises(usage.UsageError): self.parse('--op=add', '--ids=id1', *self.extra_args) def test_ids_with_update(self): with self.assertRaises(usage.UsageError): self.parse('--op=update', '--ids=id1', *self.extra_args) def test_no_ids_found_update(self): with self.assertRaises(usage.UsageError): self.parse("--op=update", "--info=svn=x", *self.extra_args) def test_id_with_add(self): with self.assertRaises(usage.UsageError): self.parse("--op=add", "--info=id:x", *self.extra_args) def test_info_with_remove(self): with self.assertRaises(usage.UsageError): self.parse('--op=remove', '--info=x=v', *self.extra_args) def test_info_with_get(self): with self.assertRaises(usage.UsageError): self.parse('--op=get', '--info=x=v', *self.extra_args) class TestOptions(OptionsMixin, misc.StdoutAssertionsMixin, unittest.TestCase): def setUp(self): self.setUpOptions() self.setUpStdoutAssertions() def parse(self, *args): self.opts = runner.Options() self.opts.parseOptions(args) return self.opts def test_defaults(self): with self.assertRaises(usage.UsageError): self.parse() def test_version(self): try: self.parse('--version') except SystemExit as e: self.assertEqual(e.args[0], 0) self.assertInStdout('Buildbot version:') def test_verbose(self): self.patch(log, 'startLogging', mock.Mock()) with self.assertRaises(usage.UsageError): self.parse("--verbose") log.startLogging.assert_called_once_with(sys.stderr) class TestRun(unittest.TestCase): class MySubCommand(usage.Options): subcommandFunction = 'buildbot.test.unit.scripts.test_runner.subcommandFunction' optFlags = [['loud', 'l', 'be noisy']] def postOptions(self): if self['loud']: raise usage.UsageError('THIS IS ME BEING LOUD') def setUp(self): # patch our subcommand in self.patch(runner.Options, 'subCommands', [['my', None, self.MySubCommand, 'my, my']]) # and patch in the callback for it global subcommandFunction subcommandFunction = mock.Mock(name='subcommandFunction', return_value=3) def test_run_good(self): self.patch(sys, 'argv', ['buildbot', 'my']) try: runner.run() except SystemExit as e: self.assertEqual(e.args[0], 3) else: self.fail("didn't exit") def test_run_bad(self): self.patch(sys, 'argv', ['buildbot', 'my', '-l']) stdout = StringIO() self.patch(sys, 'stdout', stdout) try: runner.run() except SystemExit as e: self.assertEqual(e.args[0], 1) else: self.fail("didn't exit") self.assertIn('THIS IS ME', stdout.getvalue())
30,919
Python
.py
772
30.843264
100
0.574759
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,580
test_manager.py
buildbot_buildbot/master/buildbot/test/unit/schedulers/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 typing import ClassVar from typing import Sequence from unittest import mock from twisted.internet import defer from twisted.trial import unittest from buildbot.db.schedulers import SchedulerModel from buildbot.schedulers import base from buildbot.schedulers import manager class SchedulerManager(unittest.TestCase): @defer.inlineCallbacks def setUp(self): self.next_objectid = 13 self.objectids = {} self.master = mock.Mock() self.master.master = self.master def getObjectId(sched_name, class_name): k = (sched_name, class_name) try: rv = self.objectids[k] except KeyError: rv = self.objectids[k] = self.next_objectid self.next_objectid += 1 return defer.succeed(rv) self.master.db.state.getObjectId = getObjectId def getScheduler(sched_id): return defer.succeed( SchedulerModel( id=sched_id, name=f"test-{sched_id}", enabled=True, masterid=None, ) ) self.master.db.schedulers.getScheduler = getScheduler self.new_config = mock.Mock() self.sm = manager.SchedulerManager() yield self.sm.setServiceParent(self.master) yield self.sm.startService() def tearDown(self): if self.sm.running: return self.sm.stopService() return None class Sched(base.BaseScheduler): # changing sch.attr should make a scheduler look "updated" compare_attrs: ClassVar[Sequence[str]] = ('attr',) already_started = False reconfig_count = 0 def startService(self): assert not self.already_started assert self.master is not None assert self.objectid is not None self.already_started = True return super().startService() @defer.inlineCallbacks def stopService(self): yield super().stopService() assert self.master is not None assert self.objectid is not None def __repr__(self): return f"{self.__class__.__name__}(attr={self.attr})" class ReconfigSched(Sched): def reconfigServiceWithSibling(self, sibling): self.reconfig_count += 1 self.attr = sibling.attr return super().reconfigServiceWithSibling(sibling) class ReconfigSched2(ReconfigSched): pass def makeSched(self, cls, name, attr='alpha'): sch = cls(name=name, builderNames=['x'], properties={}) sch.attr = attr return sch # tests @defer.inlineCallbacks def test_reconfigService_add_and_change_and_remove(self): sch1 = self.makeSched(self.ReconfigSched, 'sch1', attr='alpha') self.new_config.schedulers = {"sch1": sch1} yield self.sm.reconfigServiceWithBuildbotConfig(self.new_config) self.assertIdentical(sch1.parent, self.sm) self.assertIdentical(sch1.master, self.master) self.assertEqual(sch1.reconfig_count, 1) sch1_new = self.makeSched(self.ReconfigSched, 'sch1', attr='beta') sch2 = self.makeSched(self.ReconfigSched, 'sch2', attr='alpha') self.new_config.schedulers = {"sch1": sch1_new, "sch2": sch2} yield self.sm.reconfigServiceWithBuildbotConfig(self.new_config) # sch1 is still the active scheduler, and has been reconfig'd, # and has the correct attribute self.assertIdentical(sch1.parent, self.sm) self.assertIdentical(sch1.master, self.master) self.assertEqual(sch1.attr, 'beta') self.assertEqual(sch1.reconfig_count, 2) self.assertIdentical(sch1_new.parent, None) self.assertIdentical(sch1_new.master, None) self.assertIdentical(sch2.parent, self.sm) self.assertIdentical(sch2.master, self.master) self.new_config.schedulers = {} self.assertEqual(sch1.running, True) yield self.sm.reconfigServiceWithBuildbotConfig(self.new_config) self.assertEqual(sch1.running, False) @defer.inlineCallbacks def test_reconfigService_class_name_change(self): sch1 = self.makeSched(self.ReconfigSched, 'sch1') self.new_config.schedulers = {"sch1": sch1} yield self.sm.reconfigServiceWithBuildbotConfig(self.new_config) self.assertIdentical(sch1.parent, self.sm) self.assertIdentical(sch1.master, self.master) self.assertEqual(sch1.reconfig_count, 1) sch1_new = self.makeSched(self.ReconfigSched2, 'sch1') self.new_config.schedulers = {"sch1": sch1_new} yield self.sm.reconfigServiceWithBuildbotConfig(self.new_config) # sch1 had its class name change, so sch1_new is now the active # instance self.assertIdentical(sch1_new.parent, self.sm) self.assertIdentical(sch1_new.master, self.master) @defer.inlineCallbacks def test_reconfigService_not_reconfigurable(self): sch1 = self.makeSched(self.Sched, 'sch1', attr='beta') self.new_config.schedulers = {"sch1": sch1} yield self.sm.reconfigServiceWithBuildbotConfig(self.new_config) self.assertIdentical(sch1.parent, self.sm) self.assertIdentical(sch1.master, self.master) sch1_new = self.makeSched(self.Sched, 'sch1', attr='alpha') self.new_config.schedulers = {"sch1": sch1_new} yield self.sm.reconfigServiceWithBuildbotConfig(self.new_config) # sch1 had parameter change but is not reconfigurable, so sch1_new is now the active # instance self.assertEqual(sch1_new.running, True) self.assertEqual(sch1.running, False) self.assertIdentical(sch1_new.parent, self.sm) self.assertIdentical(sch1_new.master, self.master) @defer.inlineCallbacks def test_reconfigService_not_reconfigurable_no_change(self): sch1 = self.makeSched(self.Sched, 'sch1', attr='beta') self.new_config.schedulers = {"sch1": sch1} yield self.sm.reconfigServiceWithBuildbotConfig(self.new_config) self.assertIdentical(sch1.parent, self.sm) self.assertIdentical(sch1.master, self.master) sch1_new = self.makeSched(self.Sched, 'sch1', attr='beta') self.new_config.schedulers = {"sch1": sch1_new} yield self.sm.reconfigServiceWithBuildbotConfig(self.new_config) # sch1 had its class name change, so sch1_new is now the active # instance self.assertIdentical(sch1_new.parent, None) self.assertEqual(sch1_new.running, False) self.assertIdentical(sch1_new.master, None) self.assertEqual(sch1.running, True)
7,490
Python
.py
159
38.327044
92
0.676463
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,581
test_basic.py
buildbot_buildbot/master/buildbot/test/unit/schedulers/test_basic.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 task from twisted.trial import unittest from buildbot import config from buildbot.schedulers import basic from buildbot.test import fakedb from buildbot.test.reactor import TestReactorMixin from buildbot.test.util import scheduler from buildbot.test.util.state import StateTestMixin class CommonStuffMixin: @defer.inlineCallbacks def makeScheduler(self, klass, **kwargs_override): kwargs = {"name": "tsched", "treeStableTimer": 60, "builderNames": ['tbuild']} kwargs.update(kwargs_override) yield self.master.db.insert_test_data([ fakedb.Builder(name=builderName) for builderName in kwargs['builderNames'] ]) sched = yield self.attachScheduler(klass(**kwargs), self.OBJECTID, self.SCHEDULERID) # add a Clock to help checking timing issues self.clock = sched._reactor = task.Clock() # keep track of builds in self.events self.events = [] @self.assertArgSpecMatches(sched.addBuildsetForChanges) def addBuildsetForChanges( waited_for=False, reason='', external_idstring=None, changeids=None, builderNames=None, properties=None, priority=None, **kw, ): self.assertEqual(external_idstring, None) self.assertEqual(reason, sched.reason) self.events.append(f"B{repr(changeids).replace(' ', '')}@{int(self.clock.seconds())}") return defer.succeed(None) sched.addBuildsetForChanges = addBuildsetForChanges # see self.assertConsumingChanges self.consumingChanges = None def startConsumingChanges(**kwargs): self.consumingChanges = kwargs return defer.succeed(None) sched.startConsumingChanges = startConsumingChanges return sched def assertConsumingChanges(self, **kwargs): self.assertEqual(self.consumingChanges, kwargs) class BaseBasicScheduler( CommonStuffMixin, scheduler.SchedulerMixin, StateTestMixin, TestReactorMixin, unittest.TestCase ): OBJECTID = 244 SCHEDULERID = 4 # a custom subclass since we're testing the base class. This basically # re-implements SingleBranchScheduler, but with more asserts class Subclass(basic.BaseBasicScheduler): timer_started = False def getChangeFilter(self, *args, **kwargs): return kwargs.get('change_filter') def getTimerNameForChange(self, change): self.timer_started = True return "xxx" def getChangeClassificationsForTimer(self, sched_id, timer_name): assert timer_name == "xxx" assert sched_id == BaseBasicScheduler.SCHEDULERID return self.master.db.schedulers.getChangeClassifications(sched_id) @defer.inlineCallbacks def setUp(self): self.setup_test_reactor(auto_tear_down=False) yield self.setUpScheduler() @defer.inlineCallbacks def tearDown(self): self.tearDownScheduler() yield self.tear_down_test_reactor() # tests def test_constructor_positional_exception(self): with self.assertRaises(config.ConfigErrors): self.Subclass("tsched", "master", 60) @defer.inlineCallbacks def test_activate_no_treeStableTimer(self): cf = mock.Mock('cf') fII = mock.Mock('fII') sched = yield self.makeScheduler( self.Subclass, treeStableTimer=None, change_filter=cf, fileIsImportant=fII ) yield self.db.schedulers.classifyChanges(self.SCHEDULERID, {20: True}) yield sched.activate() # check that the scheduler has started to consume changes, and the # classifications *have* been flushed, since they will not be used self.assertConsumingChanges(fileIsImportant=fII, change_filter=cf, onlyImportant=False) yield self.assert_classifications(self.SCHEDULERID, {}) yield sched.deactivate() @defer.inlineCallbacks def test_subclass_fileIsImportant(self): class Subclass(self.Subclass): def fileIsImportant(self, change): return False sched = yield self.makeScheduler(Subclass, onlyImportant=True) self.assertEqual(Subclass.fileIsImportant.__get__(sched), sched.fileIsImportant) @defer.inlineCallbacks def test_activate_treeStableTimer(self): cf = mock.Mock() sched = yield self.makeScheduler(self.Subclass, treeStableTimer=10, change_filter=cf) yield self.master.db.insert_test_data([ fakedb.Change(changeid=20), ]) yield self.db.schedulers.classifyChanges(self.SCHEDULERID, {20: True}) yield sched.activate() # check that the scheduler has started to consume changes, and no # classifications have been flushed. Furthermore, the existing # classification should have been acted on, so the timer should be # running self.assertConsumingChanges(fileIsImportant=None, change_filter=cf, onlyImportant=False) yield self.assert_classifications(self.SCHEDULERID, {20: True}) self.assertTrue(sched.timer_started) self.clock.advance(10) yield sched.deactivate() @defer.inlineCallbacks def test_gotChange_no_treeStableTimer_unimportant(self): sched = yield self.makeScheduler(self.Subclass, treeStableTimer=None, branch='master') sched.activate() yield sched.gotChange(self.makeFakeChange(branch='master', number=13), False) self.assertEqual(self.events, []) yield sched.deactivate() @defer.inlineCallbacks def test_gotChange_no_treeStableTimer_important(self): sched = yield self.makeScheduler(self.Subclass, treeStableTimer=None, branch='master') sched.activate() yield sched.gotChange(self.makeFakeChange(branch='master', number=13), True) self.assertEqual(self.events, ['B[13]@0']) yield sched.deactivate() @defer.inlineCallbacks def test_gotChange_treeStableTimer_unimportant(self): sched = yield self.makeScheduler(self.Subclass, treeStableTimer=10, branch='master') sched.activate() yield sched.gotChange(self.makeFakeChange(branch='master', number=13), False) self.assertEqual(self.events, []) self.clock.advance(10) self.assertEqual(self.events, []) yield sched.deactivate() @defer.inlineCallbacks def test_gotChange_treeStableTimer_important(self): sched = yield self.makeScheduler(self.Subclass, treeStableTimer=10, branch='master') sched.activate() yield sched.gotChange(self.makeFakeChange(branch='master', number=13), True) self.clock.advance(10) self.assertEqual(self.events, ['B[13]@10']) yield sched.deactivate() @defer.inlineCallbacks def test_gotChange_treeStableTimer_sequence(self): sched = yield self.makeScheduler(self.Subclass, treeStableTimer=9, branch='master') yield self.master.db.insert_test_data([ fakedb.Change(changeid=1, branch='master', when_timestamp=1110), fakedb.ChangeFile(changeid=1, filename='readme.txt'), fakedb.Change(changeid=2, branch='master', when_timestamp=2220), fakedb.ChangeFile(changeid=2, filename='readme.txt'), fakedb.Change(changeid=3, branch='master', when_timestamp=3330), fakedb.ChangeFile(changeid=3, filename='readme.txt'), fakedb.Change(changeid=4, branch='master', when_timestamp=4440), fakedb.ChangeFile(changeid=4, filename='readme.txt'), ]) sched.activate() self.clock.advance(2220) # this important change arrives at 2220, so the stable timer will last # until 2229 yield sched.gotChange(self.makeFakeChange(branch='master', number=1, when=2220), True) self.assertEqual(self.events, []) yield self.assert_classifications(self.SCHEDULERID, {1: True}) # but another (unimportant) change arrives before then self.clock.advance(6) # to 2226 self.assertEqual(self.events, []) yield sched.gotChange(self.makeFakeChange(branch='master', number=2, when=2226), False) self.assertEqual(self.events, []) yield self.assert_classifications(self.SCHEDULERID, {1: True, 2: False}) self.clock.advance(3) # to 2229 self.assertEqual(self.events, []) self.clock.advance(3) # to 2232 self.assertEqual(self.events, []) # another important change arrives at 2232 yield sched.gotChange(self.makeFakeChange(branch='master', number=3, when=2232), True) self.assertEqual(self.events, []) yield self.assert_classifications(self.SCHEDULERID, {1: True, 2: False, 3: True}) self.clock.advance(3) # to 2235 self.assertEqual(self.events, []) # finally, time to start the build! self.clock.advance(6) # to 2241 self.assertEqual(self.events, ['B[1,2,3]@2241']) yield self.assert_classifications(self.SCHEDULERID, {}) yield sched.deactivate() @defer.inlineCallbacks def test_enabled_callback(self): sched = yield self.makeScheduler(self.Subclass) expectedValue = not sched.enabled yield sched._enabledCallback(None, {'enabled': not sched.enabled}) self.assertEqual(sched.enabled, expectedValue) expectedValue = not sched.enabled yield sched._enabledCallback(None, {'enabled': not sched.enabled}) self.assertEqual(sched.enabled, expectedValue) @defer.inlineCallbacks def test_disabled_activate(self): sched = yield self.makeScheduler(self.Subclass) yield sched._enabledCallback(None, {'enabled': not sched.enabled}) self.assertEqual(sched.enabled, False) r = yield sched.activate() self.assertEqual(r, None) @defer.inlineCallbacks def test_disabled_deactivate(self): sched = yield self.makeScheduler(self.Subclass) yield sched._enabledCallback(None, {'enabled': not sched.enabled}) self.assertEqual(sched.enabled, False) r = yield sched.deactivate() self.assertEqual(r, None) class SingleBranchScheduler( CommonStuffMixin, scheduler.SchedulerMixin, StateTestMixin, TestReactorMixin, unittest.TestCase ): SCHEDULERID = 245 OBJECTID = 224455 codebases = { 'a': {'repository': "", 'branch': 'master'}, 'b': {'repository': "", 'branch': 'master'}, } @defer.inlineCallbacks def makeFullScheduler(self, **kwargs): yield self.master.db.insert_test_data([ fakedb.Builder(name=builderName) for builderName in kwargs['builderNames'] ]) sched = yield self.attachScheduler( basic.SingleBranchScheduler(**kwargs), self.OBJECTID, self.SCHEDULERID, overrideBuildsetMethods=True, ) # add a Clock to help checking timing issues self.clock = sched._reactor = task.Clock() return sched def mkbs(self, **kwargs): # create buildset for expected_buildset in assertBuildset. bs = { "reason": self.sched.reason, "external_idstring": None, "sourcestampsetid": 100, "properties": [('scheduler', ('test', 'Scheduler'))], } bs.update(kwargs) return bs def mkss(self, **kwargs): # create sourcestamp for expected_sourcestamps in assertBuildset. ss = {"branch": 'master', "project": '', "repository": '', "sourcestampsetid": 100} ss.update(kwargs) return ss @defer.inlineCallbacks def mkch(self, **kwargs): # create changeset and insert in database. chd = {"branch": 'master', "project": '', "repository": ''} chd.update(kwargs) ch = self.makeFakeChange(**chd) # fakedb.Change requires changeid instead of number chd['changeid'] = chd['number'] del chd['number'] yield self.db.insert_test_data([fakedb.Change(**chd)]) return ch @defer.inlineCallbacks def setUp(self): self.setup_test_reactor(auto_tear_down=False) yield self.setUpScheduler() @defer.inlineCallbacks def tearDown(self): self.tearDownScheduler() yield self.tear_down_test_reactor() @defer.inlineCallbacks def test_constructor_no_reason(self): sched = yield self.makeScheduler(basic.SingleBranchScheduler, branch="master") self.assertEqual( sched.reason, "The SingleBranchScheduler scheduler named 'tsched' triggered this build" ) @defer.inlineCallbacks def test_constructor_reason(self): sched = yield self.makeScheduler( basic.SingleBranchScheduler, branch="master", reason="Changeset" ) self.assertEqual(sched.reason, "Changeset") def test_constructor_branch_mandatory(self): with self.assertRaises(config.ConfigErrors): basic.SingleBranchScheduler(name="tsched", treeStableTimer=60) def test_constructor_no_branch_but_filter(self): # this shouldn't fail basic.SingleBranchScheduler( name="tsched", treeStableTimer=60, builderNames=['a', 'b'], change_filter=mock.Mock() ) def test_constructor_branches_forbidden(self): with self.assertRaises(config.ConfigErrors): basic.SingleBranchScheduler(name="tsched", treeStableTimer=60, branches='x') @defer.inlineCallbacks def test_constructor_priority_none(self): sched = yield self.makeScheduler( basic.SingleBranchScheduler, branch="master", priority=None ) self.assertEqual(sched.priority, None) @defer.inlineCallbacks def test_constructor_priority_int(self): sched = yield self.makeScheduler(basic.SingleBranchScheduler, branch="master", priority=8) self.assertEqual(sched.priority, 8) @defer.inlineCallbacks def test_constructor_priority_function(self): def sched_priority(builderNames, changesByCodebase): return 0 sched = yield self.makeScheduler( basic.SingleBranchScheduler, branch="master", priority=sched_priority ) self.assertEqual(sched.priority, sched_priority) @defer.inlineCallbacks def test_gotChange_treeStableTimer_important(self): # this looks suspiciously like the same test above, because SingleBranchScheduler # is about the same as the test subclass used above sched = yield self.makeScheduler( basic.SingleBranchScheduler, treeStableTimer=10, branch='master' ) sched.activate() yield sched.gotChange(self.makeFakeChange(branch='master', number=13), True) self.clock.advance(10) self.assertEqual(self.events, ['B[13]@10']) yield sched.deactivate() @defer.inlineCallbacks def test_gotChange_createAbsoluteSourceStamps_saveCodebase(self): # check codebase is stored after receiving change. sched = yield self.makeFullScheduler( name='test', builderNames=['test'], treeStableTimer=None, branch='master', codebases=self.codebases, createAbsoluteSourceStamps=True, ) yield self.db.insert_test_data([ fakedb.Object(id=self.OBJECTID, name='test', class_name='SingleBranchScheduler') ]) yield sched.activate() yield sched.gotChange( (yield self.mkch(codebase='a', revision='1234:abc', repository='A', number=0)), True ) yield sched.gotChange( (yield self.mkch(codebase='b', revision='2345:bcd', repository='B', number=1)), True ) yield self.assert_state( self.OBJECTID, lastCodebases={ 'a': { "branch": 'master', "repository": 'A', "revision": '1234:abc', "lastChange": 0, }, 'b': { "branch": 'master', "repository": 'B', "revision": '2345:bcd', "lastChange": 1, }, }, ) yield sched.deactivate() @defer.inlineCallbacks def test_gotChange_createAbsoluteSourceStamps_older_change(self): # check codebase is not stored if it's older than the most recent sched = yield self.makeFullScheduler( name='test', builderNames=['test'], treeStableTimer=None, branch='master', codebases=self.codebases, createAbsoluteSourceStamps=True, ) yield self.db.insert_test_data([ fakedb.Object(id=self.OBJECTID, name='test', class_name='SingleBranchScheduler'), fakedb.ObjectState( objectid=self.OBJECTID, name='lastCodebases', value_json='{"a": {"branch": "master", "repository": "A", ' '"revision": "5555:def", "lastChange": 20}}', ), ]) yield sched.activate() # this change is not recorded, since it's older than # change 20 yield sched.gotChange( (yield self.mkch(codebase='a', revision='1234:abc', repository='A', number=10)), True ) yield self.assert_state( self.OBJECTID, lastCodebases={ 'a': { "branch": 'master', "repository": 'A', "revision": '5555:def', "lastChange": 20, } }, ) yield sched.deactivate() @defer.inlineCallbacks def test_getCodebaseDict(self): sched = yield self.makeFullScheduler( name='test', builderNames=['test'], treeStableTimer=None, branch='master', codebases=self.codebases, createAbsoluteSourceStamps=True, ) sched._lastCodebases = { 'a': {"branch": 'master', "repository": 'A', "revision": '5555:def', "lastChange": 20} } cbd = yield sched.getCodebaseDict('a') self.assertEqual( cbd, {"branch": 'master', "repository": 'A', "revision": '5555:def', "lastChange": 20} ) @defer.inlineCallbacks def test_getCodebaseDict_no_createAbsoluteSourceStamps(self): sched = yield self.makeFullScheduler( name='test', builderNames=['test'], treeStableTimer=None, branch='master', codebases=self.codebases, createAbsoluteSourceStamps=False, ) sched._lastCodebases = { 'a': {"branch": 'master', "repository": 'A', "revision": '5555:def', "lastChange": 20} } cbd = yield sched.getCodebaseDict('a') # _lastCodebases is ignored self.assertEqual(cbd, {'branch': 'master', 'repository': ''}) @defer.inlineCallbacks def test_gotChange_with_priority(self): sched = yield self.makeFullScheduler( name='test', builderNames=['test'], branch='master', priority=8 ) yield self.db.insert_test_data([ fakedb.Object(id=self.OBJECTID, name='test', class_name='SingleBranchScheduler') ]) yield sched.activate() yield sched.gotChange( (yield self.mkch(codebase='a', revision='1234:abc', repository='A', number=10)), True ) self.assertEqual( self.addBuildsetCalls, [ ( 'addBuildsetForChanges', { 'waited_for': False, 'external_idstring': None, 'changeids': [10], 'properties': None, 'reason': "The SingleBranchScheduler scheduler named 'test' triggered this build", 'builderNames': None, 'priority': 8, }, ) ], ) yield sched.deactivate() class AnyBranchScheduler( CommonStuffMixin, scheduler.SchedulerMixin, TestReactorMixin, unittest.TestCase ): SCHEDULERID = 6 OBJECTID = 246 @defer.inlineCallbacks def setUp(self): self.setup_test_reactor(auto_tear_down=False) yield self.setUpScheduler() @defer.inlineCallbacks def tearDown(self): self.tearDownScheduler() yield self.tear_down_test_reactor() def test_constructor_branch_forbidden(self): with self.assertRaises(config.ConfigErrors): basic.SingleBranchScheduler(name="tsched", treeStableTimer=60, branch='x') @defer.inlineCallbacks def test_gotChange_treeStableTimer_multiple_branches(self): """Two changes with different branches get different treeStableTimers""" sched = yield self.makeScheduler( basic.AnyBranchScheduler, treeStableTimer=10, branches=['master', 'devel', 'boring'] ) sched.activate() @defer.inlineCallbacks def mkch(**kwargs): ch = self.makeFakeChange(**kwargs) ch = yield self.addFakeChange(ch) return ch yield sched.gotChange((yield mkch(branch='master', number=500)), True) yield self.clock.advance(1) # time is now 1 yield sched.gotChange((yield mkch(branch='master', number=501)), False) yield sched.gotChange((yield mkch(branch='boring', number=502)), False) yield self.clock.pump([1] * 4) # time is now 5 yield sched.gotChange((yield mkch(branch='devel', number=503)), True) yield self.clock.pump([1] * 10) # time is now 15 self.assertEqual(self.events, ['B[500,501]@11', 'B[503]@15']) yield sched.deactivate() @defer.inlineCallbacks def test_gotChange_treeStableTimer_multiple_repositories(self): """Two repositories, even with the same branch name, have different treeStableTimers""" sched = yield self.makeScheduler( basic.AnyBranchScheduler, treeStableTimer=10, branches=['master'] ) yield sched.activate() @defer.inlineCallbacks def mkch(**kwargs): ch = self.makeFakeChange(**kwargs) ch = yield self.addFakeChange(ch) return ch yield sched.gotChange((yield mkch(branch='master', repository="repo", number=500)), True) yield self.clock.advance(1) # time is now 1 yield sched.gotChange((yield mkch(branch='master', repository="repo", number=501)), False) yield sched.gotChange( (yield mkch(branch='master', repository="other_repo", number=502)), False ) yield self.clock.pump([1] * 4) # time is now 5 yield sched.gotChange( (yield mkch(branch='master', repository="other_repo", number=503)), True ) yield self.clock.pump([1] * 10) # time is now 15 self.assertEqual(self.events, ['B[500,501]@11', 'B[502,503]@15']) yield sched.deactivate() @defer.inlineCallbacks def test_gotChange_treeStableTimer_multiple_projects(self): """Two projects, even with the same branch name, have different treeStableTimers""" sched = yield self.makeScheduler( basic.AnyBranchScheduler, treeStableTimer=10, branches=['master'] ) sched.startService() @defer.inlineCallbacks def mkch(**kwargs): ch = self.makeFakeChange(**kwargs) ch = yield self.addFakeChange(ch) return ch yield sched.gotChange((yield mkch(branch='master', project="proj", number=500)), True) yield self.clock.advance(1) # time is now 1 yield sched.gotChange((yield mkch(branch='master', project="proj", number=501)), False) yield sched.gotChange( (yield mkch(branch='master', project="other_proj", number=502)), False ) yield self.clock.pump([1] * 4) # time is now 5 yield sched.gotChange((yield mkch(branch='master', project="other_proj", number=503)), True) yield self.clock.pump([1] * 10) # time is now 15 self.assertEqual(self.events, ['B[500,501]@11', 'B[502,503]@15']) yield sched.deactivate() @defer.inlineCallbacks def test_gotChange_treeStableTimer_multiple_codebases(self): """Two codebases, even with the same branch name, have different treeStableTimers""" sched = yield self.makeScheduler( basic.AnyBranchScheduler, treeStableTimer=10, branches=['master'] ) sched.startService() @defer.inlineCallbacks def mkch(**kwargs): ch = self.makeFakeChange(**kwargs) ch = yield self.addFakeChange(ch) return ch yield sched.gotChange((yield mkch(branch='master', codebase="base", number=500)), True) self.clock.advance(1) # time is now 1 yield sched.gotChange((yield mkch(branch='master', codebase="base", number=501)), False) yield sched.gotChange( (yield mkch(branch='master', codebase="other_base", number=502)), False ) self.clock.pump([1] * 4) # time is now 5 yield sched.gotChange( (yield mkch(branch='master', codebase="other_base", number=503)), True ) self.clock.pump([1] * 10) # time is now 15 self.assertEqual(self.events, ['B[500,501]@11', 'B[502,503]@15']) yield sched.deactivate()
26,534
Python
.py
586
35.609215
106
0.641531
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,582
test_dependent.py
buildbot_buildbot/master/buildbot/test/unit/schedulers/test_dependent.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.process.results import FAILURE from buildbot.process.results import SUCCESS from buildbot.process.results import WARNINGS from buildbot.schedulers import base from buildbot.schedulers import dependent from buildbot.test import fakedb from buildbot.test.reactor import TestReactorMixin from buildbot.test.util import scheduler from buildbot.test.util.state import StateTestMixin SUBMITTED_AT_TIME = 111111111 COMPLETE_AT_TIME = 222222222 OBJECTID = 33 SCHEDULERID = 133 UPSTREAM_NAME = 'uppy' class Dependent(scheduler.SchedulerMixin, TestReactorMixin, StateTestMixin, unittest.TestCase): @defer.inlineCallbacks def setUp(self): self.setup_test_reactor(auto_tear_down=False) yield self.setUpScheduler() @defer.inlineCallbacks def tearDown(self): self.tearDownScheduler() yield self.tear_down_test_reactor() @defer.inlineCallbacks def makeScheduler(self, upstream=None): # build a fake upstream scheduler class Upstream(base.BaseScheduler): def __init__(self, name): self.name = name if not upstream: upstream = Upstream(UPSTREAM_NAME) sched = dependent.Dependent(name='n', builderNames=['b'], upstream=upstream) yield self.attachScheduler( sched, OBJECTID, SCHEDULERID, overrideBuildsetMethods=True, createBuilderDB=True ) return sched @defer.inlineCallbacks def assertBuildsetSubscriptions(self, bsids=None): yield self.assert_state(OBJECTID, upstream_bsids=bsids) # tests # NOTE: these tests take advantage of the fact that all of the fake # scheduler operations are synchronous, and thus do not return a Deferred. # The Deferred from trigger() is completely processed before this test # method returns. @defer.inlineCallbacks def test_constructor_string_arg(self): with self.assertRaises(config.ConfigErrors): yield self.makeScheduler(upstream='foo') @defer.inlineCallbacks def test_activate(self): sched = yield self.makeScheduler() sched.activate() self.assertEqual( sorted([q.filter for q in sched.master.mq.qrefs]), [ ( 'buildsets', None, 'complete', ), ( 'buildsets', None, 'new', ), ('schedulers', '133', 'updated'), ], ) yield sched.deactivate() self.assertEqual( [q.filter for q in sched.master.mq.qrefs], [('schedulers', '133', 'updated')] ) def sendBuildsetMessage(self, scheduler_name=None, results=-1, complete=False): """Call callConsumer with a buildset message. Most of the values here are hard-coded to correspond to those in do_test.""" msg = { "bsid": 44, "sourcestamps": [], # blah blah blah "submitted_at": SUBMITTED_AT_TIME, "complete": complete, "complete_at": COMPLETE_AT_TIME if complete else None, "external_idstring": None, "reason": 'Because', "results": results if complete else -1, "parent_buildid": None, "parent_relationship": None, } if not complete: msg['scheduler'] = scheduler_name self.master.mq.callConsumer(('buildsets', '44', 'complete' if complete else 'new'), msg) @defer.inlineCallbacks def do_test(self, scheduler_name, expect_subscription, results, expect_buildset): """Test the dependent scheduler by faking a buildset and subsequent completion from an upstream scheduler. @param scheduler_name: upstream scheduler's name @param expect_subscription: whether to expect the dependent to subscribe to the buildset @param results: results of the upstream scheduler's buildset @param expect_buidlset: whether to expect the dependent to generate a new buildset in response """ sched = yield self.makeScheduler() sched.activate() # announce a buildset with a matching name.. yield self.db.insert_test_data([ fakedb.SourceStamp( id=93, revision='555', branch='master', project='proj', repository='repo', codebase='cb', ), fakedb.Buildset( id=44, submitted_at=SUBMITTED_AT_TIME, complete=False, complete_at=None, external_idstring=None, reason='Because', results=-1, ), fakedb.BuildsetSourceStamp(buildsetid=44, sourcestampid=93), ]) self.sendBuildsetMessage(scheduler_name=scheduler_name, complete=False) # check whether scheduler is subscribed to that buildset if expect_subscription: yield self.assertBuildsetSubscriptions([44]) else: yield self.assertBuildsetSubscriptions([]) # pretend that the buildset is finished yield self.db.buildsets.completeBuildset(bsid=44, results=results) self.sendBuildsetMessage(results=results, complete=True) # and check whether a buildset was added in response if expect_buildset: self.assertEqual( self.addBuildsetCalls, [ ( 'addBuildsetForSourceStamps', { "builderNames": None, # defaults "external_idstring": None, "properties": None, "reason": 'downstream', "sourcestamps": [93], }, ), ], ) else: self.assertEqual(self.addBuildsetCalls, []) def test_related_buildset_SUCCESS(self): return self.do_test(UPSTREAM_NAME, True, SUCCESS, True) def test_related_buildset_WARNINGS(self): return self.do_test(UPSTREAM_NAME, True, WARNINGS, True) def test_related_buildset_FAILURE(self): return self.do_test(UPSTREAM_NAME, True, FAILURE, False) def test_unrelated_buildset(self): return self.do_test('unrelated', False, SUCCESS, False) @defer.inlineCallbacks def test_getUpstreamBuildsets_missing(self): sched = yield self.makeScheduler() # insert some state, with more bsids than exist yield self.db.insert_test_data([ fakedb.SourceStamp(id=1234), fakedb.Buildset(id=11), fakedb.Buildset(id=13), fakedb.BuildsetSourceStamp(buildsetid=13, sourcestampid=1234), fakedb.Object(id=OBJECTID), fakedb.ObjectState(objectid=OBJECTID, name='upstream_bsids', value_json='[11,12,13]'), ]) # check return value (missing 12) self.assertEqual( (yield sched._getUpstreamBuildsets()), [(11, [], False, -1), (13, [1234], False, -1)] ) # and check that it wrote the correct value back to the state yield self.assert_state(OBJECTID, upstream_bsids=[11, 13]) @defer.inlineCallbacks def test_enabled_callback(self): sched = yield self.makeScheduler() expectedValue = not sched.enabled yield sched._enabledCallback(None, {'enabled': not sched.enabled}) self.assertEqual(sched.enabled, expectedValue) expectedValue = not sched.enabled yield sched._enabledCallback(None, {'enabled': not sched.enabled}) self.assertEqual(sched.enabled, expectedValue) @defer.inlineCallbacks def test_disabled_activate(self): sched = yield self.makeScheduler() yield sched._enabledCallback(None, {'enabled': not sched.enabled}) self.assertEqual(sched.enabled, False) r = yield sched.activate() self.assertEqual(r, None) @defer.inlineCallbacks def test_disabled_deactivate(self): sched = yield self.makeScheduler() yield sched._enabledCallback(None, {'enabled': not sched.enabled}) self.assertEqual(sched.enabled, False) r = yield sched.deactivate() self.assertEqual(r, None)
9,291
Python
.py
218
32.582569
98
0.631765
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,583
test_canceller.py
buildbot_buildbot/master/buildbot/test/unit/schedulers/test_canceller.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.schedulers.canceller import OldBuildCanceller from buildbot.schedulers.canceller import _OldBuildFilterSet from buildbot.schedulers.canceller import _OldBuildrequestTracker from buildbot.test import fakedb from buildbot.test.fake import fakemaster from buildbot.test.reactor import TestReactorMixin from buildbot.test.util.config import ConfigErrorsMixin from buildbot.util.ssfilter import SourceStampFilter class TestFilterSet(unittest.TestCase): def test_empty_filter(self): filter = _OldBuildFilterSet() self.assertFalse(filter.is_matched('builder', {'prop': 'value'})) @parameterized.expand([ ('other_builder', 'builder2', {'project': 'p', 'repository': 'r'}, False), ('nothing', 'builder1', {'project': 'value_other', 'repository': 'value_other'}, False), ('single1', 'builder1', {'project': 'p', 'repository': 'value_other'}, True), ('single2', 'builder1', {'project': 'value_other', 'repository': 'r'}, True), ('all', 'builder1', {'project': 'p', 'repository': 'r'}, True), ]) def test_multiple_filters_on_builder(self, name, builder, props, expected): filter = _OldBuildFilterSet() filter.add_filter(['builder1'], SourceStampFilter(project_eq='p')) filter.add_filter(['builder1'], SourceStampFilter(repository_eq='r')) self.assertEqual(filter.is_matched(builder, props), expected) class TestOldBuildrequestTracker(unittest.TestCase, TestReactorMixin): def setUp(self): self.setup_test_reactor(auto_tear_down=False) filter = _OldBuildFilterSet() ss_filter = SourceStampFilter( codebase_eq=['cb1', 'cb2'], repository_eq=['rp1', 'rp2'], branch_eq=['br1', 'br2'] ) filter.add_filter(['bldr1', 'bldr2'], ss_filter) self.cancellations = [] self.tracker = _OldBuildrequestTracker( self.reactor, filter, lambda ss: ss['branch'], self.on_cancel ) @defer.inlineCallbacks def tearDown(self): yield self.tear_down_test_reactor() def on_cancel(self, brid): self.cancellations.append(brid) def assert_cancelled(self, cancellations): self.assertEqual(self.cancellations, cancellations) self.cancellations = [] def create_ss_dict(self, project, codebase, repository, branch): # Changes have the same structure for the attributes that we're using, so we reuse this # function for changes. return { 'project': project, 'codebase': codebase, 'repository': repository, 'branch': branch, } def test_unknown_branch_not_tracked(self): ss_dicts = [self.create_ss_dict('pr1', 'cb1', 'rp1', None)] self.tracker.on_new_buildrequest(10, 'bldr1', ss_dicts) self.assertFalse(self.tracker.is_buildrequest_tracked(10)) def test_multi_codebase_unknown_branch_not_tracked(self): ss_dicts = [ self.create_ss_dict('pr1', 'cb1', 'rp1', None), self.create_ss_dict('pr2', 'cb2', 'rp2', 'br2'), ] self.tracker.on_new_buildrequest(10, 'bldr1', ss_dicts) self.assertFalse(self.tracker.is_buildrequest_tracked(10)) def test_unmatched_ss_not_tracked(self): ss_dicts = [self.create_ss_dict('pr1', 'cb1', 'rp1', 'untracked')] self.tracker.on_new_buildrequest(10, 'bldr1', ss_dicts) self.assertFalse(self.tracker.is_buildrequest_tracked(10)) def test_multi_codebase_unmatched_ss_not_tracked(self): ss_dicts = [ self.create_ss_dict('pr1', 'cb1', 'rp1', 'untracked'), self.create_ss_dict('pr2', 'cb2', 'rp2', 'untracked'), ] self.tracker.on_new_buildrequest(10, 'bldr1', ss_dicts) self.assertFalse(self.tracker.is_buildrequest_tracked(10)) def test_multi_codebase_tracks_if_at_least_one_ss_match(self): ss_dicts = [ self.create_ss_dict('pr1', 'cb1', 'rp1', 'untracked'), self.create_ss_dict('pr2', 'cb2', 'rp2', 'br2'), ] self.tracker.on_new_buildrequest(10, 'bldr1', ss_dicts) self.assertTrue(self.tracker.is_buildrequest_tracked(10)) def test_cancel_buildrequest(self): ss_dict = self.create_ss_dict('pr1', 'cb1', 'rp1', 'br1') not_matching_ss_dict = self.create_ss_dict('pr1', 'cb1', 'rp1', 'br2') self.tracker.on_new_buildrequest(1, 'bldr1', [ss_dict]) self.assertTrue(self.tracker.is_buildrequest_tracked(1)) self.reactor.advance(1) self.tracker.on_change(not_matching_ss_dict) self.assert_cancelled([]) self.assertTrue(self.tracker.is_buildrequest_tracked(1)) self.reactor.advance(1) self.tracker.on_change(ss_dict) self.assert_cancelled([]) self.tracker.on_new_buildrequest(2, 'bldr1', [ss_dict]) self.assert_cancelled([1]) self.assertFalse(self.tracker.is_buildrequest_tracked(1)) self.tracker.on_complete_buildrequest(1) self.reactor.advance(1) self.tracker.on_change(ss_dict) self.tracker.on_new_buildrequest(3, 'bldr1', [ss_dict]) self.assert_cancelled([2]) self.tracker.on_complete_buildrequest(2) def test_cancel_buildrequest_identical_times(self): ss_dict = self.create_ss_dict('pr1', 'cb1', 'rp1', 'br1') not_matching_ss_dict = self.create_ss_dict('pr1', 'cb1', 'rp1', 'br2') self.tracker.on_new_buildrequest(1, 'bldr1', [ss_dict]) self.assertTrue(self.tracker.is_buildrequest_tracked(1)) self.tracker.on_change(not_matching_ss_dict) self.assert_cancelled([]) self.assertTrue(self.tracker.is_buildrequest_tracked(1)) self.tracker.on_change(ss_dict) self.tracker.on_new_buildrequest(2, 'bldr1', [ss_dict]) self.assert_cancelled([]) self.assertTrue(self.tracker.is_buildrequest_tracked(1)) self.tracker.on_change(ss_dict) self.tracker.on_new_buildrequest(3, 'bldr1', [ss_dict]) self.assert_cancelled([]) def test_not_cancel_finished_buildrequest(self): ss_dict = self.create_ss_dict('pr1', 'cb1', 'rp1', 'br1') self.tracker.on_new_buildrequest(1, 'bldr1', [ss_dict]) self.assertTrue(self.tracker.is_buildrequest_tracked(1)) self.reactor.advance(1) self.tracker.on_complete_buildrequest(1) self.assertFalse(self.tracker.is_buildrequest_tracked(1)) self.reactor.advance(1) self.tracker.on_change(ss_dict) self.tracker.on_new_buildrequest(2, 'bldr1', [ss_dict]) self.assert_cancelled([]) self.assertFalse(self.tracker.is_buildrequest_tracked(1)) def test_not_cancel_buildrequest_too_new(self): ss_dict = self.create_ss_dict('pr1', 'cb1', 'rp1', 'br1') self.tracker.on_change(ss_dict) self.tracker.on_new_buildrequest(1, 'bldr1', [ss_dict]) self.assertTrue(self.tracker.is_buildrequest_tracked(1)) self.reactor.advance(1) self.tracker.on_new_buildrequest(2, 'bldr1', [ss_dict]) self.assert_cancelled([]) self.assertTrue(self.tracker.is_buildrequest_tracked(2)) self.reactor.advance(1) self.tracker.on_complete_buildrequest(1) self.tracker.on_complete_buildrequest(2) def test_not_cancel_buildrequest_different_builder(self): ss_dict = self.create_ss_dict('pr1', 'cb1', 'rp1', 'br1') self.tracker.on_change(ss_dict) self.tracker.on_new_buildrequest(1, 'bldr1', [ss_dict]) self.assertTrue(self.tracker.is_buildrequest_tracked(1)) self.reactor.advance(1) self.tracker.on_change(ss_dict) self.tracker.on_new_buildrequest(2, 'bldr2', [ss_dict]) self.assert_cancelled([]) self.assertTrue(self.tracker.is_buildrequest_tracked(2)) self.reactor.advance(1) self.tracker.on_complete_buildrequest(1) self.tracker.on_complete_buildrequest(2) @parameterized.expand([ ('first', True), ('second', False), ]) def test_cancel_multi_codebase_buildrequest(self, name, cancel_first_ss): ss_dict1 = self.create_ss_dict('pr1', 'cb1', 'rp1', 'br1') ss_dict2 = self.create_ss_dict('pr2', 'cb2', 'rp2', 'br2') not_matching_ss_dict = self.create_ss_dict('pr1', 'cb1', 'rp1', 'br2') self.tracker.on_new_buildrequest(1, 'bldr1', [ss_dict1, ss_dict2]) self.assertTrue(self.tracker.is_buildrequest_tracked(1)) self.reactor.advance(1) self.tracker.on_change(not_matching_ss_dict) self.tracker.on_new_buildrequest(2, 'bldr1', [not_matching_ss_dict]) self.assert_cancelled([]) self.assertTrue(self.tracker.is_buildrequest_tracked(1)) self.reactor.advance(1) self.tracker.on_change(ss_dict1 if cancel_first_ss else ss_dict2) self.tracker.on_new_buildrequest(3, 'bldr1', [ss_dict1 if cancel_first_ss else ss_dict2]) self.assert_cancelled([1]) self.assertFalse(self.tracker.is_buildrequest_tracked(1)) self.tracker.on_complete_buildrequest(1) self.reactor.advance(1) self.tracker.on_change(ss_dict1) self.tracker.on_new_buildrequest(4, 'bldr1', [ss_dict1]) self.tracker.on_change(ss_dict2) self.tracker.on_new_buildrequest(5, 'bldr1', [ss_dict2]) self.assert_cancelled([3]) self.tracker.on_complete_buildrequest(3) def test_cancel_multi_codebase_buildrequest_ignores_non_matching_change_in_tracked_br(self): ss_dict1 = self.create_ss_dict('pr1', 'cb1', 'rp1', 'br1') non_matched_ss_dict = self.create_ss_dict('pr1', 'cb1', 'rp1', 'brZ') self.tracker.on_new_buildrequest(1, 'bldr1', [ss_dict1, non_matched_ss_dict]) self.assertTrue(self.tracker.is_buildrequest_tracked(1)) self.reactor.advance(1) self.tracker.on_change(non_matched_ss_dict) self.tracker.on_new_buildrequest(2, 'bldr1', [non_matched_ss_dict]) self.assert_cancelled([]) self.assertTrue(self.tracker.is_buildrequest_tracked(1)) def test_cancel_multiple_buildrequests(self): ss_dict = self.create_ss_dict('pr1', 'cb1', 'rp1', 'br1') not_matching_ss_dict = self.create_ss_dict('pr1', 'cb1', 'rp1', 'br2') self.tracker.on_new_buildrequest(1, 'bldr1', [ss_dict]) self.tracker.on_new_buildrequest(2, 'bldr1', [ss_dict]) self.assertTrue(self.tracker.is_buildrequest_tracked(1)) self.assertTrue(self.tracker.is_buildrequest_tracked(2)) self.reactor.advance(1) self.tracker.on_change(not_matching_ss_dict) self.tracker.on_new_buildrequest(3, 'bldr1', [not_matching_ss_dict]) self.assert_cancelled([]) self.assertTrue(self.tracker.is_buildrequest_tracked(1)) self.assertTrue(self.tracker.is_buildrequest_tracked(2)) self.reactor.advance(1) self.tracker.on_change(ss_dict) self.tracker.on_new_buildrequest(4, 'bldr1', [ss_dict]) self.assert_cancelled([1, 2]) self.assertFalse(self.tracker.is_buildrequest_tracked(1)) self.assertFalse(self.tracker.is_buildrequest_tracked(2)) self.tracker.on_complete_buildrequest(1) self.tracker.on_complete_buildrequest(2) self.reactor.advance(1) self.tracker.on_change(ss_dict) self.tracker.on_new_buildrequest(5, 'bldr1', [ss_dict]) self.assert_cancelled([4]) self.tracker.on_complete_buildrequest(4) def test_cancel_multi_codebase_multiple_buildrequests(self): ss_dict1 = self.create_ss_dict('pr1', 'cb1', 'rp1', 'br1') ss_dict2 = self.create_ss_dict('pr2', 'cb2', 'rp2', 'br2') ss_dict3 = self.create_ss_dict('pr3', 'cb3', 'rp3', 'br3') self.tracker.on_new_buildrequest(1, 'bldr1', [ss_dict1, ss_dict2]) self.tracker.on_new_buildrequest(2, 'bldr1', [ss_dict1, ss_dict3]) self.tracker.on_new_buildrequest(3, 'bldr1', [ss_dict2, ss_dict3]) self.assertTrue(self.tracker.is_buildrequest_tracked(1)) self.assertTrue(self.tracker.is_buildrequest_tracked(2)) self.assertTrue(self.tracker.is_buildrequest_tracked(3)) self.assert_cancelled([]) self.reactor.advance(1) self.tracker.on_change(ss_dict1) self.tracker.on_new_buildrequest(4, 'bldr1', [ss_dict1]) self.assert_cancelled([1, 2]) self.assertFalse(self.tracker.is_buildrequest_tracked(1)) self.assertFalse(self.tracker.is_buildrequest_tracked(2)) self.assertTrue(self.tracker.is_buildrequest_tracked(3)) self.tracker.on_complete_buildrequest(1) self.tracker.on_complete_buildrequest(2) self.reactor.advance(1) self.tracker.on_change(ss_dict1) self.tracker.on_new_buildrequest(5, 'bldr1', [ss_dict1]) self.assert_cancelled([4]) self.tracker.on_complete_buildrequest(4) class TestOldBuildCancellerUtils(ConfigErrorsMixin, unittest.TestCase): @parameterized.expand([ ('only_builder', [(['bldr'], SourceStampFilter())]), ('with_codebase', [(['bldr'], SourceStampFilter(codebase_eq=['value']))]), ('with_repository', [(['bldr'], SourceStampFilter(repository_eq=['value']))]), ('with_branch', [(['bldr'], SourceStampFilter(branch_eq=['value']))]), ( 'all', [ ( ['bldr'], SourceStampFilter( codebase_eq=['v1', 'v2'], repository_eq=['v1', 'v2'], branch_eq=['v1', 'v2'] ), ) ], ), ]) def test_check_filters_valid(self, name, filters): OldBuildCanceller.check_filters(filters) @parameterized.expand([ ('dict', {}), ('list_list', [[]]), ]) def test_check_filters_not_dict(self, name, value): with self.assertRaisesConfigError('The filters argument must be a list of tuples'): OldBuildCanceller.check_filters(value) def test_check_filters_invalid_uple(self): with self.assertRaisesConfigError('must be a list of tuples each of which'): OldBuildCanceller.check_filters([('a', 'b', 'c')]) with self.assertRaisesConfigError('must be a list of tuples each of which'): OldBuildCanceller.check_filters([('a',)]) @parameterized.expand([ ('dict', {}, 'filter builders must be list of strings or a string'), ('list_int', [1], 'Value of filter builders must be string'), ]) def test_check_builders_keys_not_list(self, name, value, error): with self.assertRaisesConfigError(error): OldBuildCanceller.check_filters([(value, SourceStampFilter())]) class TestOldBuildCanceller(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, wantData=True, wantDb=True) self.master.mq.verifyMessages = False yield self.insert_test_data() self._cancelled_build_ids = [] yield self.master.startService() @defer.inlineCallbacks def tearDown(self): yield self.master.stopService() yield self.tear_down_test_reactor() def create_ss_dict(self, project, codebase, repository, branch): # Changes have the same structure for the attributes that we're using, so we reuse this # function for changes. return { 'project': project, 'codebase': codebase, 'repository': repository, 'branch': branch, } @defer.inlineCallbacks def insert_test_data(self): yield self.master.db.insert_test_data([ fakedb.Master(id=92), fakedb.Worker(id=13, name='wrk'), fakedb.Builder(id=79, name='builder1'), fakedb.Builder(id=80, name='builder2'), fakedb.Builder(id=81, name='builder3'), fakedb.Buildset(id=98, results=None, reason="reason98"), fakedb.BuildsetSourceStamp(buildsetid=98, sourcestampid=234), fakedb.SourceStamp( id=234, revision='revision1', project='project1', codebase='codebase1', repository='repository1', branch='branch1', ), fakedb.BuildRequest(id=10, buildsetid=98, builderid=79), fakedb.Build( id=19, number=1, builderid=79, buildrequestid=10, workerid=13, masterid=92, results=None, state_string="state1", ), fakedb.Buildset(id=99, results=None, reason="reason99"), fakedb.BuildsetSourceStamp(buildsetid=99, sourcestampid=235), fakedb.SourceStamp( id=235, revision='revision2', project='project2', codebase='codebase2', repository='repository2', branch='branch2', ), fakedb.BuildRequest(id=11, buildsetid=99, builderid=80), fakedb.Build( id=20, number=1, builderid=80, buildrequestid=11, workerid=13, masterid=92, results=None, state_string="state2", ), fakedb.Buildset(id=100, results=None, reason="reason100"), fakedb.BuildsetSourceStamp(buildsetid=100, sourcestampid=236), fakedb.SourceStamp( id=236, revision='revision2', project='project2', codebase='codebase2', repository='repository2', branch='refs/changes/10/12310/2', ), fakedb.BuildRequest(id=12, buildsetid=100, builderid=81), fakedb.Build( id=21, number=1, builderid=81, buildrequestid=12, workerid=13, masterid=92, results=None, state_string="state3", ), ]) @defer.inlineCallbacks def setup_canceller_with_filters(self): self.canceller = OldBuildCanceller( 'canceller', [ (['builder1'], SourceStampFilter(branch_eq=['branch1'])), (['builder2'], SourceStampFilter(branch_eq=['branch2'])), (['builder3'], SourceStampFilter()), ], ) yield self.canceller.setServiceParent(self.master) @defer.inlineCallbacks def setup_canceller_with_no_filters(self): self.canceller = OldBuildCanceller('canceller', []) yield self.canceller.setServiceParent(self.master) def assert_cancelled(self, cancellations): expected_productions = [] for id in cancellations: expected_productions.append(( ('control', 'buildrequests', str(id), 'cancel'), {'reason': 'Build request has been obsoleted by a newer commit'}, )) self.master.mq.assertProductions(expected_productions) @defer.inlineCallbacks def test_buildrequest_no_branch(self): yield self.setup_canceller_with_filters() self.reactor.advance(1) ss_dict = self.create_ss_dict('project1', 'codebase1', 'repository1', None) yield self.master.db.insert_test_data([ fakedb.Buildset(id=199, results=None, reason='reason99'), fakedb.BuildsetSourceStamp(buildsetid=199, sourcestampid=240), fakedb.SourceStamp( id=240, revision='revision1', project='project1', codebase='codebase1', repository='repository1', branch=None, ), fakedb.BuildRequest(id=14, buildsetid=199, builderid=79), ]) self.master.mq.callConsumer(('changes', '123', 'new'), ss_dict) self.master.mq.callConsumer( ('buildrequests', '14', 'new'), {'buildrequestid': 14, 'builderid': 79, 'buildsetid': 199}, ) self.assert_cancelled([]) @defer.inlineCallbacks def test_cancel_buildrequest_after_new_commit_with_buildrequest(self): yield self.setup_canceller_with_filters() self.reactor.advance(1) ss_dict = self.create_ss_dict('project1', 'codebase1', 'repository1', 'branch1') yield self.master.db.insert_test_data([ fakedb.Buildset(id=199, results=None, reason='reason99'), fakedb.BuildsetSourceStamp(buildsetid=199, sourcestampid=240), fakedb.SourceStamp( id=240, revision='revision240', project='project1', codebase='codebase1', repository='repository1', branch='branch1', ), fakedb.BuildRequest(id=14, buildsetid=199, builderid=79), ]) self.master.mq.callConsumer(('changes', '123', 'new'), ss_dict) self.master.mq.callConsumer( ('buildrequests', '14', 'new'), {'buildrequestid': 14, 'builderid': 79, 'buildsetid': 199}, ) self.assert_cancelled([10]) self.reactor.advance(1) yield self.master.db.insert_test_data([ fakedb.Buildset(id=200, results=None, reason='reason100'), fakedb.BuildsetSourceStamp(buildsetid=200, sourcestampid=241), fakedb.SourceStamp( id=241, revision='revision241', project='project1', codebase='codebase1', repository='repository1', branch='branch1', ), fakedb.BuildRequest(id=15, buildsetid=200, builderid=79), ]) self.master.mq.callConsumer(('changes', '124', 'new'), ss_dict) self.master.mq.callConsumer( ('buildrequests', '15', 'new'), {'buildrequestid': 15, 'builderid': 79, 'buildsetid': 200}, ) self.assert_cancelled([14]) @defer.inlineCallbacks def test_no_cancel_buildrequest_after_only_new_commit(self): yield self.setup_canceller_with_filters() self.reactor.advance(1) ss_dict = self.create_ss_dict('project1', 'codebase1', 'repository1', 'branch1') self.master.mq.callConsumer(('changes', '123', 'new'), ss_dict) self.assert_cancelled([]) @defer.inlineCallbacks def test_cancel_buildrequest_after_new_commit_gerrit_branch_filter(self): yield self.setup_canceller_with_filters() self.reactor.advance(1) ss_dict = self.create_ss_dict( 'project2', 'codebase2', 'repository2', 'refs/changes/10/12310/3' ) yield self.master.db.insert_test_data([ fakedb.Buildset(id=199, results=None, reason='reason99'), fakedb.BuildsetSourceStamp(buildsetid=199, sourcestampid=240), fakedb.SourceStamp( id=240, revision='revision240', project='project2', codebase='codebase2', repository='repository2', branch='refs/changes/10/12310/3', ), fakedb.BuildRequest(id=14, buildsetid=199, builderid=81), ]) self.master.mq.callConsumer(('changes', '123', 'new'), ss_dict) self.master.mq.callConsumer( ('buildrequests', '14', 'new'), {'buildrequestid': 14, 'builderid': 81, 'buildsetid': 199}, ) self.assert_cancelled([12]) self.reactor.advance(1) yield self.master.db.insert_test_data([ fakedb.Buildset(id=200, results=None, reason='reason100'), fakedb.BuildsetSourceStamp(buildsetid=200, sourcestampid=241), fakedb.SourceStamp( id=241, revision='revision241', project='project2', codebase='codebase2', repository='repository2', branch='refs/changes/10/12310/3', ), fakedb.BuildRequest(id=15, buildsetid=200, builderid=81), ]) self.master.mq.callConsumer(('changes', '124', 'new'), ss_dict) self.master.mq.callConsumer( ('buildrequests', '15', 'new'), {'buildrequestid': 15, 'builderid': 81, 'buildsetid': 200}, ) self.assert_cancelled([14]) @defer.inlineCallbacks def test_build_finished_then_new_commit_no_cancel(self): yield self.setup_canceller_with_filters() self.reactor.advance(1) ss_dict = self.create_ss_dict('project1', 'codebase1', 'repository1', 'branch1') self.master.mq.callConsumer(('buildrequests', '10', 'complete'), {'buildrequestid': 10}) self.master.mq.callConsumer(('changes', '123', 'new'), ss_dict) self.assert_cancelled([]) @defer.inlineCallbacks def test_reconfig_no_longer_matched_tracked_build_cancelled(self): yield self.setup_canceller_with_filters() self.reactor.advance(1) ss_dict = self.create_ss_dict('project1', 'codebase1', 'repository1', 'branch1') yield self.canceller.reconfigService('canceller', []) yield self.master.db.insert_test_data([ fakedb.Buildset(id=199, results=None, reason='reason99'), fakedb.BuildsetSourceStamp(buildsetid=199, sourcestampid=242), fakedb.SourceStamp( id=242, revision='revision242', project='project1', codebase='codebase1', repository='repository1', branch='branch1', ), fakedb.BuildRequest(id=14, buildsetid=199, builderid=79), ]) self.master.mq.callConsumer(('changes', '123', 'new'), ss_dict) self.master.mq.callConsumer( ('buildrequests', '14', 'new'), {'buildrequestid': 14, 'builderid': 79, 'buildsetid': 199}, ) self.assert_cancelled([10]) self.reactor.advance(1) yield self.master.db.insert_test_data([ fakedb.Buildset(id=200, results=None, reason='reason100'), fakedb.BuildsetSourceStamp(buildsetid=200, sourcestampid=240), fakedb.SourceStamp( id=240, revision='revision240', project='project1', codebase='codebase1', repository='repository1', branch='branch1', ), fakedb.BuildRequest(id=15, buildsetid=200, builderid=79), ]) self.master.mq.callConsumer(('changes', '124', 'new'), ss_dict) self.master.mq.callConsumer( ('buildrequests', '15', 'new'), {'buildrequestid': 15, 'builderid': 79, 'buildsetid': 200}, ) self.assert_cancelled([]) @defer.inlineCallbacks def test_reconfig_defers_finished_builds_to_after_registration(self): # We need to make sure that during reconfiguration any finished build messages are not # acted before the build is tracked yield self.setup_canceller_with_no_filters() # Setup controllable blocking wait on canceller._on_buildrequest_new on_buildrequest_new_d = defer.Deferred() on_buildrequest_new_original = self.canceller._on_buildrequest_new on_buildrequest_new_breq_ids = [] @defer.inlineCallbacks def waiting_on_buildrequest_new(key, breq): on_buildrequest_new_breq_ids.append(breq['buildrequestid']) if not on_buildrequest_new_d.called: yield on_buildrequest_new_d yield on_buildrequest_new_original(key, breq) self.canceller._on_buildrequest_new = waiting_on_buildrequest_new # Start reconfig. We verify that we actually blocked in on_buildrequest_new d = self.canceller.reconfigService( 'canceller', [ {'builders': ['builder1'], 'branch_eq': ['branch1']}, {'builders': ['builder2'], 'branch_eq': ['branch2']}, ], ) self.assertEqual(on_buildrequest_new_breq_ids, [10]) self.assertFalse(d.called) # The buildrequest complete messages should be queued self.master.mq.callConsumer(('buildrequests', '10', 'complete'), {'buildrequestid': 10}) self.master.mq.callConsumer(('buildrequests', '11', 'complete'), {'buildrequestid': 11}) # Unblock reconfigService on_buildrequest_new_d.callback(None) yield d self.assertEqual(on_buildrequest_new_breq_ids, [10, 11, 12]) self.assertFalse(self.canceller._build_tracker.is_buildrequest_tracked(10)) self.assertFalse(self.canceller._build_tracker.is_buildrequest_tracked(11))
29,887
Python
.py
626
37.297125
100
0.61954
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,584
test_forcesched.py
buildbot_buildbot/master/buildbot/test/unit/schedulers/test_forcesched.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.config.master import MasterConfig from buildbot.schedulers.forcesched import AnyPropertyParameter from buildbot.schedulers.forcesched import BaseParameter from buildbot.schedulers.forcesched import BooleanParameter from buildbot.schedulers.forcesched import ChoiceStringParameter from buildbot.schedulers.forcesched import CodebaseParameter from buildbot.schedulers.forcesched import CollectedValidationError from buildbot.schedulers.forcesched import FileParameter from buildbot.schedulers.forcesched import FixedParameter from buildbot.schedulers.forcesched import ForceScheduler from buildbot.schedulers.forcesched import IntParameter from buildbot.schedulers.forcesched import NestedParameter from buildbot.schedulers.forcesched import PatchParameter from buildbot.schedulers.forcesched import StringParameter from buildbot.schedulers.forcesched import UserNameParameter from buildbot.schedulers.forcesched import oneCodebase from buildbot.test.reactor import TestReactorMixin from buildbot.test.util import scheduler from buildbot.test.util.config import ConfigErrorsMixin class TestForceScheduler( scheduler.SchedulerMixin, ConfigErrorsMixin, TestReactorMixin, unittest.TestCase ): OBJECTID = 19 SCHEDULERID = 9 maxDiff = None @defer.inlineCallbacks def setUp(self): self.setup_test_reactor(auto_tear_down=False) yield self.setUpScheduler() @defer.inlineCallbacks def tearDown(self): self.tearDownScheduler() yield self.tear_down_test_reactor() @defer.inlineCallbacks def makeScheduler(self, name='testsched', builderNames=None, **kw): if builderNames is None: builderNames = ['a', 'b'] sched = yield self.attachScheduler( ForceScheduler(name=name, builderNames=builderNames, **kw), self.OBJECTID, self.SCHEDULERID, overrideBuildsetMethods=True, createBuilderDB=True, ) sched.master.config = MasterConfig() self.assertEqual(sched.name, name) return sched # tests def test_compare_branch(self): self.assertNotEqual( ForceScheduler(name="testched", builderNames=[]), ForceScheduler( name="testched", builderNames=[], codebases=oneCodebase(branch=FixedParameter("branch", "fishing/pole")), ), ) def test_compare_reason(self): self.assertNotEqual( ForceScheduler( name="testched", builderNames=[], reason=FixedParameter("reason", "no fish for you!"), ), ForceScheduler( name="testched", builderNames=[], reason=FixedParameter("reason", "thanks for the fish!"), ), ) def test_compare_revision(self): self.assertNotEqual( ForceScheduler( name="testched", builderNames=[], codebases=oneCodebase(revision=FixedParameter("revision", "fish-v1")), ), ForceScheduler( name="testched", builderNames=[], codebases=oneCodebase(revision=FixedParameter("revision", "fish-v2")), ), ) def test_compare_repository(self): self.assertNotEqual( ForceScheduler( name="testched", builderNames=[], codebases=oneCodebase( repository=FixedParameter("repository", "git://pond.org/fisher.git") ), ), ForceScheduler( name="testched", builderNames=[], codebases=oneCodebase( repository=FixedParameter("repository", "svn://ocean.com/trawler/") ), ), ) def test_compare_project(self): self.assertNotEqual( ForceScheduler( name="testched", builderNames=[], codebases=oneCodebase(project=FixedParameter("project", "fisher")), ), ForceScheduler( name="testched", builderNames=[], codebases=oneCodebase(project=FixedParameter("project", "trawler")), ), ) def test_compare_username(self): self.assertNotEqual( ForceScheduler(name="testched", builderNames=[]), ForceScheduler( name="testched", builderNames=[], username=FixedParameter("username", "The Fisher King <[email protected]>"), ), ) def test_compare_properties(self): self.assertNotEqual( ForceScheduler(name="testched", builderNames=[], properties=[]), ForceScheduler( name="testched", builderNames=[], properties=[FixedParameter("prop", "thanks for the fish!")], ), ) def test_compare_codebases(self): self.assertNotEqual( ForceScheduler(name="testched", builderNames=[], codebases=['bar']), ForceScheduler(name="testched", builderNames=[], codebases=['foo']), ) @defer.inlineCallbacks def test_basicForce(self): sched = yield self.makeScheduler() res = yield sched.force( 'user', builderNames=['a'], branch='a', reason='because', revision='c', repository='d', project='p', ) # only one builder forced, so there should only be one brid self.assertEqual(res, (500, {300: 100})) self.assertEqual( self.addBuildsetCalls, [ ( 'addBuildsetForSourceStampsWithDefaults', { "builderNames": ['a'], "waited_for": False, "priority": 0, "properties": { 'owner': ('user', 'Force Build Form'), 'reason': ('because', 'Force Build Form'), }, "reason": "A build was forced by 'user': because", "sourcestamps": [ { 'codebase': '', 'branch': 'a', 'revision': 'c', 'repository': 'd', 'project': 'p', }, ], }, ), ], ) @defer.inlineCallbacks def test_basicForce_reasonString(self): """Same as above, but with a reasonString""" sched = yield self.makeScheduler(reasonString='%(owner)s wants it %(reason)s') res = yield sched.force( 'user', builderNames=['a'], branch='a', reason='because', revision='c', repository='d', project='p', ) _, brids = res # only one builder forced, so there should only be one brid self.assertEqual(len(brids), 1) self.assertEqual( self.addBuildsetCalls, [ ( 'addBuildsetForSourceStampsWithDefaults', { 'builderNames': ['a'], 'priority': 0, 'properties': { 'owner': ('user', 'Force Build Form'), 'reason': ('because', 'Force Build Form'), }, 'reason': 'user wants it because', 'sourcestamps': [ { 'branch': 'a', 'codebase': '', 'project': 'p', 'repository': 'd', 'revision': 'c', } ], 'waited_for': False, }, ), ], ) @defer.inlineCallbacks def test_force_allBuilders(self): sched = yield self.makeScheduler() res = yield sched.force( 'user', branch='a', reason='because', revision='c', repository='d', project='p', ) self.assertEqual(res, (500, {300: 100, 301: 101})) self.assertEqual( self.addBuildsetCalls, [ ( 'addBuildsetForSourceStampsWithDefaults', { "builderNames": ['a', 'b'], "waited_for": False, "priority": 0, "properties": { 'owner': ('user', 'Force Build Form'), 'reason': ('because', 'Force Build Form'), }, "reason": "A build was forced by 'user': because", "sourcestamps": [ { 'codebase': '', 'branch': 'a', 'revision': 'c', 'repository': 'd', 'project': 'p', }, ], }, ), ], ) @defer.inlineCallbacks def test_force_someBuilders(self): sched = yield self.makeScheduler(builderNames=['a', 'b', 'c']) res = yield sched.force( 'user', builderNames=['a', 'b'], branch='a', reason='because', revision='c', repository='d', project='p', ) self.assertEqual(res, (500, {300: 100, 301: 101})) self.assertEqual( self.addBuildsetCalls, [ ( 'addBuildsetForSourceStampsWithDefaults', { "builderNames": ['a', 'b'], "waited_for": False, "priority": 0, "properties": { 'owner': ('user', 'Force Build Form'), 'reason': ('because', 'Force Build Form'), }, "reason": "A build was forced by 'user': because", "sourcestamps": [ { 'codebase': '', 'branch': 'a', 'revision': 'c', 'repository': 'd', 'project': 'p', }, ], }, ), ], ) def test_bad_codebases(self): # codebases must be a list of either string or BaseParameter types with self.assertRaisesConfigError( "ForceScheduler 'foo': 'codebases' must be a " "list of strings or CodebaseParameter objects:" ): ForceScheduler( name='foo', builderNames=['bar'], codebases=[123], ) with self.assertRaisesConfigError( "ForceScheduler 'foo': 'codebases' must be a " "list of strings or CodebaseParameter objects:" ): ForceScheduler(name='foo', builderNames=['bar'], codebases=[IntParameter('foo')]) # codebases cannot be empty with self.assertRaisesConfigError( "ForceScheduler 'foo': 'codebases' cannot be " "empty; use [CodebaseParameter(codebase='', hide=True)] if needed:" ): ForceScheduler(name='foo', builderNames=['bar'], codebases=[]) # codebases cannot be a dictionary # dictType on Python 3 is: "<class 'dict'>" # dictType on Python 2 is: "<type 'dict'>" dictType = str(type({})) errMsg = ( "ForceScheduler 'foo': 'codebases' should be a list " "of strings or CodebaseParameter, " f"not {dictType}" ) with self.assertRaisesConfigError(errMsg): ForceScheduler(name='foo', builderNames=['bar'], codebases={'cb': {'branch': 'trunk'}}) @defer.inlineCallbacks def test_good_codebases(self): sched = yield self.makeScheduler(codebases=['foo', CodebaseParameter('bar')]) yield sched.force( 'user', builderNames=['a'], reason='because', foo_branch='a', foo_revision='c', foo_repository='d', foo_project='p', bar_branch='a2', bar_revision='c2', bar_repository='d2', bar_project='p2', ) expProperties = { 'owner': ('user', 'Force Build Form'), 'reason': ('because', 'Force Build Form'), } self.assertEqual( self.addBuildsetCalls, [ ( 'addBuildsetForSourceStampsWithDefaults', { "builderNames": ['a'], "waited_for": False, "priority": 0, "properties": expProperties, "reason": "A build was forced by 'user': because", "sourcestamps": [ { 'branch': 'a2', 'project': 'p2', 'repository': 'd2', 'revision': 'c2', 'codebase': 'bar', }, { 'branch': 'a', 'project': 'p', 'repository': 'd', 'revision': 'c', 'codebase': 'foo', }, ], }, ), ], ) @defer.inlineCallbacks def test_codebase_with_patch(self): sched = yield self.makeScheduler( codebases=['foo', CodebaseParameter('bar', patch=PatchParameter())] ) yield sched.force( 'user', builderNames=['a'], reason='because', foo_branch='a', foo_revision='c', foo_repository='d', foo_project='p', bar_branch='a2', bar_revision='c2', bar_repository='d2', bar_project='p2', bar_patch_body=b"xxx", ) expProperties = { 'owner': ('user', 'Force Build Form'), 'reason': ('because', 'Force Build Form'), } self.assertEqual( self.addBuildsetCalls, [ ( 'addBuildsetForSourceStampsWithDefaults', { "builderNames": ['a'], "waited_for": False, "priority": 0, "properties": expProperties, "reason": "A build was forced by 'user': because", "sourcestamps": [ { 'branch': 'a2', 'project': 'p2', 'repository': 'd2', 'revision': 'c2', 'codebase': 'bar', 'patch_body': b'xxx', 'patch_author': '', 'patch_subdir': '.', 'patch_comment': '', 'patch_level': 1, }, { 'branch': 'a', 'project': 'p', 'repository': 'd', 'revision': 'c', 'codebase': 'foo', }, ], }, ), ], ) def formatJsonForTest(self, gotJson): ret = "" linestart = "expectJson='" spaces = 7 * 4 + 2 while len(gotJson) > (90 - spaces): gotJson = " " * spaces + linestart + gotJson pos = gotJson[:100].rfind(",") if pos > 0: pos += 2 ret += gotJson[:pos] + "'\n" gotJson = gotJson[pos:] linestart = "'" ret += " " * spaces + linestart + gotJson + "')\n" return ret # value = the value to be sent with the parameter (ignored if req is set) # expect = the expected result (can be an exception type) # klass = the parameter class type # req = use this request instead of the auto-generated one based on value @defer.inlineCallbacks def do_ParameterTest( self, expect, klass, # None=one prop, Exception=exception, dict=many props expectKind=None, owner='user', value=None, req=None, expectJson=None, **kwargs, ): name = kwargs.setdefault('name', 'p1') # construct one if needed if isinstance(klass, type): prop = klass(**kwargs) else: prop = klass self.assertEqual(prop.name, name) self.assertEqual(prop.label, kwargs.get('label', prop.name)) if expectJson is not None: gotSpec = prop.getSpec() gotJson = json.dumps(gotSpec) expectSpec = json.loads(expectJson) if gotSpec != expectSpec: try: import xerox # pylint: disable=import-outside-toplevel formatted = self.formatJsonForTest(gotJson) print("You may update the test with (copied to clipboard):\n" + formatted) xerox.copy(formatted) input() except ImportError: print("Note: for quick fix, pip install xerox") self.assertEqual(gotSpec, expectSpec) sched = yield self.makeScheduler(properties=[prop]) if not req: req = {name: value, 'reason': 'because'} try: bsid, brids = yield sched.force(owner, builderNames=['a'], **req) except Exception as e: if expectKind is not Exception: # an exception is not expected raise if not isinstance(e, expect): # the exception is the wrong kind raise return None # success expect_props = { 'owner': ('user', 'Force Build Form'), 'reason': ('because', 'Force Build Form'), } if expectKind is None: expect_props[name] = (expect, 'Force Build Form') elif expectKind is dict: for k, v in expect.items(): expect_props[k] = (v, 'Force Build Form') else: self.fail("expectKind is wrong type!") # only forced on 'a' self.assertEqual((bsid, brids), (500, {300: 100})) self.assertEqual( self.addBuildsetCalls, [ ( 'addBuildsetForSourceStampsWithDefaults', { "builderNames": ['a'], "waited_for": False, "priority": 0, "properties": expect_props, "reason": "A build was forced by 'user': because", "sourcestamps": [ { 'branch': '', 'project': '', 'repository': '', 'revision': '', 'codebase': '', }, ], }, ), ], ) return None def test_StringParameter(self): return self.do_ParameterTest( value="testedvalue", expect="testedvalue", klass=StringParameter, expectJson='{"name": "p1", "fullName": "p1", "label": "p1", ' '"tablabel": "p1", "type": "text", "default": "", "required": false, ' '"multiple": false, "regex": null, "hide": false, "maxsize": null, ' '"size": 10, "autopopulate": null, "tooltip": ""}', ) def test_StringParameter_Required(self): return self.do_ParameterTest( value=" ", expect=CollectedValidationError, expectKind=Exception, klass=StringParameter, required=True, ) def test_StringParameter_maxsize(self): return self.do_ParameterTest( value="xx" * 20, expect=CollectedValidationError, expectKind=Exception, klass=StringParameter, maxsize=10, ) def test_FileParameter_maxsize(self): return self.do_ParameterTest( value="xx" * 20, expect=CollectedValidationError, expectKind=Exception, klass=FileParameter, maxsize=10, ) def test_FileParameter(self): return self.do_ParameterTest( value="xx", expect="xx", klass=FileParameter, expectJson='{"name": "p1", "fullName": "p1", "label": "p1", ' '"tablabel": "p1", "type": "file", "default": "", "required": false, ' '"multiple": false, "regex": null, "hide": false, ' '"maxsize": 10485760, "autopopulate": null, "tooltip": ""}', ) def test_PatchParameter(self): expect_json = ( '{"name": "p1", "fullName": "p1", "label": "p1", "autopopulate": null, ' '"tablabel": "p1", "type": "nested", "default": "", "required": false, ' '"multiple": false, "regex": null, "hide": false, "maxsize": null, ' '"layout": "vertical", "columns": 1, "tooltip": "", "fields": [{"name": "body", ' '"fullName": "p1_body", "label": "body", "tablabel": "body", "autopopulate": null, ' '"type": "file", "default": "", "required": false, "multiple": false, ' '"regex": null, "hide": false, "maxsize": 10485760, "tooltip": ""}, {"name": "level", ' '"fullName": "p1_level", "label": "level", "tablabel": "level", ' '"type": "int", "default": 1, "required": false, "multiple": false, ' '"regex": null, "hide": false, "maxsize": null, "size": 10, "autopopulate": null, "tooltip": ""}, ' '{"name": "author", "fullName": "p1_author", "label": "author", ' '"tablabel": "author", "type": "text", "default": "", "autopopulate": null, ' '"required": false, "multiple": false, "regex": null, "hide": false, ' '"maxsize": null, "size": 10, "tooltip": ""}, {"name": "comment", "autopopulate": null, ' '"fullName": "p1_comment", "label": "comment", "tablabel": "comment", ' '"type": "text", "default": "", "required": false, "multiple": false, ' '"regex": null, "hide": false, "maxsize": null, "size": 10, "tooltip": ""}, ' '{"name": "subdir", "fullName": "p1_subdir", "label": "subdir", ' '"tablabel": "subdir", "type": "text", "default": ".", "autopopulate": null, ' '"required": false, "multiple": false, "regex": null, "hide": false, ' '"maxsize": null, "size": 10, "tooltip": ""}]}' ) return self.do_ParameterTest( req={"p1_author": 'me', "reason": 'because'}, expect={'author': 'me', 'body': '', 'comment': '', 'level': 1, 'subdir': '.'}, klass=PatchParameter, expectJson=expect_json, ) def test_IntParameter(self): return self.do_ParameterTest( value="123", expect=123, klass=IntParameter, expectJson='{"name": "p1", "fullName": "p1", "label": "p1", ' '"tablabel": "p1", "type": "int", "default": 0, "required": false, ' '"multiple": false, "regex": null, "hide": false, "maxsize": null, ' '"size": 10, "autopopulate": null, "tooltip": ""}', ) def test_FixedParameter(self): return self.do_ParameterTest( value="123", expect="321", klass=FixedParameter, default="321", expectJson='{"name": "p1", "fullName": "p1", "label": "p1", ' '"tablabel": "p1", "type": "fixed", "default": "321", ' '"required": false, "multiple": false, "regex": null, "hide": true, ' '"maxsize": null, "autopopulate": null, "tooltip": ""}', ) def test_BooleanParameter_True(self): req = {"p1": True, "reason": 'because'} return self.do_ParameterTest( value="123", expect=True, klass=BooleanParameter, req=req, expectJson='{"name": "p1", "fullName": "p1", "label": "p1", ' '"tablabel": "p1", "type": "bool", "default": "", "required": false, ' '"multiple": false, "regex": null, "hide": false, ' '"maxsize": null, "autopopulate": null, "tooltip": ""}', ) def test_BooleanParameter_False(self): req = {"p2": True, "reason": 'because'} return self.do_ParameterTest(value="123", expect=False, klass=BooleanParameter, req=req) def test_UserNameParameter(self): email = "test <[email protected]>" expect_json = ( '{"name": "username", "fullName": "username", ' '"label": "Your name:", "tablabel": "Your name:", "type": "username", ' '"default": "", "required": false, "multiple": false, "regex": null, ' '"hide": false, "maxsize": null, "size": 30, ' '"need_email": true, "autopopulate": null, "tooltip": ""}' ) return self.do_ParameterTest( value=email, expect=email, klass=UserNameParameter(), name="username", label="Your name:", expectJson=expect_json, ) def test_UserNameParameterIsValidMail(self): email = "[email protected]" expect_json = ( '{"name": "username", "fullName": "username", ' '"label": "Your name:", "tablabel": "Your name:", "type": "username", ' '"default": "", "required": false, "multiple": false, "regex": null, ' '"hide": false, "maxsize": null, "size": 30, ' '"need_email": true, "autopopulate": null, "tooltip": ""}' ) return self.do_ParameterTest( value=email, expect=email, klass=UserNameParameter(), name="username", label="Your name:", expectJson=expect_json, ) def test_UserNameParameterIsValidMailBis(self): email = "<[email protected]>" expect_json = ( '{"name": "username", "fullName": "username", ' '"label": "Your name:", "tablabel": "Your name:", "type": "username", ' '"default": "", "required": false, "multiple": false, "regex": null, ' '"hide": false, "maxsize": null, "size": 30, ' '"need_email": true, "autopopulate": null, "tooltip": ""}' ) return self.do_ParameterTest( value=email, expect=email, klass=UserNameParameter(), name="username", label="Your name:", expectJson=expect_json, ) def test_ChoiceParameter(self): return self.do_ParameterTest( value='t1', expect='t1', klass=ChoiceStringParameter, choices=['t1', 't2'], expectJson='{"name": "p1", "fullName": "p1", "label": "p1", ' '"tablabel": "p1", "type": "list", "default": "", "required": false, ' '"multiple": false, "regex": null, "hide": false, "maxsize": null, ' '"choices": ["t1", "t2"], "strict": true, "autopopulate": null, "tooltip": ""}', ) def test_ChoiceParameterError(self): return self.do_ParameterTest( value='t3', expect=CollectedValidationError, expectKind=Exception, klass=ChoiceStringParameter, choices=['t1', 't2'], debug=False, ) def test_ChoiceParameterError_notStrict(self): return self.do_ParameterTest( value='t1', expect='t1', strict=False, klass=ChoiceStringParameter, choices=['t1', 't2'] ) def test_ChoiceParameterMultiple(self): return self.do_ParameterTest( value=['t1', 't2'], expect=['t1', 't2'], klass=ChoiceStringParameter, choices=['t1', 't2'], multiple=True, expectJson='{"name": "p1", "fullName": "p1", "label": "p1", ' '"tablabel": "p1", "type": "list", "default": "", "required": false, ' '"multiple": true, "regex": null, "hide": false, "maxsize": null, ' '"choices": ["t1", "t2"], "strict": true, "autopopulate": null, "tooltip": ""}', ) def test_ChoiceParameterMultipleError(self): return self.do_ParameterTest( value=['t1', 't3'], expect=CollectedValidationError, expectKind=Exception, klass=ChoiceStringParameter, choices=['t1', 't2'], multiple=True, debug=False, ) def test_NestedParameter(self): fields = [IntParameter(name="foo")] expect_json = ( '{"name": "p1", "fullName": "p1", "label": "p1", "autopopulate": null, ' '"tablabel": "p1", "type": "nested", "default": "", "required": false, ' '"multiple": false, "regex": null, "hide": false, "maxsize": null, ' '"layout": "vertical", "columns": 1, "tooltip": "", "fields": [{"name": "foo", ' '"fullName": "p1_foo", "label": "foo", "tablabel": "foo", "autopopulate": null, ' '"type": "int", "default": 0, "required": false, "multiple": false, ' '"regex": null, "hide": false, "maxsize": null, "size": 10, "tooltip": ""}]}' ) return self.do_ParameterTest( req={"p1_foo": '123', "reason": 'because'}, expect={"foo": 123}, klass=NestedParameter, fields=fields, expectJson=expect_json, ) def test_NestedNestedParameter(self): fields = [ NestedParameter( name="inner", fields=[StringParameter(name='str'), AnyPropertyParameter(name='any')] ), IntParameter(name="foo"), ] return self.do_ParameterTest( req={ "p1_foo": '123', "p1_inner_str": "bar", "p1_inner_any_name": "hello", "p1_inner_any_value": "world", "reason": "because", }, expect={"foo": 123, "inner": {"str": 'bar', "hello": 'world'}}, klass=NestedParameter, fields=fields, ) def test_NestedParameter_nullname(self): # same as above except "p1" and "any" are skipped fields = [ NestedParameter( name="inner", fields=[StringParameter(name='str'), AnyPropertyParameter(name='')] ), IntParameter(name="foo"), NestedParameter( name='bar', fields=[ NestedParameter(name='', fields=[AnyPropertyParameter(name='a')]), NestedParameter(name='', fields=[AnyPropertyParameter(name='b')]), ], ), ] return self.do_ParameterTest( req={ "foo": '123', "inner_str": "bar", "inner_name": "hello", "inner_value": "world", "reason": "because", "bar_a_name": "a", "bar_a_value": "7", "bar_b_name": "b", "bar_b_value": "8", }, expect={ "foo": 123, "inner": {"str": 'bar', "hello": 'world'}, "bar": {'a': '7', 'b': '8'}, }, expectKind=dict, klass=NestedParameter, fields=fields, name='', ) def test_bad_reason(self): with self.assertRaisesConfigError( "ForceScheduler 'testsched': reason must be a StringParameter" ): ForceScheduler(name='testsched', builderNames=[], codebases=['bar'], reason="foo") def test_bad_username(self): with self.assertRaisesConfigError( "ForceScheduler 'testsched': username must be a StringParameter" ): ForceScheduler(name='testsched', builderNames=[], codebases=['bar'], username="foo") def test_notstring_name(self): with self.assertRaisesConfigError("ForceScheduler name must be a unicode string:"): ForceScheduler(name=1234, builderNames=[], codebases=['bar'], username="foo") def test_notidentifier_name(self): # FIXME: this test should be removed eventually when bug 3460 gets a # real fix with self.assertRaisesConfigError( "ForceScheduler name must be an identifier: 'my scheduler'" ): ForceScheduler(name='my scheduler', builderNames=[], codebases=['bar'], username="foo") def test_emptystring_name(self): with self.assertRaisesConfigError("ForceScheduler name must not be empty:"): ForceScheduler(name='', builderNames=[], codebases=['bar'], username="foo") def test_integer_builderNames(self): with self.assertRaisesConfigError( "ForceScheduler 'testsched': builderNames must be a list of strings:" ): ForceScheduler(name='testsched', builderNames=1234, codebases=['bar'], username="foo") def test_listofints_builderNames(self): with self.assertRaisesConfigError( "ForceScheduler 'testsched': builderNames must be a list of strings:" ): ForceScheduler(name='testsched', builderNames=[1234], codebases=['bar'], username="foo") def test_listofunicode_builderNames(self): ForceScheduler(name='testsched', builderNames=['a', 'b']) def test_listofmixed_builderNames(self): with self.assertRaisesConfigError( "ForceScheduler 'testsched': builderNames must be a list of strings:" ): ForceScheduler( name='testsched', builderNames=['test', 1234], codebases=['bar'], username="foo" ) def test_integer_properties(self): with self.assertRaisesConfigError( "ForceScheduler 'testsched': properties must be a list of BaseParameters:" ): ForceScheduler( name='testsched', builderNames=[], codebases=['bar'], username="foo", properties=1234, ) def test_listofints_properties(self): with self.assertRaisesConfigError( "ForceScheduler 'testsched': properties must be a list of BaseParameters:" ): ForceScheduler( name='testsched', builderNames=[], codebases=['bar'], username="foo", properties=[1234, 2345], ) def test_listofmixed_properties(self): with self.assertRaisesConfigError( "ForceScheduler 'testsched': properties must be a list of BaseParameters:" ): ForceScheduler( name='testsched', builderNames=[], codebases=['bar'], username="foo", properties=[ BaseParameter( name="test", ), 4567, ], ) def test_novalue_to_parameter(self): with self.assertRaisesConfigError( "Use default='1234' instead of value=... to give a default Parameter value" ): BaseParameter(name="test", value="1234")
37,959
Python
.py
929
26.853606
111
0.489999
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,585
test_timed_Nightly.py
buildbot_buildbot/master/buildbot/test/unit/schedulers/test_timed_Nightly.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 time from unittest import mock from twisted.internet import defer from twisted.python import log from twisted.trial import unittest from buildbot.changes import filter from buildbot.schedulers import timed from buildbot.test import fakedb from buildbot.test.reactor import TestReactorMixin from buildbot.test.util import scheduler from buildbot.test.util.state import StateTestMixin class Nightly(scheduler.SchedulerMixin, TestReactorMixin, StateTestMixin, unittest.TestCase): OBJECTID = 132 SCHEDULERID = 32 # not all timezones are even multiples of 1h from GMT. This variable # holds the number of seconds ahead of the hour for the current timezone. # This is then added to the clock before each test is run (to get to 0 # minutes past the hour) and subtracted before the time offset is reported. localtime_offset = time.timezone % 3600 # Timed scheduler uses the datetime module for some time operations. Windows does not like very # small timestamps in these APIs, so tests are adjusted to different times. time_offset = 86400 * 10 + localtime_offset long_ago_time = 86400 @defer.inlineCallbacks def makeScheduler(self, **kwargs): sched = yield self.attachScheduler( timed.Nightly(**kwargs), self.OBJECTID, self.SCHEDULERID, overrideBuildsetMethods=True ) yield self.master.db.insert_test_data([ fakedb.Builder(name=bname) for bname in kwargs.get("builderNames", []) ]) # add a Clock to help checking timing issues sched._reactor = self.reactor self.reactor.advance(self.time_offset) self.addBuildsetCallTimes = [] def recordTimes(timeList, method): def timedMethod(**kw): timeList.append(self.reactor.seconds() - self.time_offset) return method(**kw) return timedMethod sched.addBuildsetForSourceStampsWithDefaults = recordTimes( self.addBuildsetCallTimes, sched.addBuildsetForSourceStampsWithDefaults ) sched.addBuildsetForChanges = recordTimes( self.addBuildsetCallTimes, sched.addBuildsetForChanges ) # see self.assertConsumingChanges self.consumingChanges = None def startConsumingChanges(**kwargs): self.consumingChanges = kwargs return defer.succeed(None) sched.startConsumingChanges = startConsumingChanges return sched def mkbs(self, **kwargs): # create buildset for expected_buildset in assertBuildset. bs = { "reason": "The Nightly scheduler named 'test' triggered this build", "external_idstring": '', "sourcestampsetid": 100, "properties": [('scheduler', ('test', 'Scheduler'))], } bs.update(kwargs) return bs def mkss(self, **kwargs): # create sourcestamp for expected_sourcestamps in assertBuildset. ss = {"branch": 'master', "project": '', "repository": '', "sourcestampsetid": 100} ss.update(kwargs) return ss @defer.inlineCallbacks def mkch(self, **kwargs): # create changeset and insert in database. chd = {"branch": 'master', "project": '', "repository": ''} chd.update(kwargs) ch = self.makeFakeChange(**chd) # fakedb.Change requires changeid instead of number chd['changeid'] = chd['number'] del chd['number'] yield self.db.insert_test_data([fakedb.Change(**chd)]) return ch @defer.inlineCallbacks def setUp(self): self.setup_test_reactor(auto_tear_down=False) yield self.setUpScheduler() @defer.inlineCallbacks def tearDown(self): self.tearDownScheduler() yield self.tear_down_test_reactor() def assertConsumingChanges(self, **kwargs): self.assertEqual(self.consumingChanges, kwargs) # Tests @defer.inlineCallbacks def test_constructor_no_reason(self): sched = yield self.makeScheduler(name='test', builderNames=['test'], branch='default') self.assertEqual(sched.reason, "The Nightly scheduler named 'test' triggered this build") @defer.inlineCallbacks def test_constructor_reason(self): sched = yield self.makeScheduler( name='test', builderNames=['test'], branch='default', reason="hourly" ) self.assertEqual(sched.reason, "hourly") @defer.inlineCallbacks def test_constructor_change_filter(self): sched = yield self.makeScheduler( name='test', builderNames=['test'], branch=None, change_filter=filter.ChangeFilter(category_re="fo+o"), ) assert sched.change_filter @defer.inlineCallbacks def test_constructor_month(self): sched = yield self.makeScheduler( name='test', builderNames=['test'], branch='default', month='1' ) self.assertEqual(sched.month, "1") @defer.inlineCallbacks def test_constructor_priority_none(self): sched = yield self.makeScheduler( name='test', builderNames=['test'], branch='default', priority=None ) self.assertEqual(sched.priority, None) @defer.inlineCallbacks def test_constructor_priority_int(self): sched = yield self.makeScheduler( name='test', builderNames=['test'], branch='default', priority=8 ) self.assertEqual(sched.priority, 8) @defer.inlineCallbacks def test_constructor_priority_function(self): def sched_priority(builderNames, changesByCodebase): return 0 sched = yield self.makeScheduler( name='test', builderNames=['test'], branch='default', priority=sched_priority ) self.assertEqual(sched.priority, sched_priority) @defer.inlineCallbacks def test_enabled_callback(self): sched = yield self.makeScheduler(name='test', builderNames=['test'], branch='default') expectedValue = not sched.enabled yield sched._enabledCallback(None, {'enabled': not sched.enabled}) self.assertEqual(sched.enabled, expectedValue) expectedValue = not sched.enabled yield sched._enabledCallback(None, {'enabled': not sched.enabled}) self.assertEqual(sched.enabled, expectedValue) @defer.inlineCallbacks def test_disabled_activate(self): sched = yield self.makeScheduler(name='test', builderNames=['test'], branch='default') yield sched._enabledCallback(None, {'enabled': not sched.enabled}) self.assertEqual(sched.enabled, False) r = yield sched.activate() self.assertEqual(r, None) @defer.inlineCallbacks def test_disabled_deactivate(self): sched = yield self.makeScheduler(name='test', builderNames=['test'], branch='default') yield sched._enabledCallback(None, {'enabled': not sched.enabled}) self.assertEqual(sched.enabled, False) r = yield sched.deactivate() self.assertEqual(r, None) @defer.inlineCallbacks def test_disabled_start_build(self): sched = yield self.makeScheduler(name='test', builderNames=['test'], branch='default') yield sched._enabledCallback(None, {'enabled': not sched.enabled}) self.assertEqual(sched.enabled, False) r = yield sched.startBuild() self.assertEqual(r, None) # end-to-end tests: let's see the scheduler in action @defer.inlineCallbacks def test_iterations_simple(self): # note that Nightly works in local time, but the TestReactor always # starts at midnight UTC, so be careful not to use times that are # timezone dependent -- stick to minutes-past-the-half-hour, as some # timezones are multiples of 30 minutes off from UTC sched = yield self.makeScheduler( name='test', builderNames=['test'], branch=None, minute=[10, 20, 21, 40, 50, 51] ) # add a change classification yield self.db.schedulers.classifyChanges(self.SCHEDULERID, {19: True}) yield sched.activate() # check that the classification has been flushed, since this # invocation has not requested onlyIfChanged yield self.assert_classifications(self.SCHEDULERID, {}) self.reactor.advance(0) while self.reactor.seconds() < self.time_offset + 30 * 60: self.reactor.advance(60) self.assertEqual(self.addBuildsetCallTimes, [600, 1200, 1260]) self.assertEqual( self.addBuildsetCalls, [ ( 'addBuildsetForSourceStampsWithDefaults', { 'builderNames': None, 'sourcestamps': [{'codebase': ''}], 'priority': None, 'properties': None, 'reason': "The Nightly scheduler named 'test' triggered this build", 'waited_for': False, }, ), ( 'addBuildsetForSourceStampsWithDefaults', { 'builderNames': None, 'sourcestamps': [{'codebase': ''}], 'priority': None, 'properties': None, 'reason': "The Nightly scheduler named 'test' triggered this build", 'waited_for': False, }, ), ( 'addBuildsetForSourceStampsWithDefaults', { 'builderNames': None, 'sourcestamps': [{'codebase': ''}], 'priority': None, 'properties': None, 'reason': "The Nightly scheduler named 'test' triggered this build", 'waited_for': False, }, ), ], ) yield self.assert_state_by_class('test', 'Nightly', last_build=1260 + self.time_offset) yield sched.deactivate() @defer.inlineCallbacks def test_iterations_simple_with_branch(self): # see timezone warning above sched = yield self.makeScheduler( name='test', builderNames=['test'], branch='master', minute=[5, 35] ) sched.activate() self.reactor.advance(0) while self.reactor.seconds() < self.time_offset + 10 * 60: self.reactor.advance(60) self.assertEqual(self.addBuildsetCallTimes, [300]) self.assertEqual( self.addBuildsetCalls, [ ( 'addBuildsetForSourceStampsWithDefaults', { 'builderNames': None, 'sourcestamps': [{'codebase': ''}], 'priority': None, 'properties': None, 'reason': "The Nightly scheduler named 'test' triggered this build", 'waited_for': False, }, ) ], ) yield self.assert_state_by_class('test', 'Nightly', last_build=300 + self.time_offset) yield sched.deactivate() @defer.inlineCallbacks def do_test_iterations_onlyIfChanged( self, changes_at, last_only_if_changed, is_new_scheduler=False, **kwargs ): fII = mock.Mock(name='fII') yield self.makeScheduler( name='test', builderNames=['test'], branch=None, minute=[5, 25, 45], onlyIfChanged=True, fileIsImportant=fII, **kwargs, ) if not is_new_scheduler: yield self.set_fake_state(self.sched, 'last_build', self.long_ago_time) if last_only_if_changed is not None: yield self.set_fake_state(self.sched, 'last_only_if_changed', last_only_if_changed) return (yield self.do_test_iterations_onlyIfChanged_test(fII, changes_at)) @defer.inlineCallbacks def do_test_iterations_onlyIfChanged_test(self, fII, changes_at): yield self.sched.activate() # check that the scheduler has started to consume changes self.assertConsumingChanges(fileIsImportant=fII, change_filter=None, onlyImportant=False) # manually run the clock forward through a half-hour, allowing any # excitement to take place self.reactor.advance(0) # let it trigger the first build while self.reactor.seconds() < self.time_offset + 30 * 60: # inject any new changes.. while changes_at and self.reactor.seconds() >= self.time_offset + changes_at[0][0]: _, newchange, important = changes_at.pop(0) newchange = yield self.addFakeChange(newchange) yield self.sched.gotChange(newchange, important).addErrback(log.err) # and advance the clock by a minute self.reactor.advance(60) @defer.inlineCallbacks def test_iterations_onlyIfChanged_no_changes_new_scheduler(self): yield self.do_test_iterations_onlyIfChanged( [], last_only_if_changed=None, is_new_scheduler=True ) self.assertEqual( self.addBuildsetCalls, [ ( 'addBuildsetForSourceStampsWithDefaults', { 'builderNames': None, 'priority': None, 'properties': None, 'reason': "The Nightly scheduler named 'test' triggered this build", 'sourcestamps': [{'codebase': ''}], 'waited_for': False, }, ) ], ) yield self.assert_state_by_class('test', 'Nightly', last_build=1500 + self.time_offset) yield self.sched.deactivate() @defer.inlineCallbacks def test_iterations_onlyIfChanged_no_changes_existing_scheduler(self): yield self.do_test_iterations_onlyIfChanged([], last_only_if_changed=True) self.assertEqual(self.addBuildsetCalls, []) yield self.assert_state_by_class('test', 'Nightly', last_build=1500 + self.time_offset) yield self.sched.deactivate() @defer.inlineCallbacks def test_iterations_onlyIfChanged_no_changes_existing_scheduler_setting_changed(self): # When onlyIfChanged==False, builds are run every time on the time set # (changes or no changes). Changes are being recognized but do not have any effect on # starting builds. # It might happen that onlyIfChanged was False, then change happened, then setting was # changed to onlyIfChanged==True. # Because onlyIfChanged was False possibly important change will be missed. # Therefore the first build should start immediately. yield self.do_test_iterations_onlyIfChanged([], last_only_if_changed=False) self.assertEqual( self.addBuildsetCalls, [ ( 'addBuildsetForSourceStampsWithDefaults', { 'builderNames': None, 'priority': None, 'properties': None, 'reason': "The Nightly scheduler named 'test' triggered this build", 'sourcestamps': [{'codebase': ''}], 'waited_for': False, }, ) ], ) yield self.assert_state_by_class('test', 'Nightly', last_build=1500 + self.time_offset) yield self.sched.deactivate() @defer.inlineCallbacks def test_iterations_onlyIfChanged_no_changes_existing_scheduler_update_to_v3_5_0(self): # v3.4.0 have not had a variable last_only_if_changed yet therefore this case is tested # separately yield self.do_test_iterations_onlyIfChanged([], last_only_if_changed=None) self.assertEqual(self.addBuildsetCallTimes, []) self.assertEqual(self.addBuildsetCalls, []) yield self.assert_state_by_class('test', 'Nightly', last_build=1500 + self.time_offset) yield self.sched.deactivate() @defer.inlineCallbacks def test_iterations_onlyIfChanged_no_changes_force_at(self): yield self.do_test_iterations_onlyIfChanged( [], last_only_if_changed=True, force_at_minute=[23, 25, 27] ) self.assertEqual(self.addBuildsetCallTimes, [1500]) self.assertEqual( self.addBuildsetCalls, [ ( 'addBuildsetForSourceStampsWithDefaults', { 'builderNames': None, 'priority': None, 'properties': None, 'reason': "The Nightly scheduler named 'test' triggered this build", 'sourcestamps': [{'codebase': ''}], 'waited_for': False, }, ) ], ) yield self.assert_state_by_class('test', 'Nightly', last_build=1500 + self.time_offset) yield self.sched.deactivate() @defer.inlineCallbacks def test_iterations_onlyIfChanged_unimp_changes_calls_for_new_scheduler(self): yield self.do_test_iterations_onlyIfChanged( [ (60, self.makeFakeChange(number=500, branch=None), False), (600, self.makeFakeChange(number=501, branch=None), False), ], last_only_if_changed=None, is_new_scheduler=True, ) self.assertEqual( self.addBuildsetCalls, [ ( 'addBuildsetForChanges', { 'builderNames': None, 'changeids': [500], 'external_idstring': None, 'priority': None, 'properties': None, 'reason': "The Nightly scheduler named 'test' triggered this build", 'waited_for': False, }, ) ], ) yield self.assert_state_by_class('test', 'Nightly', last_build=1500 + self.time_offset) yield self.sched.deactivate() @defer.inlineCallbacks def test_iterations_onlyIfChanged_unimp_changes_existing_sched_changed_only_if_changed(self): yield self.do_test_iterations_onlyIfChanged( [ (60, self.makeFakeChange(number=500, branch=None), False), (600, self.makeFakeChange(number=501, branch=None), False), ], last_only_if_changed=False, ) self.assertEqual( self.addBuildsetCalls, [ ( 'addBuildsetForSourceStampsWithDefaults', { 'builderNames': None, 'priority': None, 'properties': None, 'reason': "The Nightly scheduler named 'test' triggered this build", 'sourcestamps': [{'codebase': ''}], 'waited_for': False, }, ) ], ) yield self.assert_state_by_class('test', 'Nightly', last_build=1500 + self.time_offset) yield self.sched.deactivate() @defer.inlineCallbacks def test_iterations_onlyIfChanged_unimp_changes_existing_sched_same_only_if_changed(self): yield self.do_test_iterations_onlyIfChanged( [ (60, self.makeFakeChange(number=500, branch=None), False), (600, self.makeFakeChange(number=501, branch=None), False), ], last_only_if_changed=True, ) self.assertEqual(self.addBuildsetCalls, []) yield self.assert_state_by_class('test', 'Nightly', last_build=1500 + self.time_offset) yield self.sched.deactivate() @defer.inlineCallbacks def test_iterations_onlyIfChanged_changes_existing_scheduler_update_to_v3_5_0(self): # v3.4.0 have not had a variable last_only_if_changed yet therefore this case is tested # separately yield self.do_test_iterations_onlyIfChanged( [ (120, self.makeFakeChange(number=500, branch=None), False), (1200, self.makeFakeChange(number=501, branch=None), True), (1201, self.makeFakeChange(number=502, branch=None), False), ], last_only_if_changed=None, ) self.assertEqual(self.addBuildsetCallTimes, [1500]) self.assertEqual( self.addBuildsetCalls, [ ( 'addBuildsetForChanges', { 'waited_for': False, 'reason': "The Nightly scheduler named 'test' triggered this build", 'external_idstring': None, 'changeids': [500, 501, 502], 'priority': None, 'properties': None, 'builderNames': None, }, ), ], ) yield self.assert_state_by_class('test', 'Nightly', last_build=1500 + self.time_offset) yield self.sched.deactivate() @defer.inlineCallbacks def test_iterations_onlyIfChanged_unimp_changes_force_at(self): yield self.do_test_iterations_onlyIfChanged( [ (60, self.makeFakeChange(number=500, branch=None), False), (600, self.makeFakeChange(number=501, branch=None), False), ], last_only_if_changed=True, force_at_minute=[23, 25, 27], ) self.assertEqual(self.addBuildsetCallTimes, [1500]) self.assertEqual( self.addBuildsetCalls, [ ( 'addBuildsetForChanges', { 'builderNames': None, 'changeids': [500, 501], 'external_idstring': None, 'priority': None, 'properties': None, 'reason': "The Nightly scheduler named 'test' triggered this build", 'waited_for': False, }, ) ], ) yield self.assert_state_by_class('test', 'Nightly', last_build=1500 + self.time_offset) yield self.sched.deactivate() @defer.inlineCallbacks def test_iterations_onlyIfChanged_off_branch_changes(self): yield self.do_test_iterations_onlyIfChanged( [ (60, self.makeFakeChange(number=500, branch='testing'), True), (1700, self.makeFakeChange(number=501, branch='staging'), True), ], last_only_if_changed=True, ) self.assertEqual(self.addBuildsetCalls, []) yield self.assert_state_by_class('test', 'Nightly', last_build=1500 + self.time_offset) yield self.sched.deactivate() @defer.inlineCallbacks def test_iterations_onlyIfChanged_mixed_changes(self): yield self.do_test_iterations_onlyIfChanged( [ (120, self.makeFakeChange(number=500, branch=None), False), (130, self.makeFakeChange(number=501, branch='offbranch'), True), (1200, self.makeFakeChange(number=502, branch=None), True), (1201, self.makeFakeChange(number=503, branch=None), False), (1202, self.makeFakeChange(number=504, branch='offbranch'), True), ], last_only_if_changed=True, ) # note that the changeid list includes the unimportant changes, but not the # off-branch changes, and note that no build took place at 300s, as no important # changes had yet arrived self.assertEqual(self.addBuildsetCallTimes, [1500]) self.assertEqual( self.addBuildsetCalls, [ ( 'addBuildsetForChanges', { 'builderNames': None, 'changeids': [500, 502, 503], 'external_idstring': None, 'priority': None, 'properties': None, 'reason': "The Nightly scheduler named 'test' triggered this build", 'waited_for': False, }, ) ], ) yield self.assert_state_by_class('test', 'Nightly', last_build=1500 + self.time_offset) yield self.sched.deactivate() @defer.inlineCallbacks def test_iterations_onlyIfChanged_createAbsoluteSourceStamps_oneChanged(self): # Test createAbsoluteSourceStamps=True when only one codebase has # changed yield self.do_test_iterations_onlyIfChanged( [ (120, self.makeFakeChange(number=500, codebase='a', revision='2345:bcd'), True), ], codebases={ 'a': {'repository': "", 'branch': 'master'}, 'b': {'repository': "", 'branch': 'master'}, }, createAbsoluteSourceStamps=True, last_only_if_changed=True, ) yield self.assert_state_by_class('test', 'Nightly', last_build=1500 + self.time_offset) # addBuildsetForChanges calls getCodebase, so this isn't too # interesting self.assertEqual(self.addBuildsetCallTimes, [300]) self.assertEqual( self.addBuildsetCalls, [ ( 'addBuildsetForChanges', { 'builderNames': None, 'changeids': [500], 'external_idstring': None, 'priority': None, 'properties': None, 'reason': "The Nightly scheduler named 'test' triggered this build", 'waited_for': False, }, ) ], ) yield self.assert_state_by_class( 'test', 'Nightly', lastCodebases={ 'a': {"revision": '2345:bcd', "branch": None, "repository": '', "lastChange": 500} }, ) yield self.sched.deactivate() @defer.inlineCallbacks def test_iterations_onlyIfChanged_createAbsoluteSourceStamps_oneChanged_loadOther(self): # Test createAbsoluteSourceStamps=True when only one codebase has changed, # but the other was previously changed fII = mock.Mock(name='fII') yield self.makeScheduler( name='test', builderNames=['test'], branch=None, minute=[5, 25, 45], onlyIfChanged=True, fileIsImportant=fII, codebases={ 'a': {'repository': "", 'branch': 'master'}, 'b': {'repository': "", 'branch': 'master'}, }, createAbsoluteSourceStamps=True, ) yield self.set_fake_state(self.sched, 'last_only_if_changed', True) yield self.set_fake_state( self.sched, 'lastCodebases', { 'b': { 'branch': 'master', 'repository': 'B', 'revision': '1234:abc', 'lastChange': 499, } }, ) yield self.do_test_iterations_onlyIfChanged_test( fII, [ (120, self.makeFakeChange(number=500, codebase='a', revision='2345:bcd'), True), ], ) yield self.assert_state_by_class('test', 'Nightly', last_build=1500 + self.time_offset) # addBuildsetForChanges calls getCodebase, so this isn't too # interesting self.assertEqual(self.addBuildsetCallTimes, [300]) self.assertEqual( self.addBuildsetCalls, [ ( 'addBuildsetForChanges', { 'builderNames': None, 'changeids': [500], 'external_idstring': None, 'priority': None, 'properties': None, 'reason': "The Nightly scheduler named 'test' triggered this build", 'waited_for': False, }, ) ], ) yield self.assert_state_by_class( 'test', 'Nightly', lastCodebases={ 'a': {"revision": '2345:bcd', "branch": None, "repository": '', "lastChange": 500}, 'b': { "revision": '1234:abc', "branch": "master", "repository": 'B', "lastChange": 499, }, }, ) yield self.sched.deactivate() @defer.inlineCallbacks def test_iterations_onlyIfChanged_createAbsoluteSourceStamps_bothChanged(self): # Test createAbsoluteSourceStamps=True when both codebases have changed yield self.do_test_iterations_onlyIfChanged( [ (120, self.makeFakeChange(number=500, codebase='a', revision='2345:bcd'), True), (122, self.makeFakeChange(number=501, codebase='b', revision='1234:abc'), True), ], codebases={ 'a': {'repository': "", 'branch': 'master'}, 'b': {'repository': "", 'branch': 'master'}, }, last_only_if_changed=None, createAbsoluteSourceStamps=True, ) yield self.assert_state_by_class('test', 'Nightly', last_build=1500 + self.time_offset) # addBuildsetForChanges calls getCodebase, so this isn't too # interesting self.assertEqual(self.addBuildsetCallTimes, [300]) self.assertEqual( self.addBuildsetCalls, [ ( 'addBuildsetForChanges', { 'builderNames': None, 'changeids': [500, 501], 'external_idstring': None, 'priority': None, 'properties': None, 'reason': "The Nightly scheduler named 'test' triggered this build", 'waited_for': False, }, ) ], ) yield self.assert_state_by_class( 'test', 'Nightly', lastCodebases={ 'a': {"revision": '2345:bcd', "branch": None, "repository": '', "lastChange": 500}, 'b': {"revision": '1234:abc', "branch": None, "repository": '', "lastChange": 501}, }, ) yield self.sched.deactivate()
32,086
Python
.py
731
30.971272
99
0.565466
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,586
test_triggerable.py
buildbot_buildbot/master/buildbot/test/unit/schedulers/test_triggerable.py
# This file is part of Buildbot. Buildbot is free software: you can # redistribute it and/or modify it under the terms of the GNU General Public # License as published by the Free Software Foundation, version 2. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more # details. # # You should have received a copy of the GNU General Public License along with # this program; if not, write to the Free Software Foundation, Inc., 51 # Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # Copyright Buildbot Team Members from twisted.internet import defer from twisted.python import log from twisted.trial import unittest from buildbot.db.buildrequests import BuildRequestModel from buildbot.db.buildsets import BuildSetModel from buildbot.process import properties from buildbot.schedulers import triggerable from buildbot.test import fakedb from buildbot.test.reactor import TestReactorMixin from buildbot.test.util import interfaces from buildbot.test.util import scheduler class TriggerableInterfaceTest(unittest.TestCase, interfaces.InterfaceTests): def test_interface(self): self.assertInterfacesImplemented(triggerable.Triggerable) class Triggerable(scheduler.SchedulerMixin, TestReactorMixin, unittest.TestCase): OBJECTID = 33 SCHEDULERID = 13 @defer.inlineCallbacks def setUp(self): self.setup_test_reactor(auto_tear_down=False) # Necessary to get an assertable submitted_at time. self.reactor.advance(946684799) yield self.setUpScheduler() self.subscription = None @defer.inlineCallbacks def tearDown(self): self.tearDownScheduler() yield self.tear_down_test_reactor() @defer.inlineCallbacks def makeScheduler(self, overrideBuildsetMethods=False, **kwargs): yield self.master.db.insert_test_data([fakedb.Builder(id=77, name='b')]) sched = yield self.attachScheduler( triggerable.Triggerable(name='n', builderNames=['b'], **kwargs), self.OBJECTID, self.SCHEDULERID, overrideBuildsetMethods=overrideBuildsetMethods, ) return sched @defer.inlineCallbacks def assertTriggeredBuildset(self, idsDeferred, waited_for, properties=None, sourcestamps=None): if properties is None: properties = {} bsid, brids = yield idsDeferred properties.update({'scheduler': ('n', 'Scheduler')}) buildset = yield self.master.db.buildsets.getBuildset(bsid) got_properties = yield self.master.db.buildsets.getBuildsetProperties(bsid) self.assertEqual(got_properties, properties) from datetime import datetime from buildbot.util import UTC self.assertEqual( buildset, BuildSetModel( bsid=bsid, external_idstring=None, reason="The Triggerable scheduler named 'n' triggered this build", submitted_at=datetime(1999, 12, 31, 23, 59, 59, tzinfo=UTC), results=-1, # sourcestamps testing is just after sourcestamps=buildset.sourcestamps, ), ) actual_sourcestamps = yield defer.gatherResults([ self.master.db.sourcestamps.getSourceStamp(ssid) for ssid in buildset.sourcestamps ]) self.assertEqual(len(sourcestamps), len(actual_sourcestamps)) for expected_ss, actual_ss in zip(sourcestamps, actual_sourcestamps): # We don't care if the actual sourcestamp has *more* attributes # than expected. self.assertEqual(expected_ss, {k: getattr(actual_ss, k) for k in expected_ss.keys()}) for brid in brids.values(): buildrequest = yield self.master.db.buildrequests.getBuildRequest(brid) self.assertEqual( buildrequest, BuildRequestModel( buildrequestid=brid, buildername='b', builderid=77, buildsetid=bsid, claimed_at=None, complete=False, complete_at=None, claimed_by_masterid=None, priority=0, results=-1, submitted_at=datetime(1999, 12, 31, 23, 59, 59, tzinfo=UTC), waited_for=waited_for, ), ) return bsid def sendCompletionMessage(self, bsid, results=3): self.master.mq.callConsumer( ('buildsets', str(bsid), 'complete'), { "bsid": bsid, "submitted_at": 100, "complete": True, "complete_at": 200, "external_idstring": None, "reason": 'triggering', "results": results, "sourcestamps": [], "parent_buildid": None, "parent_relationship": None, }, ) # tests # NOTE: these tests take advantage of the fact that all of the fake # scheduler operations are synchronous, and thus do not return a Deferred. # The Deferred from trigger() is completely processed before this test # method returns. @defer.inlineCallbacks def test_constructor_no_reason(self): sched = yield self.makeScheduler() self.assertEqual(sched.reason, None) # default reason is dynamic @defer.inlineCallbacks def test_constructor_explicit_reason(self): sched = yield self.makeScheduler(reason="Because I said so") self.assertEqual(sched.reason, "Because I said so") @defer.inlineCallbacks def test_constructor_priority_none(self): sched = yield self.makeScheduler(priority=None) self.assertEqual(sched.priority, None) @defer.inlineCallbacks def test_constructor_priority_int(self): sched = yield self.makeScheduler(priority=8) self.assertEqual(sched.priority, 8) @defer.inlineCallbacks def test_constructor_priority_function(self): def sched_priority(builderNames, changesByCodebase): return 0 sched = yield self.makeScheduler(priority=sched_priority) self.assertEqual(sched.priority, sched_priority) @defer.inlineCallbacks def test_trigger(self): sched = yield self.makeScheduler(codebases={'cb': {'repository': 'r'}}) # no subscription should be in place yet self.assertEqual(sched.master.mq.qrefs, []) # trigger the scheduler, exercising properties while we're at it waited_for = True set_props = properties.Properties() set_props.setProperty('pr', 'op', 'test') ss = { 'revision': 'myrev', 'branch': 'br', 'project': 'p', 'repository': 'r', 'codebase': 'cb', } idsDeferred, d = sched.trigger(waited_for, sourcestamps=[ss], set_props=set_props) self.reactor.advance(0) # let the debounced function fire bsid = yield self.assertTriggeredBuildset( idsDeferred, waited_for, properties={'pr': ('op', 'test')}, sourcestamps=[ { "branch": 'br', "project": 'p', "repository": 'r', "codebase": 'cb', "revision": 'myrev', }, ], ) # set up a boolean so that we can know when the deferred fires self.fired = False @d.addCallback def fired(xxx_todo_changeme): (result, brids) = xxx_todo_changeme self.assertEqual(result, 3) # from sendCompletionMessage self.assertEqual(brids, {77: 1}) self.fired = True d.addErrback(log.err) # check that the scheduler has subscribed to buildset changes, but # not fired yet self.assertEqual( [q.filter for q in sched.master.mq.qrefs], [ ( 'buildsets', None, 'complete', ) ], ) self.assertFalse(self.fired) # pretend a non-matching buildset is complete self.sendCompletionMessage(27) # scheduler should not have reacted self.assertEqual( [q.filter for q in sched.master.mq.qrefs], [ ( 'buildsets', None, 'complete', ) ], ) self.assertFalse(self.fired) # pretend the matching buildset is complete self.sendCompletionMessage(bsid) self.reactor.advance(0) # let the debounced function fire # scheduler should have reacted self.assertEqual([q.filter for q in sched.master.mq.qrefs], []) self.assertTrue(self.fired) yield d @defer.inlineCallbacks def test_trigger_overlapping(self): sched = yield self.makeScheduler(codebases={'cb': {'repository': 'r'}}) # no subscription should be in place yet self.assertEqual(sched.master.mq.qrefs, []) waited_for = False def makeSS(rev): return { 'revision': rev, 'branch': 'br', 'project': 'p', 'repository': 'r', 'codebase': 'cb', } # trigger the scheduler the first time idsDeferred, d = sched.trigger(waited_for, [makeSS('myrev1')]) # triggers bsid 200 bsid1 = yield self.assertTriggeredBuildset( idsDeferred, waited_for, sourcestamps=[ { "branch": 'br', "project": 'p', "repository": 'r', "codebase": 'cb', "revision": 'myrev1', }, ], ) d.addCallback( lambda res_brids: self.assertEqual(res_brids[0], 11) and self.assertEqual(res_brids[1], {77: 1}) ) waited_for = True # and the second time idsDeferred, d = sched.trigger(waited_for, [makeSS('myrev2')]) # triggers bsid 201 self.reactor.advance(0) # let the debounced function fire bsid2 = yield self.assertTriggeredBuildset( idsDeferred, waited_for, sourcestamps=[ { "branch": 'br', "project": 'p', "repository": 'r', "codebase": 'cb', "revision": 'myrev2', }, ], ) d.addCallback( lambda res_brids1: self.assertEqual(res_brids1[0], 22) and self.assertEqual(res_brids1[1], {77: 2}) ) # check that the scheduler has subscribed to buildset changes self.assertEqual( [q.filter for q in sched.master.mq.qrefs], [ ( 'buildsets', None, 'complete', ) ], ) # let a few buildsets complete self.sendCompletionMessage(29, results=3) self.sendCompletionMessage(bsid2, results=22) self.sendCompletionMessage(9, results=3) self.sendCompletionMessage(bsid1, results=11) self.reactor.advance(0) # let the debounced function fire # both should have triggered with appropriate results, and the # subscription should be cancelled self.assertEqual(sched.master.mq.qrefs, []) @defer.inlineCallbacks def test_trigger_with_sourcestamp(self): # Test triggering a scheduler with a sourcestamp, and see that # sourcestamp handed to addBuildsetForSourceStampsWithDefaults. sched = yield self.makeScheduler(overrideBuildsetMethods=True) waited_for = False ss = { 'repository': 'r3', 'codebase': 'cb3', 'revision': 'fixrev3', 'branch': 'default', 'project': 'p', } idsDeferred = sched.trigger(waited_for, sourcestamps=[ss])[0] yield idsDeferred self.assertEqual( self.addBuildsetCalls, [ ( 'addBuildsetForSourceStampsWithDefaults', { 'builderNames': None, 'priority': None, 'properties': {'scheduler': ('n', 'Scheduler')}, 'reason': "The Triggerable scheduler named 'n' triggered this build", 'sourcestamps': [ { 'branch': 'default', 'codebase': 'cb3', 'project': 'p', 'repository': 'r3', 'revision': 'fixrev3', }, ], 'waited_for': False, }, ), ], ) @defer.inlineCallbacks def test_trigger_without_sourcestamps(self): # Test triggering *without* sourcestamps, and see that nothing is passed # to addBuildsetForSourceStampsWithDefaults waited_for = True sched = yield self.makeScheduler(overrideBuildsetMethods=True) idsDeferred = sched.trigger(waited_for, sourcestamps=[])[0] yield idsDeferred self.assertEqual( self.addBuildsetCalls, [ ( 'addBuildsetForSourceStampsWithDefaults', { 'builderNames': None, 'priority': None, 'properties': {'scheduler': ('n', 'Scheduler')}, 'reason': "The Triggerable scheduler named 'n' triggered this build", 'sourcestamps': [], 'waited_for': True, }, ), ], ) @defer.inlineCallbacks def test_trigger_with_reason(self): # Test triggering with a reason, and make sure the buildset's reason is updated accordingly # (and not the default) waited_for = True sched = yield self.makeScheduler(overrideBuildsetMethods=True) set_props = properties.Properties() set_props.setProperty('reason', 'test1', 'test') idsDeferred, _ = sched.trigger(waited_for, sourcestamps=[], set_props=set_props) yield idsDeferred self.assertEqual( self.addBuildsetCalls, [ ( 'addBuildsetForSourceStampsWithDefaults', { 'builderNames': None, 'priority': None, 'properties': { 'scheduler': ('n', 'Scheduler'), 'reason': ('test1', 'test'), }, 'reason': "test1", 'sourcestamps': [], 'waited_for': True, }, ), ], ) @defer.inlineCallbacks def test_startService_stopService(self): sched = yield self.makeScheduler() yield sched.startService() yield sched.stopService()
15,779
Python
.py
392
27.757653
99
0.559723
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,587
test_timed_NightlyBase.py
buildbot_buildbot/master/buildbot/test/unit/schedulers/test_timed_NightlyBase.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 time from twisted.internet import defer from twisted.trial import unittest from buildbot.schedulers import timed from buildbot.test.reactor import TestReactorMixin from buildbot.test.util import scheduler class NightlyBase(scheduler.SchedulerMixin, TestReactorMixin, unittest.TestCase): """detailed getNextBuildTime tests""" OBJECTID = 133 SCHEDULERID = 33 @defer.inlineCallbacks def setUp(self): self.setup_test_reactor(auto_tear_down=False) yield self.setUpScheduler() @defer.inlineCallbacks def tearDown(self): self.tearDownScheduler() yield self.tear_down_test_reactor() def makeScheduler(self, firstBuildDuration=0, **kwargs): return self.attachScheduler(timed.NightlyBase(**kwargs), self.OBJECTID, self.SCHEDULERID) @defer.inlineCallbacks def do_getNextBuildTime_test(self, sched, *expectations): for lastActuated, expected in expectations: # convert from tuples to epoch time (in local timezone) lastActuated_ep, expected_ep = [ time.mktime(t + (0,) * (8 - len(t)) + (-1,)) for t in (lastActuated, expected) ] got_ep = yield sched.getNextBuildTime(lastActuated_ep) self.assertEqual( got_ep, expected_ep, f"{lastActuated} -> {time.localtime(got_ep)} != {expected}" ) @defer.inlineCallbacks def test_getNextBuildTime_hourly(self): sched = yield self.makeScheduler(name='test', builderNames=['test']) yield self.do_getNextBuildTime_test( sched, ((2011, 1, 1, 3, 0, 0), (2011, 1, 1, 4, 0, 0)), ((2011, 1, 1, 3, 15, 0), (2011, 1, 1, 4, 0, 0)), ((2011, 1, 1, 3, 15, 1), (2011, 1, 1, 4, 0, 0)), ((2011, 1, 1, 3, 59, 1), (2011, 1, 1, 4, 0, 0)), ((2011, 1, 1, 3, 59, 59), (2011, 1, 1, 4, 0, 0)), ((2011, 1, 1, 23, 22, 22), (2011, 1, 2, 0, 0, 0)), ((2011, 1, 1, 23, 59, 0), (2011, 1, 2, 0, 0, 0)), ) @defer.inlineCallbacks def test_getNextBuildTime_minutes_single(self): # basically the same as .._hourly sched = yield self.makeScheduler(name='test', builderNames=['test'], minute=4) yield self.do_getNextBuildTime_test( sched, ((2011, 1, 1, 3, 0, 0), (2011, 1, 1, 3, 4, 0)), ((2011, 1, 1, 3, 15, 0), (2011, 1, 1, 4, 4, 0)), ) @defer.inlineCallbacks def test_getNextBuildTime_minutes_multiple(self): sched = yield self.makeScheduler(name='test', builderNames=['test'], minute=[4, 34]) yield self.do_getNextBuildTime_test( sched, ((2011, 1, 1, 3, 0, 0), (2011, 1, 1, 3, 4, 0)), ((2011, 1, 1, 3, 15, 0), (2011, 1, 1, 3, 34, 0)), ((2011, 1, 1, 3, 34, 0), (2011, 1, 1, 4, 4, 0)), ((2011, 1, 1, 3, 59, 1), (2011, 1, 1, 4, 4, 0)), ) @defer.inlineCallbacks def test_getNextBuildTime_minutes_star(self): sched = yield self.makeScheduler(name='test', builderNames=['test'], minute='*') yield self.do_getNextBuildTime_test( sched, ((2011, 1, 1, 3, 11, 30), (2011, 1, 1, 3, 12, 0)), ((2011, 1, 1, 3, 12, 0), (2011, 1, 1, 3, 13, 0)), ((2011, 1, 1, 3, 59, 0), (2011, 1, 1, 4, 0, 0)), ) @defer.inlineCallbacks def test_getNextBuildTime_hours_single(self): sched = yield self.makeScheduler(name='test', builderNames=['test'], hour=4) yield self.do_getNextBuildTime_test( sched, ((2011, 1, 1, 3, 0), (2011, 1, 1, 4, 0)), ((2011, 1, 1, 13, 0), (2011, 1, 2, 4, 0)), ) @defer.inlineCallbacks def test_getNextBuildTime_hours_multiple(self): sched = yield self.makeScheduler(name='test', builderNames=['test'], hour=[7, 19]) yield self.do_getNextBuildTime_test( sched, ((2011, 1, 1, 3, 0), (2011, 1, 1, 7, 0)), ((2011, 1, 1, 7, 1), (2011, 1, 1, 19, 0)), ((2011, 1, 1, 18, 59), (2011, 1, 1, 19, 0)), ((2011, 1, 1, 19, 59), (2011, 1, 2, 7, 0)), ) @defer.inlineCallbacks def test_getNextBuildTime_hours_minutes(self): sched = yield self.makeScheduler(name='test', builderNames=['test'], hour=13, minute=19) yield self.do_getNextBuildTime_test( sched, ((2011, 1, 1, 3, 11), (2011, 1, 1, 13, 19)), ((2011, 1, 1, 13, 19), (2011, 1, 2, 13, 19)), ((2011, 1, 1, 23, 59), (2011, 1, 2, 13, 19)), ) @defer.inlineCallbacks def test_getNextBuildTime_month_single(self): sched = yield self.makeScheduler(name='test', builderNames=['test'], month=3) yield self.do_getNextBuildTime_test( sched, ((2011, 2, 27, 3, 11), (2011, 3, 1, 0, 0)), # still hourly! ((2011, 3, 1, 1, 11), (2011, 3, 1, 2, 0)), ) @defer.inlineCallbacks def test_getNextBuildTime_month_multiple(self): sched = yield self.makeScheduler(name='test', builderNames=['test'], month=[4, 6]) yield self.do_getNextBuildTime_test( sched, ((2011, 3, 30, 3, 11), (2011, 4, 1, 0, 0)), # still hourly! ((2011, 4, 1, 1, 11), (2011, 4, 1, 2, 0)), ((2011, 5, 29, 3, 11), (2011, 6, 1, 0, 0)), ) @defer.inlineCallbacks def test_getNextBuildTime_month_dayOfMonth(self): sched = yield self.makeScheduler( name='test', builderNames=['test'], month=[3, 6], dayOfMonth=[15] ) yield self.do_getNextBuildTime_test( sched, ((2011, 2, 12, 3, 11), (2011, 3, 15, 0, 0)), ((2011, 3, 12, 3, 11), (2011, 3, 15, 0, 0)), ) @defer.inlineCallbacks def test_getNextBuildTime_dayOfMonth_single(self): sched = yield self.makeScheduler(name='test', builderNames=['test'], dayOfMonth=10) yield self.do_getNextBuildTime_test( sched, ((2011, 1, 9, 3, 0), (2011, 1, 10, 0, 0)), # still hourly! ((2011, 1, 10, 3, 0), (2011, 1, 10, 4, 0)), ((2011, 1, 30, 3, 0), (2011, 2, 10, 0, 0)), ((2011, 12, 30, 11, 0), (2012, 1, 10, 0, 0)), ) @defer.inlineCallbacks def test_getNextBuildTime_dayOfMonth_multiple(self): sched = yield self.makeScheduler( name='test', builderNames=['test'], dayOfMonth=[10, 20, 30] ) yield self.do_getNextBuildTime_test( sched, ((2011, 1, 9, 22, 0), (2011, 1, 10, 0, 0)), ((2011, 1, 19, 22, 0), (2011, 1, 20, 0, 0)), ((2011, 1, 29, 22, 0), (2011, 1, 30, 0, 0)), # no Feb 30! ((2011, 2, 29, 22, 0), (2011, 3, 10, 0, 0)), ) @defer.inlineCallbacks def test_getNextBuildTime_dayOfMonth_hours_minutes(self): sched = yield self.makeScheduler( name='test', builderNames=['test'], dayOfMonth=15, hour=20, minute=30 ) yield self.do_getNextBuildTime_test( sched, ((2011, 1, 13, 22, 19), (2011, 1, 15, 20, 30)), ((2011, 1, 15, 19, 19), (2011, 1, 15, 20, 30)), ((2011, 1, 15, 20, 29), (2011, 1, 15, 20, 30)), ) @defer.inlineCallbacks def test_getNextBuildTime_dayOfWeek_single(self): sched = yield self.makeScheduler( name='test', builderNames=['test'], dayOfWeek=1 ) # Tuesday (2011-1-1 was a Saturday) yield self.do_getNextBuildTime_test( sched, ((2011, 1, 3, 22, 19), (2011, 1, 4, 0, 0)), # still hourly! ((2011, 1, 4, 19, 19), (2011, 1, 4, 20, 0)), ) @defer.inlineCallbacks def test_getNextBuildTime_dayOfWeek_single_as_string(self): sched = yield self.makeScheduler( name='test', builderNames=['test'], dayOfWeek="1" ) # Tuesday (2011-1-1 was a Saturday) yield self.do_getNextBuildTime_test( sched, ((2011, 1, 3, 22, 19), (2011, 1, 4, 0, 0)), # still hourly! ((2011, 1, 4, 19, 19), (2011, 1, 4, 20, 0)), ) @defer.inlineCallbacks def test_getNextBuildTime_dayOfWeek_multiple_as_string(self): sched = yield self.makeScheduler( name='test', builderNames=['test'], dayOfWeek="tue,3" ) # Tuesday, Thursday (2011-1-1 was a Saturday) yield self.do_getNextBuildTime_test( sched, ((2011, 1, 3, 22, 19), (2011, 1, 4, 0, 0)), # still hourly! ((2011, 1, 4, 19, 19), (2011, 1, 4, 20, 0)), ((2011, 1, 5, 22, 19), (2011, 1, 6, 0, 0)), # still hourly! ((2011, 1, 6, 19, 19), (2011, 1, 6, 20, 0)), ) @defer.inlineCallbacks def test_getNextBuildTime_dayOfWeek_multiple_hours(self): # Tuesday, Thursday (2011-1-1 was a Saturday) sched = yield self.makeScheduler( name='test', builderNames=['test'], dayOfWeek=[1, 3], hour=1 ) yield self.do_getNextBuildTime_test( sched, ((2011, 1, 3, 22, 19), (2011, 1, 4, 1, 0)), ((2011, 1, 4, 22, 19), (2011, 1, 6, 1, 0)), ) @defer.inlineCallbacks def test_getNextBuildTime_dayOfWeek_dayOfMonth(self): sched = yield self.makeScheduler( name='test', builderNames=['test'], dayOfWeek=[1, 4], dayOfMonth=5, hour=1 ) yield self.do_getNextBuildTime_test( sched, # Tues ((2011, 1, 3, 22, 19), (2011, 1, 4, 1, 0)), # 5th ((2011, 1, 4, 22, 19), (2011, 1, 5, 1, 0)), # Thurs ((2011, 1, 5, 22, 19), (2011, 1, 7, 1, 0)), )
10,531
Python
.py
238
34.87395
97
0.551637
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,588
test_timed_NightlyTriggerable.py
buildbot_buildbot/master/buildbot/test/unit/schedulers/test_timed_NightlyTriggerable.py
# This file is part of Buildbot. Buildbot is free software: you can # redistribute it and/or modify it under the terms of the GNU General Public # License as published by the Free Software Foundation, version 2. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more # details. # # You should have received a copy of the GNU General Public License along with # this program; if not, write to the Free Software Foundation, Inc., 51 # Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # Copyright Buildbot Team Members from twisted.internet import defer from twisted.internet import task from twisted.trial import unittest from buildbot.process import properties from buildbot.schedulers import timed from buildbot.test import fakedb from buildbot.test.reactor import TestReactorMixin from buildbot.test.util import scheduler from buildbot.test.util.state import StateTestMixin class NightlyTriggerable( scheduler.SchedulerMixin, TestReactorMixin, StateTestMixin, unittest.TestCase ): SCHEDULERID = 327 OBJECTID = 1327 @defer.inlineCallbacks def makeScheduler(self, firstBuildDuration=0, **kwargs): sched = yield self.attachScheduler( timed.NightlyTriggerable(**kwargs), self.OBJECTID, self.SCHEDULERID, overrideBuildsetMethods=True, createBuilderDB=True, ) # add a Clock to help checking timing issues self.clock = sched._reactor = task.Clock() return sched @defer.inlineCallbacks def setUp(self): self.setup_test_reactor(auto_tear_down=False) yield self.setUpScheduler() @defer.inlineCallbacks def tearDown(self): self.tearDownScheduler() yield self.tear_down_test_reactor() # utilities def assertBuildsetAdded(self, sourcestamps=None, properties=None): if sourcestamps is None: sourcestamps = {} if properties is None: properties = {} properties['scheduler'] = ('test', 'Scheduler') self.assertEqual( self.addBuildsetCalls, [ ( 'addBuildsetForSourceStampsWithDefaults', { "builderNames": None, # uses the default "priority": None, "properties": properties, "reason": "The NightlyTriggerable scheduler named 'test' triggered this build", "sourcestamps": sourcestamps, "waited_for": False, }, ), ], ) self.addBuildsetCalls = [] def assertNoBuildsetAdded(self): self.assertEqual(self.addBuildsetCalls, []) # tests @defer.inlineCallbacks def test_constructor_no_reason(self): sched = yield self.makeScheduler(name='test', builderNames=['test']) self.assertEqual( sched.reason, "The NightlyTriggerable scheduler named 'test' triggered this build" ) @defer.inlineCallbacks def test_constructor_reason(self): sched = yield self.makeScheduler( name='test', builderNames=['test'], reason="hourlytriggerable" ) self.assertEqual(sched.reason, "hourlytriggerable") @defer.inlineCallbacks def test_constructor_month(self): sched = yield self.makeScheduler(name='test', builderNames=['test'], month='1') self.assertEqual(sched.month, "1") @defer.inlineCallbacks def test_timer_noBuilds(self): sched = yield self.makeScheduler(name='test', builderNames=['test'], minute=[5]) sched.activate() self.clock.advance(60 * 60) # Run for 1h self.assertEqual(self.addBuildsetCalls, []) @defer.inlineCallbacks def test_timer_oneTrigger(self): sched = yield self.makeScheduler( name='test', builderNames=['test'], minute=[5], codebases={'cb': {'repository': 'annoying'}}, ) sched.activate() sched.trigger( False, [ { "revision": 'myrev', "branch": 'br', "project": 'p', "repository": 'r', "codebase": 'cb', }, ], set_props=None, ) self.clock.advance(60 * 60) # Run for 1h self.assertBuildsetAdded( sourcestamps=[ { "codebase": 'cb', "branch": 'br', "project": 'p', "repository": 'r', "revision": 'myrev', }, ] ) @defer.inlineCallbacks def test_timer_twoTriggers(self): sched = yield self.makeScheduler( name='test', builderNames=['test'], minute=[5], codebases={'cb': {'repository': 'annoying'}}, ) sched.activate() sched.trigger( False, [ { "codebase": 'cb', "revision": 'myrev1', "branch": 'br', "project": 'p', "repository": 'r', } ], set_props=None, ) sched.trigger( False, [ { "codebase": 'cb', "revision": 'myrev2', "branch": 'br', "project": 'p', "repository": 'r', } ], set_props=None, ) self.clock.advance(60 * 60) # Run for 1h self.assertBuildsetAdded( sourcestamps=[ { "codebase": 'cb', "branch": 'br', "project": 'p', "repository": 'r', # builds the second trigger's revision "revision": 'myrev2', }, ] ) @defer.inlineCallbacks def test_timer_oneTrigger_then_noBuild(self): sched = yield self.makeScheduler( name='test', builderNames=['test'], minute=[5], codebases={'cb': {'repository': 'annoying'}}, ) sched.activate() sched.trigger( False, [ { "codebase": 'cb', "revision": 'myrev', "branch": 'br', "project": 'p', "repository": 'r', } ], set_props=None, ) self.clock.advance(60 * 60) # Run for 1h self.assertBuildsetAdded( sourcestamps=[ { "codebase": 'cb', "branch": 'br', "project": 'p', "repository": 'r', "revision": 'myrev', }, ] ) self.clock.advance(60 * 60) # Run for 1h # no trigger, so the second did not build self.assertNoBuildsetAdded() @defer.inlineCallbacks def test_timer_oneTriggers_then_oneTrigger(self): sched = yield self.makeScheduler( name='test', builderNames=['test'], minute=[5], codebases={'cb': {'repository': 'annoying'}}, ) sched.activate() sched.trigger( False, [ { "codebase": 'cb', "revision": 'myrev1', "branch": 'br', "project": 'p', "repository": 'r', } ], set_props=None, ) self.clock.advance(60 * 60) # Run for 1h self.assertBuildsetAdded( sourcestamps=[ { "codebase": 'cb', "branch": 'br', "project": 'p', "repository": 'r', "revision": 'myrev1', }, ] ) sched.trigger( False, [ { "codebase": 'cb', "revision": 'myrev2', "branch": 'br', "project": 'p', "repository": 'r', } ], set_props=None, ) self.clock.advance(60 * 60) # Run for 1h self.assertBuildsetAdded( sourcestamps=[ { "codebase": 'cb', "branch": 'br', "project": 'p', "repository": 'r', "revision": 'myrev2', }, ] ) @defer.inlineCallbacks def test_savedTrigger(self): sched = yield self.makeScheduler( name='test', builderNames=['test'], minute=[5], codebases={'cb': {'repository': 'annoying'}}, ) value_json = ( '[ [ {"codebase": "cb", "project": "p", "repository": "r", ' '"branch": "br", "revision": "myrev"} ], {}, null, null ]' ) yield self.db.insert_test_data([ fakedb.Object(id=self.SCHEDULERID, name='test', class_name='NightlyTriggerable'), fakedb.ObjectState( objectid=self.SCHEDULERID, name='lastTrigger', value_json=value_json ), ]) sched.activate() self.clock.advance(60 * 60) # Run for 1h self.assertBuildsetAdded( sourcestamps=[ { "codebase": 'cb', "branch": 'br', "project": 'p', "repository": 'r', "revision": 'myrev', }, ] ) @defer.inlineCallbacks def test_savedTrigger_dict(self): sched = yield self.makeScheduler( name='test', builderNames=['test'], minute=[5], codebases={'cb': {'repository': 'annoying'}}, ) value_json = ( '[ { "cb": {"codebase": "cb", "project": "p", "repository": "r", ' '"branch": "br", "revision": "myrev"} }, {}, null, null ]' ) yield self.db.insert_test_data([ fakedb.Object(id=self.SCHEDULERID, name='test', class_name='NightlyTriggerable'), fakedb.ObjectState( objectid=self.SCHEDULERID, name='lastTrigger', value_json=value_json ), ]) sched.activate() self.clock.advance(60 * 60) # Run for 1h self.assertBuildsetAdded( sourcestamps=[ { "codebase": 'cb', "branch": 'br', "project": 'p', "repository": 'r', "revision": 'myrev', }, ] ) @defer.inlineCallbacks def test_saveTrigger(self): sched = yield self.makeScheduler( name='test', builderNames=['test'], minute=[5], codebases={'cb': {'repository': 'annoying'}}, ) yield self.db.insert_test_data([ fakedb.Object(id=self.SCHEDULERID, name='test', class_name='NightlyTriggerable'), ]) sched.activate() _, d = sched.trigger( False, [ { "codebase": 'cb', "revision": 'myrev', "branch": 'br', "project": 'p', "repository": 'r', }, ], set_props=None, ) yield d yield self.assert_state( self.SCHEDULERID, lastTrigger=[ [ { "codebase": 'cb', "revision": 'myrev', "branch": 'br', "project": 'p', "repository": 'r', }, ], {}, None, None, ], ) @defer.inlineCallbacks def test_saveTrigger_noTrigger(self): sched = yield self.makeScheduler( name='test', builderNames=['test'], minute=[5], codebases={'cb': {'repository': 'annoying'}}, ) yield self.db.insert_test_data([ fakedb.Object(id=self.SCHEDULERID, name='test', class_name='NightlyTriggerable'), ]) sched.activate() _, d = sched.trigger( False, [ { "codebase": 'cb', "revision": 'myrev', "branch": 'br', "project": 'p', "repository": 'r', }, ], set_props=None, ) self.clock.advance(60 * 60) # Run for 1h yield d yield self.assert_state(self.SCHEDULERID, lastTrigger=None) @defer.inlineCallbacks def test_triggerProperties(self): sched = yield self.makeScheduler( name='test', builderNames=['test'], minute=[5], codebases={'cb': {'repository': 'annoying'}}, ) yield self.db.insert_test_data([ fakedb.Object(id=self.SCHEDULERID, name='test', class_name='NightlyTriggerable'), ]) sched.activate() sched.trigger( False, [ { "codebase": 'cb', "revision": 'myrev', "branch": 'br', "project": 'p', "repository": 'r', }, ], properties.Properties(testprop='test'), ) yield self.assert_state( self.SCHEDULERID, lastTrigger=[ [ { "codebase": 'cb', "revision": 'myrev', "branch": 'br', "project": 'p', "repository": 'r', }, ], {'testprop': ['test', 'TEST']}, None, None, ], ) self.clock.advance(60 * 60) # Run for 1h self.assertBuildsetAdded( properties={"testprop": ('test', 'TEST')}, sourcestamps=[ { "codebase": 'cb', "branch": 'br', "project": 'p', "repository": 'r', "revision": 'myrev', }, ], ) @defer.inlineCallbacks def test_savedProperties(self): sched = yield self.makeScheduler( name='test', builderNames=['test'], minute=[5], codebases={'cb': {'repository': 'annoying'}}, ) value_json = ( '[ [ {"codebase": "cb", "project": "p", "repository": "r", ' '"branch": "br", "revision": "myrev"} ], ' '{"testprop": ["test", "TEST"]}, null, null ]' ) yield self.db.insert_test_data([ fakedb.Object(id=self.SCHEDULERID, name='test', class_name='NightlyTriggerable'), fakedb.ObjectState( objectid=self.SCHEDULERID, name='lastTrigger', value_json=value_json ), ]) sched.activate() self.clock.advance(60 * 60) # Run for 1h self.assertBuildsetAdded( properties={'testprop': ('test', 'TEST')}, sourcestamps=[ { "codebase": 'cb', "branch": 'br', "project": 'p', "repository": 'r', "revision": 'myrev', }, ], )
16,474
Python
.py
496
20.014113
103
0.456329
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,589
test_timed_Periodic.py
buildbot_buildbot/master/buildbot/test/unit/schedulers/test_timed_Periodic.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.schedulers import timed from buildbot.test.reactor import TestReactorMixin from buildbot.test.util import scheduler class TestException(Exception): pass class Periodic(scheduler.SchedulerMixin, TestReactorMixin, unittest.TestCase): OBJECTID = 23 SCHEDULERID = 3 @defer.inlineCallbacks def setUp(self): self.setup_test_reactor(auto_tear_down=False) yield self.setUpScheduler() @defer.inlineCallbacks def tearDown(self): self.tearDownScheduler() yield self.tear_down_test_reactor() @defer.inlineCallbacks def makeScheduler(self, firstBuildDuration=0, firstBuildError=False, exp_branch=None, **kwargs): self.sched = sched = timed.Periodic(**kwargs) sched._reactor = self.reactor yield self.attachScheduler(self.sched, self.OBJECTID, self.SCHEDULERID) # keep track of builds in self.events self.events = [] def addBuildsetForSourceStampsWithDefaults( reason, sourcestamps, waited_for=False, properties=None, builderNames=None, **kw ): self.assertIn('Periodic scheduler named', reason) # TODO: check branch isFirst = not self.events if self.reactor.seconds() == 0 and firstBuildError: raise TestException() self.events.append(f'B@{int(self.reactor.seconds())}') if isFirst and firstBuildDuration: d = defer.Deferred() self.reactor.callLater(firstBuildDuration, d.callback, None) return d return defer.succeed(None) sched.addBuildsetForSourceStampsWithDefaults = addBuildsetForSourceStampsWithDefaults # handle state locally self.state = {} def getState(k, default): return defer.succeed(self.state.get(k, default)) sched.getState = getState def setState(k, v): self.state[k] = v return defer.succeed(None) sched.setState = setState return sched # tests def test_constructor_invalid(self): with self.assertRaises(config.ConfigErrors): timed.Periodic(name='test', builderNames=['test'], periodicBuildTimer=-2) @defer.inlineCallbacks def test_constructor_no_reason(self): sched = yield self.makeScheduler(name='test', builderNames=['test'], periodicBuildTimer=10) self.assertEqual(sched.reason, "The Periodic scheduler named 'test' triggered this build") @defer.inlineCallbacks def test_constructor_reason(self): sched = yield self.makeScheduler( name='test', builderNames=['test'], periodicBuildTimer=10, reason="periodic" ) self.assertEqual(sched.reason, "periodic") @defer.inlineCallbacks def test_iterations_simple(self): sched = yield self.makeScheduler(name='test', builderNames=['test'], periodicBuildTimer=13) sched.activate() self.reactor.advance(0) # let it trigger the first build while self.reactor.seconds() < 30: self.reactor.advance(1) self.assertEqual(self.events, ['B@0', 'B@13', 'B@26']) self.assertEqual(self.state.get('last_build'), 26) yield sched.deactivate() @defer.inlineCallbacks def test_iterations_simple_branch(self): sched = yield self.makeScheduler( exp_branch='newfeature', name='test', builderNames=['test'], periodicBuildTimer=13, branch='newfeature', ) sched.activate() self.reactor.advance(0) # let it trigger the first build while self.reactor.seconds() < 30: self.reactor.advance(1) self.assertEqual(self.events, ['B@0', 'B@13', 'B@26']) self.assertEqual(self.state.get('last_build'), 26) yield sched.deactivate() @defer.inlineCallbacks def test_iterations_long(self): sched = yield self.makeScheduler( name='test', builderNames=['test'], periodicBuildTimer=10, firstBuildDuration=15 ) # takes a while to start a build sched.activate() self.reactor.advance(0) # let it trigger the first (longer) build while self.reactor.seconds() < 40: self.reactor.advance(1) self.assertEqual(self.events, ['B@0', 'B@15', 'B@25', 'B@35']) self.assertEqual(self.state.get('last_build'), 35) yield sched.deactivate() @defer.inlineCallbacks def test_start_build_error(self): sched = yield self.makeScheduler( name='test', builderNames=['test'], periodicBuildTimer=10, firstBuildError=True ) # error during first build start yield sched.activate() self.reactor.advance(0) # let it trigger the first (error) build while self.reactor.seconds() < 40: self.reactor.advance(1) self.assertEqual(self.events, ['B@10', 'B@20', 'B@30', 'B@40']) self.assertEqual(self.state.get('last_build'), 40) self.assertEqual(1, len(self.flushLoggedErrors(TestException))) yield sched.deactivate() @defer.inlineCallbacks def test_iterations_stop_while_starting_build(self): sched = yield self.makeScheduler( name='test', builderNames=['test'], periodicBuildTimer=13, firstBuildDuration=6 ) # takes a while to start a build sched.activate() self.reactor.advance(0) # let it trigger the first (longer) build self.reactor.advance(3) # get partway into that build d = sched.deactivate() # begin stopping the service d.addCallback(lambda _: self.events.append(f'STOP@{int(self.reactor.seconds())}')) # run the clock out while self.reactor.seconds() < 40: self.reactor.advance(1) # note that the deactivate completes after the first build completes, and no # subsequent builds occur self.assertEqual(self.events, ['B@0', 'STOP@6']) self.assertEqual(self.state.get('last_build'), 0) yield d @defer.inlineCallbacks def test_iterations_with_initial_state(self): sched = yield self.makeScheduler(name='test', builderNames=['test'], periodicBuildTimer=13) # so next build should start in 6s self.state['last_build'] = self.reactor.seconds() - 7 sched.activate() self.reactor.advance(0) # let it trigger the first build while self.reactor.seconds() < 30: self.reactor.advance(1) self.assertEqual(self.events, ['B@6', 'B@19']) self.assertEqual(self.state.get('last_build'), 19) yield sched.deactivate() @defer.inlineCallbacks def test_getNextBuildTime_None(self): sched = yield self.makeScheduler(name='test', builderNames=['test'], periodicBuildTimer=13) # given None, build right away t = yield sched.getNextBuildTime(None) self.assertEqual(t, 0) @defer.inlineCallbacks def test_getNextBuildTime_given(self): sched = yield self.makeScheduler(name='test', builderNames=['test'], periodicBuildTimer=13) # given a time, add the periodicBuildTimer to it t = yield sched.getNextBuildTime(20) self.assertEqual(t, 33) @defer.inlineCallbacks def test_enabled_callback(self): sched = yield self.makeScheduler(name='test', builderNames=['test'], periodicBuildTimer=13) expectedValue = not sched.enabled yield sched._enabledCallback(None, {'enabled': not sched.enabled}) self.assertEqual(sched.enabled, expectedValue) expectedValue = not sched.enabled yield sched._enabledCallback(None, {'enabled': not sched.enabled}) self.assertEqual(sched.enabled, expectedValue) @defer.inlineCallbacks def test_disabled_activate(self): sched = yield self.makeScheduler(name='test', builderNames=['test'], periodicBuildTimer=13) yield sched._enabledCallback(None, {'enabled': not sched.enabled}) self.assertEqual(sched.enabled, False) r = yield sched.activate() self.assertEqual(r, None) @defer.inlineCallbacks def test_disabled_deactivate(self): sched = yield self.makeScheduler(name='test', builderNames=['test'], periodicBuildTimer=13) yield sched._enabledCallback(None, {'enabled': not sched.enabled}) self.assertEqual(sched.enabled, False) r = yield sched.deactivate() self.assertEqual(r, None) @defer.inlineCallbacks def test_disabled_start_build(self): sched = yield self.makeScheduler(name='test', builderNames=['test'], periodicBuildTimer=13) yield sched._enabledCallback(None, {'enabled': not sched.enabled}) self.assertEqual(sched.enabled, False) r = yield sched.startBuild() self.assertEqual(r, None)
9,668
Python
.py
202
39.559406
100
0.674349
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,590
test_base.py
buildbot_buildbot/master/buildbot/test/unit/schedulers/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.internet import task from twisted.trial import unittest from buildbot import config from buildbot.changes import changes from buildbot.changes import filter from buildbot.process import properties from buildbot.process.properties import Interpolate from buildbot.schedulers import base from buildbot.test import fakedb from buildbot.test.reactor import TestReactorMixin from buildbot.test.util import scheduler class BaseScheduler(scheduler.SchedulerMixin, TestReactorMixin, unittest.TestCase): OBJECTID = 19 SCHEDULERID = 9 exp_bsid_brids = (123, {'b': 456}) @defer.inlineCallbacks def setUp(self): self.setup_test_reactor(auto_tear_down=False) yield self.setUpScheduler() @defer.inlineCallbacks def tearDown(self): yield self.tearDownScheduler() yield self.tear_down_test_reactor() @defer.inlineCallbacks def makeScheduler(self, name='testsched', builderNames=None, properties=None, codebases=None): if builderNames is None: builderNames = ['a', 'b'] if properties is None: properties = {} if codebases is None: codebases = {'': {}} if isinstance(builderNames, list): dbBuilder = [] builderid = 0 for builderName in builderNames: if isinstance(builderName, str): builderid += 1 dbBuilder.append(fakedb.Builder(id=builderid, name=builderName)) yield self.master.db.insert_test_data(dbBuilder) sched = yield self.attachScheduler( base.BaseScheduler( name=name, builderNames=builderNames, properties=properties, codebases=codebases ), self.OBJECTID, self.SCHEDULERID, ) self.master.data.updates.addBuildset = mock.Mock( name='data.addBuildset', side_effect=lambda *args, **kwargs: defer.succeed(self.exp_bsid_brids), ) return sched # tests @defer.inlineCallbacks def test_constructor_builderNames(self): with self.assertRaises(config.ConfigErrors): yield self.makeScheduler(builderNames='xxx') @defer.inlineCallbacks def test_constructor_builderNames_unicode(self): yield self.makeScheduler(builderNames=['a']) @defer.inlineCallbacks def test_constructor_builderNames_renderable(self): @properties.renderer def names(props): return ['a'] yield self.makeScheduler(builderNames=names) @defer.inlineCallbacks def test_constructor_codebases_valid(self): codebases = {"codebase1": {"repository": "", "branch": "", "revision": ""}} yield self.makeScheduler(codebases=codebases) @defer.inlineCallbacks def test_constructor_codebases_valid_list(self): codebases = ['codebase1'] yield self.makeScheduler(codebases=codebases) @defer.inlineCallbacks def test_constructor_codebases_invalid(self): # scheduler only accepts codebases with at least repository set codebases = {"codebase1": {"dictionary": "", "that": "", "fails": ""}} with self.assertRaises(config.ConfigErrors): yield self.makeScheduler(codebases=codebases) @defer.inlineCallbacks def test_getCodebaseDict(self): sched = yield self.makeScheduler(codebases={'lib': {'repository': 'librepo'}}) cbd = yield sched.getCodebaseDict('lib') self.assertEqual(cbd, {'repository': 'librepo'}) @defer.inlineCallbacks def test_getCodebaseDict_constructedFromList(self): sched = yield self.makeScheduler(codebases=['lib', 'lib2']) cbd = yield sched.getCodebaseDict('lib') self.assertEqual(cbd, {}) @defer.inlineCallbacks def test_getCodebaseDict_not_found(self): sched = yield self.makeScheduler(codebases={'lib': {'repository': 'librepo'}}) with self.assertRaises(KeyError): yield sched.getCodebaseDict('app') @defer.inlineCallbacks def test_listBuilderNames(self): sched = yield self.makeScheduler(builderNames=['x', 'y']) self.assertEqual(sched.listBuilderNames(), ['x', 'y']) @defer.inlineCallbacks def test_startConsumingChanges_fileIsImportant_check(self): sched = yield self.makeScheduler() try: yield sched.startConsumingChanges(fileIsImportant="maybe") except AssertionError: pass else: self.fail("didn't assert") @defer.inlineCallbacks def test_enabled_callback(self): sched = yield self.makeScheduler() expectedValue = not sched.enabled yield sched._enabledCallback(None, {'enabled': not sched.enabled}) self.assertEqual(sched.enabled, expectedValue) expectedValue = not sched.enabled yield sched._enabledCallback(None, {'enabled': not sched.enabled}) self.assertEqual(sched.enabled, expectedValue) @defer.inlineCallbacks def do_test_change_consumption(self, kwargs, expected_result, change_kwargs=None): if change_kwargs is None: change_kwargs = {} # (expected_result should be True (important), False (unimportant), or # None (ignore the change)) sched = yield self.makeScheduler() sched.startService() self.addCleanup(sched.stopService) # set up a change message, a changedict, a change, and convince # getChange and fromChdict to convert one to the other msg = {"changeid": 12934} chdict = {"changeid": 12934, "is_chdict": True} def getChange(changeid): assert changeid == 12934 return defer.succeed(chdict) self.db.changes.getChange = getChange change = self.makeFakeChange(**change_kwargs) change.number = 12934 def fromChdict(cls, master, chdict): assert chdict['changeid'] == 12934 and chdict['is_chdict'] return defer.succeed(change) self.patch(changes.Change, 'fromChdict', classmethod(fromChdict)) change_received = [None] def gotChange(got_change, got_important): # check that we got the expected change object self.assertIdentical(got_change, change) change_received[0] = got_important return defer.succeed(None) sched.gotChange = gotChange yield sched.startConsumingChanges(**kwargs) # check that it registered callbacks self.assertEqual(len(self.mq.qrefs), 2) qref = self.mq.qrefs[1] self.assertEqual(qref.filter, ('changes', None, 'new')) # invoke the callback with the change, and check the result qref.callback('change.12934.new', msg) self.assertEqual(change_received[0], expected_result) def test_change_consumption_defaults(self): # all changes are important by default return self.do_test_change_consumption({}, True) def test_change_consumption_fileIsImportant_True(self): return self.do_test_change_consumption({"fileIsImportant": lambda c: True}, True) def test_change_consumption_fileIsImportant_False(self): return self.do_test_change_consumption({"fileIsImportant": lambda c: False}, False) @defer.inlineCallbacks def test_change_consumption_fileIsImportant_exception(self): yield self.do_test_change_consumption({"fileIsImportant": lambda c: 1 / 0}, None) self.assertEqual(1, len(self.flushLoggedErrors(ZeroDivisionError))) def test_change_consumption_change_filter_True(self): cf = mock.Mock() cf.filter_change = lambda c: True return self.do_test_change_consumption({"change_filter": cf}, True) def test_change_consumption_change_filter_False(self): cf = mock.Mock() cf.filter_change = lambda c: False return self.do_test_change_consumption({"change_filter": cf}, None) def test_change_consumption_change_filter_gerrit_ref_updates(self): cf = mock.Mock() cf.filter_change = lambda c: False return self.do_test_change_consumption( {'change_filter': cf}, None, change_kwargs={'category': 'ref-updated', 'branch': 'master'}, ) def test_change_consumption_change_filter_gerrit_ref_updates_with_refs(self): cf = mock.Mock() cf.filter_change = lambda c: False return self.do_test_change_consumption( {'change_filter': cf}, None, change_kwargs={'category': 'ref-updated', 'branch': 'refs/changes/123'}, ) def test_change_consumption_change_filter_gerrit_filters_branch_new(self): cf = filter.ChangeFilter(branch='master') return self.do_test_change_consumption( {'change_filter': cf}, True, change_kwargs={'category': 'ref-updated', 'branch': 'master'}, ) def test_change_consumption_change_filter_gerrit_filters_branch_new_not_match(self): cf = filter.ChangeFilter(branch='other') return self.do_test_change_consumption( {'change_filter': cf}, None, change_kwargs={'category': 'ref-updated', 'branch': 'master'}, ) def test_change_consumption_fileIsImportant_False_onlyImportant(self): return self.do_test_change_consumption( {"fileIsImportant": lambda c: False, "onlyImportant": True}, None ) def test_change_consumption_fileIsImportant_True_onlyImportant(self): return self.do_test_change_consumption( {"fileIsImportant": lambda c: True, "onlyImportant": True}, True ) @defer.inlineCallbacks def test_activation(self): sched = yield self.makeScheduler(name='n', builderNames=['a']) sched.clock = task.Clock() sched.activate = mock.Mock(return_value=defer.succeed(None)) sched.deactivate = mock.Mock(return_value=defer.succeed(None)) # set the schedulerid, and claim the scheduler on another master yield self.setSchedulerToMaster(self.OTHER_MASTER_ID) yield sched.startService() sched.clock.advance(sched.POLL_INTERVAL_SEC / 2) sched.clock.advance(sched.POLL_INTERVAL_SEC / 5) sched.clock.advance(sched.POLL_INTERVAL_SEC / 5) self.assertFalse(sched.activate.called) self.assertFalse(sched.deactivate.called) self.assertFalse(sched.isActive()) # objectid is attached by the test helper self.assertEqual(sched.serviceid, self.SCHEDULERID) # clear that masterid yield sched.stopService() self.setSchedulerToMaster(None) yield sched.startService() sched.clock.advance(sched.POLL_INTERVAL_SEC) self.assertTrue(sched.activate.called) self.assertFalse(sched.deactivate.called) self.assertTrue(sched.isActive()) # stop the service and see that deactivate is called yield sched.stopService() self.assertTrue(sched.activate.called) self.assertTrue(sched.deactivate.called) self.assertFalse(sched.isActive()) @defer.inlineCallbacks def test_activation_claim_raises(self): sched = yield self.makeScheduler(name='n', builderNames=['a']) sched.clock = task.Clock() # set the schedulerid, and claim the scheduler on another master self.setSchedulerToMaster(RuntimeError()) sched.startService() self.assertEqual(1, len(self.flushLoggedErrors(RuntimeError))) self.assertFalse(sched.isActive()) @defer.inlineCallbacks def test_activation_activate_fails(self): sched = yield self.makeScheduler(name='n', builderNames=['a']) sched.clock = task.Clock() def activate(): raise RuntimeError('oh noes') sched.activate = activate sched.startService() self.assertEqual(1, len(self.flushLoggedErrors(RuntimeError))) @defer.inlineCallbacks def do_addBuildsetForSourceStampsWithDefaults(self, codebases, sourcestamps, exp_sourcestamps): sched = yield self.makeScheduler(name='n', builderNames=['b'], codebases=codebases) bsid, brids = yield sched.addBuildsetForSourceStampsWithDefaults( reason='power', sourcestamps=sourcestamps, waited_for=False ) self.assertEqual((bsid, brids), self.exp_bsid_brids) call = self.master.data.updates.addBuildset.mock_calls[0] def sourceStampKey(sourceStamp): repository = sourceStamp.get('repository', '') if repository is None: repository = '' branch = sourceStamp.get('branch', '') if not None else '' if branch is None: branch = '' return (repository, branch) self.assertEqual( sorted(call[2]['sourcestamps'], key=sourceStampKey), sorted(exp_sourcestamps, key=sourceStampKey), ) def test_addBuildsetForSourceStampsWithDefaults(self): codebases = { 'cbA': {"repository": 'svn://A..', "branch": 'stable', "revision": '13579'}, 'cbB': {"repository": 'svn://B..', "branch": 'stable', "revision": '24680'}, } sourcestamps = [ {'codebase': 'cbA', 'branch': 'AA'}, {'codebase': 'cbB', 'revision': 'BB'}, ] exp_sourcestamps = [ { 'repository': 'svn://B..', 'branch': 'stable', 'revision': 'BB', 'codebase': 'cbB', 'project': '', }, { 'repository': 'svn://A..', 'branch': 'AA', 'project': '', 'revision': '13579', 'codebase': 'cbA', }, ] return self.do_addBuildsetForSourceStampsWithDefaults( codebases, sourcestamps, exp_sourcestamps ) def test_addBuildsetForSourceStampsWithDefaults_fill_in_codebases(self): codebases = { 'cbA': {"repository": 'svn://A..', "branch": 'stable', "revision": '13579'}, 'cbB': {"repository": 'svn://B..', "branch": 'stable', "revision": '24680'}, } sourcestamps = [ {'codebase': 'cbA', 'branch': 'AA'}, ] exp_sourcestamps = [ { 'repository': 'svn://B..', 'branch': 'stable', 'revision': '24680', 'codebase': 'cbB', 'project': '', }, { 'repository': 'svn://A..', 'branch': 'AA', 'project': '', 'revision': '13579', 'codebase': 'cbA', }, ] return self.do_addBuildsetForSourceStampsWithDefaults( codebases, sourcestamps, exp_sourcestamps ) def test_addBuildsetForSourceStampsWithDefaults_no_repository(self): exp_sourcestamps = [ {'repository': '', 'branch': None, 'revision': None, 'codebase': '', 'project': ''}, ] return self.do_addBuildsetForSourceStampsWithDefaults({'': {}}, [], exp_sourcestamps) def test_addBuildsetForSourceStamps_unknown_codbases(self): codebases = {} sourcestamps = [ {'codebase': 'cbA', 'branch': 'AA'}, {'codebase': 'cbB', 'revision': 'BB'}, ] exp_sourcestamps = [ {'branch': None, 'revision': 'BB', 'codebase': 'cbB', 'project': '', 'repository': ''}, {'branch': 'AA', 'revision': None, 'codebase': 'cbA', 'project': '', 'repository': ''}, ] return self.do_addBuildsetForSourceStampsWithDefaults( codebases, sourcestamps, exp_sourcestamps ) @defer.inlineCallbacks def test_addBuildsetForChanges_one_change(self): sched = yield self.makeScheduler(name='n', builderNames=['b']) yield self.db.insert_test_data([ fakedb.Change(changeid=13, sourcestampid=234), ]) bsid, brids = yield sched.addBuildsetForChanges( reason='power', waited_for=False, changeids=[13] ) self.assertEqual((bsid, brids), self.exp_bsid_brids) self.master.data.updates.addBuildset.assert_called_with( waited_for=False, builderids=[1], external_idstring=None, properties={ 'scheduler': ('n', 'Scheduler'), }, reason='power', scheduler='n', sourcestamps=[234], priority=0, ) @defer.inlineCallbacks def test_addBuildsetForChanges_properties(self): sched = yield self.makeScheduler(name='n', builderNames=['c']) yield self.db.insert_test_data([ fakedb.Change(changeid=14, sourcestampid=234), ]) bsid, brids = yield sched.addBuildsetForChanges( reason='downstream', waited_for=False, changeids=[14] ) self.assertEqual((bsid, brids), self.exp_bsid_brids) self.master.data.updates.addBuildset.assert_called_with( waited_for=False, builderids=[1], external_idstring=None, properties={ 'scheduler': ('n', 'Scheduler'), }, reason='downstream', scheduler='n', sourcestamps=[234], priority=0, ) @defer.inlineCallbacks def test_addBuildsetForChanges_properties_with_virtual_builders(self): sched = yield self.makeScheduler( name='n', builderNames=['c'], properties={'virtual_builder_name': Interpolate("myproject-%(src::branch)s")}, ) yield self.db.insert_test_data([ fakedb.SourceStamp(id=234, branch='dev1', project="linux"), fakedb.Change(changeid=14, sourcestampid=234, branch="dev1"), ]) bsid, brids = yield sched.addBuildsetForChanges( reason='downstream', waited_for=False, changeids=[14] ) self.assertEqual((bsid, brids), self.exp_bsid_brids) self.master.data.updates.addBuildset.assert_called_with( waited_for=False, builderids=[1], external_idstring=None, properties={ 'virtual_builder_name': ("myproject-dev1", "Scheduler"), 'scheduler': ('n', 'Scheduler'), }, reason='downstream', scheduler='n', sourcestamps=[234], priority=0, ) @defer.inlineCallbacks def test_addBuildsetForChanges_multiple_changes_same_codebase(self): # This is a test for backwards compatibility # Changes from different repositories come together in one build sched = yield self.makeScheduler( name='n', builderNames=['b', 'c'], codebases={'cb': {'repository': 'http://repo'}} ) # No codebaseGenerator means all changes have codebase == '' yield self.db.insert_test_data([ fakedb.Change(changeid=13, codebase='cb', sourcestampid=12), fakedb.Change(changeid=14, codebase='cb', sourcestampid=11), fakedb.Change(changeid=15, codebase='cb', sourcestampid=10), ]) # note that the changeids are given out of order here; it should still # use the most recent bsid, brids = yield sched.addBuildsetForChanges( reason='power', waited_for=False, changeids=[14, 15, 13] ) self.assertEqual((bsid, brids), self.exp_bsid_brids) self.master.data.updates.addBuildset.assert_called_with( waited_for=False, builderids=[1, 2], external_idstring=None, properties={ 'scheduler': ('n', 'Scheduler'), }, reason='power', scheduler='n', sourcestamps=[10], # sourcestampid from greatest changeid priority=0, ) @defer.inlineCallbacks def test_addBuildsetForChanges_codebases_set_multiple_codebases(self): codebases = { 'cbA': {"repository": 'svn://A..', "branch": 'stable', "revision": '13579'}, 'cbB': {"repository": 'svn://B..', "branch": 'stable', "revision": '24680'}, 'cbC': {"repository": 'svn://C..', "branch": 'stable', "revision": '12345'}, 'cbD': {"repository": 'svn://D..'}, } # Scheduler gets codebases that can be used to create extra sourcestamps # for repositories that have no changes sched = yield self.makeScheduler(name='n', builderNames=['b', 'c'], codebases=codebases) yield self.db.insert_test_data([ fakedb.Change(changeid=12, codebase='cbA', sourcestampid=912), fakedb.Change(changeid=13, codebase='cbA', sourcestampid=913), fakedb.Change(changeid=14, codebase='cbA', sourcestampid=914), fakedb.Change(changeid=15, codebase='cbB', sourcestampid=915), fakedb.Change(changeid=16, codebase='cbB', sourcestampid=916), fakedb.Change(changeid=17, codebase='cbB', sourcestampid=917), # note: no changes for cbC or cbD ]) # note that the changeids are given out of order here; it should still # use the most recent for each codebase bsid, brids = yield sched.addBuildsetForChanges( reason='power', waited_for=True, changeids=[14, 12, 17, 16, 13, 15] ) self.assertEqual((bsid, brids), self.exp_bsid_brids) self.master.data.updates.addBuildset.assert_called_with( waited_for=True, builderids=[1, 2], external_idstring=None, reason='power', scheduler='n', properties={ 'scheduler': ('n', 'Scheduler'), }, sourcestamps=[ 914, 917, { "branch": 'stable', "repository": 'svn://C..', "codebase": 'cbC', "project": '', "revision": '12345', }, { "branch": None, "repository": 'svn://D..', "codebase": 'cbD', "project": '', "revision": None, }, ], priority=0, ) @defer.inlineCallbacks def test_addBuildsetForSourceStamp(self): sched = yield self.makeScheduler(name='n', builderNames=['b']) sourcestamps = [91, {'sourcestamp': True}] bsid, brids = yield sched.addBuildsetForSourceStamps( reason='whynot', waited_for=False, sourcestamps=sourcestamps ) self.assertEqual((bsid, brids), self.exp_bsid_brids) self.master.data.updates.addBuildset.assert_called_with( waited_for=False, builderids=[1], external_idstring=None, reason='whynot', scheduler='n', properties={ 'scheduler': ('n', 'Scheduler'), }, sourcestamps=[91, {'sourcestamp': True}], priority=0, ) @defer.inlineCallbacks def test_addBuildsetForSourceStamp_explicit_builderNames(self): sched = yield self.makeScheduler(name='n', builderNames=['b', 'x', 'y']) bsid, brids = yield sched.addBuildsetForSourceStamps( reason='whynot', waited_for=True, sourcestamps=[91, {'sourcestamp': True}], builderNames=['x', 'y'], ) self.assertEqual((bsid, brids), self.exp_bsid_brids) self.master.data.updates.addBuildset.assert_called_with( waited_for=True, builderids=[2, 3], external_idstring=None, reason='whynot', scheduler='n', properties={ 'scheduler': ('n', 'Scheduler'), }, sourcestamps=[91, {'sourcestamp': True}], priority=0, ) @defer.inlineCallbacks def test_addBuildsetForSourceStamp_properties(self): props = properties.Properties(xxx="yyy") sched = yield self.makeScheduler(name='n', builderNames=['b']) bsid, brids = yield sched.addBuildsetForSourceStamps( reason='whynot', waited_for=False, sourcestamps=[91], properties=props ) self.assertEqual((bsid, brids), self.exp_bsid_brids) self.master.data.updates.addBuildset.assert_called_with( waited_for=False, builderids=[1], external_idstring=None, properties={'xxx': ('yyy', 'TEST'), 'scheduler': ('n', 'Scheduler')}, reason='whynot', scheduler='n', sourcestamps=[91], priority=0, ) @defer.inlineCallbacks def test_addBuildsetForSourceStamp_combine_change_properties(self): sched = yield self.makeScheduler() yield self.master.db.insert_test_data([ fakedb.SourceStamp(id=98, branch='stable'), fakedb.Change(changeid=25, sourcestampid=98, branch='stable'), fakedb.ChangeProperty( changeid=25, property_name='color', property_value='["pink","Change"]' ), ]) bsid, brids = yield sched.addBuildsetForSourceStamps( reason='whynot', waited_for=False, sourcestamps=[98] ) self.assertEqual((bsid, brids), self.exp_bsid_brids) self.master.data.updates.addBuildset.assert_called_with( waited_for=False, builderids=[1, 2], external_idstring=None, properties={'scheduler': ('testsched', 'Scheduler'), 'color': ('pink', 'Change')}, reason='whynot', scheduler='testsched', sourcestamps=[98], priority=0, ) @defer.inlineCallbacks def test_addBuildsetForSourceStamp_renderable_builderNames(self): @properties.renderer def names(props): if props.changes[0]['branch'] == 'stable': return ['c'] elif props.changes[0]['branch'] == 'unstable': return ['a', 'b'] return None sched = yield self.makeScheduler(name='n', builderNames=names) yield self.master.db.insert_test_data([ fakedb.Builder(id=1, name='a'), fakedb.Builder(id=2, name='b'), fakedb.Builder(id=3, name='c'), fakedb.SourceStamp(id=98, branch='stable'), fakedb.SourceStamp(id=99, branch='unstable'), fakedb.Change(changeid=25, sourcestampid=98, branch='stable'), fakedb.Change(changeid=26, sourcestampid=99, branch='unstable'), ]) bsid, brids = yield sched.addBuildsetForSourceStamps( reason='whynot', waited_for=False, sourcestamps=[98] ) self.assertEqual((bsid, brids), self.exp_bsid_brids) self.master.data.updates.addBuildset.assert_called_with( waited_for=False, builderids=[3], external_idstring=None, properties={'scheduler': ('n', 'Scheduler')}, reason='whynot', scheduler='n', sourcestamps=[98], priority=0, ) bsid, brids = yield sched.addBuildsetForSourceStamps( reason='because', waited_for=False, sourcestamps=[99] ) self.assertEqual((bsid, brids), self.exp_bsid_brids) self.master.data.updates.addBuildset.assert_called_with( waited_for=False, builderids=[1, 2], external_idstring=None, properties={'scheduler': ('n', 'Scheduler')}, reason='because', scheduler='n', sourcestamps=[99], priority=0, ) @defer.inlineCallbacks def test_addBuildsetForSourceStamp_list_of_renderable_builderNames(self): names = ['a', 'b', properties.Interpolate('%(prop:extra_builder)s')] sched = yield self.makeScheduler(name='n', builderNames=names) yield self.master.db.insert_test_data([ fakedb.Builder(id=3, name='c'), fakedb.SourceStamp(id=98, branch='stable'), fakedb.Change(changeid=25, sourcestampid=98, branch='stable'), fakedb.ChangeProperty( changeid=25, property_name='extra_builder', property_value='["c","Change"]' ), ]) bsid, brids = yield sched.addBuildsetForSourceStamps( reason='whynot', waited_for=False, sourcestamps=[98] ) self.assertEqual((bsid, brids), self.exp_bsid_brids) self.master.data.updates.addBuildset.assert_called_with( waited_for=False, builderids=[1, 2, 3], external_idstring=None, properties={'scheduler': ('n', 'Scheduler'), 'extra_builder': ('c', 'Change')}, reason='whynot', scheduler='n', sourcestamps=[98], priority=0, ) @defer.inlineCallbacks def test_signature_addBuildsetForChanges(self): sched = yield self.makeScheduler(builderNames=['xxx']) @self.assertArgSpecMatches( sched.addBuildsetForChanges, # Real self.fake_addBuildsetForChanges, # Real ) def addBuildsetForChanges( self, waited_for=False, reason='', external_idstring=None, changeids=None, builderNames=None, properties=None, priority=None, **kw, ): pass @defer.inlineCallbacks def test_signature_addBuildsetForSourceStamps(self): sched = yield self.makeScheduler(builderNames=['xxx']) @self.assertArgSpecMatches( sched.addBuildsetForSourceStamps, # Real self.fake_addBuildsetForSourceStamps, # Fake ) def addBuildsetForSourceStamps( self, waited_for=False, sourcestamps=None, reason='', external_idstring=None, properties=None, builderNames=None, priority=None, **kw, ): pass @defer.inlineCallbacks def test_signature_addBuildsetForSourceStampsWithDefaults(self): sched = yield self.makeScheduler(builderNames=['xxx']) @self.assertArgSpecMatches( sched.addBuildsetForSourceStampsWithDefaults, # Real self.fake_addBuildsetForSourceStampsWithDefaults, # Fake ) def addBuildsetForSourceStampsWithDefaults( self, reason, sourcestamps=None, waited_for=False, properties=None, builderNames=None, priority=None, **kw, ): pass
31,793
Python
.py
739
32.55751
99
0.606067
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,591
test_timed_Timed.py
buildbot_buildbot/master/buildbot/test/unit/schedulers/test_timed_Timed.py
# This file is part of Buildbot. Buildbot is free software: you can # redistribute it and/or modify it under the terms of the GNU General Public # License as published by the Free Software Foundation, version 2. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more # details. # # You should have received a copy of the GNU General Public License along with # this program; if not, write to the Free Software Foundation, Inc., 51 # Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # Copyright Buildbot Team Members from twisted.internet import defer from twisted.internet import task from twisted.trial import unittest from buildbot.schedulers import timed from buildbot.test.reactor import TestReactorMixin from buildbot.test.util import scheduler class Timed(scheduler.SchedulerMixin, TestReactorMixin, unittest.TestCase): OBJECTID = 928754 @defer.inlineCallbacks def setUp(self): self.setup_test_reactor(auto_tear_down=False) yield self.setUpScheduler() @defer.inlineCallbacks def tearDown(self): self.tearDownScheduler() yield self.tear_down_test_reactor() class Subclass(timed.Timed): def getNextBuildTime(self, lastActuation): self.got_lastActuation = lastActuation return defer.succeed((lastActuation or 1000) + 60) def startBuild(self): self.started_build = True return defer.succeed(None) @defer.inlineCallbacks def makeScheduler(self, firstBuildDuration=0, **kwargs): sched = yield self.attachScheduler(self.Subclass(**kwargs), self.OBJECTID) self.clock = sched._reactor = task.Clock() return sched # tests # note that most of the heavy-lifting for testing this class is handled by # the subclasses' tests, as that's the more natural place for it
2,022
Python
.py
45
40.044444
82
0.747711
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,592
test_trysched.py
buildbot_buildbot/master/buildbot/test/unit/schedulers/test_trysched.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 shutil from io import StringIO from unittest import mock from twisted.internet import defer from twisted.protocols import basic from twisted.trial import unittest from buildbot.schedulers import trysched from buildbot.test.reactor import TestReactorMixin from buildbot.test.util import dirs from buildbot.test.util import scheduler class TryBase(scheduler.SchedulerMixin, TestReactorMixin, unittest.TestCase): OBJECTID = 26 SCHEDULERID = 6 @defer.inlineCallbacks def setUp(self): self.setup_test_reactor(auto_tear_down=False) yield self.setUpScheduler() @defer.inlineCallbacks def tearDown(self): self.tearDownScheduler() yield self.tear_down_test_reactor() def makeScheduler(self, **kwargs): return self.attachScheduler( trysched.Try_Userpass(**kwargs), self.OBJECTID, self.SCHEDULERID ) def test_filterBuilderList_ok(self): sched = trysched.TryBase(name='tsched', builderNames=['a', 'b', 'c'], properties={}) self.assertEqual(sched.filterBuilderList(['b', 'c']), ['b', 'c']) def test_filterBuilderList_bad(self): sched = trysched.TryBase(name='tsched', builderNames=['a', 'b'], properties={}) self.assertEqual(sched.filterBuilderList(['b', 'c']), []) def test_filterBuilderList_empty(self): sched = trysched.TryBase(name='tsched', builderNames=['a', 'b'], properties={}) self.assertEqual(sched.filterBuilderList([]), ['a', 'b']) @defer.inlineCallbacks def test_enabled_callback(self): sched = yield self.makeScheduler( name='tsched', builderNames=['a'], port='tcp:9999', userpass=[('fred', 'derf')] ) expectedValue = not sched.enabled yield sched._enabledCallback(None, {'enabled': not sched.enabled}) self.assertEqual(sched.enabled, expectedValue) expectedValue = not sched.enabled yield sched._enabledCallback(None, {'enabled': not sched.enabled}) self.assertEqual(sched.enabled, expectedValue) @defer.inlineCallbacks def test_disabled_activate(self): sched = yield self.makeScheduler( name='tsched', builderNames=['a'], port='tcp:9999', userpass=[('fred', 'derf')] ) yield sched._enabledCallback(None, {'enabled': not sched.enabled}) self.assertEqual(sched.enabled, False) r = yield sched.activate() self.assertEqual(r, None) @defer.inlineCallbacks def test_disabled_deactivate(self): sched = yield self.makeScheduler( name='tsched', builderNames=['a'], port='tcp:9999', userpass=[('fred', 'derf')] ) yield sched._enabledCallback(None, {'enabled': not sched.enabled}) self.assertEqual(sched.enabled, False) r = yield sched.deactivate() self.assertEqual(r, None) class JobdirService(dirs.DirsMixin, unittest.TestCase): def setUp(self): self.jobdir = 'jobdir' self.newdir = os.path.join(self.jobdir, 'new') self.curdir = os.path.join(self.jobdir, 'cur') self.tmpdir = os.path.join(self.jobdir, 'tmp') self.setUpDirs(self.jobdir, self.newdir, self.curdir, self.tmpdir) def tearDown(self): self.tearDownDirs() def test_messageReceived(self): # stub out svc.scheduler.handleJobFile and .jobdir scheduler = mock.Mock() def handleJobFile(filename, f): self.assertEqual(filename, 'jobdata') self.assertEqual(f.read(), 'JOBDATA') scheduler.handleJobFile = handleJobFile scheduler.jobdir = self.jobdir svc = trysched.JobdirService(scheduler=scheduler, basedir=self.jobdir) # create some new data to process jobdata = os.path.join(self.newdir, 'jobdata') with open(jobdata, "w", encoding='utf-8') as f: f.write('JOBDATA') # run it svc.messageReceived('jobdata') class Try_Jobdir(scheduler.SchedulerMixin, TestReactorMixin, unittest.TestCase): OBJECTID = 23 SCHEDULERID = 3 @defer.inlineCallbacks def setUp(self): self.setup_test_reactor(auto_tear_down=False) yield self.setUpScheduler() self.jobdir = None @defer.inlineCallbacks def tearDown(self): self.tearDownScheduler() if self.jobdir: shutil.rmtree(self.jobdir) yield self.tear_down_test_reactor() # tests @defer.inlineCallbacks def setup_test_startService(self, jobdir, exp_jobdir): # set up jobdir self.jobdir = os.path.abspath('jobdir') if os.path.exists(self.jobdir): shutil.rmtree(self.jobdir) os.mkdir(self.jobdir) # build scheduler kwargs = {"name": 'tsched', "builderNames": ['a'], "jobdir": self.jobdir} sched = yield self.attachScheduler( trysched.Try_Jobdir(**kwargs), self.OBJECTID, self.SCHEDULERID, overrideBuildsetMethods=True, ) # watch interaction with the watcher service sched.watcher.startService = mock.Mock() sched.watcher.stopService = mock.Mock() @defer.inlineCallbacks def do_test_startService(self): # start it yield self.sched.startService() # check that it has set the basedir correctly self.assertEqual(self.sched.watcher.basedir, self.jobdir) self.assertEqual(1, self.sched.watcher.startService.call_count) self.assertEqual(0, self.sched.watcher.stopService.call_count) yield self.sched.stopService() self.assertEqual(1, self.sched.watcher.startService.call_count) self.assertEqual(1, self.sched.watcher.stopService.call_count) @defer.inlineCallbacks def test_startService_reldir(self): yield self.setup_test_startService('jobdir', os.path.abspath('basedir/jobdir')) yield self.do_test_startService() @defer.inlineCallbacks def test_startService_reldir_subdir(self): yield self.setup_test_startService('jobdir', os.path.abspath('basedir/jobdir/cur')) yield self.do_test_startService() @defer.inlineCallbacks def test_startService_absdir(self): yield self.setup_test_startService(os.path.abspath('jobdir'), os.path.abspath('jobdir')) yield self.do_test_startService() @defer.inlineCallbacks def do_test_startService_but_not_active(self, jobdir, exp_jobdir): """Same as do_test_startService, but the master wont activate this service""" yield self.setup_test_startService('jobdir', os.path.abspath('basedir/jobdir')) self.setSchedulerToMaster(self.OTHER_MASTER_ID) # start it self.sched.startService() # check that it has set the basedir correctly, even if it doesn't start self.assertEqual(self.sched.watcher.basedir, self.jobdir) yield self.sched.stopService() self.assertEqual(0, self.sched.watcher.startService.call_count) self.assertEqual(0, self.sched.watcher.stopService.call_count) # parseJob def test_parseJob_empty(self): sched = trysched.Try_Jobdir(name='tsched', builderNames=['a'], jobdir='foo') with self.assertRaises(trysched.BadJobfile): sched.parseJob(StringIO('')) def test_parseJob_longer_than_netstring_MAXLENGTH(self): self.patch(basic.NetstringReceiver, 'MAX_LENGTH', 100) sched = trysched.Try_Jobdir(name='tsched', builderNames=['a'], jobdir='foo') jobstr = self.makeNetstring( '1', 'extid', 'trunk', '1234', '1', 'this is my diff, -- ++, etc.', 'buildera', 'builderc', ) jobstr += 'x' * 200 test_temp_file = StringIO(jobstr) with self.assertRaises(trysched.BadJobfile): sched.parseJob(test_temp_file) def test_parseJob_invalid(self): sched = trysched.Try_Jobdir(name='tsched', builderNames=['a'], jobdir='foo') with self.assertRaises(trysched.BadJobfile): sched.parseJob(StringIO('this is not a netstring')) def test_parseJob_invalid_version(self): sched = trysched.Try_Jobdir(name='tsched', builderNames=['a'], jobdir='foo') with self.assertRaises(trysched.BadJobfile): sched.parseJob(StringIO('1:9,')) def makeNetstring(self, *strings): return ''.join([f'{len(s)}:{s},' for s in strings]) def test_parseJob_v1(self): sched = trysched.Try_Jobdir( name='tsched', builderNames=['buildera', 'builderb'], jobdir='foo' ) jobstr = self.makeNetstring( '1', 'extid', 'trunk', '1234', '1', 'this is my diff, -- ++, etc.', 'buildera', 'builderc', ) parsedjob = sched.parseJob(StringIO(jobstr)) self.assertEqual( parsedjob, { 'baserev': '1234', 'branch': 'trunk', 'builderNames': ['buildera', 'builderc'], 'jobid': 'extid', 'patch_body': b'this is my diff, -- ++, etc.', 'patch_level': 1, 'project': '', 'who': '', 'comment': '', 'repository': '', 'properties': {}, }, ) def test_parseJob_v1_empty_branch_rev(self): sched = trysched.Try_Jobdir( name='tsched', builderNames=['buildera', 'builderb'], jobdir='foo' ) jobstr = self.makeNetstring( # blank branch, rev are turned to None '1', 'extid', '', '', '1', 'this is my diff, -- ++, etc.', 'buildera', 'builderc', ) parsedjob = sched.parseJob(StringIO(jobstr)) self.assertEqual(parsedjob['branch'], None) self.assertEqual(parsedjob['baserev'], None) def test_parseJob_v1_no_builders(self): sched = trysched.Try_Jobdir( name='tsched', builderNames=['buildera', 'builderb'], jobdir='foo' ) jobstr = self.makeNetstring('1', 'extid', '', '', '1', 'this is my diff, -- ++, etc.') parsedjob = sched.parseJob(StringIO(jobstr)) self.assertEqual(parsedjob['builderNames'], []) def test_parseJob_v1_no_properties(self): sched = trysched.Try_Jobdir( name='tsched', builderNames=['buildera', 'builderb'], jobdir='foo' ) jobstr = self.makeNetstring('1', 'extid', '', '', '1', 'this is my diff, -- ++, etc.') parsedjob = sched.parseJob(StringIO(jobstr)) self.assertEqual(parsedjob['properties'], {}) def test_parseJob_v2(self): sched = trysched.Try_Jobdir( name='tsched', builderNames=['buildera', 'builderb'], jobdir='foo' ) jobstr = self.makeNetstring( '2', 'extid', 'trunk', '1234', '1', 'this is my diff, -- ++, etc.', 'repo', 'proj', 'buildera', 'builderc', ) parsedjob = sched.parseJob(StringIO(jobstr)) self.assertEqual( parsedjob, { 'baserev': '1234', 'branch': 'trunk', 'builderNames': ['buildera', 'builderc'], 'jobid': 'extid', 'patch_body': b'this is my diff, -- ++, etc.', 'patch_level': 1, 'project': 'proj', 'who': '', 'comment': '', 'repository': 'repo', 'properties': {}, }, ) def test_parseJob_v2_empty_branch_rev(self): sched = trysched.Try_Jobdir( name='tsched', builderNames=['buildera', 'builderb'], jobdir='foo' ) jobstr = self.makeNetstring( # blank branch, rev are turned to None '2', 'extid', '', '', '1', 'this is my diff, -- ++, etc.', 'repo', 'proj', 'buildera', 'builderc', ) parsedjob = sched.parseJob(StringIO(jobstr)) self.assertEqual(parsedjob['branch'], None) self.assertEqual(parsedjob['baserev'], None) def test_parseJob_v2_no_builders(self): sched = trysched.Try_Jobdir( name='tsched', builderNames=['buildera', 'builderb'], jobdir='foo' ) jobstr = self.makeNetstring( '2', 'extid', 'trunk', '1234', '1', 'this is my diff, -- ++, etc.', 'repo', 'proj', ) parsedjob = sched.parseJob(StringIO(jobstr)) self.assertEqual(parsedjob['builderNames'], []) def test_parseJob_v2_no_properties(self): sched = trysched.Try_Jobdir( name='tsched', builderNames=['buildera', 'builderb'], jobdir='foo' ) jobstr = self.makeNetstring( '2', 'extid', 'trunk', '1234', '1', 'this is my diff, -- ++, etc.', 'repo', 'proj', ) parsedjob = sched.parseJob(StringIO(jobstr)) self.assertEqual(parsedjob['properties'], {}) def test_parseJob_v3(self): sched = trysched.Try_Jobdir( name='tsched', builderNames=['buildera', 'builderb'], jobdir='foo' ) jobstr = self.makeNetstring( '3', 'extid', 'trunk', '1234', '1', 'this is my diff, -- ++, etc.', 'repo', 'proj', 'who', 'buildera', 'builderc', ) parsedjob = sched.parseJob(StringIO(jobstr)) self.assertEqual( parsedjob, { 'baserev': '1234', 'branch': 'trunk', 'builderNames': ['buildera', 'builderc'], 'jobid': 'extid', 'patch_body': b'this is my diff, -- ++, etc.', 'patch_level': 1, 'project': 'proj', 'who': 'who', 'comment': '', 'repository': 'repo', 'properties': {}, }, ) def test_parseJob_v3_empty_branch_rev(self): sched = trysched.Try_Jobdir( name='tsched', builderNames=['buildera', 'builderb'], jobdir='foo' ) jobstr = self.makeNetstring( # blank branch, rev are turned to None '3', 'extid', '', '', '1', 'this is my diff, -- ++, etc.', 'repo', 'proj', 'who', 'buildera', 'builderc', ) parsedjob = sched.parseJob(StringIO(jobstr)) self.assertEqual(parsedjob['branch'], None) self.assertEqual(parsedjob['baserev'], None) def test_parseJob_v3_no_builders(self): sched = trysched.Try_Jobdir( name='tsched', builderNames=['buildera', 'builderb'], jobdir='foo' ) jobstr = self.makeNetstring( '3', 'extid', 'trunk', '1234', '1', 'this is my diff, -- ++, etc.', 'repo', 'proj', 'who', ) parsedjob = sched.parseJob(StringIO(jobstr)) self.assertEqual(parsedjob['builderNames'], []) def test_parseJob_v3_no_properties(self): sched = trysched.Try_Jobdir( name='tsched', builderNames=['buildera', 'builderb'], jobdir='foo' ) jobstr = self.makeNetstring( '3', 'extid', 'trunk', '1234', '1', 'this is my diff, -- ++, etc.', 'repo', 'proj', 'who', ) parsedjob = sched.parseJob(StringIO(jobstr)) self.assertEqual(parsedjob['properties'], {}) def test_parseJob_v4(self): sched = trysched.Try_Jobdir( name='tsched', builderNames=['buildera', 'builderb'], jobdir='foo' ) jobstr = self.makeNetstring( '4', 'extid', 'trunk', '1234', '1', 'this is my diff, -- ++, etc.', 'repo', 'proj', 'who', 'comment', 'buildera', 'builderc', ) parsedjob = sched.parseJob(StringIO(jobstr)) self.assertEqual( parsedjob, { 'baserev': '1234', 'branch': 'trunk', 'builderNames': ['buildera', 'builderc'], 'jobid': 'extid', 'patch_body': b'this is my diff, -- ++, etc.', 'patch_level': 1, 'project': 'proj', 'who': 'who', 'comment': 'comment', 'repository': 'repo', 'properties': {}, }, ) def test_parseJob_v4_empty_branch_rev(self): sched = trysched.Try_Jobdir( name='tsched', builderNames=['buildera', 'builderb'], jobdir='foo' ) jobstr = self.makeNetstring( # blank branch, rev are turned to None '4', 'extid', '', '', '1', 'this is my diff, -- ++, etc.', 'repo', 'proj', 'who', 'comment', 'buildera', 'builderc', ) parsedjob = sched.parseJob(StringIO(jobstr)) self.assertEqual(parsedjob['branch'], None) self.assertEqual(parsedjob['baserev'], None) def test_parseJob_v4_no_builders(self): sched = trysched.Try_Jobdir( name='tsched', builderNames=['buildera', 'builderb'], jobdir='foo' ) jobstr = self.makeNetstring( '4', 'extid', 'trunk', '1234', '1', 'this is my diff, -- ++, etc.', 'repo', 'proj', 'who', 'comment', ) parsedjob = sched.parseJob(StringIO(jobstr)) self.assertEqual(parsedjob['builderNames'], []) def test_parseJob_v4_no_properties(self): sched = trysched.Try_Jobdir( name='tsched', builderNames=['buildera', 'builderb'], jobdir='foo' ) jobstr = self.makeNetstring( '4', 'extid', 'trunk', '1234', '1', 'this is my diff, -- ++, etc.', 'repo', 'proj', 'who', 'comment', ) parsedjob = sched.parseJob(StringIO(jobstr)) self.assertEqual(parsedjob['properties'], {}) def test_parseJob_v5(self): sched = trysched.Try_Jobdir( name='tsched', builderNames=['buildera', 'builderb'], jobdir='foo' ) jobstr = self.makeNetstring( '5', json.dumps({ 'jobid': 'extid', 'branch': 'trunk', 'baserev': '1234', 'patch_level': 1, 'patch_body': 'this is my diff, -- ++, etc.', 'repository': 'repo', 'project': 'proj', 'who': 'who', 'comment': 'comment', 'builderNames': ['buildera', 'builderc'], 'properties': {'foo': 'bar'}, }), ) parsedjob = sched.parseJob(StringIO(jobstr)) self.assertEqual( parsedjob, { 'baserev': '1234', 'branch': 'trunk', 'builderNames': ['buildera', 'builderc'], 'jobid': 'extid', 'patch_body': b'this is my diff, -- ++, etc.', 'patch_level': 1, 'project': 'proj', 'who': 'who', 'comment': 'comment', 'repository': 'repo', 'properties': {'foo': 'bar'}, }, ) def test_parseJob_v5_empty_branch_rev(self): sched = trysched.Try_Jobdir( name='tsched', builderNames=['buildera', 'builderb'], jobdir='foo' ) jobstr = self.makeNetstring( # blank branch, rev are turned to None '4', 'extid', '', '', '1', 'this is my diff, -- ++, etc.', 'repo', 'proj', 'who', 'comment', 'buildera', 'builderc', ) parsedjob = sched.parseJob(StringIO(jobstr)) self.assertEqual(parsedjob['branch'], None) self.assertEqual(parsedjob['baserev'], None) def test_parseJob_v5_no_builders(self): sched = trysched.Try_Jobdir( name='tsched', builderNames=['buildera', 'builderb'], jobdir='foo' ) jobstr = self.makeNetstring( '5', json.dumps({ 'jobid': 'extid', 'branch': 'trunk', 'baserev': '1234', 'patch_level': '1', 'patch_body': 'this is my diff, -- ++, etc.', 'repository': 'repo', 'project': 'proj', 'who': 'who', 'comment': 'comment', 'builderNames': [], 'properties': {'foo': 'bar'}, }), ) parsedjob = sched.parseJob(StringIO(jobstr)) self.assertEqual(parsedjob['builderNames'], []) def test_parseJob_v5_no_properties(self): sched = trysched.Try_Jobdir( name='tsched', builderNames=['buildera', 'builderb'], jobdir='foo' ) jobstr = self.makeNetstring( '5', json.dumps({ 'jobid': 'extid', 'branch': 'trunk', 'baserev': '1234', 'patch_level': '1', 'patch_body': 'this is my diff, -- ++, etc.', 'repository': 'repo', 'project': 'proj', 'who': 'who', 'comment': 'comment', 'builderNames': ['buildera', 'builderb'], 'properties': {}, }), ) parsedjob = sched.parseJob(StringIO(jobstr)) self.assertEqual(parsedjob['properties'], {}) def test_parseJob_v5_invalid_json(self): sched = trysched.Try_Jobdir( name='tsched', builderNames=['buildera', 'builderb'], jobdir='foo' ) jobstr = self.makeNetstring('5', '{"comment": "com}') with self.assertRaises(trysched.BadJobfile): sched.parseJob(StringIO(jobstr)) # handleJobFile @defer.inlineCallbacks def call_handleJobFile(self, parseJob): sched = yield self.attachScheduler( trysched.Try_Jobdir(name='tsched', builderNames=['buildera', 'builderb'], jobdir='foo'), self.OBJECTID, self.SCHEDULERID, overrideBuildsetMethods=True, createBuilderDB=True, ) fakefile = mock.Mock() def parseJob_(f): assert f is fakefile return parseJob(f) sched.parseJob = parseJob_ yield sched.handleJobFile('fakefile', fakefile) def makeSampleParsedJob(self, **overrides): pj = { "baserev": '1234', "branch": 'trunk', "builderNames": ['buildera', 'builderb'], "jobid": 'extid', "patch_body": b'this is my diff, -- ++, etc.', "patch_level": 1, "project": 'proj', "repository": 'repo', "who": 'who', "comment": 'comment', "properties": {}, } pj.update(overrides) return pj @defer.inlineCallbacks def test_handleJobFile(self): yield self.call_handleJobFile(lambda f: self.makeSampleParsedJob()) self.assertEqual( self.addBuildsetCalls, [ ( 'addBuildsetForSourceStamps', { "builderNames": ['buildera', 'builderb'], "external_idstring": 'extid', "properties": {}, "reason": "'try' job by user who", "sourcestamps": [ { "branch": 'trunk', "codebase": '', "patch_author": 'who', "patch_body": b'this is my diff, -- ++, etc.', "patch_comment": 'comment', "patch_level": 1, "patch_subdir": '', "project": 'proj', "repository": 'repo', "revision": '1234', }, ], }, ), ], ) @defer.inlineCallbacks def test_handleJobFile_exception(self): def parseJob(f): raise trysched.BadJobfile yield self.call_handleJobFile(parseJob) self.assertEqual(self.addBuildsetCalls, []) self.assertEqual(1, len(self.flushLoggedErrors(trysched.BadJobfile))) @defer.inlineCallbacks def test_handleJobFile_bad_builders(self): yield self.call_handleJobFile(lambda f: self.makeSampleParsedJob(builderNames=['xxx'])) self.assertEqual(self.addBuildsetCalls, []) @defer.inlineCallbacks def test_handleJobFile_subset_builders(self): yield self.call_handleJobFile(lambda f: self.makeSampleParsedJob(builderNames=['buildera'])) self.assertEqual( self.addBuildsetCalls, [ ( 'addBuildsetForSourceStamps', { "builderNames": ['buildera'], "external_idstring": 'extid', "properties": {}, "reason": "'try' job by user who", "sourcestamps": [ { "branch": 'trunk', "codebase": '', "patch_author": 'who', "patch_body": b'this is my diff, -- ++, etc.', "patch_comment": 'comment', "patch_level": 1, "patch_subdir": '', "project": 'proj', "repository": 'repo', "revision": '1234', }, ], }, ), ], ) @defer.inlineCallbacks def test_handleJobFile_with_try_properties(self): yield self.call_handleJobFile(lambda f: self.makeSampleParsedJob(properties={'foo': 'bar'})) self.assertEqual( self.addBuildsetCalls, [ ( 'addBuildsetForSourceStamps', { "builderNames": ['buildera', 'builderb'], "external_idstring": 'extid', "properties": {'foo': ('bar', 'try build')}, "reason": "'try' job by user who", "sourcestamps": [ { "branch": 'trunk', "codebase": '', "patch_author": 'who', "patch_body": b'this is my diff, -- ++, etc.', "patch_comment": 'comment', "patch_level": 1, "patch_subdir": '', "project": 'proj', "repository": 'repo', "revision": '1234', }, ], }, ), ], ) def test_handleJobFile_with_invalid_try_properties(self): d = self.call_handleJobFile(lambda f: self.makeSampleParsedJob(properties=['foo', 'bar'])) return self.assertFailure(d, AttributeError) class Try_Userpass_Perspective(scheduler.SchedulerMixin, TestReactorMixin, unittest.TestCase): OBJECTID = 26 SCHEDULERID = 6 @defer.inlineCallbacks def setUp(self): self.setup_test_reactor(auto_tear_down=False) yield self.setUpScheduler() @defer.inlineCallbacks def tearDown(self): self.tearDownScheduler() yield self.tear_down_test_reactor() def makeScheduler(self, **kwargs): return self.attachScheduler( trysched.Try_Userpass(**kwargs), self.OBJECTID, self.SCHEDULERID, overrideBuildsetMethods=True, createBuilderDB=True, ) @defer.inlineCallbacks def call_perspective_try(self, *args, **kwargs): sched = yield self.makeScheduler( name='tsched', builderNames=['a', 'b'], port='xxx', userpass=[('a', 'b')], properties={"frm": 'schd'}, ) persp = trysched.Try_Userpass_Perspective(sched, 'a') # patch out all of the handling after addBuildsetForSourceStamp def getBuildset(bsid): return {"bsid": bsid} self.db.buildsets.getBuildset = getBuildset rbss = yield persp.perspective_try(*args, **kwargs) if rbss is None: return self.assertIsInstance(rbss, trysched.RemoteBuildSetStatus) @defer.inlineCallbacks def test_perspective_try(self): yield self.call_perspective_try( 'default', 'abcdef', (1, '-- ++'), 'repo', 'proj', ['a'], properties={'pr': 'op'} ) self.maxDiff = None self.assertEqual( self.addBuildsetCalls, [ ( 'addBuildsetForSourceStamps', { "builderNames": ['a'], "external_idstring": None, "properties": {'pr': ('op', 'try build')}, "reason": "'try' job", "sourcestamps": [ { "branch": 'default', "codebase": '', "patch_author": '', "patch_body": b'-- ++', "patch_comment": '', "patch_level": 1, "patch_subdir": '', "project": 'proj', "repository": 'repo', "revision": 'abcdef', }, ], }, ), ], ) @defer.inlineCallbacks def test_perspective_try_bytes(self): yield self.call_perspective_try( 'default', 'abcdef', (1, b'-- ++\xf8'), 'repo', 'proj', ['a'], properties={'pr': 'op'} ) self.assertEqual( self.addBuildsetCalls, [ ( 'addBuildsetForSourceStamps', { 'builderNames': ['a'], 'external_idstring': None, 'properties': {'pr': ('op', 'try build')}, 'reason': "'try' job", 'sourcestamps': [ { 'branch': 'default', 'codebase': '', 'patch_author': '', 'patch_body': b'-- ++\xf8', 'patch_comment': '', 'patch_level': 1, 'patch_subdir': '', 'project': 'proj', 'repository': 'repo', 'revision': 'abcdef', } ], }, ), ], ) @defer.inlineCallbacks def test_perspective_try_who(self): yield self.call_perspective_try( 'default', 'abcdef', (1, '-- ++'), 'repo', 'proj', ['a'], who='who', comment='comment', properties={'pr': 'op'}, ) self.assertEqual( self.addBuildsetCalls, [ ( 'addBuildsetForSourceStamps', { "builderNames": ['a'], "external_idstring": None, "properties": {'pr': ('op', 'try build')}, "reason": "'try' job by user who (comment)", "sourcestamps": [ { "branch": 'default', "codebase": '', "patch_author": 'who', "patch_body": b'-- ++', "patch_comment": 'comment', "patch_level": 1, "patch_subdir": '', "project": 'proj', "repository": 'repo', "revision": 'abcdef', }, ], }, ), ], ) @defer.inlineCallbacks def test_perspective_try_bad_builders(self): yield self.call_perspective_try( 'default', 'abcdef', (1, '-- ++'), 'repo', 'proj', ['xxx'], properties={'pr': 'op'} ) self.assertEqual(self.addBuildsetCalls, []) @defer.inlineCallbacks def test_getAvailableBuilderNames(self): sched = yield self.makeScheduler( name='tsched', builderNames=['a', 'b'], port='xxx', userpass=[('a', 'b')] ) persp = trysched.Try_Userpass_Perspective(sched, 'a') buildernames = yield persp.perspective_getAvailableBuilderNames() self.assertEqual(buildernames, ['a', 'b']) class Try_Userpass(scheduler.SchedulerMixin, TestReactorMixin, unittest.TestCase): OBJECTID = 25 SCHEDULERID = 5 @defer.inlineCallbacks def setUp(self): self.setup_test_reactor(auto_tear_down=False) yield self.setUpScheduler() @defer.inlineCallbacks def tearDown(self): self.tearDownScheduler() yield self.tear_down_test_reactor() @defer.inlineCallbacks def makeScheduler(self, **kwargs): sched = yield self.attachScheduler( trysched.Try_Userpass(**kwargs), self.OBJECTID, self.SCHEDULERID ) return sched @defer.inlineCallbacks def test_service(self): sched = yield self.makeScheduler( name='tsched', builderNames=['a'], port='tcp:9999', userpass=[('fred', 'derf')] ) # patch out the pbmanager's 'register' command both to be sure # the registration is correct and to get a copy of the factory registration = mock.Mock() registration.unregister = lambda: defer.succeed(None) sched.master.pbmanager = mock.Mock() def register(portstr, user, passwd, factory): self.assertEqual([portstr, user, passwd], ['tcp:9999', 'fred', 'derf']) self.got_factory = factory return defer.succeed(registration) sched.master.pbmanager.register = register # start it yield sched.startService() # make a fake connection by invoking the factory, and check that we # get the correct perspective persp = self.got_factory(mock.Mock(), 'fred') self.assertTrue(isinstance(persp, trysched.Try_Userpass_Perspective)) yield sched.stopService() @defer.inlineCallbacks def test_service_but_not_active(self): sched = yield self.makeScheduler( name='tsched', builderNames=['a'], port='tcp:9999', userpass=[('fred', 'derf')] ) self.setSchedulerToMaster(self.OTHER_MASTER_ID) sched.master.pbmanager = mock.Mock() sched.startService() yield sched.stopService() self.assertFalse(sched.master.pbmanager.register.called)
37,834
Python
.py
990
25.306061
100
0.502437
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,593
test_canceller_buildset.py
buildbot_buildbot/master/buildbot/test/unit/schedulers/test_canceller_buildset.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.results import FAILURE from buildbot.process.results import SUCCESS from buildbot.schedulers.canceller_buildset import FailingBuildsetCanceller from buildbot.test import fakedb from buildbot.test.fake import fakemaster from buildbot.test.reactor import TestReactorMixin from buildbot.util.ssfilter import SourceStampFilter class TestOldBuildCanceller(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, wantData=True, wantDb=True) self.master.mq.verifyMessages = False yield self.insert_test_data() self._cancelled_build_ids = [] yield self.master.startService() @defer.inlineCallbacks def tearDown(self): yield self.master.stopService() yield self.tear_down_test_reactor() @defer.inlineCallbacks def insert_test_data(self): yield self.master.db.insert_test_data([ fakedb.Master(id=92), fakedb.Worker(id=13, name='wrk'), fakedb.Builder(id=100, name='builder1'), fakedb.Builder(id=101, name='builder2'), fakedb.Builder(id=102, name='builder3'), fakedb.Buildset(id=200, results=None, reason="reason98"), fakedb.BuildsetSourceStamp(buildsetid=200, sourcestampid=300), fakedb.SourceStamp( id=300, revision='revision1', project='project1', codebase='codebase1', repository='repository1', branch='branch1', ), fakedb.BuildRequest(id=400, buildsetid=200, builderid=100), fakedb.BuildRequestClaim(brid=400, masterid=92, claimed_at=1), fakedb.Build( id=500, number=1, builderid=100, buildrequestid=400, workerid=13, masterid=92, results=None, state_string="state1", ), fakedb.BuildRequest(id=401, buildsetid=200, builderid=101), fakedb.BuildRequestClaim(brid=401, masterid=92, claimed_at=1), fakedb.Build( id=501, number=1, builderid=101, buildrequestid=401, workerid=13, masterid=92, results=None, state_string="state2", ), fakedb.BuildRequest(id=402, buildsetid=200, builderid=102), fakedb.BuildRequestClaim(brid=402, masterid=92, claimed_at=1), fakedb.Build( id=502, number=1, builderid=102, buildrequestid=402, workerid=13, masterid=92, results=None, state_string="state3", ), ]) def assert_cancelled(self, cancellations): expected_productions = [] reason = 'Build has been cancelled because another build in the same buildset failed' for kind, id in cancellations: if kind == 'build': expected_productions.append(( ('control', 'builds', str(id), 'stop'), {'reason': reason}, )) elif kind == 'breq': expected_productions.append(( ('control', 'buildrequests', str(id), 'cancel'), {'reason': reason}, )) self.master.mq.assertProductions(expected_productions) @defer.inlineCallbacks def send_build_finished(self, id, results): build = yield self.master.data.get(('builds', str(id))) build['results'] = results self.master.mq.callConsumer(('builds', str(id), 'finished'), build) yield self.master.mq.wait_consumed() @defer.inlineCallbacks def test_cancel_buildrequests_ss_filter_does_not_match(self): self.canceller = FailingBuildsetCanceller( 'canceller', [ ( ['builder1'], ['builder1', 'builder2', 'builder3'], SourceStampFilter(branch_eq=['branch_other']), ), ], ) yield self.canceller.setServiceParent(self.master) yield self.send_build_finished(500, FAILURE) self.assert_cancelled([]) @defer.inlineCallbacks def test_cancel_buildrequests_builder_filter_does_not_match(self): self.canceller = FailingBuildsetCanceller( 'canceller', [ ( ['builder2'], ['builder1', 'builder2', 'builder3'], SourceStampFilter(branch_eq=['branch1']), ), ], ) yield self.canceller.setServiceParent(self.master) yield self.send_build_finished(500, FAILURE) self.assert_cancelled([]) @defer.inlineCallbacks def test_cancel_buildrequests_not_failure(self): self.canceller = FailingBuildsetCanceller( 'canceller', [ ( ['builder1'], ['builder1', 'builder2', 'builder3'], SourceStampFilter(branch_eq=['branch1']), ), ], ) yield self.canceller.setServiceParent(self.master) yield self.send_build_finished(500, SUCCESS) self.assert_cancelled([]) @defer.inlineCallbacks def test_cancel_buildrequests_matches(self): self.canceller = FailingBuildsetCanceller( 'canceller', [ ( ['builder1'], ['builder1', 'builder2', 'builder3'], SourceStampFilter(branch_eq=['branch1']), ), ], ) yield self.canceller.setServiceParent(self.master) yield self.send_build_finished(500, FAILURE) # Buildrequest cancelling happens in BotMaster and this test uses a fake one that does # not implement build cancelling after buildrequest cancels self.assert_cancelled([('breq', 401), ('breq', 402)]) @defer.inlineCallbacks def test_cancel_buildrequests_matches_any_builder(self): self.canceller = FailingBuildsetCanceller( 'canceller', [ (['builder1'], None, SourceStampFilter(branch_eq=['branch1'])), ], ) yield self.canceller.setServiceParent(self.master) yield self.send_build_finished(500, FAILURE) # Buildrequest cancelling happens in BotMaster and this test uses a fake one that does # not implement build cancelling after buildrequest cancels self.assert_cancelled([('breq', 401), ('breq', 402)])
7,706
Python
.py
187
29.871658
97
0.594108
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,594
test_versions_066_add_build_locks_duration_s.py
buildbot_buildbot/master/buildbot/test/unit/db_migrate/test_versions_066_add_build_locks_duration_s.py
# This file is part of Buildbot. Buildbot is free software: you can # redistribute it and/or modify it under the terms of the GNU General Public # License as published by the Free Software Foundation, version 2. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more # details. # # You should have received a copy of the GNU General Public License along with # this program; if not, write to the Free Software Foundation, Inc., 51 # Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # Copyright Buildbot Team Members import sqlalchemy as sa from twisted.trial import unittest from buildbot.test.util import migration from buildbot.util import sautils class Migration(migration.MigrateTestMixin, unittest.TestCase): def setUp(self): return self.setUpMigrateTest() def tearDown(self): return self.tearDownMigrateTest() def create_tables_thd(self, conn): metadata = sa.MetaData() metadata.bind = conn # builderid, buildrequestid, workerid, masterid foreign keys are removed for the # purposes of the test builds = sautils.Table( 'builds', metadata, sa.Column('id', sa.Integer, primary_key=True), sa.Column('number', sa.Integer, nullable=False), sa.Column('started_at', sa.Integer, nullable=False), sa.Column('complete_at', sa.Integer), sa.Column('state_string', sa.Text, nullable=False), sa.Column('results', sa.Integer), ) builds.create(bind=conn) conn.execute( builds.insert(), [ { "id": 4, "number": 5, "started_at": 1695730972, "complete_at": 1695730975, "state_string": "test build", "results": 0, } ], ) conn.commit() def test_update(self): def setup_thd(conn): self.create_tables_thd(conn) def verify_thd(conn): metadata = sa.MetaData() metadata.bind = conn builds = sautils.Table('builds', metadata, autoload_with=conn) self.assertIsInstance(builds.c.locks_duration_s.type, sa.Integer) conn.execute( builds.insert(), [ { "id": 5, "number": 6, "started_at": 1695730982, "complete_at": 1695730985, "locks_duration_s": 12, "state_string": "test build", "results": 0, } ], ) durations = [] for row in conn.execute(sa.select(builds.c.locks_duration_s)): durations.append(row.locks_duration_s) self.assertEqual(durations, [0, 12]) return self.do_test_migration('065', '066', setup_thd, verify_thd)
3,211
Python
.py
80
28.8125
88
0.572666
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,595
test_versions_060_add_builder_projects.py
buildbot_buildbot/master/buildbot/test/unit/db_migrate/test_versions_060_add_builder_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 import hashlib import sqlalchemy as sa from twisted.trial import unittest from buildbot.test.util import migration from buildbot.util import sautils class Migration(migration.MigrateTestMixin, unittest.TestCase): def setUp(self): return self.setUpMigrateTest() def tearDown(self): return self.tearDownMigrateTest() def create_tables_thd(self, conn): metadata = sa.MetaData() metadata.bind = conn builders = sautils.Table( 'builders', metadata, sa.Column('id', sa.Integer, primary_key=True), sa.Column('name', sa.Text, nullable=False), sa.Column('description', sa.Text, nullable=True), sa.Column('name_hash', sa.String(40), nullable=False), ) builders.create(bind=conn) conn.execute( builders.insert(), [ { "id": 3, "name": "foo", "description": "foo_description", "name_hash": hashlib.sha1(b'foo').hexdigest(), } ], ) conn.commit() def test_update(self): def setup_thd(conn): self.create_tables_thd(conn) def verify_thd(conn): metadata = sa.MetaData() metadata.bind = conn # check that projects table has been added projects = sautils.Table('projects', metadata, autoload_with=conn) q = sa.select( projects.c.id, projects.c.name, projects.c.name_hash, projects.c.slug, projects.c.description, ) self.assertEqual(conn.execute(q).fetchall(), []) # check that builders.projectid has been added builders = sautils.Table('builders', metadata, autoload_with=conn) self.assertIsInstance(builders.c.projectid.type, sa.Integer) q = sa.select(builders.c.name, builders.c.projectid) num_rows = 0 for row in conn.execute(q): # verify that the default value was set correctly self.assertIsNone(row.projectid) num_rows += 1 self.assertEqual(num_rows, 1) # check that new indexes have been added insp = sa.inspect(conn) indexes = insp.get_indexes('projects') index_names = [item['name'] for item in indexes] self.assertTrue('projects_name_hash' in index_names) indexes = insp.get_indexes('builders') index_names = [item['name'] for item in indexes] self.assertTrue('builders_projectid' in index_names) return self.do_test_migration('059', '060', setup_thd, verify_thd)
3,522
Python
.py
83
32.240964
79
0.612281
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,596
test_versions_062_add_project_description_format.py
buildbot_buildbot/master/buildbot/test/unit/db_migrate/test_versions_062_add_project_description_format.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 hashlib import sqlalchemy as sa from twisted.trial import unittest from buildbot.test.util import migration from buildbot.util import sautils class Migration(migration.MigrateTestMixin, unittest.TestCase): def setUp(self): return self.setUpMigrateTest() def tearDown(self): return self.tearDownMigrateTest() def create_tables_thd(self, conn): metadata = sa.MetaData() metadata.bind = conn hash_length = 40 projects = sautils.Table( 'projects', metadata, sa.Column('id', sa.Integer, primary_key=True), sa.Column('name', sa.Text, nullable=False), sa.Column('name_hash', sa.String(hash_length), nullable=False), sa.Column('slug', sa.String(50), nullable=False), sa.Column('description', sa.Text, nullable=True), ) projects.create(bind=conn) conn.execute( projects.insert(), [ { "id": 4, "name": "foo", "description": "foo_description", "description_html": None, "description_format": None, "slug": "foo", "name_hash": hashlib.sha1(b'foo').hexdigest(), } ], ) conn.commit() def test_update(self): def setup_thd(conn): self.create_tables_thd(conn) def verify_thd(conn): metadata = sa.MetaData() metadata.bind = conn projects = sautils.Table('projects', metadata, autoload_with=conn) self.assertIsInstance(projects.c.description_format.type, sa.Text) self.assertIsInstance(projects.c.description_html.type, sa.Text) q = sa.select( projects.c.name, projects.c.description_format, projects.c.description_html, ) num_rows = 0 for row in conn.execute(q): self.assertIsNone(row.description_format) self.assertIsNone(row.description_html) num_rows += 1 self.assertEqual(num_rows, 1) return self.do_test_migration('061', '062', setup_thd, verify_thd)
3,014
Python
.py
74
30.756757
79
0.611149
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,597
test_versions_064_add_worker_pause_reason.py
buildbot_buildbot/master/buildbot/test/unit/db_migrate/test_versions_064_add_worker_pause_reason.py
# This file is part of Buildbot. Buildbot is free software: you can # redistribute it and/or modify it under the terms of the GNU General Public # License as published by the Free Software Foundation, version 2. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more # details. # # You should have received a copy of the GNU General Public License along with # this program; if not, write to the Free Software Foundation, Inc., 51 # Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # Copyright Buildbot Team Members import sqlalchemy as sa from twisted.trial import unittest from buildbot.db.types.json import JsonObject from buildbot.test.util import migration from buildbot.util import sautils class Migration(migration.MigrateTestMixin, unittest.TestCase): def setUp(self): return self.setUpMigrateTest() def tearDown(self): return self.tearDownMigrateTest() def create_tables_thd(self, conn): metadata = sa.MetaData() metadata.bind = conn workers = sautils.Table( "workers", metadata, sa.Column("id", sa.Integer, primary_key=True), sa.Column("name", sa.String(50), nullable=False), sa.Column("info", JsonObject, nullable=False), sa.Column("paused", sa.SmallInteger, nullable=False, server_default="0"), sa.Column("graceful", sa.SmallInteger, nullable=False, server_default="0"), ) workers.create(bind=conn) conn.execute( workers.insert(), [ { "id": 4, "name": "worker1", "info": "{\"key\": \"value\"}", "paused": 0, "graceful": 0, } ], ) conn.commit() def test_update(self): def setup_thd(conn): self.create_tables_thd(conn) def verify_thd(conn): metadata = sa.MetaData() metadata.bind = conn workers = sautils.Table('workers', metadata, autoload_with=conn) self.assertIsInstance(workers.c.pause_reason.type, sa.Text) q = sa.select( workers.c.name, workers.c.pause_reason, ) num_rows = 0 for row in conn.execute(q): self.assertEqual(row.name, "worker1") self.assertIsNone(row.pause_reason) num_rows += 1 self.assertEqual(num_rows, 1) return self.do_test_migration('063', '064', setup_thd, verify_thd)
2,780
Python
.py
69
30.797101
87
0.612162
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,598
test_versions_061_add_builder_description_format.py
buildbot_buildbot/master/buildbot/test/unit/db_migrate/test_versions_061_add_builder_description_format.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 hashlib import sqlalchemy as sa from twisted.trial import unittest from buildbot.test.util import migration from buildbot.util import sautils class Migration(migration.MigrateTestMixin, unittest.TestCase): def setUp(self): return self.setUpMigrateTest() def tearDown(self): return self.tearDownMigrateTest() def create_tables_thd(self, conn): metadata = sa.MetaData() metadata.bind = conn builders = sautils.Table( 'builders', metadata, sa.Column('id', sa.Integer, primary_key=True), sa.Column('name', sa.Text, nullable=False), sa.Column('description', sa.Text, nullable=True), sa.Column('projectid', sa.Integer, nullable=True), sa.Column('name_hash', sa.String(40), nullable=False), ) builders.create(bind=conn) conn.execute( builders.insert(), [ { "id": 3, "name": "foo", "description": "foo_description", "projectid": None, "name_hash": hashlib.sha1(b'foo').hexdigest(), } ], ) conn.commit() def test_update(self): def setup_thd(conn): self.create_tables_thd(conn) def verify_thd(conn): metadata = sa.MetaData() metadata.bind = conn builders = sautils.Table('builders', metadata, autoload_with=conn) self.assertIsInstance(builders.c.description_format.type, sa.Text) self.assertIsInstance(builders.c.description_html.type, sa.Text) q = sa.select( builders.c.name, builders.c.description_format, builders.c.description_html, ) num_rows = 0 for row in conn.execute(q): self.assertIsNone(row.description_format) self.assertIsNone(row.description_html) num_rows += 1 self.assertEqual(num_rows, 1) return self.do_test_migration('060', '061', setup_thd, verify_thd)
2,890
Python
.py
71
31.042254
79
0.619116
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,599
test_versions_065_add_buildsets_rebuilt_buildid.py
buildbot_buildbot/master/buildbot/test/unit/db_migrate/test_versions_065_add_buildsets_rebuilt_buildid.py
# This file is part of Buildbot. Buildbot is free software: you can # redistribute it and/or modify it under the terms of the GNU General Public # License as published by the Free Software Foundation, version 2. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more # details. # # You should have received a copy of the GNU General Public License along with # this program; if not, write to the Free Software Foundation, Inc., 51 # Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # Copyright Buildbot Team Members import sqlalchemy as sa from sqlalchemy.inspection import inspect from twisted.trial import unittest from buildbot.test.util import migration from buildbot.util import sautils class Migration(migration.MigrateTestMixin, unittest.TestCase): def setUp(self): return self.setUpMigrateTest() def tearDown(self): return self.tearDownMigrateTest() def create_tables_thd(self, conn): metadata = sa.MetaData() metadata.bind = conn # parent_buildid foreign key is removed for the purposes of the test buildsets = sautils.Table( "buildsets", metadata, sa.Column("id", sa.Integer, primary_key=True), sa.Column("external_idstring", sa.String(256)), sa.Column("reason", sa.String(256)), sa.Column("submitted_at", sa.Integer, nullable=False), sa.Column( "complete", sa.SmallInteger, nullable=False, server_default=sa.DefaultClause("0") ), sa.Column("complete_at", sa.Integer), sa.Column("results", sa.SmallInteger), sa.Column("parent_relationship", sa.Text), ) buildsets.create(bind=conn) conn.execute( buildsets.insert(), [ { "id": 4, "external_idstring": 5, "reason": "rebuild", "submitted_at": 1695730972, "complete": 1, "complete_at": 1695730977, "results": 0, "parent_relationship": "Triggered from", } ], ) conn.commit() builds = sautils.Table("builds", metadata, sa.Column("id", sa.Integer, primary_key=True)) builds.create(bind=conn) conn.execute( builds.insert(), [ { "id": 123, } ], ) conn.commit() def test_update(self): def setup_thd(conn): self.create_tables_thd(conn) def verify_thd(conn): metadata = sa.MetaData() metadata.bind = conn # check that builsets.rebuilt_buildid has been added buildsets = sautils.Table('buildsets', metadata, autoload_with=conn) self.assertIsInstance(buildsets.c.rebuilt_buildid.type, sa.Integer) q = sa.select( buildsets.c.rebuilt_buildid, ) all_fk_info = inspect(conn).get_foreign_keys("buildsets") fk_in_search = [] for fk in all_fk_info: if fk["name"] == "rebuilt_buildid": fk_in_search.append(fk) # verify that a foreign with name "fk_buildsets_rebuilt_buildid" was found self.assertEqual(len(fk_in_search), 1) conn.execute( buildsets.insert(), [ { "id": 5, "external_idstring": 6, "reason": "rebuild", "submitted_at": 1695730973, "complete": 1, "complete_at": 1695730978, "results": 0, "rebuilt_buildid": 123, "parent_relationship": "Triggered from", } ], ) conn.commit() rebuilt_buildid_list = [] for row in conn.execute(q): rebuilt_buildid_list.append(row.rebuilt_buildid) # verify that the 1st default value was set correctly to None self.assertEqual(rebuilt_buildid_list, [None, 123]) return self.do_test_migration('064', '065', setup_thd, verify_thd)
4,567
Python
.py
112
28.428571
97
0.555455
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)