예제 #1
0
    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': nc('./python:'),
                'PATH': nc('./python/scripts:')
            })
        expected_info_calls = [
            call('Running Cram command line tests'),
            call('Cram tests were fine'),
            call('results'),
        ]
        self.assertEqual(expected_info_calls, logger.info.call_args_list)
예제 #2
0
    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': nc('./python:'), 'PATH': nc('./python/scripts:')}
        )
        expected_info_calls = [call('Running Cram command line tests'),
                               call('Cram tests were fine'),
                               call('results'),
                               ]
        self.assertEqual(expected_info_calls, logger.info.call_args_list)
예제 #3
0
        def patched_preparation_data(name):
            d = old_preparation_data(name)
            sys_path = d["sys_path"]

            # Python 2
            if sys_path is sys.path:
                sys_path = list(sys_path)
                d["sys_path"] = sys_path

            exec_prefix = nc(sys.exec_prefix) + sep

            trailing_paths = []
            for idx, path in enumerate(sys_path):
                nc_path = nc(path)

                if nc_path.startswith(exec_prefix):
                    sys_path[idx] = pyenv.env_dir + sep + path[len(exec_prefix
                                                                   ):]
                    trailing_paths.append(path)

            # Push current exec_prefix paths to the very end
            sys_path.extend(trailing_paths)

            logger.debug("Process sys.path will be: %r", sys_path)
            return d
예제 #4
0
    def test_should_register_source_paths(self):
        system_path = [nc('some/python/path')]

        _register_test_and_source_path_and_return_test_dir(self.project, system_path, "unittest")

        self.assertTrue(nc('/path/to/project/unittest') in system_path)
        self.assertTrue(nc('/path/to/project/src') in system_path)
예제 #5
0
파일: cli.py 프로젝트: ufo2011/pybuilder
def get_failure_message():
    exc_type, exc_obj, exc_tb = sys.exc_info()

    filename = None
    lineno = None

    while exc_tb.tb_next:
        exc_tb = exc_tb.tb_next

    frame = exc_tb.tb_frame
    if hasattr(frame, "f_code"):
        code = frame.f_code
        filename = code.co_filename
        lineno = exc_tb.tb_lineno

        filename = nc(filename)
        for path in sys.path:
            path = nc(path)
            if filename.startswith(path) and len(filename) > len(path) and filename[len(path)] == sep:
                filename = filename[len(path) + 1:]
                break

    return "%s%s%s" % ("%s: " % exc_type.__name__ if not isinstance(exc_obj, PyBuilderException) else "",
                       exc_obj,
                       " (%s:%d)" % (filename, lineno) if filename else "")
예제 #6
0
    def test_upload(self, proc_runner, walk, *args):
        proc_runner.return_value = 0
        walk.return_value = [["dist", "", ["a", "b"]]]

        upload(self.project, MagicMock(Logger))
        self.assertEqual(popen_distutils_args(self, 1, proc_runner),
                         [["twine", "upload", nc("/whatever dist/dist/a"), nc("/whatever dist/dist/b")]])
예제 #7
0
    def test_get_sphinx_apidoc_command_enabled_with_pep420(self):
        sphinx_mock = Mock()
        sys.modules["sphinx"] = sphinx_mock

        try:
            sphinx_mock.version_info = (1, 5, 3, 4, 5)

            self.project.set_property("sphinx_run_apidoc", True)
            self.project.set_property("dir_target", "dir_target")
            self.project.set_property("dir_source_main_python", "dir_source")
            self.project.set_property("sphinx_project_name", "project_name")

            self.assertEqual(get_sphinx_apidoc_command(self.project),
                             ['sphinx.apidoc',
                              '-H',
                              'project_name',
                              '--implicit-namespaces',
                              '-o',
                              nc('basedir/dir_target/sphinx_pyb/apidoc'),
                              nc('basedir/dir_source')
                              ] if sys.version_info[:3] >= (3, 3) else
                             ['sphinx.apidoc',
                              '-H',
                              'project_name',
                              '-o',
                              nc('basedir/dir_target/sphinx_pyb/apidoc'),
                              nc('basedir/dir_source')
                              ]
                             )
        finally:
            del sys.modules["sphinx"]
