summaryrefslogtreecommitdiffstats
path: root/tests
diff options
context:
space:
mode:
authorThanh Ha <zxiiro@gmail.com>2019-08-23 09:14:39 -0400
committerSorin Sbarnea <ssbarnea@redhat.com>2019-09-09 19:23:24 +0100
commit4d90c187a945c04b9949d5ee7738a049dd634897 (patch)
tree106bf6e05ad1f2260823e7cd68651b535b8ac3ef /tests
parentead185134d8aa5d3d0974207356de6c4fdb2e6e8 (diff)
downloadpython-jenkins-job-builder-4d90c187a945c04b9949d5ee7738a049dd634897.tar.gz
python-jenkins-job-builder-4d90c187a945c04b9949d5ee7738a049dd634897.tar.xz
python-jenkins-job-builder-4d90c187a945c04b9949d5ee7738a049dd634897.zip
Auto-generated output from python-black
Please review the following patch containing the code changes in the repo. This patch is a transition patch and is the auto-generated output of the python-black tool. Change-Id: I2d2de71da8a105fb62b561899ae78441ddab4032 Signed-off-by: Thanh Ha <zxiiro@gmail.com>
Diffstat (limited to 'tests')
-rw-r--r--tests/base.py209
-rw-r--r--tests/builders/test_builders.py2
-rw-r--r--tests/cachestorage/test_cachestorage.py19
-rw-r--r--tests/cmd/subcommands/test_delete.py48
-rw-r--r--tests/cmd/subcommands/test_delete_all.py26
-rw-r--r--tests/cmd/subcommands/test_list.py79
-rw-r--r--tests/cmd/subcommands/test_test.py338
-rw-r--r--tests/cmd/subcommands/test_update.py96
-rw-r--r--tests/cmd/test_cmd.py11
-rw-r--r--tests/cmd/test_config.py107
-rw-r--r--tests/cmd/test_recurse_path.py79
-rw-r--r--tests/duplicates/test_duplicates.py4
-rw-r--r--tests/errors/test_exceptions.py39
-rw-r--r--tests/general/test_general.py2
-rw-r--r--tests/hipchat/test_hipchat.py2
-rw-r--r--tests/jenkins_manager/test_manager.py55
-rw-r--r--tests/jsonparser/test_jsonparser.py4
-rw-r--r--tests/localyaml/test_localyaml.py45
-rw-r--r--tests/macros/test_macros.py2
-rw-r--r--tests/moduleregistry/test_moduleregistry.py79
-rw-r--r--tests/modules/test_helpers.py117
-rw-r--r--tests/multibranch/test_multibranch.py6
-rw-r--r--tests/notifications/test_notifications.py2
-rw-r--r--tests/parallel/test_parallel.py13
-rw-r--r--tests/parameters/test_parameters.py2
-rw-r--r--tests/properties/test_properties.py2
-rw-r--r--tests/publishers/test_publishers.py2
-rw-r--r--tests/reporters/test_reporters.py2
-rw-r--r--tests/scm/test_scm.py2
-rw-r--r--tests/triggers/test_triggers.py2
-rw-r--r--tests/views/test_views.py6
-rw-r--r--tests/wrappers/test_wrappers.py2
-rw-r--r--tests/xml_config/test_xml_config.py18
-rw-r--r--tests/yamlparser/test_yamlparser.py24
34 files changed, 773 insertions, 673 deletions
diff --git a/tests/base.py b/tests/base.py
index b239f64e..660a3af7 100644
--- a/tests/base.py
+++ b/tests/base.py
@@ -59,9 +59,13 @@ except ImportError:
import mock # noqa
-def get_scenarios(fixtures_path, in_ext='yaml', out_ext='xml',
- plugins_info_ext='plugins_info.yaml',
- filter_func=None):
+def get_scenarios(
+ fixtures_path,
+ in_ext="yaml",
+ out_ext="xml",
+ plugins_info_ext="plugins_info.yaml",
+ filter_func=None,
+):
"""Returns a list of scenarios, each scenario being described
by two parameters (yaml and xml filenames by default).
- content of the fixture output file (aka expected)
@@ -75,8 +79,9 @@ def get_scenarios(fixtures_path, in_ext='yaml', out_ext='xml',
else:
files[fn] = [os.path.join(dirpath, fn)]
- input_files = [files[f][0] for f in files if
- re.match(r'.*\.{0}$'.format(in_ext), f)]
+ input_files = [
+ files[f][0] for f in files if re.match(r".*\.{0}$".format(in_ext), f)
+ ]
for input_filename in input_files:
if input_filename.endswith(plugins_info_ext):
@@ -85,21 +90,22 @@ def get_scenarios(fixtures_path, in_ext='yaml', out_ext='xml',
if callable(filter_func) and filter_func(input_filename):
continue
- output_candidate = re.sub(r'\.{0}$'.format(in_ext),
- '.{0}'.format(out_ext), input_filename)
+ output_candidate = re.sub(
+ r"\.{0}$".format(in_ext), ".{0}".format(out_ext), input_filename
+ )
# assume empty file if no output candidate found
if os.path.basename(output_candidate) in files:
out_filenames = files[os.path.basename(output_candidate)]
else:
out_filenames = None
- plugins_info_candidate = re.sub(r'\.{0}$'.format(in_ext),
- '.{0}'.format(plugins_info_ext),
- input_filename)
+ plugins_info_candidate = re.sub(
+ r"\.{0}$".format(in_ext), ".{0}".format(plugins_info_ext), input_filename
+ )
if os.path.basename(plugins_info_candidate) not in files:
plugins_info_candidate = None
- conf_candidate = re.sub(r'\.yaml$|\.json$', '.conf', input_filename)
+ conf_candidate = re.sub(r"\.yaml$|\.json$", ".conf", input_filename)
conf_filename = files.get(os.path.basename(conf_candidate), None)
if conf_filename:
@@ -108,12 +114,17 @@ def get_scenarios(fixtures_path, in_ext='yaml', out_ext='xml',
# for testing purposes we want to avoid using user config files
conf_filename = os.devnull
- scenarios.append((input_filename, {
- 'in_filename': input_filename,
- 'out_filenames': out_filenames,
- 'conf_filename': conf_filename,
- 'plugins_info_filename': plugins_info_candidate,
- }))
+ scenarios.append(
+ (
+ input_filename,
+ {
+ "in_filename": input_filename,
+ "out_filenames": out_filenames,
+ "conf_filename": conf_filename,
+ "plugins_info_filename": plugins_info_candidate,
+ },
+ )
+ )
return scenarios
@@ -121,7 +132,7 @@ def get_scenarios(fixtures_path, in_ext='yaml', out_ext='xml',
class BaseTestCase(testtools.TestCase):
# TestCase settings:
- maxDiff = None # always dump text difference
+ maxDiff = None # always dump text difference
longMessage = True # keep normal error message when providing our
def setUp(self):
@@ -137,12 +148,12 @@ class BaseTestCase(testtools.TestCase):
# Read XML content, assuming it is unicode encoded
xml_content = ""
for f in sorted(self.out_filenames):
- with io.open(f, 'r', encoding='utf-8') as xml_file:
+ with io.open(f, "r", encoding="utf-8") as xml_file:
xml_content += u"%s" % xml_file.read()
return xml_content
def _read_yaml_content(self, filename):
- with io.open(filename, 'r', encoding='utf-8') as yaml_file:
+ with io.open(filename, "r", encoding="utf-8") as yaml_file:
yaml_content = yaml.load(yaml_file)
return yaml_content
@@ -170,10 +181,10 @@ class BaseScenariosTestCase(testscenarios.TestWithScenarios, BaseTestCase):
plugins_info = None
if self.plugins_info_filename:
plugins_info = self._read_yaml_content(self.plugins_info_filename)
- self.addDetail("plugins-info-filename",
- text_content(self.plugins_info_filename))
- self.addDetail("plugins-info",
- text_content(str(plugins_info)))
+ self.addDetail(
+ "plugins-info-filename", text_content(self.plugins_info_filename)
+ )
+ self.addDetail("plugins-info", text_content(str(plugins_info)))
parser = YamlParser(jjb_config)
registry = ModuleRegistry(jjb_config, plugins_info)
@@ -182,76 +193,89 @@ class BaseScenariosTestCase(testscenarios.TestWithScenarios, BaseTestCase):
pub = self.klass(registry)
project = None
- if ('project-type' in yaml_content):
- if (yaml_content['project-type'] == "maven"):
+ if "project-type" in yaml_content:
+ if yaml_content["project-type"] == "maven":
project = project_maven.Maven(registry)
- elif (yaml_content['project-type'] == "matrix"):
+ elif yaml_content["project-type"] == "matrix":
project = project_matrix.Matrix(registry)
- elif (yaml_content['project-type'] == "flow"):
+ elif yaml_content["project-type"] == "flow":
project = project_flow.Flow(registry)
- elif (yaml_content['project-type'] == "multijob"):
+ elif yaml_content["project-type"] == "multijob":
project = project_multijob.MultiJob(registry)
- elif (yaml_content['project-type'] == "multibranch"):
+ elif yaml_content["project-type"] == "multibranch":
project = project_multibranch.WorkflowMultiBranch(registry)
- elif (yaml_content['project-type'] == "multibranch-defaults"):
- project = project_multibranch.WorkflowMultiBranchDefaults(registry) # noqa
- elif (yaml_content['project-type'] == "externaljob"):
+ elif yaml_content["project-type"] == "multibranch-defaults":
+ project = project_multibranch.WorkflowMultiBranchDefaults(
+ registry
+ ) # noqa
+ elif yaml_content["project-type"] == "externaljob":
project = project_externaljob.ExternalJob(registry)
- if 'view-type' in yaml_content:
- if yaml_content['view-type'] == "all":
+ if "view-type" in yaml_content:
+ if yaml_content["view-type"] == "all":
project = view_all.All(None)
- elif yaml_content['view-type'] == "list":
+ elif yaml_content["view-type"] == "list":
project = view_list.List(None)
- elif yaml_content['view-type'] == "pipeline":
+ elif yaml_content["view-type"] == "pipeline":
project = view_pipeline.Pipeline(None)
else:
- raise InvalidAttributeError(
- 'view-type', yaml_content['view-type'])
+ raise InvalidAttributeError("view-type", yaml_content["view-type"])
if project:
xml_project = project.root_xml(yaml_content)
else:
- xml_project = XML.Element('project')
+ xml_project = XML.Element("project")
# Generate the XML tree directly with modules/general
pub.gen_xml(xml_project, yaml_content)
# check output file is under correct path
- if 'name' in yaml_content:
+ if "name" in yaml_content:
prefix = os.path.dirname(self.in_filename)
# split using '/' since fullname uses URL path separator
- expected_folders = [os.path.normpath(
- os.path.join(prefix,
- '/'.join(parser._getfullname(yaml_content).
- split('/')[:-1])))]
+ expected_folders = [
+ os.path.normpath(
+ os.path.join(
+ prefix,
+ "/".join(parser._getfullname(yaml_content).split("/")[:-1]),
+ )
+ )
+ ]
actual_folders = [os.path.dirname(f) for f in self.out_filenames]
self.assertEquals(
- expected_folders, actual_folders,
- "Output file under wrong path, was '%s', should be '%s'" %
- (self.out_filenames[0],
- os.path.join(expected_folders[0],
- os.path.basename(self.out_filenames[0]))))
+ expected_folders,
+ actual_folders,
+ "Output file under wrong path, was '%s', should be '%s'"
+ % (
+ self.out_filenames[0],
+ os.path.join(
+ expected_folders[0], os.path.basename(self.out_filenames[0])
+ ),
+ ),
+ )
# Prettify generated XML
- pretty_xml = XmlJob(xml_project, 'fixturejob').output().decode('utf-8')
+ pretty_xml = XmlJob(xml_project, "fixturejob").output().decode("utf-8")
self.assertThat(
pretty_xml,
- testtools.matchers.DocTestMatches(expected_xml,
- doctest.ELLIPSIS |
- doctest.REPORT_NDIFF)
+ testtools.matchers.DocTestMatches(
+ expected_xml, doctest.ELLIPSIS | doctest.REPORT_NDIFF
+ ),
)
class SingleJobTestCase(BaseScenariosTestCase):
-
def test_yaml_snippet(self):
config = self._get_config()
- expected_xml = self._read_utf8_content().strip() \
- .replace('<BLANKLINE>', '').replace('\n\n', '\n')
+ expected_xml = (
+ self._read_utf8_content()
+ .strip()
+ .replace("<BLANKLINE>", "")
+ .replace("\n\n", "\n")
+ )
parser = YamlParser(config)
parser.parse(self.in_filename)
@@ -259,10 +283,10 @@ class SingleJobTestCase(BaseScenariosTestCase):
plugins_info = None
if self.plugins_info_filename:
plugins_info = self._read_yaml_content(self.plugins_info_filename)
- self.addDetail("plugins-info-filename",
- text_content(self.plugins_info_filename))
- self.addDetail("plugins-info",
- text_content(str(plugins_info)))
+ self.addDetail(
+ "plugins-info-filename", text_content(self.plugins_info_filename)
+ )
+ self.addDetail("plugins-info", text_content(str(plugins_info)))
registry = ModuleRegistry(config, plugins_info)
registry.set_parser_data(parser.data)
@@ -277,53 +301,62 @@ class SingleJobTestCase(BaseScenariosTestCase):
# check reference files are under correct path for folders
prefix = os.path.dirname(self.in_filename)
# split using '/' since fullname uses URL path separator
- expected_folders = list(set([
- os.path.normpath(
- os.path.join(prefix,
- '/'.join(job_data['name'].split('/')[:-1])))
- for job_data in job_data_list
- ]))
+ expected_folders = list(
+ set(
+ [
+ os.path.normpath(
+ os.path.join(prefix, "/".join(job_data["name"].split("/")[:-1]))
+ )
+ for job_data in job_data_list
+ ]
+ )
+ )
actual_folders = [os.path.dirname(f) for f in self.out_filenames]
six.assertCountEqual(
self,
- expected_folders, actual_folders,
- "Output file under wrong path, was '%s', should be '%s'" %
- (self.out_filenames[0],
- os.path.join(expected_folders[0],
- os.path.basename(self.out_filenames[0]))))
+ expected_folders,
+ actual_folders,
+ "Output file under wrong path, was '%s', should be '%s'"
+ % (
+ self.out_filenames[0],
+ os.path.join(
+ expected_folders[0], os.path.basename(self.out_filenames[0])
+ ),
+ ),
+ )
# Prettify generated XML
- pretty_xml = u"\n".join(job.output().decode('utf-8')
- for job in xml_jobs) \
- .strip().replace('\n\n', '\n')
+ pretty_xml = (
+ u"\n".join(job.output().decode("utf-8") for job in xml_jobs)
+ .strip()
+ .replace("\n\n", "\n")
+ )
self.assertThat(
pretty_xml,
- testtools.matchers.DocTestMatches(expected_xml,
- doctest.ELLIPSIS |
- doctest.REPORT_NDIFF))
+ testtools.matchers.DocTestMatches(
+ expected_xml, doctest.ELLIPSIS | doctest.REPORT_NDIFF
+ ),
+ )
class JsonTestCase(BaseScenariosTestCase):
-
def test_yaml_snippet(self):
expected_json = self._read_utf8_content()
yaml_content = self._read_yaml_content(self.in_filename)
- pretty_json = json.dumps(yaml_content, indent=4,
- separators=(',', ': '))
+ pretty_json = json.dumps(yaml_content, indent=4, separators=(",", ": "))
self.assertThat(
pretty_json,
- testtools.matchers.DocTestMatches(expected_json,
- doctest.ELLIPSIS |
- doctest.REPORT_NDIFF)
+ testtools.matchers.DocTestMatches(
+ expected_json, doctest.ELLIPSIS | doctest.REPORT_NDIFF
+ ),
)
class YamlTestCase(BaseScenariosTestCase):
-
def test_yaml_snippet(self):
expected_yaml = self._read_utf8_content()
yaml_content = self._read_yaml_content(self.in_filename)
@@ -337,7 +370,7 @@ class YamlTestCase(BaseScenariosTestCase):
self.assertThat(
pretty_yaml,
- testtools.matchers.DocTestMatches(expected_yaml,
- doctest.ELLIPSIS |
- doctest.REPORT_NDIFF)
+ testtools.matchers.DocTestMatches(
+ expected_yaml, doctest.ELLIPSIS | doctest.REPORT_NDIFF
+ ),
)
diff --git a/tests/builders/test_builders.py b/tests/builders/test_builders.py
index 350d10e8..9d9f77d4 100644
--- a/tests/builders/test_builders.py
+++ b/tests/builders/test_builders.py
@@ -22,6 +22,6 @@ from tests import base
class TestCaseModuleBuilders(base.BaseScenariosTestCase):
- fixtures_path = os.path.join(os.path.dirname(__file__), 'fixtures')
+ fixtures_path = os.path.join(os.path.dirname(__file__), "fixtures")
scenarios = base.get_scenarios(fixtures_path)
klass = builders.Builders
diff --git a/tests/cachestorage/test_cachestorage.py b/tests/cachestorage/test_cachestorage.py
index 138f1406..34803895 100644
--- a/tests/cachestorage/test_cachestorage.py
+++ b/tests/cachestorage/test_cachestorage.py
@@ -21,28 +21,25 @@ from tests.base import mock
class TestCaseJobCache(base.BaseTestCase):
-
- @mock.patch('jenkins_jobs.builder.JobCache.get_cache_dir',
- lambda x: '/bad/file')
+ @mock.patch("jenkins_jobs.builder.JobCache.get_cache_dir", lambda x: "/bad/file")
def test_save_on_exit(self):
"""
Test that the cache is saved on normal object deletion
"""
- with mock.patch('jenkins_jobs.builder.JobCache.save') as save_mock:
- with mock.patch('os.path.isfile', return_value=False):
- with mock.patch('jenkins_jobs.builder.JobCache._lock'):
+ with mock.patch("jenkins_jobs.builder.JobCache.save") as save_mock:
+ with mock.patch("os.path.isfile", return_value=False):
+ with mock.patch("jenkins_jobs.builder.JobCache._lock"):
jenkins_jobs.builder.JobCache("dummy")
save_mock.assert_called_with()
- @mock.patch('jenkins_jobs.builder.JobCache.get_cache_dir',
- lambda x: '/bad/file')
+ @mock.patch("jenkins_jobs.builder.JobCache.get_cache_dir", lambda x: "/bad/file")
def test_cache_file(self):
"""
Test providing a cachefile.
"""
test_file = os.path.abspath(__file__)
- with mock.patch('os.path.join', return_value=test_file):
- with mock.patch('yaml.load'):
- with mock.patch('jenkins_jobs.builder.JobCache._lock'):
+ with mock.patch("os.path.join", return_value=test_file):
+ with mock.patch("yaml.load"):
+ with mock.patch("jenkins_jobs.builder.JobCache._lock"):
jenkins_jobs.builder.JobCache("dummy").data = None
diff --git a/tests/cmd/subcommands/test_delete.py b/tests/cmd/subcommands/test_delete.py
index 4e577fd6..252b82ec 100644
--- a/tests/cmd/subcommands/test_delete.py
+++ b/tests/cmd/subcommands/test_delete.py
@@ -24,51 +24,49 @@ from tests.base import mock
from tests.cmd.test_cmd import CmdTestsBase
-@mock.patch('jenkins_jobs.builder.JenkinsManager.get_plugins_info',
- mock.MagicMock)
+@mock.patch("jenkins_jobs.builder.JenkinsManager.get_plugins_info", mock.MagicMock)
class DeleteTests(CmdTestsBase):
-
- @mock.patch('jenkins_jobs.cli.subcommand.update.'
- 'JenkinsManager.delete_jobs')
- @mock.patch('jenkins_jobs.cli.subcommand.update.'
- 'JenkinsManager.delete_views')
+ @mock.patch("jenkins_jobs.cli.subcommand.update." "JenkinsManager.delete_jobs")
+ @mock.patch("jenkins_jobs.cli.subcommand.update." "JenkinsManager.delete_views")
def test_delete_single_job(self, delete_job_mock, delete_view_mock):
"""
Test handling the deletion of a single Jenkins job.
"""
- args = ['--conf', self.default_config_file, 'delete', 'test_job']
+ args = ["--conf", self.default_config_file, "delete", "test_job"]
self.execute_jenkins_jobs_with_args(args)
- @mock.patch('jenkins_jobs.cli.subcommand.update.'
- 'JenkinsManager.delete_jobs')
- @mock.patch('jenkins_jobs.cli.subcommand.update.'
- 'JenkinsManager.delete_views')
+ @mock.patch("jenkins_jobs.cli.subcommand.update." "JenkinsManager.delete_jobs")
+ @mock.patch("jenkins_jobs.cli.subcommand.update." "JenkinsManager.delete_views")
def test_delete_multiple_jobs(self, delete_job_mock, delete_view_mock):
"""
Test handling the deletion of multiple Jenkins jobs.
"""
- args = ['--conf', self.default_config_file,
- 'delete', 'test_job1', 'test_job2']
+ args = ["--conf", self.default_config_file, "delete", "test_job1", "test_job2"]
self.execute_jenkins_jobs_with_args(args)
- @mock.patch('jenkins_jobs.builder.JenkinsManager.delete_job')
+ @mock.patch("jenkins_jobs.builder.JenkinsManager.delete_job")
def test_delete_using_glob_params(self, delete_job_mock):
"""
Test handling the deletion of multiple Jenkins jobs using the glob
parameters feature.
"""
- args = ['--conf', self.default_config_file,
- 'delete', '--path',
- os.path.join(self.fixtures_path,
- 'cmd-002.yaml'),
- '*bar*']
+ args = [
+ "--conf",
+ self.default_config_file,
+ "delete",
+ "--path",
+ os.path.join(self.fixtures_path, "cmd-002.yaml"),
+ "*bar*",
+ ]
self.execute_jenkins_jobs_with_args(args)
- calls = [mock.call('bar001'), mock.call('bar002')]
+ calls = [mock.call("bar001"), mock.call("bar002")]
delete_job_mock.assert_has_calls(calls, any_order=True)
- self.assertEqual(delete_job_mock.call_count, len(calls),
- "Jenkins.delete_job() was called '%s' times when "
- "expected '%s'" % (delete_job_mock.call_count,
- len(calls)))
+ self.assertEqual(
+ delete_job_mock.call_count,
+ len(calls),
+ "Jenkins.delete_job() was called '%s' times when "
+ "expected '%s'" % (delete_job_mock.call_count, len(calls)),
+ )
diff --git a/tests/cmd/subcommands/test_delete_all.py b/tests/cmd/subcommands/test_delete_all.py
index a8f6e0b4..f2ef46e8 100644
--- a/tests/cmd/subcommands/test_delete_all.py
+++ b/tests/cmd/subcommands/test_delete_all.py
@@ -21,31 +21,27 @@ from tests.base import mock
from tests.cmd.test_cmd import CmdTestsBase
-@mock.patch('jenkins_jobs.builder.JenkinsManager.get_plugins_info',
- mock.MagicMock)
+@mock.patch("jenkins_jobs.builder.JenkinsManager.get_plugins_info", mock.MagicMock)
class DeleteAllTests(CmdTestsBase):
-
- @mock.patch('jenkins_jobs.cli.subcommand.update.'
- 'JenkinsManager.delete_all_jobs')
+ @mock.patch("jenkins_jobs.cli.subcommand.update." "JenkinsManager.delete_all_jobs")
def test_delete_all_accept(self, delete_job_mock):
"""
Test handling the deletion of a single Jenkins job.
"""
- args = ['--conf', self.default_config_file, 'delete-all']
- with mock.patch('jenkins_jobs.builder.JenkinsManager.get_views',
- return_value=[None]):
- with mock.patch('jenkins_jobs.utils.input', return_value="y"):
+ args = ["--conf", self.default_config_file, "delete-all"]
+ with mock.patch(
+ "jenkins_jobs.builder.JenkinsManager.get_views", return_value=[None]
+ ):
+ with mock.patch("jenkins_jobs.utils.input", return_value="y"):
self.execute_jenkins_jobs_with_args(args)
- @mock.patch('jenkins_jobs.cli.subcommand.update.'
- 'JenkinsManager.delete_all_jobs')
+ @mock.patch("jenkins_jobs.cli.subcommand.update." "JenkinsManager.delete_all_jobs")
def test_delete_all_abort(self, delete_job_mock):
"""
Test handling the deletion of a single Jenkins job.
"""
- args = ['--conf', self.default_config_file, 'delete-all']
- with mock.patch('jenkins_jobs.utils.input', return_value="n"):
- self.assertRaises(SystemExit,
- self.execute_jenkins_jobs_with_args, args)
+ args = ["--conf", self.default_config_file, "delete-all"]
+ with mock.patch("jenkins_jobs.utils.input", return_value="n"):
+ self.assertRaises(SystemExit, self.execute_jenkins_jobs_with_args, args)
diff --git a/tests/cmd/subcommands/test_list.py b/tests/cmd/subcommands/test_list.py
index 1e413ee1..4f3ebd7a 100644
--- a/tests/cmd/subcommands/test_list.py
+++ b/tests/cmd/subcommands/test_list.py
@@ -21,65 +21,70 @@ from tests.base import mock
from tests.cmd.test_cmd import CmdTestsBase
-@mock.patch('jenkins_jobs.builder.JenkinsManager.get_plugins_info',
- mock.MagicMock)
+@mock.patch("jenkins_jobs.builder.JenkinsManager.get_plugins_info", mock.MagicMock)
class ListFromJenkinsTests(TestWithScenarios, CmdTestsBase):
scenarios = [
- ('single',
- dict(jobs=['job1'], globs=[], found=['job1'])),
- ('multiple',
- dict(jobs=['job1', 'job2'], globs=[], found=['job1', 'job2'])),
- ('multiple_with_glob',
- dict(jobs=['job1', 'job2', 'job3'], globs=["job[1-2]"],
- found=['job1', 'job2'])),
- ('multiple_with_multi_glob',
- dict(jobs=['job1', 'job2', 'job3', 'job4'],
- globs=["job1", "job[24]"],
- found=['job1', 'job2', 'job4'])),
+ ("single", dict(jobs=["job1"], globs=[], found=["job1"])),
+ ("multiple", dict(jobs=["job1", "job2"], globs=[], found=["job1", "job2"])),
+ (
+ "multiple_with_glob",
+ dict(
+ jobs=["job1", "job2", "job3"],
+ globs=["job[1-2]"],
+ found=["job1", "job2"],
+ ),
+ ),
+ (
+ "multiple_with_multi_glob",
+ dict(
+ jobs=["job1", "job2", "job3", "job4"],
+ globs=["job1", "job[24]"],
+ found=["job1", "job2", "job4"],
+ ),
+ ),
]
- @mock.patch('jenkins_jobs.builder.JenkinsManager.get_jobs')
+ @mock.patch("jenkins_jobs.builder.JenkinsManager.get_jobs")
def test_list(self, get_jobs_mock):
-
def _get_jobs():
- return [{'name': name} for name in self.jobs]
+ return [{"name": name} for name in self.jobs]
get_jobs_mock.side_effect = _get_jobs
console_out = io.BytesIO()
- args = ['--conf', self.default_config_file, 'list'] + self.globs
+ args = ["--conf", self.default_config_file, "list"] + self.globs
- with mock.patch('sys.stdout', console_out):
+ with mock.patch("sys.stdout", console_out):
self.execute_jenkins_jobs_with_args(args)
- self.assertEqual(console_out.getvalue().decode('utf-8').rstrip(),
- ('\n'.join(self.found)))
+ self.assertEqual(
+ console_out.getvalue().decode("utf-8").rstrip(), ("\n".join(self.found))
+ )
-@mock.patch('jenkins_jobs.builder.JenkinsManager.get_plugins_info',
- mock.MagicMock)
+@mock.patch("jenkins_jobs.builder.JenkinsManager.get_plugins_info", mock.MagicMock)
class ListFromYamlTests(TestWithScenarios, CmdTestsBase):
scenarios = [
- ('all',
- dict(globs=[], found=['bam001', 'bar001', 'bar002', 'baz001'])),
- ('some',
- dict(globs=["*am*", "*002", "bar001"],
- found=['bam001', 'bar001', 'bar002'])),
+ ("all", dict(globs=[], found=["bam001", "bar001", "bar002", "baz001"])),
+ (
+ "some",
+ dict(
+ globs=["*am*", "*002", "bar001"], found=["bam001", "bar001", "bar002"]
+ ),
+ ),
]
def test_list(self):
- path = os.path.join(self.fixtures_path, 'cmd-002.yaml')
+ path = os.path.join(self.fixtures_path, "cmd-002.yaml")
console_out = io.BytesIO()
- with mock.patch('sys.stdout', console_out):
+ with mock.patch("sys.stdout", console_out):
self.execute_jenkins_jobs_with_args(
- ['--conf',
- self.default_config_file,
- 'list',
- '-p',
- path] + self.globs)
-
- self.assertEqual(console_out.getvalue().decode('utf-8').rstrip(),
- ('\n'.join(self.found)))
+ ["--conf", self.default_config_file, "list", "-p", path] + self.globs
+ )
+
+ self.assertEqual(
+ console_out.getvalue().decode("utf-8").rstrip(), ("\n".join(self.found))
+ )
diff --git a/tests/cmd/subcommands/test_test.py b/tests/cmd/subcommands/test_test.py
index 0ac06d4a..1e0234a9 100644
--- a/tests/cmd/subcommands/test_test.py
+++ b/tests/cmd/subcommands/test_test.py
@@ -35,31 +35,35 @@ from tests.base import mock
from tests.cmd.test_cmd import CmdTestsBase
-@mock.patch('jenkins_jobs.builder.JenkinsManager.get_plugins_info',
- mock.MagicMock)
+@mock.patch("jenkins_jobs.builder.JenkinsManager.get_plugins_info", mock.MagicMock)
class TestTests(CmdTestsBase):
-
def test_non_existing_job(self):
"""
Run test mode and pass a non-existing job name
(probably better to fail here)
"""
- args = ['--conf', self.default_config_file, 'test',
- os.path.join(self.fixtures_path,
- 'cmd-001.yaml'),
- 'invalid']
+ args = [
+ "--conf",
+ self.default_config_file,
+ "test",
+ os.path.join(self.fixtures_path, "cmd-001.yaml"),
+ "invalid",
+ ]
self.execute_jenkins_jobs_with_args(args)
def test_valid_job(self):
"""
Run test mode and pass a valid job name
"""
- args = ['--conf', self.default_config_file, 'test',
- os.path.join(self.fixtures_path,
- 'cmd-001.yaml'),
- 'foo-job']
+ args = [
+ "--conf",
+ self.default_config_file,
+ "test",
+ os.path.join(self.fixtures_path, "cmd-001.yaml"),
+ "foo-job",
+ ]
console_out = io.BytesIO()
- with mock.patch('sys.stdout', console_out):
+ with mock.patch("sys.stdout", console_out):
self.execute_jenkins_jobs_with_args(args)
def test_console_output(self):
@@ -68,13 +72,18 @@ class TestTests(CmdTestsBase):
"""
console_out = io.BytesIO()
- with mock.patch('sys.stdout', console_out):
- args = ['--conf', self.default_config_file, 'test',
- os.path.join(self.fixtures_path, 'cmd-001.yaml')]
+ with mock.patch("sys.stdout", console_out):
+ args = [
+ "--conf",
+ self.default_config_file,
+ "test",
+ os.path.join(self.fixtures_path, "cmd-001.yaml"),
+ ]
self.execute_jenkins_jobs_with_args(args)
- xml_content = io.open(os.path.join(self.fixtures_path, 'cmd-001.xml'),
- 'r', encoding='utf-8').read()
- self.assertEqual(console_out.getvalue().decode('utf-8'), xml_content)
+ xml_content = io.open(
+ os.path.join(self.fixtures_path, "cmd-001.xml"), "r", encoding="utf-8"
+ ).read()
+ self.assertEqual(console_out.getvalue().decode("utf-8"), xml_content)
def test_output_dir(self):
"""
@@ -83,11 +92,11 @@ class TestTests(CmdTestsBase):
"""
tmpdir = tempfile.mkdtemp()
self.addCleanup(shutil.rmtree, tmpdir)
- args = ['test', os.path.join(self.fixtures_path, 'cmd-001.yaml'),
- '-o', tmpdir]
+ args = ["test", os.path.join(self.fixtures_path, "cmd-001.yaml"), "-o", tmpdir]
self.execute_jenkins_jobs_with_args(args)
- self.expectThat(os.path.join(tmpdir, 'foo-job'),
- testtools.matchers.FileExists())
+ self.expectThat(
+ os.path.join(tmpdir, "foo-job"), testtools.matchers.FileExists()
+ )
def test_output_dir_config_xml(self):
"""
@@ -96,11 +105,18 @@ class TestTests(CmdTestsBase):
"""
tmpdir = tempfile.mkdtemp()
self.addCleanup(shutil.rmtree, tmpdir)
- args = ['test', os.path.join(self.fixtures_path, 'cmd-001.yaml'),
- '-o', tmpdir, '--config-xml']
+ args = [
+ "test",
+ os.path.join(self.fixtures_path, "cmd-001.yaml"),
+ "-o",
+ tmpdir,
+ "--config-xml",
+ ]
self.execute_jenkins_jobs_with_args(args)
- self.expectThat(os.path.join(tmpdir, 'foo-job', 'config.xml'),
- testtools.matchers.FileExists())
+ self.expectThat(
+ os.path.join(tmpdir, "foo-job", "config.xml"),
+ testtools.matchers.FileExists(),
+ )
def test_stream_input_output_no_encoding_exceed_recursion(self):
"""
@@ -109,13 +125,12 @@ class TestTests(CmdTestsBase):
"""
console_out = io.BytesIO()
- input_file = os.path.join(self.fixtures_path,
- 'large-number-of-jobs-001.yaml')
- with io.open(input_file, 'r') as f:
- with mock.patch('sys.stdout', console_out):
+ input_file = os.path.join(self.fixtures_path, "large-number-of-jobs-001.yaml")
+ with io.open(input_file, "r") as f:
+ with mock.patch("sys.stdout", console_out):
console_out.encoding = None
- with mock.patch('sys.stdin', f):
- args = ['test']
+ with mock.patch("sys.stdin", f):
+ args = ["test"]
self.execute_jenkins_jobs_with_args(args)
def test_stream_input_output_utf8_encoding(self):
@@ -125,16 +140,17 @@ class TestTests(CmdTestsBase):
"""
console_out = io.BytesIO()
- input_file = os.path.join(self.fixtures_path, 'cmd-001.yaml')
- with io.open(input_file, 'r') as f:
- with mock.patch('sys.stdout', console_out):
- with mock.patch('sys.stdin', f):
- args = ['--conf', self.default_config_file, 'test']
+ input_file = os.path.join(self.fixtures_path, "cmd-001.yaml")
+ with io.open(input_file, "r") as f:
+ with mock.patch("sys.stdout", console_out):
+ with mock.patch("sys.stdin", f):
+ args = ["--conf", self.default_config_file, "test"]
self.execute_jenkins_jobs_with_args(args)
- xml_content = io.open(os.path.join(self.fixtures_path, 'cmd-001.xml'),
- 'r', encoding='utf-8').read()
- value = console_out.getvalue().decode('utf-8')
+ xml_content = io.open(
+ os.path.join(self.fixtures_path, "cmd-001.xml"), "r", encoding="utf-8"
+ ).read()
+ value = console_out.getvalue().decode("utf-8")
self.assertEqual(value, xml_content)
def test_stream_input_output_ascii_encoding(self):
@@ -143,18 +159,19 @@ class TestTests(CmdTestsBase):
ascii encoding with unicode input
"""
console_out = io.BytesIO()
- console_out.encoding = 'ascii'
+ console_out.encoding = "ascii"
- input_file = os.path.join(self.fixtures_path, 'cmd-001.yaml')
- with io.open(input_file, 'r') as f:
- with mock.patch('sys.stdout', console_out):
- with mock.patch('sys.stdin', f):
- args = ['--conf', self.default_config_file, 'test']
+ input_file = os.path.join(self.fixtures_path, "cmd-001.yaml")
+ with io.open(input_file, "r") as f:
+ with mock.patch("sys.stdout", console_out):
+ with mock.patch("sys.stdin", f):
+ args = ["--conf", self.default_config_file, "test"]
self.execute_jenkins_jobs_with_args(args)
- xml_content = io.open(os.path.join(self.fixtures_path, 'cmd-001.xml'),
- 'r', encoding='utf-8').read()
- value = console_out.getvalue().decode('ascii')
+ xml_content = io.open(
+ os.path.join(self.fixtures_path, "cmd-001.xml"), "r", encoding="utf-8"
+ ).read()
+ value = console_out.getvalue().decode("ascii")
self.assertEqual(value, xml_content)
def test_stream_output_ascii_encoding_invalid_char(self):
@@ -164,65 +181,65 @@ class TestTests(CmdTestsBase):
that cannot be converted.
"""
console_out = io.BytesIO()
- console_out.encoding = 'ascii'
+ console_out.encoding = "ascii"
- input_file = os.path.join(self.fixtures_path, 'unicode001.yaml')
- with io.open(input_file, 'r', encoding='utf-8') as f:
- with mock.patch('sys.stdout', console_out):
- with mock.patch('sys.stdin', f):
- args = ['--conf', self.default_config_file, 'test']
+ input_file = os.path.join(self.fixtures_path, "unicode001.yaml")
+ with io.open(input_file, "r", encoding="utf-8") as f:
+ with mock.patch("sys.stdout", console_out):
+ with mock.patch("sys.stdin", f):
+ args = ["--conf", self.default_config_file, "test"]
jenkins_jobs = entry.JenkinsJobs(args)
e = self.assertRaises(UnicodeError, jenkins_jobs.execute)
self.assertIn("'ascii' codec can't encode character", str(e))
- @mock.patch(
- 'jenkins_jobs.cli.subcommand.update.XmlJobGenerator.generateXML')
- @mock.patch('jenkins_jobs.cli.subcommand.update.ModuleRegistry')
+ @mock.patch("jenkins_jobs.cli.subcommand.update.XmlJobGenerator.generateXML")
+ @mock.patch("jenkins_jobs.cli.subcommand.update.ModuleRegistry")
def test_plugins_info_stub_option(self, registry_mock, generateXML_mock):
"""
Test handling of plugins_info stub option.
"""
- plugins_info_stub_yaml_file = os.path.join(self.fixtures_path,
- 'plugins-info.yaml')
- args = ['--conf',
- os.path.join(self.fixtures_path, 'cmd-001.conf'),
- 'test',
- '-p',
- plugins_info_stub_yaml_file,
- os.path.join(self.fixtures_path, 'cmd-001.yaml')]
+ plugins_info_stub_yaml_file = os.path.join(
+ self.fixtures_path, "plugins-info.yaml"
+ )
+ args = [
+ "--conf",
+ os.path.join(self.fixtures_path, "cmd-001.conf"),
+ "test",
+ "-p",
+ plugins_info_stub_yaml_file,
+ os.path.join(self.fixtures_path, "cmd-001.yaml"),
+ ]
self.execute_jenkins_jobs_with_args(args)
- with io.open(plugins_info_stub_yaml_file,
- 'r', encoding='utf-8') as yaml_file:
+ with io.open(plugins_info_stub_yaml_file, "r", encoding="utf-8") as yaml_file:
plugins_info_list = yaml.load(yaml_file)
- registry_mock.assert_called_with(mock.ANY,
- plugins_info_list)
+ registry_mock.assert_called_with(mock.ANY, plugins_info_list)
- @mock.patch(
- 'jenkins_jobs.cli.subcommand.update.XmlJobGenerator.generateXML')
- @mock.patch('jenkins_jobs.cli.subcommand.update.ModuleRegistry')
- def test_bogus_plugins_info_stub_option(self, registry_mock,
- generateXML_mock):
+ @mock.patch("jenkins_jobs.cli.subcommand.update.XmlJobGenerator.generateXML")
+ @mock.patch("jenkins_jobs.cli.subcommand.update.ModuleRegistry")
+ def test_bogus_plugins_info_stub_option(self, registry_mock, generateXML_mock):
"""
Verify that a JenkinsJobException is raised if the plugins_info stub
file does not yield a list as its top-level object.
"""
- plugins_info_stub_yaml_file = os.path.join(self.fixtures_path,
- 'bogus-plugins-info.yaml')
- args = ['--conf',
- os.path.join(self.fixtures_path, 'cmd-001.conf'),
- 'test',
- '-p',
- plugins_info_stub_yaml_file,
- os.path.join(self.fixtures_path, 'cmd-001.yaml')]
+ plugins_info_stub_yaml_file = os.path.join(
+ self.fixtures_path, "bogus-plugins-info.yaml"
+ )
+ args = [
+ "--conf",
+ os.path.join(self.fixtures_path, "cmd-001.conf"),
+ "test",
+ "-p",
+ plugins_info_stub_yaml_file,
+ os.path.join(self.fixtures_path, "cmd-001.yaml"),
+ ]
stderr = StringIO()
- with mock.patch('sys.stderr', stderr):
+ with mock.patch("sys.stderr", stderr):
self.assertRaises(SystemExit, entry.JenkinsJobs, args)
- self.assertIn("must contain a Yaml list",
- stderr.getvalue())
+ self.assertIn("must contain a Yaml list", stderr.getvalue())
class TestJenkinsGetPluginInfoError(CmdTestsBase):
@@ -231,9 +248,8 @@ class TestJenkinsGetPluginInfoError(CmdTestsBase):
jenkins_jobs.builder.JenkinsManager.get_plugins_info
"""
- @mock.patch('jenkins.Jenkins.get_plugins')
- def test_console_output_jenkins_connection_failure_warning(
- self, get_plugins_mock):
+ @mock.patch("jenkins.Jenkins.get_plugins")
+ def test_console_output_jenkins_connection_failure_warning(self, get_plugins_mock):
"""
Run test mode and verify that failed Jenkins connection attempt
exception does not bubble out of cmd.main. Ideally, we would also test
@@ -242,44 +258,51 @@ class TestJenkinsGetPluginInfoError(CmdTestsBase):
suite.
"""
- get_plugins_mock.side_effect = \
- jenkins.JenkinsException("Connection refused")
- with mock.patch('sys.stdout'):
+ get_plugins_mock.side_effect = jenkins.JenkinsException("Connection refused")
+ with mock.patch("sys.stdout"):
try:
- args = ['--conf', self.default_config_file, 'test',
- os.path.join(self.fixtures_path, 'cmd-001.yaml')]
+ args = [
+ "--conf",
+ self.default_config_file,
+ "test",
+ os.path.join(self.fixtures_path, "cmd-001.yaml"),
+ ]
self.execute_jenkins_jobs_with_args(args)
except jenkins.JenkinsException:
self.fail("jenkins.JenkinsException propagated to main")
except Exception:
pass # only care about jenkins.JenkinsException for now
- @mock.patch('jenkins.Jenkins.get_plugins')
- def test_skip_plugin_retrieval_if_no_config_provided(
- self, get_plugins_mock):
+ @mock.patch("jenkins.Jenkins.get_plugins")
+ def test_skip_plugin_retrieval_if_no_config_provided(self, get_plugins_mock):
"""
Verify that retrieval of information from Jenkins instance about its
plugins will be skipped when run if no config file provided.
"""
- with mock.patch('sys.stdout', new_callable=io.BytesIO):
- args = ['--conf', self.default_config_file, 'test',
- os.path.join(self.fixtures_path, 'cmd-001.yaml')]
+ with mock.patch("sys.stdout", new_callable=io.BytesIO):
+ args = [
+ "--conf",
+ self.default_config_file,
+ "test",
+ os.path.join(self.fixtures_path, "cmd-001.yaml"),
+ ]
entry.JenkinsJobs(args)
self.assertFalse(get_plugins_mock.called)
- @mock.patch('jenkins.Jenkins.get_plugins_info')
+ @mock.patch("jenkins.Jenkins.get_plugins_info")
def test_skip_plugin_retrieval_if_disabled(self, get_plugins_mock):
"""
Verify that retrieval of information from Jenkins instance about its
plugins will be skipped when run if a config file provided and disables
querying through a config option.
"""
- with mock.patch('sys.stdout', new_callable=io.BytesIO):
- args = ['--conf',
- os.path.join(self.fixtures_path,
- 'disable-query-plugins.conf'),
- 'test',
- os.path.join(self.fixtures_path, 'cmd-001.yaml')]
+ with mock.patch("sys.stdout", new_callable=io.BytesIO):
+ args = [
+ "--conf",
+ os.path.join(self.fixtures_path, "disable-query-plugins.conf"),
+ "test",
+ os.path.join(self.fixtures_path, "cmd-001.yaml"),
+ ]
entry.JenkinsJobs(args)
self.assertFalse(get_plugins_mock.called)
@@ -291,8 +314,8 @@ class MatchesDirMissingFilesMismatch(object):
def describe(self):
return "{0} and {1} contain different files".format(
- self.left_directory,
- self.right_directory)
+ self.left_directory, self.right_directory
+ )
def get_details(self):
return {}
@@ -308,11 +331,15 @@ class MatchesDirFileContentsMismatch(object):
right_contents = open(self.right_file).readlines()
return "{0} is not equal to {1}:\n{2}".format(
- difflib.unified_diff(left_contents, right_contents,
- fromfile=self.left_file,
- tofile=self.right_file),
+ difflib.unified_diff(
+ left_contents,
+ right_contents,
+ fromfile=self.left_file,
+ tofile=self.right_file,
+ ),
self.left_file,
- self.right_file)
+ self.right_file,
+ )
def get_details(self):
return {}
@@ -337,8 +364,7 @@ class MatchesDir(object):
other_files.sort()
if self.__files != other_files:
- return MatchesDirMissingFilesMismatch(self.__directory,
- other_directory)
+ return MatchesDirMissingFilesMismatch(self.__directory, other_directory)
for i, file in enumerate(self.__files):
my_file = os.path.join(self.__directory, file)
@@ -349,16 +375,15 @@ class MatchesDir(object):
return None
-@mock.patch('jenkins_jobs.builder.JenkinsManager.get_plugins_info',
- mock.MagicMock)
+@mock.patch("jenkins_jobs.builder.JenkinsManager.get_plugins_info", mock.MagicMock)
class TestTestsMultiPath(CmdTestsBase):
-
def setUp(self):
super(TestTestsMultiPath, self).setUp()
- path_list = [os.path.join(self.fixtures_path,
- 'multi-path/yamldirs/', p)
- for p in ['dir1', 'dir2']]
+ path_list = [
+ os.path.join(self.fixtures_path, "multi-path/yamldirs/", p)
+ for p in ["dir1", "dir2"]
+ ]
self.multipath = os.pathsep.join(path_list)
self.output_dir = tempfile.mkdtemp()
@@ -374,45 +399,74 @@ class TestTestsMultiPath(CmdTestsBase):
"""
Run test mode and pass multiple paths.
"""
- args = ['--conf', self.default_config_file, 'test',
- '-o', self.output_dir, self.multipath]
+ args = [
+ "--conf",
+ self.default_config_file,
+ "test",
+ "-o",
+ self.output_dir,
+ self.multipath,
+ ]
self.execute_jenkins_jobs_with_args(args)
- self.check_dirs_match(os.path.join(self.fixtures_path,
- 'multi-path/output_simple'))
+ self.check_dirs_match(
+ os.path.join(self.fixtures_path, "multi-path/output_simple")
+ )
def test_recursive_multi_path_command_line(self):
"""
Run test mode and pass multiple paths with recursive path option.
"""
- args = ['--conf', self.default_config_file, 'test',
- '-o', self.output_dir, '-r', self.multipath]
+ args = [
+ "--conf",
+ self.default_config_file,
+ "test",
+ "-o",
+ self.output_dir,
+ "-r",
+ self.multipath,
+ ]
self.execute_jenkins_jobs_with_args(args)
- self.check_dirs_match(os.path.join(self.fixtures_path,
- 'multi-path/output_recursive'))
+ self.check_dirs_match(
+ os.path.join(self.fixtures_path, "multi-path/output_recursive")
+ )
def test_recursive_multi_path_config_file(self):
# test recursive set in configuration file
- args = ['--conf', os.path.join(self.fixtures_path,
- 'multi-path/builder-recursive.ini'),
- 'test', '-o', self.output_dir, self.multipath]
+ args = [
+ "--conf",
+ os.path.join(self.fixtures_path, "multi-path/builder-recursive.ini"),
+ "test",
+ "-o",
+ self.output_dir,
+ self.multipath,
+ ]
self.execute_jenkins_jobs_with_args(args)
- self.check_dirs_match(os.path.join(self.fixtures_path,
- 'multi-path/output_recursive'))
+ self.check_dirs_match(
+ os.path.join(self.fixtures_path, "multi-path/output_recursive")
+ )
def test_recursive_multi_path_with_excludes(self):
"""
Run test mode and pass multiple paths with recursive path option.
"""
- exclude_path = os.path.join(self.fixtures_path,
- 'multi-path/yamldirs/dir2/dir1')
- args = ['--conf', self.default_config_file, 'test',
- '-x', exclude_path,
- '-o', self.output_dir,
- '-r', self.multipath]
+ exclude_path = os.path.join(self.fixtures_path, "multi-path/yamldirs/dir2/dir1")
+ args = [
+ "--conf",
+ self.default_config_file,
+ "test",
+ "-x",
+ exclude_path,
+ "-o",
+ self.output_dir,
+ "-r",
+ self.multipath,
+ ]
self.execute_jenkins_jobs_with_args(args)
self.check_dirs_match(
- os.path.join(self.fixtures_path,
- 'multi-path/output_recursive_with_excludes'))
+ os.path.join(
+ self.fixtures_path, "multi-path/output_recursive_with_excludes"
+ )
+ )
diff --git a/tests/cmd/subcommands/test_update.py b/tests/cmd/subcommands/test_update.py
index 9606951f..f755f4b8 100644
--- a/tests/cmd/subcommands/test_update.py
+++ b/tests/cmd/subcommands/test_update.py
@@ -25,61 +25,60 @@ from tests.base import mock
from tests.cmd.test_cmd import CmdTestsBase
-@mock.patch('jenkins_jobs.builder.JenkinsManager.get_plugins_info',
- mock.MagicMock)
+@mock.patch("jenkins_jobs.builder.JenkinsManager.get_plugins_info", mock.MagicMock)
class UpdateTests(CmdTestsBase):
-
- @mock.patch('jenkins_jobs.builder.jenkins.Jenkins.job_exists')
- @mock.patch('jenkins_jobs.builder.jenkins.Jenkins.get_all_jobs')
- @mock.patch('jenkins_jobs.builder.jenkins.Jenkins.reconfig_job')
- def test_update_jobs(self,
- jenkins_reconfig_job,
- jenkins_get_jobs,
- jenkins_job_exists, ):
+ @mock.patch("jenkins_jobs.builder.jenkins.Jenkins.job_exists")
+ @mock.patch("jenkins_jobs.builder.jenkins.Jenkins.get_all_jobs")
+ @mock.patch("jenkins_jobs.builder.jenkins.Jenkins.reconfig_job")
+ def test_update_jobs(
+ self, jenkins_reconfig_job, jenkins_get_jobs, jenkins_job_exists
+ ):
"""
Test update_job is called
"""
- path = os.path.join(self.fixtures_path, 'cmd-002.yaml')
- args = ['--conf', self.default_config_file, 'update', path]
+ path = os.path.join(self.fixtures_path, "cmd-002.yaml")
+ args = ["--conf", self.default_config_file, "update", path]
self.execute_jenkins_jobs_with_args(args)
jenkins_reconfig_job.assert_has_calls(
- [mock.call(job_name, mock.ANY)
- for job_name in ['bar001', 'bar002', 'baz001', 'bam001']],
- any_order=True
+ [
+ mock.call(job_name, mock.ANY)
+ for job_name in ["bar001", "bar002", "baz001", "bam001"]
+ ],
+ any_order=True,
)
- @mock.patch('jenkins_jobs.builder.JenkinsManager.is_job',
- return_value=True)
- @mock.patch('jenkins_jobs.builder.JenkinsManager.get_jobs')
- @mock.patch('jenkins_jobs.builder.JenkinsManager.get_job_md5')
- @mock.patch('jenkins_jobs.builder.JenkinsManager.update_job')
- def test_update_jobs_decode_job_output(self, update_job_mock,
- get_job_md5_mock, get_jobs_mock,
- is_job_mock):
+ @mock.patch("jenkins_jobs.builder.JenkinsManager.is_job", return_value=True)
+ @mock.patch("jenkins_jobs.builder.JenkinsManager.get_jobs")
+ @mock.patch("jenkins_jobs.builder.JenkinsManager.get_job_md5")
+ @mock.patch("jenkins_jobs.builder.JenkinsManager.update_job")
+ def test_update_jobs_decode_job_output(
+ self, update_job_mock, get_job_md5_mock, get_jobs_mock, is_job_mock
+ ):
"""
Test that job xml output has been decoded before attempting to update
"""
# don't care about the value returned here
update_job_mock.return_value = ([], 0)
- path = os.path.join(self.fixtures_path, 'cmd-002.yaml')
- args = ['--conf', self.default_config_file, 'update', path]
+ path = os.path.join(self.fixtures_path, "cmd-002.yaml")
+ args = ["--conf", self.default_config_file, "update", path]
self.execute_jenkins_jobs_with_args(args)
- self.assertTrue(isinstance(update_job_mock.call_args[0][1],
- six.text_type))
-
- @mock.patch('jenkins_jobs.builder.jenkins.Jenkins.job_exists')
- @mock.patch('jenkins_jobs.builder.jenkins.Jenkins.get_all_jobs')
- @mock.patch('jenkins_jobs.builder.jenkins.Jenkins.reconfig_job')
- @mock.patch('jenkins_jobs.builder.jenkins.Jenkins.delete_job')
- def test_update_jobs_and_delete_old(self,
- jenkins_delete_job,
- jenkins_reconfig_job,
- jenkins_get_all_jobs,
- jenkins_job_exists):
+ self.assertTrue(isinstance(update_job_mock.call_args[0][1], six.text_type))
+
+ @mock.patch("jenkins_jobs.builder.jenkins.Jenkins.job_exists")
+ @mock.patch("jenkins_jobs.builder.jenkins.Jenkins.get_all_jobs")
+ @mock.patch("jenkins_jobs.builder.jenkins.Jenkins.reconfig_job")
+ @mock.patch("jenkins_jobs.builder.jenkins.Jenkins.delete_job")
+ def test_update_jobs_and_delete_old(
+ self,
+ jenkins_delete_job,
+ jenkins_reconfig_job,
+ jenkins_get_all_jobs,
+ jenkins_job_exists,
+ ):
"""
Test update behaviour with --delete-old option
@@ -92,25 +91,26 @@ class UpdateTests(CmdTestsBase):
* mock out a call to jenkins.Jenkins.job_exists() to always return
True.
"""
- yaml_jobs = ['bar001', 'bar002', 'baz001', 'bam001']
- extra_jobs = ['old_job001', 'old_job002', 'unmanaged']
+ yaml_jobs = ["bar001", "bar002", "baz001", "bam001"]
+ extra_jobs = ["old_job001", "old_job002", "unmanaged"]
- path = os.path.join(self.fixtures_path, 'cmd-002.yaml')
- args = ['--conf', self.default_config_file, 'update', '--delete-old',
- path]
+ path = os.path.join(self.fixtures_path, "cmd-002.yaml")
+ args = ["--conf", self.default_config_file, "update", "--delete-old", path]
jenkins_get_all_jobs.return_value = [
- {'fullname': name} for name in yaml_jobs + extra_jobs]
+ {"fullname": name} for name in yaml_jobs + extra_jobs
+ ]
- with mock.patch('jenkins_jobs.builder.JenkinsManager.is_managed',
- side_effect=(lambda name: name != 'unmanaged')):
+ with mock.patch(
+ "jenkins_jobs.builder.JenkinsManager.is_managed",
+ side_effect=(lambda name: name != "unmanaged"),
+ ):
self.execute_jenkins_jobs_with_args(args)
jenkins_reconfig_job.assert_has_calls(
- [mock.call(job_name, mock.ANY) for job_name in yaml_jobs],
- any_order=True
+ [mock.call(job_name, mock.ANY) for job_name in yaml_jobs], any_order=True
)
- calls = [mock.call(name) for name in extra_jobs if name != 'unmanaged']
+ calls = [mock.call(name) for name in extra_jobs if name != "unmanaged"]
jenkins_delete_job.assert_has_calls(calls)
# to ensure only the calls we expected were made, have to check
# there were no others, as no API call for assert_has_only_calls
diff --git a/tests/cmd/test_cmd.py b/tests/cmd/test_cmd.py
index 5ec1dd7a..e847ec39 100644
--- a/tests/cmd/test_cmd.py
+++ b/tests/cmd/test_cmd.py
@@ -7,7 +7,7 @@ from tests.base import mock
class CmdTestsBase(base.BaseTestCase):
- fixtures_path = os.path.join(os.path.dirname(__file__), 'fixtures')
+ fixtures_path = os.path.join(os.path.dirname(__file__), "fixtures")
def setUp(self):
super(CmdTestsBase, self).setUp()
@@ -17,13 +17,11 @@ class CmdTestsBase(base.BaseTestCase):
# are run in parallel. Stub out the JobCache to ensure that each
# test can safely create the cache directory without risk of
# interference.
- cache_patch = mock.patch('jenkins_jobs.builder.JobCache',
- autospec=True)
+ cache_patch = mock.patch("jenkins_jobs.builder.JobCache", autospec=True)
self.cache_mock = cache_patch.start()
self.addCleanup(cache_patch.stop)
- self.default_config_file = os.path.join(self.fixtures_path,
- 'empty_builder.ini')
+ self.default_config_file = os.path.join(self.fixtures_path, "empty_builder.ini")
def execute_jenkins_jobs_with_args(self, args):
jenkins_jobs = entry.JenkinsJobs(args)
@@ -31,10 +29,9 @@ class CmdTestsBase(base.BaseTestCase):
class TestCmd(CmdTestsBase):
-
def test_with_empty_args(self):
"""
User passes no args, should fail with SystemExit
"""
- with mock.patch('sys.stderr'):
+ with mock.patch("sys.stderr"):
self.assertRaises(SystemExit, entry.JenkinsJobs, [])
diff --git a/tests/cmd/test_config.py b/tests/cmd/test_config.py
index 6cbb6d4d..ecae8a9a 100644
--- a/tests/cmd/test_config.py
+++ b/tests/cmd/test_config.py
@@ -9,25 +9,25 @@ from jenkins_jobs.cli import entry
from jenkins_jobs import builder
-@mock.patch('jenkins_jobs.builder.JenkinsManager.get_plugins_info',
- mock.MagicMock)
+@mock.patch("jenkins_jobs.builder.JenkinsManager.get_plugins_info", mock.MagicMock)
class TestConfigs(CmdTestsBase):
- global_conf = '/etc/jenkins_jobs/jenkins_jobs.ini'
- user_conf = os.path.join(os.path.expanduser('~'), '.config',
- 'jenkins_jobs', 'jenkins_jobs.ini')
- local_conf = os.path.join(os.path.dirname(__file__),
- 'jenkins_jobs.ini')
+ global_conf = "/etc/jenkins_jobs/jenkins_jobs.ini"
+ user_conf = os.path.join(
+ os.path.expanduser("~"), ".config", "jenkins_jobs", "jenkins_jobs.ini"
+ )
+ local_conf = os.path.join(os.path.dirname(__file__), "jenkins_jobs.ini")
def test_use_global_config(self):
"""
Verify that JJB uses the global config file by default
"""
- args = ['test', 'foo']
- conffp = io.open(self.default_config_file, 'r', encoding='utf-8')
+ args = ["test", "foo"]
+ conffp = io.open(self.default_config_file, "r", encoding="utf-8")
+
+ with patch("os.path.isfile", return_value=True) as m_isfile:
- with patch('os.path.isfile', return_value=True) as m_isfile:
def side_effect(path):
if path == self.global_conf:
return True
@@ -35,36 +35,35 @@ class TestConfigs(CmdTestsBase):
m_isfile.side_effect = side_effect
- with patch('io.open', return_value=conffp) as m_open:
+ with patch("io.open", return_value=conffp) as m_open:
entry.JenkinsJobs(args, config_file_required=True)
- m_open.assert_called_with(self.global_conf, 'r',
- encoding='utf-8')
+ m_open.assert_called_with(self.global_conf, "r", encoding="utf-8")
def test_use_config_in_user_home(self):
"""
Verify that JJB uses config file in user home folder
"""
- args = ['test', 'foo']
+ args = ["test", "foo"]
+
+ conffp = io.open(self.default_config_file, "r", encoding="utf-8")
+ with patch("os.path.isfile", return_value=True) as m_isfile:
- conffp = io.open(self.default_config_file, 'r', encoding='utf-8')
- with patch('os.path.isfile', return_value=True) as m_isfile:
def side_effect(path):
if path == self.user_conf:
return True
return False
m_isfile.side_effect = side_effect
- with patch('io.open', return_value=conffp) as m_open:
+ with patch("io.open", return_value=conffp) as m_open:
entry.JenkinsJobs(args, config_file_required=True)
- m_open.assert_called_with(self.user_conf, 'r',
- encoding='utf-8')
+ m_open.assert_called_with(self.user_conf, "r", encoding="utf-8")
def test_non_existing_config_dir(self):
"""
Run test mode and pass a non-existing configuration directory
"""
- args = ['--conf', self.default_config_file, 'test', 'foo']
+ args = ["--conf", self.default_config_file, "test", "foo"]
jenkins_jobs = entry.JenkinsJobs(args)
self.assertRaises(IOError, jenkins_jobs.execute)
@@ -72,8 +71,7 @@ class TestConfigs(CmdTestsBase):
"""
Run test mode and pass a non-existing configuration file
"""
- args = ['--conf', self.default_config_file, 'test',
- 'non-existing.yaml']
+ args = ["--conf", self.default_config_file, "test", "non-existing.yaml"]
jenkins_jobs = entry.JenkinsJobs(args)
self.assertRaises(IOError, jenkins_jobs.execute)
@@ -82,37 +80,42 @@ class TestConfigs(CmdTestsBase):
Run test mode and check config settings from conf file retained
when none of the global CLI options are set.
"""
- config_file = os.path.join(self.fixtures_path,
- 'settings_from_config.ini')
- args = ['--conf', config_file, 'test', 'dummy.yaml']
+ config_file = os.path.join(self.fixtures_path, "settings_from_config.ini")
+ args = ["--conf", config_file, "test", "dummy.yaml"]
jenkins_jobs = entry.JenkinsJobs(args)
jjb_config = jenkins_jobs.jjb_config
- self.assertEqual(jjb_config.jenkins['user'], "jenkins_user")
- self.assertEqual(jjb_config.jenkins['password'], "jenkins_password")
- self.assertEqual(jjb_config.builder['ignore_cache'], True)
- self.assertEqual(jjb_config.builder['flush_cache'], True)
- self.assertEqual(jjb_config.builder['update'], "all")
- self.assertEqual(
- jjb_config.yamlparser['allow_empty_variables'], True)
+ self.assertEqual(jjb_config.jenkins["user"], "jenkins_user")
+ self.assertEqual(jjb_config.jenkins["password"], "jenkins_password")
+ self.assertEqual(jjb_config.builder["ignore_cache"], True)
+ self.assertEqual(jjb_config.builder["flush_cache"], True)
+ self.assertEqual(jjb_config.builder["update"], "all")
+ self.assertEqual(jjb_config.yamlparser["allow_empty_variables"], True)
def test_config_options_overriden_by_cli(self):
"""
Run test mode and check config settings from conf file retained
when none of the global CLI options are set.
"""
- args = ['--user', 'myuser', '--password', 'mypassword',
- '--ignore-cache', '--flush-cache', '--allow-empty-variables',
- 'test', 'dummy.yaml']
+ args = [
+ "--user",
+ "myuser",
+ "--password",
+ "mypassword",
+ "--ignore-cache",
+ "--flush-cache",
+ "--allow-empty-variables",
+ "test",
+ "dummy.yaml",
+ ]
jenkins_jobs = entry.JenkinsJobs(args)
jjb_config = jenkins_jobs.jjb_config
- self.assertEqual(jjb_config.jenkins['user'], "myuser")
- self.assertEqual(jjb_config.jenkins['password'], "mypassword")
- self.assertEqual(jjb_config.builder['ignore_cache'], True)
- self.assertEqual(jjb_config.builder['flush_cache'], True)
- self.assertEqual(
- jjb_config.yamlparser['allow_empty_variables'], True)
-
- @mock.patch('jenkins_jobs.cli.subcommand.update.JenkinsManager')
+ self.assertEqual(jjb_config.jenkins["user"], "myuser")
+ self.assertEqual(jjb_config.jenkins["password"], "mypassword")
+ self.assertEqual(jjb_config.builder["ignore_cache"], True)
+ self.assertEqual(jjb_config.builder["flush_cache"], True)
+ self.assertEqual(jjb_config.yamlparser["allow_empty_variables"], True)
+
+ @mock.patch("jenkins_jobs.cli.subcommand.update.JenkinsManager")
def test_update_timeout_not_set(self, jenkins_mock):
"""Check that timeout is left unset
@@ -120,8 +123,8 @@ class TestConfigs(CmdTestsBase):
provided via the config option.
"""
- path = os.path.join(self.fixtures_path, 'cmd-002.yaml')
- args = ['--conf', self.default_config_file, 'update', path]
+ path = os.path.join(self.fixtures_path, "cmd-002.yaml")
+ args = ["--conf", self.default_config_file, "update", path]
jenkins_mock.return_value.update_jobs.return_value = ([], 0)
jenkins_mock.return_value.update_views.return_value = ([], 0)
@@ -131,10 +134,9 @@ class TestConfigs(CmdTestsBase):
# contains the expected timeout value.
jjb_config = jenkins_mock.call_args[0][0]
- self.assertEqual(jjb_config.jenkins['timeout'],
- builder._DEFAULT_TIMEOUT)
+ self.assertEqual(jjb_config.jenkins["timeout"], builder._DEFAULT_TIMEOUT)
- @mock.patch('jenkins_jobs.cli.subcommand.update.JenkinsManager')
+ @mock.patch("jenkins_jobs.cli.subcommand.update.JenkinsManager")
def test_update_timeout_set(self, jenkins_mock):
"""Check that timeout is set correctly
@@ -142,10 +144,9 @@ class TestConfigs(CmdTestsBase):
provided via the config option.
"""
- path = os.path.join(self.fixtures_path, 'cmd-002.yaml')
- config_file = os.path.join(self.fixtures_path,
- 'non-default-timeout.ini')
- args = ['--conf', config_file, 'update', path]
+ path = os.path.join(self.fixtures_path, "cmd-002.yaml")
+ config_file = os.path.join(self.fixtures_path, "non-default-timeout.ini")
+ args = ["--conf", config_file, "update", path]
jenkins_mock.return_value.update_jobs.return_value = ([], 0)
jenkins_mock.return_value.update_views.return_value = ([], 0)
@@ -155,4 +156,4 @@ class TestConfigs(CmdTestsBase):
# contains the expected timeout value.
jjb_config = jenkins_mock.call_args[0][0]
- self.assertEqual(jjb_config.jenkins['timeout'], 0.2)
+ self.assertEqual(jjb_config.jenkins["timeout"], 0.2)
diff --git a/tests/cmd/test_recurse_path.py b/tests/cmd/test_recurse_path.py
index 2fb3eb32..acb609f3 100644
--- a/tests/cmd/test_recurse_path.py
+++ b/tests/cmd/test_recurse_path.py
@@ -22,6 +22,7 @@ def fake_os_walk(paths):
new_path = "/".join([top, name])
for x in os_walk(new_path, topdown):
yield x
+
return os_walk
@@ -29,10 +30,9 @@ def fake_os_walk(paths):
# attempting to create the cache directory multiple times as the tests
# are run in parallel. Stub out the JobCache to ensure that each
# test can safely create the object without effect.
-@mock.patch('jenkins_jobs.builder.JobCache', mock.MagicMock)
+@mock.patch("jenkins_jobs.builder.JobCache", mock.MagicMock)
class CmdRecursePath(testtools.TestCase):
-
- @mock.patch('jenkins_jobs.utils.os.walk')
+ @mock.patch("jenkins_jobs.utils.os.walk")
def test_recursive_path_option_exclude_pattern(self, oswalk_mock):
"""
Test paths returned by the recursive processing when using pattern
@@ -48,21 +48,21 @@ class CmdRecursePath(testtools.TestCase):
"""
os_walk_paths = [
- ('/jjb_configs', (['dir1', 'dir2', 'dir3', 'test3'], ())),
- ('/jjb_configs/dir1', (['test1'], ('file'))),
- ('/jjb_configs/dir2', (['test2'], ())),
- ('/jjb_configs/dir3', (['bar'], ())),
- ('/jjb_configs/dir3/bar', ([], ())),
- ('/jjb_configs/test3/bar', None),
- ('/jjb_configs/test3/baz', None)
+ ("/jjb_configs", (["dir1", "dir2", "dir3", "test3"], ())),
+ ("/jjb_configs/dir1", (["test1"], ("file"))),
+ ("/jjb_configs/dir2", (["test2"], ())),
+ ("/jjb_configs/dir3", (["bar"], ())),
+ ("/jjb_configs/dir3/bar", ([], ())),
+ ("/jjb_configs/test3/bar", None),
+ ("/jjb_configs/test3/baz", None),
]
paths = [k for k, v in os_walk_paths if v is not None]
oswalk_mock.side_effect = fake_os_walk(os_walk_paths)
- self.assertEqual(paths, utils.recurse_path('/jjb_configs', ['test*']))
+ self.assertEqual(paths, utils.recurse_path("/jjb_configs", ["test*"]))
- @mock.patch('jenkins_jobs.utils.os.walk')
+ @mock.patch("jenkins_jobs.utils.os.walk")
def test_recursive_path_option_exclude_absolute(self, oswalk_mock):
"""
Test paths returned by the recursive processing when using absolute
@@ -78,25 +78,26 @@ class CmdRecursePath(testtools.TestCase):
"""
os_walk_paths = [
- ('/jjb_configs', (['dir1', 'dir2', 'dir3', 'test3'], ())),
- ('/jjb_configs/dir1', None),
- ('/jjb_configs/dir2', (['test2'], ())),
- ('/jjb_configs/dir3', (['bar'], ())),
- ('/jjb_configs/test3', (['bar', 'baz'], ())),
- ('/jjb_configs/dir2/test2', ([], ())),
- ('/jjb_configs/dir3/bar', ([], ())),
- ('/jjb_configs/test3/bar', ([], ())),
- ('/jjb_configs/test3/baz', ([], ()))
+ ("/jjb_configs", (["dir1", "dir2", "dir3", "test3"], ())),
+ ("/jjb_configs/dir1", None),
+ ("/jjb_configs/dir2", (["test2"], ())),
+ ("/jjb_configs/dir3", (["bar"], ())),
+ ("/jjb_configs/test3", (["bar", "baz"], ())),
+ ("/jjb_configs/dir2/test2", ([], ())),
+ ("/jjb_configs/dir3/bar", ([], ())),
+ ("/jjb_configs/test3/bar", ([], ())),
+ ("/jjb_configs/test3/baz", ([], ())),
]
paths = [k for k, v in os_walk_paths if v is not None]
oswalk_mock.side_effect = fake_os_walk(os_walk_paths)
- self.assertEqual(paths, utils.recurse_path('/jjb_configs',
- ['/jjb_configs/dir1']))
+ self.assertEqual(
+ paths, utils.recurse_path("/jjb_configs", ["/jjb_configs/dir1"])
+ )
- @mock.patch('jenkins_jobs.utils.os.walk')
+ @mock.patch("jenkins_jobs.utils.os.walk")
def test_recursive_path_option_exclude_relative(self, oswalk_mock):
"""
Test paths returned by the recursive processing when using relative
@@ -112,25 +113,27 @@ class CmdRecursePath(testtools.TestCase):
"""
os_walk_paths = [
- ('jjb_configs', (['dir1', 'dir2', 'dir3', 'test3'], ())),
- ('jjb_configs/dir1', (['test'], ('file'))),
- ('jjb_configs/dir2', (['test2'], ())),
- ('jjb_configs/dir3', (['bar'], ())),
- ('jjb_configs/test3', (['bar', 'baz'], ())),
- ('jjb_configs/dir1/test', ([], ())),
- ('jjb_configs/dir2/test2', ([], ())),
- ('jjb_configs/dir3/bar', ([], ())),
- ('jjb_configs/test3/bar', None),
- ('jjb_configs/test3/baz', ([], ()))
+ ("jjb_configs", (["dir1", "dir2", "dir3", "test3"], ())),
+ ("jjb_configs/dir1", (["test"], ("file"))),
+ ("jjb_configs/dir2", (["test2"], ())),
+ ("jjb_configs/dir3", (["bar"], ())),
+ ("jjb_configs/test3", (["bar", "baz"], ())),
+ ("jjb_configs/dir1/test", ([], ())),
+ ("jjb_configs/dir2/test2", ([], ())),
+ ("jjb_configs/dir3/bar", ([], ())),
+ ("jjb_configs/test3/bar", None),
+ ("jjb_configs/test3/baz", ([], ())),
]
rel_os_walk_paths = [
- (os.path.abspath(
- os.path.join(os.path.curdir, k)), v) for k, v in os_walk_paths]
+ (os.path.abspath(os.path.join(os.path.curdir, k)), v)
+ for k, v in os_walk_paths
+ ]
paths = [k for k, v in rel_os_walk_paths if v is not None]
oswalk_mock.side_effect = fake_os_walk(rel_os_walk_paths)
- self.assertEqual(paths, utils.recurse_path('jjb_configs',
- ['jjb_configs/test3/bar']))
+ self.assertEqual(
+ paths, utils.recurse_path("jjb_configs", ["jjb_configs/test3/bar"])
+ )
diff --git a/tests/duplicates/test_duplicates.py b/tests/duplicates/test_duplicates.py
index 0a90c9b4..d22aea2a 100644
--- a/tests/duplicates/test_duplicates.py
+++ b/tests/duplicates/test_duplicates.py
@@ -23,10 +23,10 @@ from tests.base import mock
class TestCaseModuleDuplicates(base.SingleJobTestCase):
- fixtures_path = os.path.join(os.path.dirname(__file__), 'fixtures')
+ fixtures_path = os.path.join(os.path.dirname(__file__), "fixtures")
scenarios = base.get_scenarios(fixtures_path)
- @mock.patch('jenkins_jobs.builder.logger', autospec=True)
+ @mock.patch("jenkins_jobs.builder.logger", autospec=True)
def test_yaml_snippet(self, mock_logger):
if os.path.basename(self.in_filename).startswith("exception_"):
diff --git a/tests/errors/test_exceptions.py b/tests/errors/test_exceptions.py
index 2fba25a6..079a5406 100644
--- a/tests/errors/test_exceptions.py
+++ b/tests/errors/test_exceptions.py
@@ -16,19 +16,19 @@ def dispatch(exc, *args):
def gen_xml(exc, *args):
- data = {'module': 'data'} # noqa
+ data = {"module": "data"} # noqa
raise exc(*args)
class TestInvalidAttributeError(base.BaseTestCase):
-
def test_no_valid_values(self):
# When given no valid values, InvalidAttributeError simply displays a
# message indicating the invalid value, the component type, the
# component name, and the attribute name.
message = "'{0}' is an invalid value for attribute {1}.{2}".format(
- "fnord", "type.name", "fubar")
+ "fnord", "type.name", "fubar"
+ )
with ExpectedException(errors.InvalidAttributeError, message):
dispatch(errors.InvalidAttributeError, "fubar", "fnord")
@@ -37,46 +37,49 @@ class TestInvalidAttributeError(base.BaseTestCase):
# indicating the invalid value, the component type, the component name,
# and the attribute name; additionally, it lists the valid values for
# the current component type & name.
- valid_values = ['herp', 'derp']
+ valid_values = ["herp", "derp"]
message = "'{0}' is an invalid value for attribute {1}.{2}".format(
- "fnord", "type.name", "fubar")
+ "fnord", "type.name", "fubar"
+ )
message += "\nValid values include: {0}".format(
- ', '.join("'{0}'".format(value) for value in valid_values))
+ ", ".join("'{0}'".format(value) for value in valid_values)
+ )
with ExpectedException(errors.InvalidAttributeError, message):
- dispatch(errors.InvalidAttributeError, "fubar", "fnord",
- valid_values)
+ dispatch(errors.InvalidAttributeError, "fubar", "fnord", valid_values)
class TestMissingAttributeError(base.BaseTestCase):
-
def test_with_single_missing_attribute(self):
# When passed a single missing attribute, display a message indicating
# * the missing attribute
# * which component type and component name is missing it.
- missing_attribute = 'herp'
+ missing_attribute = "herp"
message = "Missing {0} from an instance of '{1}'".format(
- missing_attribute, 'type.name')
+ missing_attribute, "type.name"
+ )
with ExpectedException(errors.MissingAttributeError, message):
dispatch(errors.MissingAttributeError, missing_attribute)
- with ExpectedException(errors.MissingAttributeError,
- message.replace('type.name', 'module')):
+ with ExpectedException(
+ errors.MissingAttributeError, message.replace("type.name", "module")
+ ):
gen_xml(errors.MissingAttributeError, missing_attribute)
def test_with_multiple_missing_attributes(self):
# When passed multiple missing attributes, display a message indicating
# * the missing attributes
# * which component type and component name is missing it.
- missing_attribute = ['herp', 'derp']
+ missing_attribute = ["herp", "derp"]
message = "One of {0} must be present in '{1}'".format(
- ', '.join("'{0}'".format(value) for value in missing_attribute),
- 'type.name')
+ ", ".join("'{0}'".format(value) for value in missing_attribute), "type.name"
+ )
with ExpectedException(errors.MissingAttributeError, message):
dispatch(errors.MissingAttributeError, missing_attribute)
- with ExpectedException(errors.MissingAttributeError,
- message.replace('type.name', 'module')):
+ with ExpectedException(
+ errors.MissingAttributeError, message.replace("type.name", "module")
+ ):
gen_xml(errors.MissingAttributeError, missing_attribute)
diff --git a/tests/general/test_general.py b/tests/general/test_general.py
index 503310fa..d7a7d77e 100644
--- a/tests/general/test_general.py
+++ b/tests/general/test_general.py
@@ -22,6 +22,6 @@ from tests import base
class TestCaseModuleGeneral(base.BaseScenariosTestCase):
- fixtures_path = os.path.join(os.path.dirname(__file__), 'fixtures')
+ fixtures_path = os.path.join(os.path.dirname(__file__), "fixtures")
scenarios = base.get_scenarios(fixtures_path)
klass = general.General
diff --git a/tests/hipchat/test_hipchat.py b/tests/hipchat/test_hipchat.py
index 6ff6d969..9e276754 100644
--- a/tests/hipchat/test_hipchat.py
+++ b/tests/hipchat/test_hipchat.py
@@ -19,6 +19,6 @@ from tests import base
class TestCaseModulePublishers(base.BaseScenariosTestCase):
- fixtures_path = os.path.join(os.path.dirname(__file__), 'fixtures')
+ fixtures_path = os.path.join(os.path.dirname(__file__), "fixtures")
scenarios = base.get_scenarios(fixtures_path)
klass = hipchat_notif.HipChat
diff --git a/tests/jenkins_manager/test_manager.py b/tests/jenkins_manager/test_manager.py
index ba579d15..530a8eaf 100644
--- a/tests/jenkins_manager/test_manager.py
+++ b/tests/jenkins_manager/test_manager.py
@@ -21,66 +21,65 @@ from tests.base import mock
_plugins_info = {}
-_plugins_info['plugin1'] = {'longName': '',
- 'shortName': '',
- 'version': ''}
+_plugins_info["plugin1"] = {"longName": "", "shortName": "", "version": ""}
-@mock.patch('jenkins_jobs.builder.JobCache', mock.MagicMock)
+@mock.patch("jenkins_jobs.builder.JobCache", mock.MagicMock)
class TestCaseTestJenkinsManager(base.BaseTestCase):
-
def setUp(self):
super(TestCaseTestJenkinsManager, self).setUp()
self.jjb_config = JJBConfig()
self.jjb_config.validate()
def test_plugins_list(self):
- self.jjb_config.builder['plugins_info'] = _plugins_info
+ self.jjb_config.builder["plugins_info"] = _plugins_info
self.builder = jenkins_jobs.builder.JenkinsManager(self.jjb_config)
self.assertEqual(self.builder.plugins_list, _plugins_info)
- @mock.patch.object(jenkins_jobs.builder.jenkins.Jenkins,
- 'get_plugins',
- return_value=_plugins_info)
+ @mock.patch.object(
+ jenkins_jobs.builder.jenkins.Jenkins, "get_plugins", return_value=_plugins_info
+ )
def test_plugins_list_from_jenkins(self, jenkins_mock):
# Trigger fetching the plugins from jenkins when accessing the property
- self.jjb_config.builder['plugins_info'] = {}
+ self.jjb_config.builder["plugins_info"] = {}
self.builder = jenkins_jobs.builder.JenkinsManager(self.jjb_config)
# See https://github.com/formiaczek/multi_key_dict/issues/17
# self.assertEqual(self.builder.plugins_list, k)
for key_tuple in self.builder.plugins_list.keys():
for key in key_tuple:
- self.assertEqual(self.builder.plugins_list[key],
- _plugins_info[key])
+ self.assertEqual(self.builder.plugins_list[key], _plugins_info[key])
def test_delete_managed(self):
- self.jjb_config.builder['plugins_info'] = {}
+ self.jjb_config.builder["plugins_info"] = {}
self.builder = jenkins_jobs.builder.JenkinsManager(self.jjb_config)
- with mock.patch.multiple('jenkins_jobs.builder.JenkinsManager',
- get_jobs=mock.DEFAULT,
- is_job=mock.DEFAULT,
- is_managed=mock.DEFAULT,
- delete_job=mock.DEFAULT) as patches:
- patches['get_jobs'].return_value = [{'fullname': 'job1'},
- {'fullname': 'job2'}]
- patches['is_managed'].side_effect = [True, True]
- patches['is_job'].side_effect = [True, True]
+ with mock.patch.multiple(
+ "jenkins_jobs.builder.JenkinsManager",
+ get_jobs=mock.DEFAULT,
+ is_job=mock.DEFAULT,
+ is_managed=mock.DEFAULT,
+ delete_job=mock.DEFAULT,
+ ) as patches:
+ patches["get_jobs"].return_value = [
+ {"fullname": "job1"},
+ {"fullname": "job2"},
+ ]
+ patches["is_managed"].side_effect = [True, True]
+ patches["is_job"].side_effect = [True, True]
self.builder.delete_old_managed()
- self.assertEqual(patches['delete_job'].call_count, 2)
+ self.assertEqual(patches["delete_job"].call_count, 2)
def _get_plugins_info_error_test(self, error_string):
builder = jenkins_jobs.builder.JenkinsManager(self.jjb_config)
exception = jenkins_jobs.builder.jenkins.JenkinsException(error_string)
- with mock.patch.object(builder.jenkins, 'get_plugins',
- side_effect=exception):
+ with mock.patch.object(builder.jenkins, "get_plugins", side_effect=exception):
plugins_info = builder.get_plugins_info()
- self.assertEqual([_plugins_info['plugin1']], plugins_info)
+ self.assertEqual([_plugins_info["plugin1"]], plugins_info)
def test_get_plugins_info_handles_connectionrefused_errors(self):
- self._get_plugins_info_error_test('Connection refused')
+ self._get_plugins_info_error_test("Connection refused")
def test_get_plugins_info_handles_forbidden_errors(self):
- self._get_plugins_info_error_test('Forbidden')
+ self._get_plugins_info_error_test("Forbidden")
diff --git a/tests/jsonparser/test_jsonparser.py b/tests/jsonparser/test_jsonparser.py
index 5e62534b..6257b4d3 100644
--- a/tests/jsonparser/test_jsonparser.py
+++ b/tests/jsonparser/test_jsonparser.py
@@ -21,5 +21,5 @@ from tests import base
class TestCaseModuleJsonParser(base.SingleJobTestCase):
- fixtures_path = os.path.join(os.path.dirname(__file__), 'fixtures')
- scenarios = base.get_scenarios(fixtures_path, in_ext='json', out_ext='xml')
+ fixtures_path = os.path.join(os.path.dirname(__file__), "fixtures")
+ scenarios = base.get_scenarios(fixtures_path, in_ext="json", out_ext="xml")
diff --git a/tests/localyaml/test_localyaml.py b/tests/localyaml/test_localyaml.py
index 788bb3b2..c41c9ed8 100644
--- a/tests/localyaml/test_localyaml.py
+++ b/tests/localyaml/test_localyaml.py
@@ -34,15 +34,16 @@ class TestCaseLocalYamlInclude(base.JsonTestCase):
Verify application specific tags independently of any changes to
modules XML parsing behaviour
"""
- fixtures_path = os.path.join(os.path.dirname(__file__), 'fixtures')
- scenarios = base.get_scenarios(fixtures_path, 'yaml', 'json',
- filter_func=_exclude_scenarios)
+
+ fixtures_path = os.path.join(os.path.dirname(__file__), "fixtures")
+ scenarios = base.get_scenarios(
+ fixtures_path, "yaml", "json", filter_func=_exclude_scenarios
+ )
def test_yaml_snippet(self):
if os.path.basename(self.in_filename).startswith("exception_"):
- with ExpectedException(ComposerError,
- "^found duplicate anchor .*"):
+ with ExpectedException(ComposerError, "^found duplicate anchor .*"):
super(TestCaseLocalYamlInclude, self).test_yaml_snippet()
else:
super(TestCaseLocalYamlInclude, self).test_yaml_snippet()
@@ -53,13 +54,14 @@ class TestCaseLocalYamlAnchorAlias(base.YamlTestCase):
Verify yaml input is expanded to the expected yaml output when using yaml
anchors and aliases.
"""
- fixtures_path = os.path.join(os.path.dirname(__file__), 'fixtures')
- scenarios = base.get_scenarios(fixtures_path, 'iyaml', 'oyaml')
+
+ fixtures_path = os.path.join(os.path.dirname(__file__), "fixtures")
+ scenarios = base.get_scenarios(fixtures_path, "iyaml", "oyaml")
class TestCaseLocalYamlIncludeAnchors(base.BaseTestCase):
- fixtures_path = os.path.join(os.path.dirname(__file__), 'fixtures')
+ fixtures_path = os.path.join(os.path.dirname(__file__), "fixtures")
def test_multiple_same_anchor_in_multiple_toplevel_yaml(self):
"""
@@ -70,14 +72,16 @@ class TestCaseLocalYamlIncludeAnchors(base.BaseTestCase):
are treated by the yaml loader as independent.
"""
- files = ["custom_same_anchor-001-part1.yaml",
- "custom_same_anchor-001-part2.yaml"]
+ files = [
+ "custom_same_anchor-001-part1.yaml",
+ "custom_same_anchor-001-part2.yaml",
+ ]
jjb_config = JJBConfig()
- jjb_config.jenkins['url'] = 'http://example.com'
- jjb_config.jenkins['user'] = 'jenkins'
- jjb_config.jenkins['password'] = 'password'
- jjb_config.builder['plugins_info'] = []
+ jjb_config.jenkins["url"] = "http://example.com"
+ jjb_config.jenkins["user"] = "jenkins"
+ jjb_config.jenkins["password"] = "password"
+ jjb_config.builder["plugins_info"] = []
jjb_config.validate()
j = YamlParser(jjb_config)
j.load_files([os.path.join(self.fixtures_path, f) for f in files])
@@ -85,22 +89,20 @@ class TestCaseLocalYamlIncludeAnchors(base.BaseTestCase):
class TestCaseLocalYamlRetainAnchors(base.BaseTestCase):
- fixtures_path = os.path.join(os.path.dirname(__file__), 'fixtures')
+ fixtures_path = os.path.join(os.path.dirname(__file__), "fixtures")
def test_retain_anchors_default(self):
"""
Verify that anchors are NOT retained across files by default.
"""
- files = ["custom_retain_anchors_include001.yaml",
- "custom_retain_anchors.yaml"]
+ files = ["custom_retain_anchors_include001.yaml", "custom_retain_anchors.yaml"]
jjb_config = JJBConfig()
# use the default value for retain_anchors
jjb_config.validate()
j = YamlParser(jjb_config)
- with ExpectedException(yaml.composer.ComposerError,
- "found undefined alias.*"):
+ with ExpectedException(yaml.composer.ComposerError, "found undefined alias.*"):
j.load_files([os.path.join(self.fixtures_path, f) for f in files])
def test_retain_anchors_enabled(self):
@@ -109,11 +111,10 @@ class TestCaseLocalYamlRetainAnchors(base.BaseTestCase):
enabled in the config.
"""
- files = ["custom_retain_anchors_include001.yaml",
- "custom_retain_anchors.yaml"]
+ files = ["custom_retain_anchors_include001.yaml", "custom_retain_anchors.yaml"]
jjb_config = JJBConfig()
- jjb_config.yamlparser['retain_anchors'] = True
+ jjb_config.yamlparser["retain_anchors"] = True
jjb_config.validate()
j = YamlParser(jjb_config)
j.load_files([os.path.join(self.fixtures_path, f) for f in files])
diff --git a/tests/macros/test_macros.py b/tests/macros/test_macros.py
index 392154ff..1535e333 100644
--- a/tests/macros/test_macros.py
+++ b/tests/macros/test_macros.py
@@ -21,5 +21,5 @@ from tests import base
class TestCaseModuleSCMMacro(base.SingleJobTestCase):
- fixtures_path = os.path.join(os.path.dirname(__file__), 'fixtures')
+ fixtures_path = os.path.join(os.path.dirname(__file__), "fixtures")
scenarios = base.get_scenarios(fixtures_path)
diff --git a/tests/moduleregistry/test_moduleregistry.py b/tests/moduleregistry/test_moduleregistry.py
index 0b0c54a4..743f180f 100644
--- a/tests/moduleregistry/test_moduleregistry.py
+++ b/tests/moduleregistry/test_moduleregistry.py
@@ -9,25 +9,34 @@ from tests import base
class ModuleRegistryPluginInfoTestsWithScenarios(
- testscenarios.TestWithScenarios, base.BaseTestCase):
+ testscenarios.TestWithScenarios, base.BaseTestCase
+):
scenarios = [
- ('s1', dict(v1='1.0.0', op='__gt__', v2='0.8.0')),
- ('s2', dict(v1='1.0.1alpha', op='__gt__', v2='1.0.0')),
- ('s3', dict(v1='1.0', op='__eq__', v2='1.0.0')),
- ('s4', dict(v1='1.0', op='__eq__', v2='1.0')),
- ('s5', dict(v1='1.0', op='__lt__', v2='1.8.0')),
- ('s6', dict(v1='1.0.1alpha', op='__lt__', v2='1.0.1')),
- ('s7', dict(v1='1.0alpha', op='__lt__', v2='1.0.0')),
- ('s8', dict(v1='1.0-alpha', op='__lt__', v2='1.0.0')),
- ('s9', dict(v1='1.1-alpha', op='__gt__', v2='1.0')),
- ('s10', dict(v1='1.0-SNAPSHOT', op='__lt__', v2='1.0')),
- ('s11', dict(v1='1.0.preview', op='__lt__', v2='1.0')),
- ('s12', dict(v1='1.1-SNAPSHOT', op='__gt__', v2='1.0')),
- ('s13', dict(v1='1.0a-SNAPSHOT', op='__lt__', v2='1.0a')),
- ('s14', dict(v1='1.4.6-SNAPSHOT (private-0986edd9-example)',
- op='__lt__', v2='1.4.6')),
- ('s15', dict(v1='1.4.6-SNAPSHOT (private-0986edd9-example)',
- op='__gt__', v2='1.4.5')),
+ ("s1", dict(v1="1.0.0", op="__gt__", v2="0.8.0")),
+ ("s2", dict(v1="1.0.1alpha", op="__gt__", v2="1.0.0")),
+ ("s3", dict(v1="1.0", op="__eq__", v2="1.0.0")),
+ ("s4", dict(v1="1.0", op="__eq__", v2="1.0")),
+ ("s5", dict(v1="1.0", op="__lt__", v2="1.8.0")),
+ ("s6", dict(v1="1.0.1alpha", op="__lt__", v2="1.0.1")),
+ ("s7", dict(v1="1.0alpha", op="__lt__", v2="1.0.0")),
+ ("s8", dict(v1="1.0-alpha", op="__lt__", v2="1.0.0")),
+ ("s9", dict(v1="1.1-alpha", op="__gt__", v2="1.0")),
+ ("s10", dict(v1="1.0-SNAPSHOT", op="__lt__", v2="1.0")),
+ ("s11", dict(v1="1.0.preview", op="__lt__", v2="1.0")),
+ ("s12", dict(v1="1.1-SNAPSHOT", op="__gt__", v2="1.0")),
+ ("s13", dict(v1="1.0a-SNAPSHOT", op="__lt__", v2="1.0a")),
+ (
+ "s14",
+ dict(
+ v1="1.4.6-SNAPSHOT (private-0986edd9-example)", op="__lt__", v2="1.4.6"
+ ),
+ ),
+ (
+ "s15",
+ dict(
+ v1="1.4.6-SNAPSHOT (private-0986edd9-example)", op="__gt__", v2="1.4.5"
+ ),
+ ),
]
def setUp(self):
@@ -36,13 +45,16 @@ class ModuleRegistryPluginInfoTestsWithScenarios(
jjb_config = JJBConfig()
jjb_config.validate()
- plugin_info = [{'shortName': "HerpDerpPlugin",
- 'longName': "Blah Blah Blah Plugin"
- }]
- plugin_info.append({'shortName': "JankyPlugin1",
- 'longName': "Not A Real Plugin",
- 'version': self.v1
- })
+ plugin_info = [
+ {"shortName": "HerpDerpPlugin", "longName": "Blah Blah Blah Plugin"}
+ ]
+ plugin_info.append(
+ {
+ "shortName": "JankyPlugin1",
+ "longName": "Not A Real Plugin",
+ "version": self.v1,
+ }
+ )
self.addDetail("plugin_info", text_content(str(plugin_info)))
self.registry = ModuleRegistry(jjb_config, plugin_info)
@@ -61,7 +73,7 @@ class ModuleRegistryPluginInfoTestsWithScenarios(
plugin_info = self.registry.get_plugin_info(plugin_name)
self.assertIsInstance(plugin_info, dict)
- self.assertEqual(plugin_info['shortName'], plugin_name)
+ self.assertEqual(plugin_info["shortName"], plugin_name)
def test_get_plugin_info_dict_using_longName(self):
"""
@@ -74,7 +86,7 @@ class ModuleRegistryPluginInfoTestsWithScenarios(
plugin_info = self.registry.get_plugin_info(plugin_name)
self.assertIsInstance(plugin_info, dict)
- self.assertEqual(plugin_info['longName'], plugin_name)
+ self.assertEqual(plugin_info["longName"], plugin_name)
def test_get_plugin_info_dict_no_plugin(self):
"""
@@ -101,8 +113,8 @@ class ModuleRegistryPluginInfoTestsWithScenarios(
plugin_info = self.registry.get_plugin_info(plugin_name)
self.assertIsInstance(plugin_info, dict)
- self.assertEqual(plugin_info['shortName'], plugin_name)
- self.assertEqual(plugin_info['version'], '0')
+ self.assertEqual(plugin_info["shortName"], plugin_name)
+ self.assertEqual(plugin_info["version"], "0")
def test_plugin_version_comparison(self):
"""
@@ -117,7 +129,8 @@ class ModuleRegistryPluginInfoTestsWithScenarios(
op = getattr(pkg_resources.parse_version(v1), self.op)
test = op(pkg_resources.parse_version(self.v2))
- self.assertTrue(test,
- msg="Unexpectedly found {0} {2} {1} == False "
- "when comparing versions!"
- .format(v1, self.v2, self.op))
+ self.assertTrue(
+ test,
+ msg="Unexpectedly found {0} {2} {1} == False "
+ "when comparing versions!".format(v1, self.v2, self.op),
+ )
diff --git a/tests/modules/test_helpers.py b/tests/modules/test_helpers.py
index cdfc4d74..f0cebb41 100644
--- a/tests/modules/test_helpers.py
+++ b/tests/modules/test_helpers.py
@@ -24,86 +24,91 @@ from tests import base
class TestCaseTestHelpers(base.BaseTestCase):
-
def test_convert_mapping_to_xml(self):
"""
Tests the test_convert_mapping_to_xml_fail_required function
"""
# Test default values
- default_root = XML.Element('testdefault')
+ default_root = XML.Element("testdefault")
default_data = yaml.load("string: hello")
- default_mappings = [('default-string', 'defaultString', 'default')]
+ default_mappings = [("default-string", "defaultString", "default")]
convert_mapping_to_xml(
- default_root,
- default_data,
- default_mappings,
- fail_required=True)
- result = default_root.find('defaultString').text
- self.assertThat(result, Equals('default'))
+ default_root, default_data, default_mappings, fail_required=True
+ )
+ result = default_root.find("defaultString").text
+ self.assertThat(result, Equals("default"))
# Test user input
- user_input_root = XML.Element('testUserInput')
+ user_input_root = XML.Element("testUserInput")
user_input_data = yaml.load("user-input-string: hello")
- user_input_mappings = [('user-input-string', 'userInputString',
- 'user-input')]
+ user_input_mappings = [("user-input-string", "userInputString", "user-input")]
convert_mapping_to_xml(
- user_input_root,
- user_input_data,
- user_input_mappings,
- fail_required=True)
- result = user_input_root.find('userInputString').text
- self.assertThat(result, Equals('hello'))
+ user_input_root, user_input_data, user_input_mappings, fail_required=True
+ )
+ result = user_input_root.find("userInputString").text
+ self.assertThat(result, Equals("hello"))
# Test missing required input
- required_root = XML.Element('testrequired')
+ required_root = XML.Element("testrequired")
required_data = yaml.load("string: hello")
- required_mappings = [('required-string', 'requiredString', None)]
+ required_mappings = [("required-string", "requiredString", None)]
- self.assertRaises(MissingAttributeError,
- convert_mapping_to_xml,
- required_root,
- required_data,
- required_mappings,
- fail_required=True)
+ self.assertRaises(
+ MissingAttributeError,
+ convert_mapping_to_xml,
+ required_root,
+ required_data,
+ required_mappings,
+ fail_required=True,
+ )
# Test invalid user input for list
- user_input_root = XML.Element('testUserInput')
+ user_input_root = XML.Element("testUserInput")
user_input_data = yaml.load("user-input-string: bye")
- valid_inputs = ['hello']
- user_input_mappings = [('user-input-string', 'userInputString',
- 'user-input', valid_inputs)]
-
- self.assertRaises(InvalidAttributeError,
- convert_mapping_to_xml,
- user_input_root,
- user_input_data,
- user_input_mappings)
+ valid_inputs = ["hello"]
+ user_input_mappings = [
+ ("user-input-string", "userInputString", "user-input", valid_inputs)
+ ]
+
+ self.assertRaises(
+ InvalidAttributeError,
+ convert_mapping_to_xml,
+ user_input_root,
+ user_input_data,
+ user_input_mappings,
+ )
# Test invalid user input for dict
- user_input_root = XML.Element('testUserInput')
+ user_input_root = XML.Element("testUserInput")
user_input_data = yaml.load("user-input-string: later")
- valid_inputs = {'hello': 'world'}
- user_input_mappings = [('user-input-string', 'userInputString',
- 'user-input', valid_inputs)]
-
- self.assertRaises(InvalidAttributeError,
- convert_mapping_to_xml,
- user_input_root,
- user_input_data,
- user_input_mappings)
+ valid_inputs = {"hello": "world"}
+ user_input_mappings = [
+ ("user-input-string", "userInputString", "user-input", valid_inputs)
+ ]
+
+ self.assertRaises(
+ InvalidAttributeError,
+ convert_mapping_to_xml,
+ user_input_root,
+ user_input_data,
+ user_input_mappings,
+ )
# Test invalid key for dict
- user_input_root = XML.Element('testUserInput')
+ user_input_root = XML.Element("testUserInput")
user_input_data = yaml.load("user-input-string: world")
- valid_inputs = {'hello': 'world'}
- user_input_mappings = [('user-input-string', 'userInputString',
- 'user-input', valid_inputs)]
-
- self.assertRaises(InvalidAttributeError,
- convert_mapping_to_xml,
- user_input_root,
- user_input_data,
- user_input_mappings)
+ valid_inputs = {"hello": "world"}
+ user_input_mappings = [
+ ("user-input-string", "userInputString", "user-input", valid_inputs)
+ ]
+
+ self.assertRaises(
+ InvalidAttributeError,
+ convert_mapping_to_xml,
+ user_input_root,
+ user_input_data,
+ user_input_mappings,
+ )
diff --git a/tests/multibranch/test_multibranch.py b/tests/multibranch/test_multibranch.py
index 6a1cca0b..84ecb012 100644
--- a/tests/multibranch/test_multibranch.py
+++ b/tests/multibranch/test_multibranch.py
@@ -19,9 +19,9 @@ import os
from jenkins_jobs.modules import project_multibranch
-@mock.patch('uuid.uuid4', mock.Mock(return_value='1-1-1-1-1'))
+@mock.patch("uuid.uuid4", mock.Mock(return_value="1-1-1-1-1"))
class TestCaseMultibranchPipeline(base.BaseScenariosTestCase):
- fixtures_path = os.path.join(os.path.dirname(__file__), 'fixtures')
+ fixtures_path = os.path.join(os.path.dirname(__file__), "fixtures")
scenarios = base.get_scenarios(fixtures_path)
- default_config_file = '/dev/null'
+ default_config_file = "/dev/null"
klass = project_multibranch.WorkflowMultiBranch
diff --git a/tests/notifications/test_notifications.py b/tests/notifications/test_notifications.py
index e68a269d..e1935efa 100644
--- a/tests/notifications/test_notifications.py
+++ b/tests/notifications/test_notifications.py
@@ -22,6 +22,6 @@ from tests import base
class TestCaseModuleNotifications(base.BaseScenariosTestCase):
- fixtures_path = os.path.join(os.path.dirname(__file__), 'fixtures')
+ fixtures_path = os.path.join(os.path.dirname(__file__), "fixtures")
scenarios = base.get_scenarios(fixtures_path)
klass = notifications.Notifications
diff --git a/tests/parallel/test_parallel.py b/tests/parallel/test_parallel.py
index a3b68092..b7ccd20b 100644
--- a/tests/parallel/test_parallel.py
+++ b/tests/parallel/test_parallel.py
@@ -30,19 +30,18 @@ class TestCaseParallel(TestCase):
def parallel_test(num_base, num_extra):
return num_base + num_extra
- parallel_args = [{'num_extra': num} for num in range(10)]
+ parallel_args = [{"num_extra": num} for num in range(10)]
result = parallel_test(10, concurrent=parallel_args)
self.assertThat(result, matchers.Equals(expected))
def test_parallel_time_less_than_serial(self):
-
@concurrent
def wait(secs):
time.sleep(secs)
before = time.time()
# ten threads to make it as fast as possible
- wait(concurrent=[{'secs': 1} for _ in range(10)], n_workers=10)
+ wait(concurrent=[{"secs": 1} for _ in range(10)], n_workers=10)
after = time.time()
self.assertThat(after - before, matchers.LessThan(5))
@@ -53,18 +52,16 @@ class TestCaseParallel(TestCase):
def parallel_test(num_base, num_extra):
return num_base + num_extra
- parallel_args = [{'num_extra': num} for num in range(10)]
+ parallel_args = [{"num_extra": num} for num in range(10)]
result = parallel_test(10, concurrent=parallel_args, n_workers=1)
self.assertThat(result, matchers.Equals(expected))
- @mock.patch('jenkins_jobs.parallel.cpu_count', wraps=cpu_count)
+ @mock.patch("jenkins_jobs.parallel.cpu_count", wraps=cpu_count)
def test_use_auto_detect_cores(self, mockCpu_count):
-
@concurrent
def parallel_test():
return True
- result = parallel_test(concurrent=[{} for _ in range(10)],
- n_workers=0)
+ result = parallel_test(concurrent=[{} for _ in range(10)], n_workers=0)
self.assertThat(result, matchers.Equals([True for _ in range(10)]))
mockCpu_count.assert_called_once_with()
diff --git a/tests/parameters/test_parameters.py b/tests/parameters/test_parameters.py
index ab637ca2..fad81a00 100644
--- a/tests/parameters/test_parameters.py
+++ b/tests/parameters/test_parameters.py
@@ -22,6 +22,6 @@ from tests import base
class TestCaseModuleParameters(base.BaseScenariosTestCase):
- fixtures_path = os.path.join(os.path.dirname(__file__), 'fixtures')
+ fixtures_path = os.path.join(os.path.dirname(__file__), "fixtures")
scenarios = base.get_scenarios(fixtures_path)
klass = parameters.Parameters
diff --git a/tests/properties/test_properties.py b/tests/properties/test_properties.py
index f527d8dc..5c722a2b 100644
--- a/tests/properties/test_properties.py
+++ b/tests/properties/test_properties.py
@@ -22,6 +22,6 @@ from tests import base
class TestCaseModuleProperties(base.BaseScenariosTestCase):
- fixtures_path = os.path.join(os.path.dirname(__file__), 'fixtures')
+ fixtures_path = os.path.join(os.path.dirname(__file__), "fixtures")
scenarios = base.get_scenarios(fixtures_path)
klass = properties.Properties
diff --git a/tests/publishers/test_publishers.py b/tests/publishers/test_publishers.py
index e44a4dba..16d2295e 100644
--- a/tests/publishers/test_publishers.py
+++ b/tests/publishers/test_publishers.py
@@ -22,6 +22,6 @@ from tests import base
class TestCaseModulePublishers(base.BaseScenariosTestCase):
- fixtures_path = os.path.join(os.path.dirname(__file__), 'fixtures')
+ fixtures_path = os.path.join(os.path.dirname(__file__), "fixtures")
scenarios = base.get_scenarios(fixtures_path)
klass = publishers.Publishers
diff --git a/tests/reporters/test_reporters.py b/tests/reporters/test_reporters.py
index 920c463f..5b419e80 100644
--- a/tests/reporters/test_reporters.py
+++ b/tests/reporters/test_reporters.py
@@ -21,6 +21,6 @@ from tests import base
class TestCaseModuleReporters(base.BaseScenariosTestCase):
- fixtures_path = os.path.join(os.path.dirname(__file__), 'fixtures')
+ fixtures_path = os.path.join(os.path.dirname(__file__), "fixtures")
scenarios = base.get_scenarios(fixtures_path)
klass = reporters.Reporters
diff --git a/tests/scm/test_scm.py b/tests/scm/test_scm.py
index a4fa998d..62ee8762 100644
--- a/tests/scm/test_scm.py
+++ b/tests/scm/test_scm.py
@@ -22,6 +22,6 @@ from tests import base
class TestCaseModuleSCM(base.BaseScenariosTestCase):
- fixtures_path = os.path.join(os.path.dirname(__file__), 'fixtures')
+ fixtures_path = os.path.join(os.path.dirname(__file__), "fixtures")
scenarios = base.get_scenarios(fixtures_path)
klass = scm.SCM
diff --git a/tests/triggers/test_triggers.py b/tests/triggers/test_triggers.py
index 04b7c8cd..9f0ae5f4 100644
--- a/tests/triggers/test_triggers.py
+++ b/tests/triggers/test_triggers.py
@@ -22,6 +22,6 @@ from tests import base
class TestCaseModuleTriggers(base.BaseScenariosTestCase):
- fixtures_path = os.path.join(os.path.dirname(__file__), 'fixtures')
+ fixtures_path = os.path.join(os.path.dirname(__file__), "fixtures")
scenarios = base.get_scenarios(fixtures_path)
klass = triggers.Triggers
diff --git a/tests/views/test_views.py b/tests/views/test_views.py
index 4ce73330..700b174d 100644
--- a/tests/views/test_views.py
+++ b/tests/views/test_views.py
@@ -20,18 +20,18 @@ from tests import base
class TestCaseModuleViewAll(base.BaseScenariosTestCase):
- fixtures_path = os.path.join(os.path.dirname(__file__), 'fixtures')
+ fixtures_path = os.path.join(os.path.dirname(__file__), "fixtures")
scenarios = base.get_scenarios(fixtures_path)
klass = view_all.All
class TestCaseModuleViewList(base.BaseScenariosTestCase):
- fixtures_path = os.path.join(os.path.dirname(__file__), 'fixtures')
+ fixtures_path = os.path.join(os.path.dirname(__file__), "fixtures")
scenarios = base.get_scenarios(fixtures_path)
klass = view_list.List
class TestCaseModuleViewPipeline(base.BaseScenariosTestCase):
- fixtures_path = os.path.join(os.path.dirname(__file__), 'fixtures')
+ fixtures_path = os.path.join(os.path.dirname(__file__), "fixtures")
scenarios = base.get_scenarios(fixtures_path)
klass = view_pipeline.Pipeline
diff --git a/tests/wrappers/test_wrappers.py b/tests/wrappers/test_wrappers.py
index 717a9955..f84d040f 100644
--- a/tests/wrappers/test_wrappers.py
+++ b/tests/wrappers/test_wrappers.py
@@ -22,6 +22,6 @@ from tests import base
class TestCaseModuleWrappers(base.BaseScenariosTestCase):
- fixtures_path = os.path.join(os.path.dirname(__file__), 'fixtures')
+ fixtures_path = os.path.join(os.path.dirname(__file__), "fixtures")
scenarios = base.get_scenarios(fixtures_path)
klass = wrappers.Wrappers
diff --git a/tests/xml_config/test_xml_config.py b/tests/xml_config/test_xml_config.py
index 76858db2..6f8fd0b7 100644
--- a/tests/xml_config/test_xml_config.py
+++ b/tests/xml_config/test_xml_config.py
@@ -23,23 +23,23 @@ from tests import base
class TestXmlJobGeneratorExceptions(base.BaseTestCase):
- fixtures_path = os.path.join(os.path.dirname(__file__), 'exceptions')
+ fixtures_path = os.path.join(os.path.dirname(__file__), "exceptions")
def test_invalid_project(self):
self.conf_filename = None
config = self._get_config()
yp = parser.YamlParser(config)
- yp.parse(os.path.join(self.fixtures_path,
- "invalid_project.yaml"))
+ yp.parse(os.path.join(self.fixtures_path, "invalid_project.yaml"))
reg = registry.ModuleRegistry(config)
job_data, _ = yp.expandYaml(reg)
# Generate the XML tree
xml_generator = xml_config.XmlJobGenerator(reg)
- e = self.assertRaises(errors.JenkinsJobsException,
- xml_generator.generateXML, job_data)
+ e = self.assertRaises(
+ errors.JenkinsJobsException, xml_generator.generateXML, job_data
+ )
self.assertIn("Unrecognized project-type:", str(e))
def test_invalid_view(self):
@@ -54,8 +54,9 @@ class TestXmlJobGeneratorExceptions(base.BaseTestCase):
# Generate the XML tree
xml_generator = xml_config.XmlViewGenerator(reg)
- e = self.assertRaises(errors.JenkinsJobsException,
- xml_generator.generateXML, view_data)
+ e = self.assertRaises(
+ errors.JenkinsJobsException, xml_generator.generateXML, view_data
+ )
self.assertIn("Unrecognized view-type:", str(e))
def test_incorrect_template_params(self):
@@ -63,8 +64,7 @@ class TestXmlJobGeneratorExceptions(base.BaseTestCase):
config = self._get_config()
yp = parser.YamlParser(config)
- yp.parse(os.path.join(self.fixtures_path,
- "failure_formatting_component.yaml"))
+ yp.parse(os.path.join(self.fixtures_path, "failure_formatting_component.yaml"))
reg = registry.ModuleRegistry(config)
reg.set_parser_data(yp.data)
diff --git a/tests/yamlparser/test_yamlparser.py b/tests/yamlparser/test_yamlparser.py
index cfc0c690..32030835 100644
--- a/tests/yamlparser/test_yamlparser.py
+++ b/tests/yamlparser/test_yamlparser.py
@@ -24,20 +24,19 @@ from tests import base
class TestCaseModuleYamlInclude(base.SingleJobTestCase):
- fixtures_path = os.path.join(os.path.dirname(__file__), 'fixtures')
+ fixtures_path = os.path.join(os.path.dirname(__file__), "fixtures")
scenarios = base.get_scenarios(fixtures_path)
class TestYamlParserExceptions(base.BaseTestCase):
- fixtures_path = os.path.join(os.path.dirname(__file__), 'exceptions')
+ fixtures_path = os.path.join(os.path.dirname(__file__), "exceptions")
def test_incorrect_template_dimensions(self):
self.conf_filename = None
config = self._get_config()
yp = parser.YamlParser(config)
- yp.parse(os.path.join(self.fixtures_path,
- "incorrect_template_dimensions.yaml"))
+ yp.parse(os.path.join(self.fixtures_path, "incorrect_template_dimensions.yaml"))
reg = registry.ModuleRegistry(config)
@@ -47,23 +46,22 @@ class TestYamlParserExceptions(base.BaseTestCase):
class TestYamlParserFailureFormattingExceptions(base.BaseScenariosTestCase):
- fixtures_path = os.path.join(os.path.dirname(__file__), 'exceptions')
- scenarios = [
- ('s1', {'name': 'template'}),
- ('s2', {'name': 'params'})
- ]
+ fixtures_path = os.path.join(os.path.dirname(__file__), "exceptions")
+ scenarios = [("s1", {"name": "template"}), ("s2", {"name": "params"})]
def test_yaml_snippet(self):
self.conf_filename = None
config = self._get_config()
yp = parser.YamlParser(config)
- yp.parse(os.path.join(self.fixtures_path,
- "failure_formatting_{}.yaml".format(self.name)))
+ yp.parse(
+ os.path.join(
+ self.fixtures_path, "failure_formatting_{}.yaml".format(self.name)
+ )
+ )
reg = registry.ModuleRegistry(config)
self.assertRaises(Exception, yp.expandYaml, reg)
- self.assertIn("Failure formatting {}".format(self.name),
- self.logger.output)
+ self.assertIn("Failure formatting {}".format(self.name), self.logger.output)
self.assertIn("Problem formatting with args", self.logger.output)