class InstallRuntimeDependenciesTest(unittest.TestCase): def setUp(self): self.project = Project("unittest", ".") self.project.set_property("dir_install_logs", "any_directory") self.logger = Mock(Logger) initialize_install_dependencies_plugin(self.project) @patch("pybuilder.plugins.python.install_dependencies_plugin.execute_command", return_value=0) def test_should_install_multiple_dependencies(self, exec_command, get_package_version): self.project.depends_on("spam") self.project.depends_on("eggs") self.project.depends_on_requirements("requirements.txt") install_runtime_dependencies(self.logger, self.project) exec_command(PIP_EXEC_STANZA + ["install", 'spam'], ANY, shell=False) exec_command(PIP_EXEC_STANZA + ["install", 'eggs'], ANY, shell=False) exec_command(PIP_EXEC_STANZA + ["install", '-r', 'requirements.txt'], ANY, shell=False) @patch("pybuilder.plugins.python.install_dependencies_plugin.execute_command", return_value=0) def test_should_install_multiple_dependencies_locally(self, exec_command, get_package_version): self.project.depends_on("spam") self.project.depends_on("eggs") self.project.depends_on("foo") self.project.set_property("install_dependencies_local_mapping", { "spam": "any-dir", "eggs": "any-other-dir" }) install_runtime_dependencies(self.logger, self.project) exec_command(PIP_EXEC_STANZA + ["install", "-t", "any-dir", 'spam'], ANY, shell=False) exec_command(PIP_EXEC_STANZA + ["install", "-t", "any-other-dir", 'eggs'], ANY, shell=False) exec_command(PIP_EXEC_STANZA + ["install", 'foo'], ANY, shell=False)
def test_should_break_build_when_warnings_and_set(self, execute_tool, warnings): project = Project(".") init_pylint(project) project.set_property("pylint_break_build", True) with self.assertRaises(BuildFailedException): execute_pylint(project, Mock(Logger))
def create_project(): project = Project("/") project.build_depends_on("testingframework") project.depends_on("sometool") project.depends_on( "pyassert", url="https://github.com/downloads/halimath/pyassert/pyassert-0.2.2.tar.gz") project.name = "Spam and Eggs" project.version = "1.2.3" project.summary = "This is a simple integration-test for distutils plugin." project.description = "As you might have guessed we have nothing to say here." project.authors = [ Author("Udo Juettner", "*****@*****.**"), Author("Michael Gruber", "*****@*****.**")] project.license = "WTFPL" project.url = "http://github.com/pybuilder/pybuilder" def return_dummy_list(): return ["spam", "eggs"] project.list_scripts = return_dummy_list project.list_packages = return_dummy_list project.list_modules = return_dummy_list project.set_property("distutils_classifiers", [ "Development Status :: 5 - Beta", "Environment :: Console"]) project.install_file("dir", "file1") project.install_file("dir", "file2") project.include_file("spam", "eggs") return project
class InstallBuildDependenciesTest(unittest.TestCase): def setUp(self): self.project = Project("unittest", ".") self.project.set_property("dir_install_logs", "any_directory") self.logger = mock(Logger) initialize_install_dependencies_plugin(self.project) when(pybuilder.plugins.python.install_dependencies_plugin).execute_command(any_value(), any_value(), env=any_value(), shell=False).thenReturn(0) def tearDown(self): unstub() def test_should_install_multiple_dependencies(self): self.project.build_depends_on("spam") self.project.build_depends_on("eggs") self.project.build_depends_on_requirements("requirements-dev.txt") install_build_dependencies(self.logger, self.project) verify(pybuilder.plugins.python.install_dependencies_plugin).execute_command( PIP_EXEC_STANZA + ["install", "spam"], any_value(), shell=False) verify(pybuilder.plugins.python.install_dependencies_plugin).execute_command( PIP_EXEC_STANZA + ["install", "eggs"], any_value(), shell=False) verify(pybuilder.plugins.python.install_dependencies_plugin).execute_command( PIP_EXEC_STANZA + ["install", '-r', 'requirements-dev.txt'], any_value(), shell=False)
class PythonPathTests(TestCase): def setUp(self): self.project = Project('/path/to/project') self.project.set_property('dir_source_unittest_python', 'unittest') self.project.set_property('dir_source_main_python', 'src') def test_should_register_source_paths(self): system_path = ['some/python/path'] _register_test_and_source_path_and_return_test_dir(self.project, system_path) self.assertTrue('/path/to/project/unittest' in system_path) self.assertTrue('/path/to/project/src' in system_path) def test_should_put_project_sources_before_other_sources(self): system_path = ['irrelevant/sources'] _register_test_and_source_path_and_return_test_dir(self.project, system_path) test_sources_index_in_path = system_path.index('/path/to/project/unittest') main_sources_index_in_path = system_path.index('/path/to/project/src') irrelevant_sources_index_in_path = system_path.index('irrelevant/sources') self.assertTrue(test_sources_index_in_path < irrelevant_sources_index_in_path and main_sources_index_in_path < irrelevant_sources_index_in_path)
class InstallDependenciesTest(unittest.TestCase): def setUp(self): self.project = Project("unittest", ".") self.project.set_property("dir_install_logs", "any_directory") self.logger = mock(Logger) when( pybuilder.plugins.python.install_dependencies_plugin).execute_command(any_value(), any_value(), shell=True).thenReturn(0) def tearDown(self): unstub() def test_should_install_single_dependency_without_version(self): self.project.depends_on("spam") self.project.build_depends_on("eggs") install_dependencies(self.logger, self.project) verify( pybuilder.plugins.python.install_dependencies_plugin).execute_command("pip install 'spam'", any_value(), shell=True) verify( pybuilder.plugins.python.install_dependencies_plugin).execute_command("pip install 'eggs'", any_value(), shell=True)
class FlakePluginInitializationTests(TestCase): def setUp(self): self.project = Project("basedir") def test_should_set_dependency(self): mock_project = Mock(Project) initialize_flake8_plugin(mock_project) mock_project.build_depends_on.assert_called_with('flake8') def test_should_leave_user_specified_properties_when_initializing_plugin(self): expected_properties = { "flake8_break_build": True, "flake8_max_line_length": 80, "flake8_exclude_patterns": ".svn", "flake8_include_test_sources": True, "flake8_include_scripts": True } for property_name, property_value in expected_properties.items(): self.project.set_property(property_name, property_value) initialize_flake8_plugin(self.project) for property_name, property_value in expected_properties.items(): self.assertEquals( self.project.get_property("flake8_break_build"), True) self.assertEquals( self.project.get_property("flake8_max_line_length"), 80) self.assertEquals( self.project.get_property("flake8_exclude_patterns"), ".svn") self.assertEquals( self.project.get_property("flake8_include_test_sources"), True) self.assertEquals( self.project.get_property("flake8_include_scripts"), True)
class RunSonarAnalysisTest(TestCase): def setUp(self): self.project = Project("any-project") self.project.version = "0.0.1" self.project.set_property("sonarqube_project_key", "project_key") self.project.set_property("sonarqube_project_name", "project_name") self.project.set_property("dir_source_main_python", "src/main/python") self.project.set_property("dir_target", "target") self.project.set_property("dir_reports", "target/reports") def test_should_build_sonar_runner_for_project(self): self.assertEqual( build_sonar_runner(self.project).as_string, "sonar-runner -Dsonar.projectKey=project_key " "-Dsonar.projectName=project_name " "-Dsonar.projectVersion=0.0.1 " "-Dsonar.sources=src/main/python " "-Dsonar.python.coverage.reportPath=target/reports/coverage*.xml") @patch("pybuilder.plugins.python.sonarqube_plugin.SonarCommandBuilder.run") def test_should_break_build_when_sonar_runner_fails(self, run_sonar_command): run_sonar_command.return_value = Mock(exit_code=1) self.assertRaises(BuildFailedException, run_sonar_analysis, self.project, Mock()) @patch("pybuilder.plugins.python.sonarqube_plugin.SonarCommandBuilder.run") def test_should_not_break_build_when_sonar_runner_succeeds(self, run_sonar_command): run_sonar_command.return_value = Mock(exit_code=0) run_sonar_analysis(self.project, Mock())
class PythonPathTests(TestCase): def setUp(self): self.project = Project("/path/to/project") self.project.set_property("dir_source_unittest_python", "unittest") self.project.set_property("dir_source_main_python", "src") def test_should_register_source_paths(self): system_path = ["some/python/path"] _register_test_and_source_path_and_return_test_dir(self.project, system_path) self.assertTrue("/path/to/project/unittest" in system_path) self.assertTrue("/path/to/project/src" in system_path) def test_should_put_project_sources_before_other_sources(self): system_path = ["irrelevant/sources"] _register_test_and_source_path_and_return_test_dir(self.project, system_path) test_sources_index_in_path = system_path.index("/path/to/project/unittest") main_sources_index_in_path = system_path.index("/path/to/project/src") irrelevant_sources_index_in_path = system_path.index("irrelevant/sources") self.assertTrue( test_sources_index_in_path < irrelevant_sources_index_in_path and main_sources_index_in_path < irrelevant_sources_index_in_path )
class SonarCommandBuilderTests(TestCase): def setUp(self): self.project = Project("any-project") self.project.set_property("any-property-name", "any-property-value") self.sonar_builder = SonarCommandBuilder("sonar", self.project) def test_should_set_sonar_key_to_specific_value(self): self.sonar_builder.set_sonar_key("anySonarKey").to("anyValue") self.assertEqual( self.sonar_builder.as_string, "sonar -DanySonarKey=anyValue") def test_should_set_sonar_key_to_two_specific_values(self): self.sonar_builder.set_sonar_key("anySonarKey").to("anyValue").set_sonar_key("other").to("otherValue") self.assertEqual( self.sonar_builder.as_string, "sonar -DanySonarKey=anyValue -Dother=otherValue") def test_should_set_sonar_key_to_property_value(self): self.sonar_builder.set_sonar_key("anySonarKey").to_property_value("any-property-name") self.assertEqual(self.sonar_builder.as_string, "sonar -DanySonarKey=any-property-value")
def test_should_write_pycharm_file(self, os, mock_open): project = Project('basedir', name='pybuilder') project.set_property('dir_source_main_python', 'src/main/python') mock_open.return_value = MagicMock(spec=TYPE_FILE) os.path.join.side_effect = lambda first, second: first + '/' + second pycharm_generate(project, Mock()) mock_open.assert_called_with('basedir/.idea/pybuilder.iml', 'w') metadata_file = mock_open.return_value.__enter__.return_value metadata_file.write.assert_called_with("""<?xml version="1.0" encoding="UTF-8"?> <!-- This file has been generated by the PyBuilder PyCharm Plugin --> <module type="PYTHON_MODULE" version="4"> <component name="NewModuleRootManager"> <content url="file://$MODULE_DIR$"> <sourceFolder url="file://$MODULE_DIR$/src/main/python" isTestSource="false" /> </content> <orderEntry type="inheritedJdk" /> <orderEntry type="sourceFolder" forTests="false" /> </component> <component name="PyDocumentationSettings"> <option name="myDocStringFormat" value="Plain" /> </component> <component name="TestRunnerService"> <option name="projectConfiguration" value="Unittests" /> <option name="PROJECT_TEST_RUNNER" value="Unittests" /> </component> </module> """)
def test_should_run_pylint_with_custom_options(self, execute_tool): project = Project(".") init_pylint(project) project.set_property("pylint_options", ["--test", "-f", "--x=y"]) execute_pylint(project, Mock(Logger)) execute_tool.assert_called_with(project, "pylint", ["pylint", "--test", "-f", "--x=y"], True)
def test_find_files(self, discover_mock): project = Project('.') project.set_property('dir_source_cmdlinetest', '/any/dir') project.set_property('cram_test_file_glob', '*.t') expected = ['/any/dir/test.cram'] discover_mock.return_value = expected received = _find_files(project) self.assertEquals(expected, received) discover_mock.assert_called_once_with('/any/dir', '*.t')
def test_should_merge_additional_environment_into_current_one(self): project = Project('any-directory') project.set_property('integrationtest_additional_environment', {'foo': 'bar'}) environment = {'bar': 'baz'} add_additional_environment_keys(environment, project) self.assertEqual(environment, {'foo': 'bar', 'bar': 'baz'})
def test_should_override_current_environment_keys_with_additional_environment( self): project = Project('any-directory') project.set_property('integrationtest_additional_environment', {'foo': 'mooh'}) environment = {'foo': 'bar'} add_additional_environment_keys(environment, project) self.assertEqual(environment, {'foo': 'mooh'})
class InstallRuntimeDependenciesTest(unittest.TestCase): def setUp(self): self.project = Project("unittest", ".") self.project.set_property("dir_install_logs", "any_directory") self.logger = Mock(Logger) initialize_install_dependencies_plugin(self.project) @patch( "pybuilder.plugins.python.install_dependencies_plugin.execute_command", return_value=0) def test_should_install_multiple_dependencies(self, exec_command, get_package_version): self.project.depends_on("spam") self.project.depends_on("eggs") self.project.depends_on_requirements("requirements.txt") install_runtime_dependencies(self.logger, self.project) exec_command(PIP_EXEC_STANZA + ["install", 'spam'], ANY, shell=False) exec_command(PIP_EXEC_STANZA + ["install", 'eggs'], ANY, shell=False) exec_command(PIP_EXEC_STANZA + ["install", '-r', 'requirements.txt'], ANY, shell=False) @patch( "pybuilder.plugins.python.install_dependencies_plugin.execute_command", return_value=0) def test_should_install_multiple_dependencies_locally( self, exec_command, get_package_version): self.project.depends_on("spam") self.project.depends_on("eggs") self.project.depends_on("foo") self.project.set_property("install_dependencies_local_mapping", { "spam": "any-dir", "eggs": "any-other-dir" }) install_runtime_dependencies(self.logger, self.project) exec_command(PIP_EXEC_STANZA + ["install", "-t", "any-dir", 'spam'], ANY, shell=False) exec_command(PIP_EXEC_STANZA + ["install", "-t", "any-other-dir", 'eggs'], ANY, shell=False) exec_command(PIP_EXEC_STANZA + ["install", 'foo'], ANY, shell=False)
def test_should_run_pytddmon(self, subprocess): subprocess.check_output.side_effect = lambda *args, **kwargs: ' '.join(a for a in args) project = Project('/path/to/project', name='pybuilder') project.set_property('dir_source_main_python', 'path/to/source') project.set_property( 'dir_source_unittest_python', 'src/unittest/python') pytddmon_plugin.pytddmon(project, Mock()) subprocess.Popen.assert_called_with( ['which python', 'which pytddmon.py', '--no-pulse'], shell=False, cwd='src/unittest/python', env=ANY)
def test_should_override_current_environment_keys_with_additional_environment(self): project = Project('any-directory') project.set_property( 'integrationtest_additional_environment', {'foo': 'mooh'}) environment = {'foo': 'bar'} add_additional_environment_keys(environment, project) self.assertEqual(environment, { 'foo': 'mooh' })
def test_should_write_pydev_files(self, os, mock_open): project = Project('basedir', name='pybuilder') project.set_property('dir_source_main_python', 'src/main/python') init_pydev_plugin(project) mock_open.return_value = MagicMock(spec=TYPE_FILE) os.path.join.side_effect = lambda first, second: first + '/' + second pydev_generate(project, Mock()) self.assertEqual(mock_open.call_args_list, [ call('basedir/.project', 'w'), call('basedir/.pydevproject', 'w') ]) metadata_file = mock_open.return_value.__enter__.return_value self.assertEqual(metadata_file.write.call_args_list, [ call("""<?xml version="1.0" encoding="UTF-8"?> <!-- This file has been generated by the PyBuilder Pydev Plugin --> <projectDescription> <name>pybuilder</name> <comment></comment> <projects> </projects> <buildSpec> <buildCommand> <name>org.python.pydev.PyDevBuilder</name> <arguments> </arguments> </buildCommand> </buildSpec> <natures> <nature>org.python.pydev.pythonNature</nature> </natures> </projectDescription> """), call("""<?xml version="1.0" encoding="UTF-8" standalone="no"?> <?eclipse-pydev version="1.0"?> <!-- This file has been generated by the PyBuilder Pydev Plugin --> <pydev_project> <pydev_property name="org.python.pydev.PYTHON_PROJECT_INTERPRETER">Default</pydev_property> <pydev_property name="org.python.pydev.PYTHON_PROJECT_VERSION">python 2.7</pydev_property> <pydev_pathproperty name="org.python.pydev.PROJECT_SOURCE_PATH"> \t\t<path>/pybuilder/src/main/python</path> </pydev_pathproperty> </pydev_project> """) ])
def test_ensure_project_properties_are_logged_when_calling_log_project_properties(self): project = Project("spam") project.set_property("spam", "spam") project.set_property("eggs", "eggs") self.reactor.project = project self.reactor.log_project_properties() call_args = self.logger.debug.call_args self.assertEqual(call_args[0][0], "Project properties: %s") self.assertTrue("basedir : spam" in call_args[0][1]) self.assertTrue("eggs : eggs" in call_args[0][1]) self.assertTrue("spam : spam" in call_args[0][1])
def test_ensure_project_properties_are_logged_when_calling_log_project_properties(self): project = Project("spam") project.set_property("spam", "spam") project.set_property("eggs", "eggs") self.reactor.project = project self.reactor.log_project_properties() call_args = self.logger.debug.call_args self.assertEquals(call_args[0][0], "Project properties: %s") self.assertTrue("basedir : spam" in call_args[0][1]) self.assertTrue("eggs : eggs" in call_args[0][1]) self.assertTrue("spam : spam" in call_args[0][1])
def test_should_merge_additional_environment_into_current_one(self): project = Project('any-directory') project.set_property( 'integrationtest_additional_environment', {'foo': 'bar'}) environment = {'bar': 'baz'} add_additional_environment_keys(environment, project) self.assertEqual(environment, { 'foo': 'bar', 'bar': 'baz' })
class InstallRuntimeDependenciesTest(unittest.TestCase): def setUp(self): self.project = Project("unittest", ".") self.project.set_property("dir_install_logs", "any_directory") self.logger = mock(Logger) when( pybuilder.plugins.python.install_dependencies_plugin).execute_command(any_value(), any_value(), shell=True).thenReturn(0) def tearDown(self): unstub() def test_should_install_multiple_dependencies(self): self.project.depends_on("spam") self.project.depends_on("eggs") self.project.depends_on_requirements("requirements.txt") install_runtime_dependencies(self.logger, self.project) verify( pybuilder.plugins.python.install_dependencies_plugin).execute_command("pip install 'spam'", any_value(), shell=True) verify( pybuilder.plugins.python.install_dependencies_plugin).execute_command("pip install 'eggs'", any_value(), shell=True) verify( pybuilder.plugins.python.install_dependencies_plugin).execute_command("pip install '-rrequirements.txt'", any_value(), shell=True) def test_should_install_multiple_dependencies_locally(self): self.project.depends_on("spam") self.project.depends_on("eggs") self.project.depends_on("foo") self.project.set_property("install_dependencies_local_mapping", { "spam": "any-dir", "eggs": "any-other-dir" }) install_runtime_dependencies(self.logger, self.project) verify( pybuilder.plugins.python.install_dependencies_plugin).execute_command("pip install -t any-dir 'spam'", any_value(), shell=True) verify( pybuilder.plugins.python.install_dependencies_plugin).execute_command("pip install -t any-other-dir 'eggs'", any_value(), shell=True) verify( pybuilder.plugins.python.install_dependencies_plugin).execute_command("pip install 'foo'", any_value(), shell=True)
class TestProxyTests(unittest.TestCase): def setUp(self): self.project = Project('basedir') def test_should_use_teamcity_proxy_if_project_property_is_set(self): self.project.set_property('teamcity_output', True) proxy = test_proxy_for(self.project) self.assertEquals(type(proxy), TeamCityTestProxy) def test_should_use_default_proxy_if_project_property_is_not_set(self): self.project.set_property('teamcity_output', False) proxy = test_proxy_for(self.project) self.assertEquals(type(proxy), TestProxy) def test_should_use_default_proxy_if_project_property_is_set_but_coverage_is_running(self): self.project.set_property('teamcity_output', True) self.project.set_property('__running_coverage', True) proxy = test_proxy_for(self.project) self.assertEquals(type(proxy), TestProxy)
class TestsWithS3(TestCase): def setUp(self): self.tempdir = tempfile.mkdtemp(prefix='palp-') self.project = Project( basedir=self.tempdir, name='palp', version='123') self.project.set_property('dir_target', 'target') self.bucket_name = 'palp-lambda-zips' self.project.set_property( 'lambda_file_access_control', 'bucket-owner-full-control') self.project.set_property('bucket_name', self.bucket_name) self.project.set_property('bucket_prefix', '') self.dir_target = os.path.join(self.tempdir, 'target') os.mkdir(self.dir_target) self.zipfile_name = os.path.join(self.dir_target, 'palp.zip') self.test_data = b'testdata' with open(self.zipfile_name, 'wb') as fp: fp.write(self.test_data) self.my_mock_s3 = mock_s3() self.my_mock_s3.start() self.s3 = boto3.resource('s3') self.s3.create_bucket(Bucket=self.bucket_name) def tearDown(self): shutil.rmtree(self.tempdir) self.my_mock_s3.stop()
def test_running_plugin_failure_no_tests(self, read_file_mock, report_mock, find_files_mock, command_mock): project = Project('.') project.set_property('verbose', True) project.set_property('dir_source_main_python', 'python') project.set_property('dir_source_main_scripts', 'scripts') project.set_property("cram_fail_if_no_tests", True) project._plugin_env = {} logger = Mock() reactor = Mock() reactor.python_env_registry = {} reactor.python_env_registry["pybuilder"] = pyb_env = Mock() pyb_env.environ = {} execute_mock = pyb_env.execute_command = Mock() command_mock.return_value = ['cram'] find_files_mock.return_value = [] report_mock.return_value = 'report_file' read_file_mock.return_value = ['test failes for file', '# results'] execute_mock.return_value = 1 self.assertRaises(BuildFailedException, run_cram_tests, project, logger, reactor) execute_mock.assert_not_called() expected_info_calls = [ call('Running Cram command line tests'), ] self.assertEqual(expected_info_calls, logger.info.call_args_list)
class TestProxyTests(unittest.TestCase): def setUp(self): self.project = Project('basedir') def test_should_use_teamcity_proxy_if_project_property_is_set(self): self.project.set_property('teamcity_output', True) proxy = test_proxy_for(self.project) self.assertEquals(type(proxy), TeamCityTestProxy) def test_should_use_default_proxy_if_project_property_is_not_set(self): self.project.set_property('teamcity_output', False) proxy = test_proxy_for(self.project) self.assertEquals(type(proxy), TestProxy) def test_should_use_default_proxy_if_project_property_is_set_but_coverage_is_running( self): self.project.set_property('teamcity_output', True) self.project.set_property('__running_coverage', True) proxy = test_proxy_for(self.project) self.assertEquals(type(proxy), TestProxy)
def test_ensure_project_properties_are_logged_when_calling_log_project_properties(self): project = Project("spam") project.set_property("spam", "spam") project.set_property("eggs", "eggs") self.reactor.project = project self.reactor.log_project_properties() verify(self.logger).debug( "Project properties: %s", contains("basedir : spam")) verify(self.logger).debug( "Project properties: %s", contains("eggs : eggs")) verify(self.logger).debug( "Project properties: %s", contains("spam : spam"))
def test_running_plugin_cram_from_target(self, execute_mock, read_file_mock, os_mock, report_mock, find_files_mock, command_mock ): project = Project('.') project.set_property('cram_run_test_from_target', True) project.set_property('dir_dist', 'python') project.set_property('dir_dist_scripts', 'scripts') project.set_property('verbose', False) logger = Mock() command_mock.return_value = ['cram'] find_files_mock.return_value = ['test1.cram', 'test2.cram'] report_mock.return_value = 'report_file' os_mock.copy.return_value = {} read_file_mock.return_value = ['test failes for file', '# results'] execute_mock.return_value = 0 run_cram_tests(project, logger) execute_mock.assert_called_once_with( ['cram', 'test1.cram', 'test2.cram'], 'report_file', error_file_name='report_file', env={'PYTHONPATH': './python:', 'PATH': './python/scripts:'} ) expected_info_calls = [call('Running Cram command line tests'), call('Cram tests were fine'), call('results'), ] self.assertEquals(expected_info_calls, logger.info.call_args_list)
def test_running_plugin_failure_no_tests(self, execute_mock, read_file_mock, os_mock, report_mock, find_files_mock, command_mock ): project = Project('.') project.set_property('verbose', True) project.set_property('dir_source_main_python', 'python') project.set_property('dir_source_main_scripts', 'scripts') project.set_property("cram_fail_if_no_tests", True) logger = Mock() command_mock.return_value = ['cram'] find_files_mock.return_value = [] report_mock.return_value = 'report_file' os_mock.copy.return_value = {} read_file_mock.return_value = ['test failes for file', '# results'] execute_mock.return_value = 1 self.assertRaises( BuildFailedException, run_cram_tests, project, logger) execute_mock.assert_not_called() expected_info_calls = [call('Running Cram command line tests'), ] self.assertEquals(expected_info_calls, logger.info.call_args_list)
class SemVerGitPluginInitializationTests(TestCase): """ Test initialize_cram_console_scripts """ def setUp(self): self.project = Project("basedir") def test_should_set_default_properties(self): # pylint: disable=invalid-name """ We need to init properties""" initialize_semver_git_tag(self.project) self.assertEquals( self.project.get_property('semver_git_tag_increment_part'), 'patch') self.assertEquals( self.project.get_property('semver_git_tag_version_prefix'), '') def test_should_leave_user_specified_properties(self): # pylint: disable=invalid-name """ We need to keep user-defined properties""" self.project.set_property('semver_git_tag_increment_part', 'minor') self.project.set_property('semver_git_tag_repo_dir', '/some/dir') self.project.set_property('semver_git_tag_changelog', 'dir/CHANGELOG.md') self.project.set_property('semver_git_tag_version_prefix', 'v') initialize_semver_git_tag(self.project) self.assertEquals( self.project.get_property('semver_git_tag_increment_part'), 'minor') self.assertEquals( self.project.get_property('semver_git_tag_repo_dir'), '/some/dir') self.assertEquals( self.project.get_property('semver_git_tag_changelog'), 'dir/CHANGELOG.md') self.assertEquals( self.project.get_property('semver_git_tag_version_prefix'), 'v')
def test_should_write_pydev_files(self, os, mock_open): project = Project('basedir', name='pybuilder') project.set_property('dir_source_main_python', 'src/main/python') init_pydev_plugin(project) mock_open.return_value = MagicMock(spec=TYPE_FILE) os.path.join.side_effect = lambda first, second: first + '/' + second pydev_generate(project, Mock()) self.assertEqual(mock_open.call_args_list, [call('basedir/.project', 'w'), call('basedir/.pydevproject', 'w')]) metadata_file = mock_open.return_value.__enter__.return_value self.assertEqual(metadata_file.write.call_args_list, [call("""<?xml version="1.0" encoding="UTF-8"?> <!-- This file has been generated by the PyBuilder Pydev Plugin --> <projectDescription> <name>pybuilder</name> <comment></comment> <projects> </projects> <buildSpec> <buildCommand> <name>org.python.pydev.PyDevBuilder</name> <arguments> </arguments> </buildCommand> </buildSpec> <natures> <nature>org.python.pydev.pythonNature</nature> </natures> </projectDescription> """), call("""<?xml version="1.0" encoding="UTF-8" standalone="no"?> <?eclipse-pydev version="1.0"?> <!-- This file has been generated by the PyBuilder Pydev Plugin --> <pydev_project> <pydev_property name="org.python.pydev.PYTHON_PROJECT_INTERPRETER">Default</pydev_property> <pydev_property name="org.python.pydev.PYTHON_PROJECT_VERSION">python 2.7</pydev_property> <pydev_pathproperty name="org.python.pydev.PROJECT_SOURCE_PATH"> \t\t<path>/pybuilder/src/main/python</path> </pydev_pathproperty> </pydev_project> """)])
class PytestPluginInitializationTests(TestCase): def setUp(self): self.project = Project("basedir") self.project.set_property("pytest_extra_args", ["pytest_stub"]) self.project.set_property("dir_source_main_python", "") def test_should_set_default_properties(self): initialize_pytest_coverage(self.project) expected_default_properties = { "pytest_coverage_skip_covered": False, "pytest_coverage_xml": False, "pytest_coverage_html": False, "pytest_coverage_annotate": False, "pytest_coverage_break_build_threshold": 0 } for property_name, property_value in expected_default_properties.items( ): self.assertEquals(self.project.get_property(property_name), property_value) def test_should_set_enable_default_properties(self): initialize_pytest_coverage(self.project) enable_pytest_coverage(self.project, Mock()) self.assertEquals( self.project.get_property("pytest_extra_args"), ["pytest_stub", "--cov-branch", "--cov-report=term-missing"]) @patch("pybuilder_pytest_coverage.discover_modules", return_value=['module1', 'module2']) def test_should_leave_user_specified_properties_when_initializing_plugin( self, discover_modules): self.project.set_property("dir_reports", "target/reports") expected_properties = { "pytest_coverage_skip_covered": True, "pytest_coverage_xml": True, "pytest_coverage_html": True, "pytest_coverage_annotate": True, "pytest_coverage_break_build_threshold": 50 } for property_name, property_value in expected_properties.items(): self.project.set_property(property_name, property_value) initialize_pytest_coverage(self.project) for property_name, property_value in expected_properties.items(): self.assertEquals(self.project.get_property(property_name), property_value) enable_pytest_coverage(self.project, Mock()) self.assertEquals(self.project.get_property("pytest_extra_args"), [ "pytest_stub", "--cov=module1", "--cov=module2", "--cov-branch", "--cov-report=term-missing:skip-covered", "--cov-report=xml:basedir/target/reports/pytest_coverage.xml", "--cov-report=html:basedir/target/reports/pytest_coverage_html", "--cov-report=annotate:basedir/target/reports/pytest_coverage_annotate", "--cov-fail-under=50" ])
class InstallDependenciesTest(unittest.TestCase): def setUp(self): self.project = Project("unittest", ".") self.project.set_property("dir_install_logs", "any_directory") self.logger = Mock(Logger) initialize_install_dependencies_plugin(self.project) @patch("pybuilder.plugins.python.install_dependencies_plugin.execute_command", return_value=0) def test_should_install_single_dependency_without_version(self, exec_command, get_package_version): self.project.depends_on("spam") self.project.build_depends_on("eggs") install_dependencies(self.logger, self.project) exec_command(PIP_EXEC_STANZA + ["install", 'spam'], ANY, shell=False) exec_command(PIP_EXEC_STANZA + ["install", 'eggs'], ANY, shell=False)
class InstallRuntimeDependenciesTest(unittest.TestCase): def setUp(self): self.project = Project("unittest", ".") self.project.set_property("dir_install_logs", "any_directory") self.logger = mock(Logger) when(pybuilder.plugins.python.install_dependencies_plugin).execute_command( any_value(), any_value(), shell=True ).thenReturn(0) def tearDown(self): unstub() def test_should_install_multiple_dependencies(self): self.project.depends_on("spam") self.project.depends_on("eggs") self.project.depends_on_requirements("requirements.txt") install_runtime_dependencies(self.logger, self.project) verify(pybuilder.plugins.python.install_dependencies_plugin).execute_command( "pip install 'spam'", any_value(), shell=True ) verify(pybuilder.plugins.python.install_dependencies_plugin).execute_command( "pip install 'eggs'", any_value(), shell=True ) verify(pybuilder.plugins.python.install_dependencies_plugin).execute_command( "pip install '-rrequirements.txt'", any_value(), shell=True ) def test_should_install_multiple_dependencies_locally(self): self.project.depends_on("spam") self.project.depends_on("eggs") self.project.depends_on("foo") self.project.set_property("install_dependencies_local_mapping", {"spam": "any-dir", "eggs": "any-other-dir"}) install_runtime_dependencies(self.logger, self.project) verify(pybuilder.plugins.python.install_dependencies_plugin).execute_command( "pip install -t any-dir 'spam'", any_value(), shell=True ) verify(pybuilder.plugins.python.install_dependencies_plugin).execute_command( "pip install -t any-other-dir 'eggs'", any_value(), shell=True ) verify(pybuilder.plugins.python.install_dependencies_plugin).execute_command( "pip install 'foo'", any_value(), shell=True )
def test_reinitialize_pypi_server_plugin(from_pypirc, mocker): # pylint: disable=invalid-name,redefined-outer-name """ Check reinitialize_pypi_server_plugin function""" (pypi_server, pypi_url) = from_pypirc[0] project = Project("basedir") project.set_property('pypi_server', pypi_server) logger_mock = mocker.Mock() reinitialize_pypi_server_plugin(project, logger_mock) assert project.get_property('distutils_upload_repository') == pypi_server assert project.get_property('install_dependencies_index_url') == pypi_url logger_mock.warn.assert_called_once_with( "Property `pypi_server` defined on initialize stage. " "Please use command line `pyb ... -P pypi_server=...`, " "otherwise some packages could be downloaded " "from default PyPi index.") logger_mock.info.assert_called_once_with( "Repository `%s` will be used to install_dependencies and " "distutils plugins." % pypi_server)
class RonnPluginInitializationTests(TestCase): def setUp(self): self.project = Project("basedir") def test_should_leave_user_specified_properties_when_initializing_plugin( self): expected_properties = { "dir_manpages": "foo", "manpage_source": "bar", "manpage_section": 1 } for property_name, property_value in expected_properties.items(): self.project.set_property(property_name, property_value) init_ronn_manpage_plugin(self.project) for property_name, property_value in expected_properties.items(): self.assertEquals(self.project.get_property(property_name), property_value) @patch('pybuilder.plugins.ronn_manpage_plugin.assert_can_execute') def test_should_check_that_ronn_is_executable(self, mock_assert_can_execute): mock_logger = Mock(Logger) assert_ronn_is_executable(mock_logger) mock_assert_can_execute.assert_called_with( caller='plugin ronn_manpage_plugin', command_and_arguments=['ronn', '--version'], prerequisite='ronn') @patch('pybuilder.plugins.ronn_manpage_plugin.assert_can_execute') def test_should_check_that_gzip_is_executable(self, mock_assert_can_execute): mock_logger = Mock(Logger) assert_gzip_is_executable(mock_logger) mock_assert_can_execute.assert_called_with( caller="plugin ronn_manpage_plugin", command_and_arguments=["gzip", "--version"], prerequisite="gzip")
class RonnPluginInitializationTests(TestCase): def setUp(self): self.project = Project("basedir") def test_should_leave_user_specified_properties_when_initializing_plugin(self): expected_properties = { "dir_manpages": "foo", "manpage_source": "bar", "manpage_section": 1 } for property_name, property_value in expected_properties.items(): self.project.set_property(property_name, property_value) init_ronn_manpage_plugin(self.project) for property_name, property_value in expected_properties.items(): self.assertEquals( self.project.get_property(property_name), property_value) @patch('pybuilder.plugins.ronn_manpage_plugin.assert_can_execute') def test_should_check_that_ronn_is_executable(self, mock_assert_can_execute): mock_logger = Mock(Logger) assert_ronn_is_executable(mock_logger) mock_assert_can_execute.assert_called_with( caller='plugin ronn_manpage_plugin', command_and_arguments=['ronn', '--version'], prerequisite='ronn') @patch('pybuilder.plugins.ronn_manpage_plugin.assert_can_execute') def test_should_check_that_gzip_is_executable(self, mock_assert_can_execute): mock_logger = Mock(Logger) assert_gzip_is_executable(mock_logger) mock_assert_can_execute.assert_called_with( caller="plugin ronn_manpage_plugin", command_and_arguments=["gzip", "--version"], prerequisite="gzip")
def test_should_generate_sphinx_build_command_per_project_properties(self): project = Project('basedir') project.set_property("sphinx_builder", "html") project.set_property("sphinx_config_path", "docs/") project.set_property("sphinx_source_dir", "docs/") project.set_property("sphinx_output_dir", "docs/_build/") sphinx_build_command = get_sphinx_build_command(project) self.assertEqual(sphinx_build_command, "sphinx-build -b html -c basedir/docs/ basedir/docs/ basedir/docs/_build/")
class UtilsTest(unittest.TestCase): def setUp(self): self.project = Project('/path/to/project') self.project.set_property('dir_source_unittest_python', 'src/unittest/python') self.project.set_property('dir_target', 'target') def test_importDirs(self): cwd = os.getcwd() dirs = utils.getImportantDirs(self.project) # test_dir self.assertEquals( dirs[0], cwd + "/" + self.project.get_property('dir_source_unittest_python')) # log_dir self.assertEquals(dirs[1], cwd + "/target/allure_report_logs")
class FlakePluginInitializationTests(TestCase): def setUp(self): self.project = Project("basedir") def test_should_set_dependency(self): mock_project = Mock(Project) initialize_flake8_plugin(mock_project) mock_project.plugin_depends_on.assert_called_with('flake8', "~=3.2") def test_should_leave_user_specified_properties_when_initializing_plugin( self): expected_properties = { "flake8_break_build": True, "flake8_max_line_length": 80, "flake8_include_patterns": "*.py", "flake8_exclude_patterns": ".svn", "flake8_include_test_sources": True, "flake8_include_scripts": True, "flake8_max_complexity": 10 } for property_name, property_value in expected_properties.items(): self.project.set_property(property_name, property_value) initialize_flake8_plugin(self.project) for property_name, property_value in expected_properties.items(): self.assertEquals(self.project.get_property("flake8_break_build"), True) self.assertEquals( self.project.get_property("flake8_max_line_length"), 80) self.assertEquals( self.project.get_property("flake8_include_patterns"), "*.py") self.assertEquals( self.project.get_property("flake8_exclude_patterns"), ".svn") self.assertEquals( self.project.get_property("flake8_include_test_sources"), True) self.assertEquals( self.project.get_property("flake8_include_scripts"), True) self.assertEquals( self.project.get_property("flake8_max_complexity"), 10)
def create_project(): project = Project("/") project.build_depends_on("testingframework") project.depends_on("sometool") project.depends_on( "pyassert", url= "https://github.com/downloads/halimath/pyassert/pyassert-0.2.2.tar.gz") project.name = "Spam and Eggs" project.version = "1.2.3" project.summary = "This is a simple integration-test for distutils plugin." project.description = "As you might have guessed we have nothing to say here." project.authors = [ Author("Udo Juettner", "*****@*****.**"), Author("Michael Gruber", "*****@*****.**") ] project.license = "WTFPL" project.url = "http://github.com/pybuilder/pybuilder" project.urls = { "b": "http://b", "a": "http://a", } project.explicit_namespaces = ["foo.bar", "quick.brown.fox"] def return_dummy_list(): return ["spam", "eggs"] project.list_scripts = return_dummy_list project.list_packages = return_dummy_list project.list_modules = return_dummy_list project.set_property( "distutils_classifiers", ["Development Status :: 5 - Beta", "Environment :: Console"]) project.install_file("dir", "file1") project.install_file("dir", "file2") project.include_file("spam", "eggs") project.set_property("distutils_zip_safe", True) return project
def test_should_generate_command_abiding_to_configuration(self): project = Project('egg') project.set_property("dir_manpages", "docs/man") project.set_property("manpage_source", "README.md") project.set_property("manpage_section", 1) self.assertEqual(build_generate_manpages_command(project), 'ronn -r --pipe README.md | gzip -9 > docs/man/egg.1.gz')
def test_should_generate_sphinx_build_command_per_project_properties(self): project = Project('basedir') project.set_property("sphinx_builder", "html") project.set_property("sphinx_config_path", "docs/") project.set_property("sphinx_source_dir", "docs/") project.set_property("sphinx_output_dir", "docs/_build/") sphinx_build_command = get_sphinx_build_command(project) self.assertEqual( sphinx_build_command, "sphinx-build -b html -c basedir/docs/ basedir/docs/ basedir/docs/_build/" )
class RonnPluginInitializationTests(TestCase): def setUp(self): self.project = Project("basedir") self.logger = Mock(Logger) self.reactor = Mock() self.pyb_env = pyb_env = Mock() self.reactor.python_env_registry = {"pybuilder": pyb_env} self.reactor.pybuilder_venv = pyb_env def test_should_leave_user_specified_properties_when_initializing_plugin( self): expected_properties = { "dir_manpages": "foo", "manpage_source": "bar", "manpage_section": 1 } for property_name, property_value in expected_properties.items(): self.project.set_property(property_name, property_value) init_ronn_manpage_plugin(self.project) for property_name, property_value in expected_properties.items(): self.assertEqual(self.project.get_property(property_name), property_value) def test_should_check_that_ronn_is_executable(self): assert_ronn_is_executable(self.project, self.logger, self.reactor) self.pyb_env.verify_can_execute.assert_called_with( caller='plugin ronn_manpage_plugin', command_and_arguments=['ronn', '--version'], prerequisite='ronn') def test_should_check_that_gzip_is_executable(self): assert_gzip_is_executable(self.project, self.logger, self.reactor) self.pyb_env.verify_can_execute.assert_called_with( caller="plugin ronn_manpage_plugin", command_and_arguments=["gzip", "--version"], prerequisite="gzip")
class PackageLambdaCodeTest(TestCase): def setUp(self): self.tempdir = tempfile.mkdtemp(prefix='palp-') self.testdir = os.path.join(self.tempdir, 'package_lambda_code_test') self.project = Project(basedir=self.testdir, name='palp') shutil.copytree('src/unittest/python/package_lambda_code_test/', self.testdir) self.project.set_property('dir_target', 'target') self.project.set_property('dir_source_main_python', 'src/main/python') self.project.set_property('dir_source_main_scripts', 'src/main/scripts') self.dir_target = os.path.join(self.testdir, 'target') self.zipfile_name = os.path.join(self.dir_target, 'palp.zip') def tearDown(self): shutil.rmtree(self.tempdir) @mock.patch('pybuilder_aws_lambda_plugin.prepare_dependencies_dir') def test_package_lambda_assembles_zipfile_correctly(self, prepare_dependencies_dir_mock): package_lambda_code(self.project, mock.MagicMock(Logger)) zf = zipfile.ZipFile(self.zipfile_name) expected = sorted(['test_dependency_module.py', 'test_dependency_package/__init__.py', 'test_package_directory/__init__.py', 'test_module_file.py', 'test_script.py']) self.assertEqual(sorted(zf.namelist()), expected)
def test_running_plugin_fails(self, execute_mock, read_file_mock, os_mock, report_mock, find_files_mock, command_mock): project = Project('.') project.set_property('verbose', False) project.set_property('dir_source_main_python', 'python') project.set_property('dir_source_main_scripts', 'scripts') logger = Mock() command_mock.return_value = ['cram'] find_files_mock.return_value = ['test1.cram', 'test2.cram'] report_mock.return_value = 'report_file' os_mock.copy.return_value = {} read_file_mock.return_value = ['test failes for file', '# results'] execute_mock.return_value = 1 self.assertRaises(BuildFailedException, run_cram_tests, project, logger) execute_mock.assert_called_once_with( ['cram', 'test1.cram', 'test2.cram'], 'report_file', error_file_name='report_file', env={ 'PYTHONPATH': './python:', 'PATH': './scripts:' }) expected_info_calls = [ call('Running Cram command line tests'), ] expected_error_calls = [ call('Cram tests failed!'), call('results'), call("See: 'report_file' for details"), ] self.assertEquals(expected_info_calls, logger.info.call_args_list) self.assertEquals(expected_error_calls, logger.error.call_args_list)
class UploadZipToS3Test(TestCase): def setUp(self): self.tempdir = tempfile.mkdtemp(prefix='palp-') self.project = Project(basedir=self.tempdir, name='palp') self.project.set_property('dir_target', 'target') self.project.set_property('bucket_name', 'palp-lambda-zips') self.project.set_property('lambda_file_access_control', 'bucket-owner-full-control') self.dir_target = os.path.join(self.tempdir, 'target') os.mkdir(self.dir_target) self.zipfile_name = os.path.join(self.dir_target, 'palp.zip') self.test_data = b'testdata' with open(self.zipfile_name, 'wb') as fp: fp.write(self.test_data) def tearDown(self): shutil.rmtree(self.tempdir) @mock_s3 @mock.patch('pybuilder_aws_lambda_plugin.timestamp') def test_if_file_was_uploaded_to_s3(self, timestamp_mock): timestamp_mock.return_value = '197001010000' s3 = boto3.resource('s3') s3.create_bucket(Bucket='palp-lambda-zips') upload_zip_to_s3(self.project, mock.MagicMock(Logger)) s3_object = [o for o in s3.Bucket('palp-lambda-zips').objects.all()][0] self.assertEqual(s3_object.bucket_name, 'palp-lambda-zips') self.assertEqual(s3_object.key, 'palp-197001010000.zip') @mock_s3 @mock.patch('pybuilder_aws_lambda_plugin.timestamp') def test_handle_failure_if_no_such_bucket(self, timestamp_mock): pass
class InstallDependenciesTest(unittest.TestCase): def setUp(self): self.project = Project("unittest", ".") self.project.set_property("dir_install_logs", "any_directory") self.logger = mock(Logger) when(pybuilder.plugins.python.install_dependencies_plugin ).execute_command(any_value(), any_value(), shell=True).thenReturn(0) def tearDown(self): unstub() def test_should_install_single_dependency_without_version(self): self.project.depends_on("spam") self.project.build_depends_on("eggs") install_dependencies(self.logger, self.project) verify(pybuilder.plugins.python.install_dependencies_plugin ).execute_command("pip install 'spam'", any_value(), shell=True) verify(pybuilder.plugins.python.install_dependencies_plugin ).execute_command("pip install 'eggs'", any_value(), shell=True)
def create_test_project(self, name, content_dict): """ Create test PyB project with specific content. Key into `content_dict` specifies file name and value contains content""" project_dir = path_join(self.tmp_test_folder, name) mkdir(project_dir) test_project = Project(project_dir) tests_dir = path_join(project_dir, 'tests') mkdir(tests_dir) test_project.set_property('dir_source_pytest_python', 'tests') initialize_pytest_plugin(test_project) src_dir = path_join(project_dir, 'src') mkdir(src_dir) test_project.set_property('dir_source_main_python', 'src') for file_name, content in content_dict.items(): file_out = open(path_join(tests_dir, file_name), 'w') file_out.write(content) file_out.flush() file_out.close() return test_project
class UpdateVersionTests(TestCase): """ Test update_version_from_git_tag function""" def setUp(self): self.project = Project("basedir") self.logger = Mock() @patch("pybuilder_semver_git_tag.set_version_from_git_tag") @patch("pybuilder_semver_git_tag._get_repo_name") def test_force_and_update(self, _get_repo_name, # pylint: disable=unused-argument set_version_from_git_tag_mock): """ Test force set and update after that""" force_semver_git_tag_plugin(self.project, self.logger) self.project.set_property('semver_git_tag_increment_part', 'minor') update_version_from_git_tag(self.project, self.logger) self.assertEqual(set_version_from_git_tag_mock.call_count, 2) self.assertEqual(self.logger.info.call_count, 2) self.logger.warn.assert_called_once_with( "Property `semver_git_tag_increment_part` was changed. " "For better compatibility recommended to use " "command line `pyb ... -P semver_git_tag_increment_part=...`, " "otherwise some version-related properties could " "be spoiled." )
class RunSonarAnalysisTest(TestCase): def setUp(self): self.project = Project("any-project") self.project.version = "0.0.1" self.project.set_property("sonarqube_project_key", "project_key") self.project.set_property("sonarqube_project_name", "project_name") self.project.set_property("dir_source_main_python", "src/main/python") self.project.set_property("dir_target", "target") self.project.set_property("dir_reports", "target/reports") self.reactor = Mock(Reactor) pyb_env = Mock() self.reactor.python_env_registry = {"pybuilder": pyb_env} def test_should_build_sonar_scanner_for_project(self): self.assertEqual( build_sonar_scanner(self.project, self.reactor).as_string, "sonar-scanner -Dsonar.projectKey=project_key " "-Dsonar.projectName=project_name " "-Dsonar.projectVersion=0.0.1 " "-Dsonar.sources=src/main/python " "-Dsonar.python.coverage.reportPath=%s" % nc("target/reports/coverage*.xml")) @patch("pybuilder.plugins.python.sonarqube_plugin.SonarCommandBuilder.run") def test_should_break_build_when_sonar_scanner_fails( self, run_sonar_command): run_sonar_command.return_value = Mock(exit_code=1) self.assertRaises(BuildFailedException, run_sonar_analysis, self.project, Mock(), self.reactor) @patch("pybuilder.plugins.python.sonarqube_plugin.SonarCommandBuilder.run") def test_should_not_break_build_when_sonar_scanner_succeeds( self, run_sonar_command): run_sonar_command.return_value = Mock(exit_code=0) run_sonar_analysis(self.project, Mock(), self.reactor)