예제 #8
0
    def test_sphinx_pyb_quickstart_generate(self, execute_command, symlink,
                                            mkdir, exists, rmtree, open):
        execute_command.return_value = 0
        exists.return_value = False

        self.project.set_property("sphinx_source_dir", "sphinx_source_dir")
        self.project.set_property("sphinx_config_path", "sphinx_config_path")
        self.project.set_property("dir_target", "dir_target")
        self.project.set_property("dir_source_main_python", "dir_source")
        self.project.set_property("sphinx_project_name", "project_name")

        sphinx_pyb_quickstart_generate(self.project, Mock())

        open().__enter__().write.assert_called_with("""\
# Automatically generated by PyB
import sys
from os import path

sphinx_pyb_dir = path.abspath(path.join(path.dirname(__file__) if __file__ else ".", "%s"))
sphinx_pyb_module = "sphinx_pyb_conf"
sphinx_pyb_module_file = path.abspath(path.join(sphinx_pyb_dir, sphinx_pyb_module + ".py"))

sys.path.insert(0, sphinx_pyb_dir)

if not path.exists(sphinx_pyb_module_file):
    raise RuntimeError("No PyB-based Sphinx configuration found in " + sphinx_pyb_module_file)

from sphinx_pyb_conf import *

# Overwrite PyB-settings here statically if that's the thing that you want
""" % nc("../basedir/dir_target/sphinx_pyb"))
        symlink.assert_called_with(
            nc("../basedir/dir_target/sphinx_pyb/apidoc"),
            nc("basedir/sphinx_source_dir/apidoc"),
            target_is_directory=True)
예제 #9
0
    def test_should_parse_report(self):
        project = Mock()
        project.expand_path.return_value = nc("/path/to")

        warnings = [
            nc("/path/to/package/module_one") + ":2: Sample warning",
            nc("/path/to/package/module_one") + ":4: Another sample warning",
            "",
            nc("/path/to/package/module_two") + ":33: Another sample warning",
            nc("/path/to/package/module_two") +
            ":332: Yet another sample warning"
        ]

        report = parse_pychecker_output(project, warnings)

        self.assertEqual(2, len(report.module_reports))

        self.assertEqual("package.module_one", report.module_reports[0].name)
        self.assertEqual(2, len(report.module_reports[0].warnings))
        self.assertEqual("Sample warning",
                         report.module_reports[0].warnings[0].message)
        self.assertEqual(2, report.module_reports[0].warnings[0].line_number)
        self.assertEqual("Another sample warning",
                         report.module_reports[0].warnings[1].message)
        self.assertEqual(4, report.module_reports[0].warnings[1].line_number)

        self.assertEqual("package.module_two", report.module_reports[1].name)
        self.assertEqual(2, len(report.module_reports[1].warnings))
        self.assertEqual("Another sample warning",
                         report.module_reports[1].warnings[0].message)
        self.assertEqual(33, report.module_reports[1].warnings[0].line_number)
        self.assertEqual("Yet another sample warning",
                         report.module_reports[1].warnings[1].message)
        self.assertEqual(332, report.module_reports[1].warnings[1].line_number)
예제 #10
0
    def test_should_parse_report(self):
        project = Mock()
        project.expand_path.return_value = nc("/path/to")

        warnings = [
            nc("/path/to/package/module_one") + ":2: Sample warning",
            nc("/path/to/package/module_one") + ":4: Another sample warning",
            "",
            nc("/path/to/package/module_two") + ":33: Another sample warning",
            nc("/path/to/package/module_two") + ":332: Yet another sample warning"
        ]

        report = parse_pychecker_output(project, warnings)

        self.assertEqual(2, len(report.module_reports))

        self.assertEqual("package.module_one", report.module_reports[0].name)
        self.assertEqual(2, len(report.module_reports[0].warnings))
        self.assertEqual(
            "Sample warning", report.module_reports[0].warnings[0].message)
        self.assertEqual(2, report.module_reports[0].warnings[0].line_number)
        self.assertEqual("Another sample warning",
                         report.module_reports[0].warnings[1].message)
        self.assertEqual(4, report.module_reports[0].warnings[1].line_number)

        self.assertEqual("package.module_two", report.module_reports[1].name)
        self.assertEqual(2, len(report.module_reports[1].warnings))
        self.assertEqual("Another sample warning",
                         report.module_reports[1].warnings[0].message)
        self.assertEqual(33, report.module_reports[1].warnings[0].line_number)
        self.assertEqual("Yet another sample warning",
                         report.module_reports[1].warnings[1].message)
        self.assertEqual(
            332, report.module_reports[1].warnings[1].line_number)
예제 #11
0
    def test_upload_with_signature(self, proc_runner, walk, *args):
        proc_runner.return_value = 0
        walk.return_value = [["dist", "", ["a", "b"]]]
        self.project.set_property("distutils_upload_sign", True)

        upload(self.project, MagicMock(Logger))
        self.assertEqual(popen_distutils_args(self, 1, proc_runner),
                         [["twine", "upload", "--sign", nc("/whatever dist/dist/a"), nc("/whatever dist/dist/b")]])
    def test_should_generate_command_abiding_to_configuration(self):
        project = Project('egg')
        project.set_property("dir_manpages", nc("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 > ' + nc('docs/man/egg.1.gz'))
예제 #13
0
    def test_should_add_two_filenames_to_list_of_included_files_and_to_manifest(self):
        self.project.include_file("spam", "eggs")
        self.project.include_file("monty", "ham")

        self.assertEqual(
            {"monty": ["ham"], "spam": ["eggs"]}, self.project.package_data)
        self.assertEqual(
            [nc("spam/eggs"), nc("monty/ham")], self.project.manifest_included_files)
예제 #14
0
 def test_find_files(self, discover_mock):
     project = Project('.')
     project.set_property('dir_source_cmdlinetest', nc('/any/dir'))
     project.set_property('cram_test_file_glob', '*.t')
     expected = [nc('./any/dir/test.cram')]
     discover_mock.return_value = expected
     received = _find_files(project)
     self.assertEqual(expected, received)
     discover_mock.assert_called_once_with(nc('/any/dir'), '*.t')
예제 #15
0
    def test_upload_with_repo_key_only(self, proc_runner, walk, *args):
        proc_runner.return_value = 0
        walk.return_value = [["dist", "", ["a", "b"]]]
        self.project.set_property("distutils_upload_repository_key", "test repo key")

        upload(self.project, MagicMock(Logger))
        self.assertEqual(popen_distutils_args(self, 1, proc_runner),
                         [["twine", "upload", "--repository", "test repo key", nc("/whatever dist/dist/a"),
                           nc("/whatever dist/dist/b")]])
예제 #16
0
 def test_find_files(self, discover_mock):
     project = Project('.')
     project.set_property('dir_source_cmdlinetest', nc('/any/dir'))
     project.set_property('cram_test_file_glob', '*.t')
     expected = [nc('./any/dir/test.cram')]
     discover_mock.return_value = expected
     received = _find_files(project)
     self.assertEqual(expected, received)
     discover_mock.assert_called_once_with(nc('/any/dir'), '*.t')
    def test_should_generate_command_abiding_to_configuration(self):
        project = Project('egg')
        project.set_property("dir_manpages", nc("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 > ' + nc('docs/man/egg.1.gz'))
예제 #18
0
    def test_should_generate_sphinx_build_command_builder_dir(self):
        self.project.set_property("sphinx_config_path", "docs/")
        self.project.set_property("sphinx_source_dir", "docs/")
        self.project.set_property("sphinx_output_dir", "docs/_build/")
        self.project.set_property("sphinx_doc_builder", ['JSONx', 'pdf'])

        sphinx_build_command = get_sphinx_build_command(self.project, Mock(), 'JSONx')

        self.assertEqual(sphinx_build_command,
                         ["sphinx", "-b", "JSONx", nc("basedir/docs/"), nc("basedir/docs/_build/JSONx")])
예제 #19
0
    def test_upload(self, proc_runner, walk, *args):
        proc_runner.return_value = 0
        walk.return_value = [["dist", "", ["a", "b"]]]

        upload(self.project, MagicMock(Logger))
        self.assertEqual(popen_distutils_args(self, 1, proc_runner), [[
            "twine", "upload",
            nc("/whatever dist/dist/a"),
            nc("/whatever dist/dist/b")
        ]])
예제 #20
0
    def test_should_put_project_sources_before_other_sources(self):
        system_path = [nc('irrelevant/sources')]

        _register_test_and_source_path_and_return_test_dir(self.project, system_path, "unittest")

        test_sources_index_in_path = system_path.index(nc('/path/to/project/unittest'))
        main_sources_index_in_path = system_path.index(nc('/path/to/project/src'))
        irrelevant_sources_index_in_path = system_path.index(nc('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)
예제 #21
0
def find_project_base_dir():
    cur_dir = dirname(nc(__file__))
    while True:
        if exists(jp(cur_dir, "build.py")):
            return cur_dir
        else:
            new_cur_dir = nc(jp(cur_dir, ".."))
            if new_cur_dir == cur_dir:
                return None
            cur_dir = new_cur_dir
예제 #22
0
    def test_should_add_two_filenames_to_list_of_included_files_and_to_manifest(
            self):
        self.project.include_file("spam", "eggs")
        self.project.include_file("monty", "ham")

        self.assertEqual({
            "monty": ["ham"],
            "spam": ["eggs"]
        }, self.project.package_data)
        self.assertEqual([nc("spam/eggs"), nc("monty/ham")],
                         self.project.manifest_included_files)
예제 #23
0
    def test_upload_with_signature(self, proc_runner, walk, *args):
        proc_runner.return_value = 0
        walk.return_value = [["dist", "", ["a", "b"]]]
        self.project.set_property("distutils_upload_sign", True)

        upload(self.project, MagicMock(Logger))
        self.assertEqual(popen_distutils_args(self, 1, proc_runner), [[
            "twine", "upload", "--sign",
            nc("/whatever dist/dist/a"),
            nc("/whatever dist/dist/b")
        ]])
예제 #24
0
    def test_upload_with_repo_key_only(self, proc_runner, walk, *args):
        proc_runner.return_value = 0
        walk.return_value = [["dist", "", ["a", "b"]]]
        self.project.set_property("distutils_upload_repository_key",
                                  "test repo key")

        upload(self.project, MagicMock(Logger))
        self.assertEqual(popen_distutils_args(self, 1, proc_runner), [[
            "twine", "upload", "--repository", "test repo key",
            nc("/whatever dist/dist/a"),
            nc("/whatever dist/dist/b")
        ]])
예제 #25
0
    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(nc('basedir/.project'), 'w'),
            call(nc('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>
""")
        ])
예제 #26
0
    def test_should_apply_callback_to_all_files_when_expression_matches_all_files(self, walk):
        absolute_file_names = []
        relative_file_names = []

        def callback(absolute_file_name, relative_file_name):
            absolute_file_names.append(absolute_file_name)
            relative_file_names.append(relative_file_name)

        apply_on_files("spam", callback, "*")
        self.assertEqual([nc("spam/a"), nc("spam/b"), nc("spam/c")], absolute_file_names)
        self.assertEqual(["a", "b", "c"], relative_file_names)

        walk.assert_called_with("spam")
예제 #27
0
    def test_should_generate_sphinx_build_command_builder_dir(self):
        self.project.set_property("sphinx_config_path", "docs/")
        self.project.set_property("sphinx_source_dir", "docs/")
        self.project.set_property("sphinx_output_dir", "docs/_build/")
        self.project.set_property("sphinx_doc_builder", ['JSONx', 'pdf'])

        sphinx_build_command = get_sphinx_build_command(
            self.project, Mock(), 'JSONx')

        self.assertEqual(sphinx_build_command, [
            "sphinx", "-b", "JSONx",
            nc("basedir/docs/"),
            nc("basedir/docs/_build/JSONx")
        ])
예제 #28
0
    def test_should_generate_sphinx_build_command_debug(self):
        self.project.set_property("sphinx_config_path", "docs/")
        self.project.set_property("sphinx_source_dir", "docs/")
        self.project.set_property("sphinx_output_dir", "docs/_build/")
        self.project.set_property("sphinx_doc_builder", 'JSONx')

        logger = Mock()
        logger.threshold = 1
        logger.DEBUG = 1

        sphinx_build_command = get_sphinx_build_command(self.project, logger, 'JSONx')

        self.assertEqual(sphinx_build_command,
                         ["sphinx", "-b", "JSONx", "-vvvv", nc("basedir/docs/"), nc("basedir/docs/_build/")])
예제 #29
0
    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(nc('basedir/.project'), 'w'), call(nc('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>
""")])
예제 #30
0
    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')
        project.set_property('dir_source_unittest_python', 'src/unittest/python')
        project.set_property('dir_source_integrationtest_python', 'src/integrationtest/python')
        project.set_property('dir_target', 'build')
        mock_open.return_value = MagicMock(spec=TYPE_FILE)
        os.path.join.side_effect = lambda first, second: first + sep + second

        pycharm_generate(project, Mock())

        mock_open.assert_called_with(nc('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" />
      <sourceFolder url="file://$MODULE_DIR$/src/unittest/python" isTestSource="true" />
      <sourceFolder url="file://$MODULE_DIR$/src/integrationtest/python" isTestSource="true" />
      <excludeFolder url="file://$MODULE_DIR$/build" />
    </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>""")
예제 #31
0
 def test_expand_path_should_return_expanded_path_and_additional_parts_when_additional_parts_are_given(
         self):
     self.project.set_property("spam", "spam")
     self.project.set_property("eggs", "eggs")
     self.assertEqual(
         nc(os.path.join("/imaginary", "spam", "eggs", "foo", "bar")),
         self.project.expand_path("$spam/$eggs", "foo", "bar"))
예제 #32
0
    def test_should_apply_callback_to_all_files_when_expression_matches_all_files(
            self, walk):
        absolute_file_names = []
        relative_file_names = []

        def callback(absolute_file_name, relative_file_name):
            absolute_file_names.append(absolute_file_name)
            relative_file_names.append(relative_file_name)

        apply_on_files("spam", callback, "*")
        self.assertEqual(
            [nc("spam/a"), nc("spam/b"),
             nc("spam/c")], absolute_file_names)
        self.assertEqual(["a", "b", "c"], relative_file_names)

        walk.assert_called_with("spam")
예제 #33
0
 def test_should_build_sonar_scanner_for_project(self):
     self.assertEqual(
         build_sonar_scanner(self.project).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"))
예제 #34
0
    def test_should_render_manifest_file(self):
        project = create_project()

        actual_manifest_file = render_manifest_file(project)

        self.assertEqual("""include file1
include file2
include %s
""" % nc("spam/eggs"), actual_manifest_file)
예제 #35
0
    def test_get_sphinx_apidoc_command_enabled(self):
        sphinx_mock = Mock()
        sys.modules["sphinx"] = sphinx_mock
        try:
            sphinx_mock.version_info = (1, 2, 3, 4, 5)

            self.project.set_property("sphinx_run_apidoc", True)
            self.project.set_property("dir_target", "dir_target")
            self.project.set_property("dir_source_main_python", "dir_source")
            self.project.set_property("sphinx_project_name", "project_name")

            self.assertEqual(get_sphinx_apidoc_command(self.project), [
                'sphinx.apidoc', '-H', 'project_name', '-o',
                nc('basedir/dir_target/sphinx_pyb/apidoc'),
                nc('basedir/dir_source')
            ])
        finally:
            del sys.modules["sphinx"]
예제 #36
0
    def test_should_generate_sphinx_build_command_debug(self):
        self.project.set_property("sphinx_config_path", "docs/")
        self.project.set_property("sphinx_source_dir", "docs/")
        self.project.set_property("sphinx_output_dir", "docs/_build/")
        self.project.set_property("sphinx_doc_builder", 'JSONx')

        logger = Mock()
        logger.threshold = 1
        logger.DEBUG = 1

        sphinx_build_command = get_sphinx_build_command(
            self.project, logger, 'JSONx')

        self.assertEqual(sphinx_build_command, [
            "sphinx", "-b", "JSONx", "-vvvv",
            nc("basedir/docs/"),
            nc("basedir/docs/_build/")
        ])
예제 #37
0
    def test_install_with_index_url(self, execute_command, *args):
        self.project.set_property("install_dependencies_index_url", "index_url")
        self.project.set_property("install_dependencies_extra_index_url", "extra_index_url")

        install_distribution(self.project, MagicMock(Logger))
        execute_command.assert_called_with(
            PIP_EXEC_STANZA + ["install", "--index-url", "index_url", "--extra-index-url", "extra_index_url",
                               "--force-reinstall", nc('/whatever dist')], cwd=".", env=ANY, outfile_name=ANY,
            error_file_name=ANY, shell=False)
예제 #38
0
    def test_running_plugin_fails(
        self,
        execute_mock,
        read_file_mock,
        os_mock,
        report_mock,
        find_files_mock,
        command_mock,
        tail_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
        tail_mock.return_value = "tail data"

        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': nc('./python:'),
                'PATH': nc('./scripts:')
            })
        expected_info_calls = [
            call('Running Cram command line tests'),
        ]
        expected_error_calls = [
            call(
                'Cram tests failed! See report_file for full details:\ntail data'
            ),
        ]
        self.assertEqual(expected_info_calls, logger.info.call_args_list)
        self.assertEqual(expected_error_calls, logger.error.call_args_list)
예제 #39
0
    def test_should_render_manifest_file(self):
        project = create_project()

        actual_manifest_file = render_manifest_file(project)

        self.assertEqual(
            """include file1
include file2
include %s
""" % nc("spam/eggs"), actual_manifest_file)
예제 #40
0
    def test_should_apply_callback_to_one_file_when_expression_matches_one_file(self, walk):
        called_on_file = []

        def callback(absolute_file_name, relative_file_name):
            called_on_file.append(absolute_file_name)

        apply_on_files("spam", callback, "a")
        self.assertEqual([nc("spam/a")], called_on_file)

        walk.assert_called_with("spam")
예제 #41
0
    def test_should_apply_callback_to_one_file_when_expression_matches_one_file(
            self, walk):
        called_on_file = []

        def callback(absolute_file_name, relative_file_name):
            called_on_file.append(absolute_file_name)

        apply_on_files("spam", callback, "a")
        self.assertEqual([nc("spam/a")], called_on_file)

        walk.assert_called_with("spam")
예제 #42
0
    def test_should_pass_additional_arguments_to_closure(self, walk):
        called_on_file = []

        def callback(absolute_file_name, relative_file_name, additional_argument):
            self.assertEqual("additional argument", additional_argument)
            called_on_file.append(absolute_file_name)

        apply_on_files("spam", callback, "a", "additional argument")
        self.assertEqual([nc("spam/a")], called_on_file)

        walk.assert_called_with("spam")
예제 #43
0
 def test_install(self, execute_command, *args):
     install_distribution(self.project, MagicMock(Logger))
     execute_command.assert_called_with(
         PIP_EXEC_STANZA +
         ["install", "--force-reinstall",
          nc('/whatever dist')],
         cwd=".",
         env=ANY,
         outfile_name=ANY,
         error_file_name=ANY,
         shell=False)
예제 #44
0
    def test_should_pass_additional_arguments_to_closure(self, walk):
        called_on_file = []

        def callback(absolute_file_name, relative_file_name,
                     additional_argument):
            self.assertEqual("additional argument", additional_argument)
            called_on_file.append(absolute_file_name)

        apply_on_files("spam", callback, "a", "additional argument")
        self.assertEqual([nc("spam/a")], called_on_file)

        walk.assert_called_with("spam")
예제 #45
0
    def test_sphinx_pyb_quickstart_generate(self,
                                            execute_command,
                                            symlink,
                                            mkdir,
                                            exists,
                                            rmtree,
                                            open
                                            ):
        execute_command.return_value = 0
        exists.return_value = False

        self.project.set_property("sphinx_source_dir", "sphinx_source_dir")
        self.project.set_property("sphinx_config_path", "sphinx_config_path")
        self.project.set_property("dir_target", "dir_target")
        self.project.set_property("dir_source_main_python", "dir_source")
        self.project.set_property("sphinx_project_name", "project_name")

        sphinx_pyb_quickstart_generate(self.project, Mock())

        open().__enter__().write.assert_called_with("""\
# Automatically generated by PyB
import sys
from os import path

sphinx_pyb_dir = path.abspath(path.join(path.dirname(__file__) if __file__ else ".", "%s"))
sphinx_pyb_module = "sphinx_pyb_conf"
sphinx_pyb_module_file = path.abspath(path.join(sphinx_pyb_dir, sphinx_pyb_module + ".py"))

sys.path.insert(0, sphinx_pyb_dir)

if not path.exists(sphinx_pyb_module_file):
    raise RuntimeError("No PyB-based Sphinx configuration found in " + sphinx_pyb_module_file)

from sphinx_pyb_conf import *

# Overwrite PyB-settings here statically if that's the thing that you want
""" % nc("../basedir/dir_target/sphinx_pyb"))
        symlink.assert_called_with(nc("../basedir/dir_target/sphinx_pyb/apidoc"),
                                   nc("basedir/sphinx_source_dir/apidoc"),
                                   target_is_directory=True)
예제 #46
0
    def test_should_generate_sphinx_quickstart_command_with_project_properties(
            self):
        self.project.set_property("sphinx_doc_author", "bar")
        self.project.set_property("sphinx_project_name", "foo")
        self.project.set_property("sphinx_project_version", "3")
        self.project.set_property("sphinx_source_dir", "docs/")

        sphinx_quickstart_command = get_sphinx_quickstart_command(self.project)

        self.assertEqual(sphinx_quickstart_command, [
            "sphinx.quickstart", "-q", "-p", "foo", "-a", "bar", "-v", "3",
            nc("basedir/docs/")
        ])
예제 #47
0
    def test_running_plugin_fails(self,
                                  execute_mock,
                                  read_file_mock,
                                  os_mock,
                                  report_mock,
                                  find_files_mock,
                                  command_mock,
                                  tail_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
        tail_mock.return_value = "tail data"

        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': nc('./python:'), 'PATH': nc('./scripts:')}
        )
        expected_info_calls = [call('Running Cram command line tests'),
                               ]
        expected_error_calls = [call('Cram tests failed! See report_file for full details:\ntail data'),
                                ]
        self.assertEqual(expected_info_calls, logger.info.call_args_list)
        self.assertEqual(expected_error_calls, logger.error.call_args_list)
예제 #48
0
    def test_install_with_index_url(self, execute_command, *args):
        self.project.set_property("install_dependencies_index_url",
                                  "index_url")
        self.project.set_property("install_dependencies_extra_index_url",
                                  "extra_index_url")

        install_distribution(self.project, MagicMock(Logger))
        execute_command.assert_called_with(PIP_EXEC_STANZA + [
            "install", "--index-url", "index_url", "--extra-index-url",
            "extra_index_url", "--force-reinstall",
            nc('/whatever dist')
        ],
                                           cwd=".",
                                           env=ANY,
                                           outfile_name=ANY,
                                           error_file_name=ANY,
                                           shell=False)
예제 #49
0
    def file_mapper(path):
        path = nc(path)
        best_candidate = None
        for p in normalized_paths:
            if path == p:
                return path

            if path.startswith(p):
                candidate = relpath(path, p)
                if not best_candidate or len(candidate) < len(best_candidate):
                    best_candidate = candidate

        if best_candidate:
            final_candidate = jp(source_path, best_candidate)
            if exists(final_candidate):
                return final_candidate
            return best_candidate
        else:
            return path
    def test(self):
        self.write_build_file("""
from pybuilder.core import use_plugin, init

use_plugin('python.core')
use_plugin('python.distutils')

name = 'integration-test'
default_task = 'publish'

@init
def init (project):
    project.include_file('spam', 'eggs')
    project.install_file('spam_dir', 'more_spam')
    project.install_file('eggs_dir', 'more_eggs')
""")
        self.create_directory("src/main/python/spam")
        self.write_file("src/main/python/spam/eggs", "")
        self.write_file("src/main/python/more_spam", "")
        self.write_file("src/main/python/more_eggs", "")

        reactor = self.prepare_reactor()
        reactor.build()

        self.assert_directory_exists(
            "target/dist/integration-test-1.0.dev0")
        self.assert_directory_exists(
            "target/dist/integration-test-1.0.dev0/spam")
        self.assert_file_empty(
            "target/dist/integration-test-1.0.dev0/spam/eggs")
        self.assert_file_empty(
            "target/dist/integration-test-1.0.dev0/more_spam")
        self.assert_file_empty(
            "target/dist/integration-test-1.0.dev0/more_eggs")

        manifest_in = "target/dist/integration-test-1.0.dev0/MANIFEST.in"

        self.assert_file_exists(manifest_in)
        self.assert_file_permissions(0o664, manifest_in)
        self.assert_file_content(manifest_in, """include %s
include more_spam
include more_eggs
""" % nc("spam/eggs"))
예제 #51
0
    def test(self):
        self.write_build_file("""
from pybuilder.core import use_plugin, init

use_plugin('python.core')
use_plugin('python.distutils')

name = 'integration-test'
default_task = 'publish'

@init
def init (project):
    project.include_file('spam', 'eggs')
    project.install_file('spam_dir', 'more_spam')
    project.install_file('eggs_dir', 'more_eggs')
""")
        self.create_directory("src/main/python/spam")
        self.write_file("src/main/python/spam/eggs", "")
        self.write_file("src/main/python/more_spam", "")
        self.write_file("src/main/python/more_eggs", "")

        reactor = self.prepare_reactor()
        reactor.build()

        self.assert_directory_exists(
            "target/dist/integration-test-1.0.dev0")
        self.assert_directory_exists(
            "target/dist/integration-test-1.0.dev0/spam")
        self.assert_file_empty(
            "target/dist/integration-test-1.0.dev0/spam/eggs")
        self.assert_file_empty(
            "target/dist/integration-test-1.0.dev0/more_spam")
        self.assert_file_empty(
            "target/dist/integration-test-1.0.dev0/more_eggs")

        manifest_in = "target/dist/integration-test-1.0.dev0/MANIFEST.in"

        self.assert_file_exists(manifest_in)
        self.assert_file_permissions(0o664, manifest_in)
        self.assert_file_content(manifest_in, """include %s
include more_spam
include more_eggs
""" % nc("spam/eggs"))
예제 #52
0
    def test_should_set_default_values_when_initializing_plugin(self):
        self.project.authors = [
            Author("John Doe", "*****@*****.**"),
            Author("Jane Doe", "*****@*****.**")]
        initialize_sphinx_plugin(self.project)

        self.project.set_property("sphinx_project_name", "foo")
        self.project.set_property("sphinx_project_version", "1.0")

        self.assertEqual(
            self.project.get_property("sphinx_source_dir"), "docs")
        self.assertEqual(
            self.project.get_property("sphinx_output_dir"), nc("docs/_build/"))
        self.assertEqual(
            self.project.get_property("sphinx_config_path"), "docs")
        self.assertEqual(
            self.project.get_property("sphinx_doc_author"), 'John Doe, Jane Doe')
        self.assertEqual(
            self.project.get_property("sphinx_doc_builder"), "html")
        self.assertEqual(
            self.project.get_property("sphinx_project_name"), "foo")
        self.assertEqual(
            self.project.get_property("sphinx_project_version"), "1.0")
예제 #53
0
 def test_should_only_return_py_suffix(self, walk):
     expected_result = [nc("spam/spam.py"), nc("spam/eggs.py")]
     actual_result = set(discover_files("spam", ".py"))
     self.assertEqual(set(expected_result), actual_result)
     walk.assert_called_with("spam")
예제 #54
0
 def test_should_only_return_py_glob(self, walk):
     expected_result = [nc("spam/readme.md")]
     actual_result = set(discover_files_matching("spam", "readme.?d"))
     self.assertEqual(set(expected_result), actual_result)
     walk.assert_called_with("spam")
예제 #55
0
 def test_install(self, execute_command, *args):
     install_distribution(self.project, MagicMock(Logger))
     execute_command.assert_called_with(PIP_EXEC_STANZA + ["install", "--force-reinstall", nc('/whatever dist')],
                                        cwd=".", env=ANY,
                                        outfile_name=ANY, error_file_name=ANY, shell=False)
예제 #56
0
파일: test.py 프로젝트: tkern0/misc
from os import system as cmd
from os import chdir as cd
from os.path import join
from os.path import normcase as nc
from os.path import normpath as np
path = "C:\\"
cd(path)
while True:
    i = input('> ')
    if i.startswith('cd ') and not i == 'cd ':
        path = nc(np(join(path, i[3:])))
        cd(path)
    else:
        cmd(i)
예제 #57
0
 def test_report(self):
     project = Project('.')
     project.set_property('dir_reports', '/any/dir')
     expected = nc('./any/dir/cram.err')
     received = _report_file(project)
     self.assertEqual(expected, received)