Пример #1
0
 def test_list(self):
     self.create_score()
     script = commandlinetools.ManageBuildTargetScript()
     command = ['--new', 'big-version']
     with systemtools.TemporaryDirectoryChange(str(self.score_path)):
         try:
             script(command)
         except SystemExit:
             raise RuntimeError('SystemExit')
     command = ['--new', 'medium-version']
     with systemtools.TemporaryDirectoryChange(str(self.score_path)):
         try:
             script(command)
         except SystemExit:
             raise RuntimeError('SystemExit')
     command = ['--new', 'small-version']
     with systemtools.TemporaryDirectoryChange(str(self.score_path)):
         try:
             script(command)
         except SystemExit:
             raise RuntimeError('SystemExit')
     command = ['--list']
     with systemtools.RedirectedStreams(stdout=self.string_io):
         with systemtools.TemporaryDirectoryChange(str(self.score_path)):
             try:
                 script(command)
             except SystemExit:
                 raise RuntimeError('SystemExit')
     self.compare_captured_output(r'''
     Available build targets:
         big-version
         medium-version
         small-version
     ''')
 def test_success(self, open_file_mock):
     self.create_score()
     self.install_fancy_segment_maker()
     self.create_segment('test_segment')
     self.illustrate_segments()
     self.collect_segments()
     self.create_build_target()
     script = commandlinetools.ManageBuildTargetScript()
     command = ['--render', 'letter-portrait']
     with systemtools.TemporaryDirectoryChange(str(self.score_path)):
         try:
             script(command)
         except SystemExit:
             raise RuntimeError('SystemExit')
     command = ['--distribute', 'letter-portrait']
     with systemtools.RedirectedStreams(stdout=self.string_io):
         with systemtools.TemporaryDirectoryChange(str(self.score_path)):
             try:
                 script(command)
             except SystemExit:
                 raise RuntimeError('SystemExit')
     self.compare_captured_output(r'''
     Distributing 'letter-portrait'
         score.pdf --> letter-portrait-score.pdf
         parts-cello.pdf --> letter-portrait-parts-cello.pdf
         parts-viola.pdf --> letter-portrait-parts-viola.pdf
         parts-violin-i.pdf --> letter-portrait-parts-violin-i.pdf
         parts-violin-ii.pdf --> letter-portrait-parts-violin-ii.pdf
     ''')
     self.compare_path_contents(
         self.distribution_path,
         self.expected_files,
     )
Пример #3
0
    def cleanup_graphviz_svg(app):
        def process_svg(filename, delete_attributes):
            try:
                with open(filename, 'r') as file_pointer:
                    contents = file_pointer.read()
                document = minidom.parseString(contents)
                svg_element = document.getElementsByTagName('svg')[0]
                view_box = svg_element.getAttribute('viewBox')
                view_box = [float(_) for _ in view_box.split()]
                if delete_attributes:
                    if len(svg_element.attributes) and \
                        'height' in svg_element.attributes:
                        del (svg_element.attributes['height'])
                    if len(svg_element.attributes) and \
                        'width' in svg_element.attributes:
                        del (svg_element.attributes['width'])
                else:
                    height = '{}pt'.format(int(view_box[-1] * 0.6))
                    width = '{}pt'.format(int(view_box[-2] * 0.6))
                    svg_element.setAttribute('height', height)
                    svg_element.setAttribute('width', width)
                svg_element.setAttribute('preserveAspectRatio', 'xMinYMin')
                with open(filename, 'w') as file_pointer:
                    document.writexml(file_pointer)
            except KeyError:
                traceback.print_exc()

        image_directory = os.path.join(
            app.builder.outdir,
            app.builder.imagedir,
        )
        with systemtools.TemporaryDirectoryChange(image_directory):
            svg_paths = glob.glob('graphviz*.svg')
            for filename in app.builder.status_iterator(
                    svg_paths,
                    'cleaning-up svg files (A)...',
                    brown,
                    len(svg_paths),
            ):
                process_svg(filename, delete_attributes=True)
        image_directory = os.path.join(image_directory, 'abjadbook')
        with systemtools.TemporaryDirectoryChange(image_directory):
            svg_paths = glob.glob('graphviz*.svg')
            for filename in app.builder.status_iterator(
                    svg_paths,
                    'cleaning-up svg files (B)...',
                    brown,
                    len(svg_paths),
            ):
                process_svg(filename, delete_attributes=False)
 def test_success(self):
     self.create_score()
     script = commandlinetools.ManageSegmentScript()
     try:
         names = script._read_segments_list_json(
             self.score_path,
             verbose=False,
             )
         assert names == []
     except SystemExit:
         raise RuntimeError('SystemExit')
     command = ['--new', 'test_segment']
     with systemtools.RedirectedStreams(stdout=self.string_io):
         with systemtools.TemporaryDirectoryChange(str(self.score_path)):
             try:
                 script(command)
             except SystemExit:
                 raise RuntimeError('SystemExit')
     self.compare_captured_output(r'''
         Creating segment subpackage 'test_segment' ...
             Reading test_score/metadata.json ... OK!
             Reading test_score/segments/metadata.json ... JSON does not exist.
             Writing test_score/segments/metadata.json
             Created test_score/segments/test_segment/
     '''.replace('/', os.path.sep))
     assert self.segments_path.joinpath('test_segment').exists()
     self.compare_path_contents(self.segments_path, self.expected_files)
     try:
         names = script._read_segments_list_json(
             self.score_path,
             verbose=False,
             )
         assert names == ['test_segment']
     except SystemExit:
         raise RuntimeError('SystemExit')
Пример #5
0
 def _write_lilypond_pdf(
     self,
     ly_path,
     output_directory,
 ):
     from abjad import abjad_configuration
     pdf_path = output_directory.joinpath('illustration.pdf')
     message = '    Writing {!s} ... '
     message = message.format(
         pdf_path.relative_to(self._score_repository_path))
     print(message, end='')
     command = '{} -dno-point-and-click -o {} {}'.format(
         # not sure why the call to abjad_configuration.get() returns none:
         #abjad_configuration.get('lilypond_path', 'lilypond'),
         'lilypond',
         str(ly_path).replace('.ly', ''),
         str(ly_path),
     )
     with systemtools.Timer() as timer:
         with systemtools.TemporaryDirectoryChange(str(ly_path.parent)):
             exit_code = subprocess.call(command, shell=True)
     if exit_code:
         print('Failed!')
         sys.exit(1)
     print('OK!')
     self._report_time(timer, prefix='LilyPond runtime')
Пример #6
0
    def test_both(self):
        script = commandlinetools.DoctestScript()
        command = [str(self.doctest_path)]
        with systemtools.TemporaryDirectoryChange(str(self.test_path)):
            with systemtools.RedirectedStreams(stdout=self.string_io):
                with self.assertRaises(SystemExit) as context_manager:
                    script(command)
        assert context_manager.exception.code == 1
        script_output = self.ansi_escape.sub('', self.string_io.getvalue())
        script_output = stringtools.normalize(script_output)
        expected = stringtools.normalize('''
        doctest_test/doctest_fail.py FAILED
        doctest_test/doctest_pass.py OK

        **********************************************************************
        File ".../doctest_test/doctest_fail.py", line 7, in doctest_fail.py
        Failed example:
            True is False
        Expected:
            True
        Got:
            False
        **********************************************************************
        1 items had failures:
            1 of   1 in doctest_fail.py
        ***Test Failed*** 1 failures.

        FAILED: doctest_test/doctest_fail.py

        1 passed, 1 failed out of 2 tests in 2 modules.
        '''.replace('/', os.path.sep))
        self.compare_strings(expected, script_output)
Пример #7
0
    def test_diff(self):
        script = commandlinetools.DoctestScript()
        command = ['--diff', str(self.failing_module_path)]
        with systemtools.TemporaryDirectoryChange(str(self.test_path)):
            with systemtools.RedirectedStreams(stdout=self.string_io):
                with self.assertRaises(SystemExit) as context_manager:
                    script(command)
        assert context_manager.exception.code == 1
        script_output = self.ansi_escape.sub('', self.string_io.getvalue())
        script_output = stringtools.normalize(script_output)
        expected = stringtools.normalize('''
        doctest_test/doctest_fail.py FAILED

        **********************************************************************
        File ".../doctest_test/doctest_fail.py", line 7, in doctest_fail.py
        Failed example:
            True is False
        Differences (ndiff with -expected +actual):
            - True
            + False
        **********************************************************************
        1 items had failures:
            1 of   1 in doctest_fail.py
        ***Test Failed*** 1 failures.

        FAILED: doctest_test/doctest_fail.py

        0 passed, 1 failed out of 1 test in 1 module.
        '''.replace('/', os.path.sep))
        self.compare_strings(expected, script_output)
    def test_python_error_on_illustrate(self):
        """
        Handle exceptions inside the Python module on __call__().
        """
        self.create_score()
        material_path = self.create_material('test_material')
        definition_path = material_path.joinpath('definition.py')
        with open(str(definition_path), 'w') as file_pointer:
            file_pointer.write(
                stringtools.normalize(r'''
            # -*- coding: utf-8 -*-
            from abjad.tools import abctools


            class Foo(object):
                def __illustrate__(self):
                    raise TypeError('This is fake.')

            test_material = Foo()
            '''))
        script = commandlinetools.ManageMaterialScript()
        command = ['--illustrate', 'test_material']
        with systemtools.RedirectedStreams(stdout=self.string_io):
            with systemtools.TemporaryDirectoryChange(str(self.score_path)):
                with self.assertRaises(SystemExit) as context_manager:
                    script(command)
                assert context_manager.exception.code == 1
        self.compare_captured_output(r'''
            Illustration candidates: 'test_material' ...
            Illustrating test_score/materials/test_material/
                Importing test_score.materials.test_material.definition
        '''.replace('/', os.path.sep))
    def test_python_cannot_illustrate(self):
        """
        Handle un-illustrables.
        """
        self.create_score()
        material_path = self.create_material('test_material')
        definition_path = material_path.joinpath('definition.py')
        with open(str(definition_path), 'w') as file_pointer:
            file_pointer.write(
                stringtools.normalize(r'''
            # -*- coding: utf-8 -*-

            test_material = None
            '''))
        script = commandlinetools.ManageMaterialScript()
        command = ['--illustrate', 'test_material']
        with systemtools.RedirectedStreams(stdout=self.string_io):
            with systemtools.TemporaryDirectoryChange(str(self.score_path)):
                with self.assertRaises(SystemExit) as context_manager:
                    script(command)
                assert context_manager.exception.code == 1
        self.compare_captured_output(r'''
            Illustration candidates: 'test_material' ...
            Illustrating test_score/materials/test_material/
                Importing test_score.materials.test_material.definition
                Cannot illustrate material of type NoneType.
        '''.replace('/', os.path.sep))
 def test_list_segments_unstaged(self):
     self.create_score()
     self.create_segment('segment_one')
     self.create_segment('segment_two')
     self.create_segment('segment_three')
     script = commandlinetools.ManageSegmentScript()
     segment_names = script._read_segments_list_json(
         self.score_path,
         verbose=False,
         )
     segment_names.remove('segment_two')
     script._write_segments_list_json(
         segment_names,
         score_path=self.score_path,
         verbose=False,
         )
     command = ['--list']
     with systemtools.RedirectedStreams(stdout=self.string_io):
         with systemtools.TemporaryDirectoryChange(str(self.score_path)):
             with self.assertRaises(SystemExit) as context_manager:
                 script(command)
             assert context_manager.exception.code == 2
     self.compare_captured_output(r'''
         Available segments:
             Reading test_score/segments/metadata.json ... OK!
             segment_one   [1]
             segment_three [2]
             segment_two
     '''.replace('/', os.path.sep))
Пример #11
0
 def create_segment(
     self,
     segment_name='test_segment',
     force=False,
     expect_error=False,
 ):
     script = commandlinetools.ManageSegmentScript()
     command = ['--new', segment_name]
     if force:
         command.insert(0, '-f')
     with systemtools.TemporaryDirectoryChange(str(self.score_path)):
         if expect_error:
             with self.assertRaises(SystemExit) as context_manager:
                 script(command)
             assert context_manager.exception.code == 1
         else:
             try:
                 script(command)
             except SystemExit:
                 raise RuntimeError('SystemExit')
     return self.score_path.joinpath(
         self.score_path.name,
         'segments',
         segment_name,
     )
Пример #12
0
 def create_score(self, force=False, expect_error=False):
     script = commandlinetools.ManageScoreScript()
     command = [
         '--new',
         'Test Score',
         '-y',
         '2016',
         '-n',
         'Josiah Wolf Oberholtzer',
         '-e',
         '*****@*****.**',
         '-g',
         'josiah-wolf-oberholtzer',
         '-l',
         'consort',
         '-w',
         'www.josiahwolfoberholtzer.com',
     ]
     if force:
         command.insert(0, '-f')
     with systemtools.TemporaryDirectoryChange(str(self.test_path)):
         if expect_error:
             with self.assertRaises(SystemExit) as context_manager:
                 script(command)
             assert context_manager.exception.code == 1
         else:
             try:
                 script(command)
             except SystemExit:
                 raise RuntimeError('SystemExit')
 def test_success_front_cover(self, open_file_mock):
     expected_files = [
         'test_score/test_score/build/letter-portrait/back-cover.tex',
         'test_score/test_score/build/letter-portrait/front-cover.pdf',
         'test_score/test_score/build/letter-portrait/front-cover.tex',
         'test_score/test_score/build/letter-portrait/music.ly',
         'test_score/test_score/build/letter-portrait/parts.ly',
         'test_score/test_score/build/letter-portrait/preface.tex',
         'test_score/test_score/build/letter-portrait/score.tex',
     ]
     if platform.system().lower() == 'windows':
         expected_files = [
             _.replace('/', os.path.sep) for _ in expected_files
         ]
     self.create_score()
     self.create_segment('test_segment')
     self.illustrate_segments()
     self.collect_segments()
     target_path = self.create_build_target()
     script = commandlinetools.ManageBuildTargetScript()
     command = [
         '--render',
         'letter-portrait',
         '--front-cover',
     ]
     #with systemtools.RedirectedStreams(stdout=self.string_io):
     with systemtools.TemporaryDirectoryChange(str(self.score_path)):
         try:
             script(command)
         except SystemExit:
             raise RuntimeError('SystemExit')
     self.compare_path_contents(target_path, expected_files)
     assert open_file_mock.called
Пример #14
0
 def test_success_one_segment(self, open_file_mock):
     self.create_score()
     self.create_segment('test_segment')
     script = commandlinetools.ManageSegmentScript()
     command = ['--illustrate', 'test_segment']
     with systemtools.RedirectedStreams(stdout=self.string_io):
         with systemtools.TemporaryDirectoryChange(str(self.score_path)):
             try:
                 script(command)
             except SystemExit as e:
                 raise RuntimeError('SystemExit: {}'.format(e.code))
     self.compare_captured_output(r'''
         Illustration candidates: 'test_segment' ...
             Reading test_score/segments/metadata.json ... OK!
         Illustrating test_score/segments/test_segment/
             Reading test_score/segments/metadata.json ... OK!
             Reading test_score/segments/test_segment/metadata.json ... JSON does not exist.
             Importing test_score.segments.test_segment.definition
             Writing test_score/segments/test_segment/metadata.json
                 Abjad runtime: ... second...
             Writing test_score/segments/test_segment/illustration.ly ... OK!
             Writing test_score/segments/test_segment/illustration.pdf ... OK!
                 LilyPond runtime: ... second...
             Illustrated test_score/segments/test_segment/
     '''.replace('/', os.path.sep))
     self.compare_path_contents(self.segments_path, self.expected_files)
     illustration_path = self.segments_path.joinpath(
         'test_segment', 'illustration.ly')
     self.compare_lilypond_contents(
         illustration_path,
         self.expected_illustration_contents,
     )
Пример #15
0
 def _build_api(
     self,
     docs_directory=None,
     api_generator=None,
     api_title=None,
     api_format='html',
     clean=False,
     rst_only=False,
     ):
     api_generator(verbose=True)
     if rst_only:
         return
     print('Now building the {} {} docs ...'.format(
         api_title,
         api_format.upper(),
         ))
     print('')
     with systemtools.TemporaryDirectoryChange(docs_directory):
         if clean:
             print('Cleaning build directory ...')
             command = 'make clean'
             systemtools.IOManager.spawn_subprocess(command)
         if format == 'coverage':
             command = 'sphinx-build -b coverage {} {}'.format(
                 'source',
                 os.path.join('build', 'coverage'),
                 )
             systemtools.IOManager.spawn_subprocess(command)
         else:
             command = 'make {}'.format(api_format)
             systemtools.IOManager.spawn_subprocess(command)
Пример #16
0
    def add(self, dry_run=False):
        r'''Adds files to repository.

        Returns none.
        '''
        change = systemtools.TemporaryDirectoryChange(directory=self._path)
        with change:
            inputs = self._get_unadded_asset_paths()
            outputs = []
            if dry_run:
                return inputs, outputs
            if not inputs:
                message = 'nothing to add.'
                self._io_manager._display(message)
                return
            messages = []
            messages.append('will add ...')
            for path in inputs:
                messages.append(self._tab + path)
            self._io_manager._display(messages)
            result = self._io_manager._confirm()
            if self._session.is_backtracking or not result:
                return
            command = self._repository_add_command
            assert isinstance(command, str)
            self._io_manager.run_command(command)
Пример #17
0
 def find_target_file_paths(
     absolute_directory_path,
     relative_directory_path,
     file_name_pattern,
     pages,
     ):
     #print(file_name_pattern, pages)
     with systemtools.TemporaryDirectoryChange(absolute_directory_path):
         file_name_matches = glob.glob(file_name_pattern)
         file_name_matches = [_ for _ in file_name_matches
             if '-thumbnail' not in _]
     #print('\t', file_name_matches)
     target_file_name_dict = {}
     if len(file_name_matches) == 1 and '-page' not in file_name_matches[0]:
         target_file_name_dict[1] = file_name_matches[0]
     else:
         for file_name_match in file_name_matches:
             re_match = SphinxDocumentHandler._image_target_pattern.match(
                 file_name_match)
             page = int(re_match.groups()[0])
             target_file_name_dict[page] = file_name_match
     target_file_names = []
     found_all_pages = False
     if pages is None:
         target_file_names.extend(target_file_name_dict.values())
         found_all_pages = bool(target_file_names)
     else:
         for page in pages:
             if page in target_file_name_dict:
                 target_file_names.append(target_file_name_dict[page])
         if len(target_file_names) == len(pages):
             found_all_pages = True
     target_file_paths = [posixpath.join(relative_directory_path, _)
         for _ in target_file_names]
     return target_file_paths, found_all_pages
 def _handle_stage(self):
     from abjad import abjad_configuration
     print('Staging segments:')
     all_names = [
         path.name for path in self._list_segment_subpackages(
             self._score_package_path)
     ]
     old_staged_names = self._read_segments_list_json()
     contents = self._create_staging_contents(all_names, old_staged_names)
     with systemtools.TemporaryDirectory() as directory:
         with systemtools.TemporaryDirectoryChange(directory):
             file_path = 'segments.txt'
             with open(file_path, 'w') as file_pointer:
                 file_pointer.write(contents)
             command = '{} {}'.format(
                 abjad_configuration.get_text_editor(),
                 file_path,
             )
             self._call_subprocess(command)
             with open(file_path, 'r') as file_pointer:
                 contents = file_pointer.read()
     lines = (line.strip() for line in contents.splitlines())
     lines = (line for line in lines if not line.startswith('#'))
     lines = (line for line in lines if line in all_names)
     new_staged_names = list(lines)
     if new_staged_names != old_staged_names:
         self._write_segments_list_json(new_staged_names)
     print('Staged:')
     for name in new_staged_names:
         print('    {}'.format(name))
Пример #19
0
    def revert(self):
        r'''Reverts files to repository.

        Returns none.
        '''
        change = systemtools.TemporaryDirectoryChange(directory=self._path)
        with change:
            self._session._attempted_to_revert = True
            if self._session.is_repository_test:
                return
            paths = []
            paths.extend(self._get_added_asset_paths())
            paths.extend(self._get_modified_asset_paths())
            messages = []
            messages.append('will revert ...')
            for path in paths:
                messages.append(self._io_manager._tab + path)
            self._io_manager._display(messages)
            result = self._io_manager._confirm()
            if self._session.is_backtracking or not result:
                return
            commands = []
            if self._is_in_git_repository():
                for path in paths:
                    command = 'git checkout {}'.format(path)
                    commands.append(command)
            elif self._is_svn_versioned():
                for path in paths:
                    command = 'svn revert {}'.format(path)
                    commands.append(command)
            else:
                raise ValueError(self)
            command = ' && '.join(commands)
            self._io_manager.spawn_subprocess(command)
Пример #20
0
    def commit(self, commit_message=None):
        r'''Commits files to repository.

        Returns none.
        '''
        change = systemtools.TemporaryDirectoryChange(directory=self._path)
        with change:
            self._session._attempted_to_commit = True
            if self._session.is_repository_test:
                return
            if commit_message is None:
                getter = self._io_manager._make_getter()
                getter.append_string('commit message')
                commit_message = getter._run()
                if self._session.is_backtracking or commit_message is None:
                    return
                message = 'commit message will be: "{}"'
                message = message.format(commit_message)
                self._io_manager._display(message)
                result = self._io_manager._confirm()
                if self._session.is_backtracking or not result:
                    return
            message = self._get_score_package_directory_name()
            message = message + ' ...'
            command = self._make_repository_commit_command(commit_message)
            self._io_manager.run_command(command, capitalize=False)
    def test_explicit(self):
        self.create_score()
        script = commandlinetools.ManageBuildTargetScript()
        command = [
            '--new',
            '--paper-size', 'a3',
            '--orientation', 'landscape',
            ]
        with systemtools.RedirectedStreams(stdout=self.string_io):
            with systemtools.TemporaryDirectoryChange(str(self.score_path)):
                try:
                    script(command)
                except SystemExit:
                    raise RuntimeError('SystemExit')
        self.compare_captured_output(r'''
        Creating build target 'a3-landscape' (297mm x 420mm)
            Reading test_score/metadata.json ... OK!
            Created test_score/build/a3-landscape
        '''.replace('/', os.path.sep))
        path = self.build_path.joinpath('a3-landscape', 'score.tex')
        self.compare_lilypond_contents(path, r'''
            \documentclass{article}
            \usepackage[papersize={420mm, 297mm}]{geometry}
            \usepackage{pdfpages}
            \begin{document}

            \includepdf[pages=-]{front-cover.pdf}
            \includepdf[pages=-]{preface.pdf}
            \includepdf[angle=-90,pages=-]{music.pdf}
            \includepdf[pages=-]{back-cover.pdf}

            \end{document}
        ''')
Пример #22
0
 def illustrate_segment(self, segment_name):
     script = commandlinetools.ManageSegmentScript()
     command = ['--illustrate', segment_name]
     with systemtools.TemporaryDirectoryChange(str(self.score_path)):
         try:
             script(command)
         except SystemExit as e:
             raise RuntimeError('SystemExit: {}'.format(e.code))
 def test_success(self, call_subprocess_mock):
     call_subprocess_mock.return_value = 0
     self.create_score()
     self.create_segment('segment_a')
     self.create_segment('segment_b')
     self.create_segment('segment_c')
     script = commandlinetools.ManageSegmentScript()
     command = ['--stage']
     with systemtools.RedirectedStreams(stdout=self.string_io):
         with systemtools.TemporaryDirectoryChange(str(self.score_path)):
             try:
                 script(command)
             except SystemExit as e:
                 raise RuntimeError('SystemExit: {}'.format(e.code))
     self.compare_captured_output(r'''
     Staging segments:
         Reading test_score/segments/metadata.json ... OK!
     Staged:
         segment_a
         segment_b
         segment_c
     '''.replace('/', os.path.sep))
     call_subprocess_mock.assert_called_with(
         '{} segments.txt'.format(abjad_configuration.get_text_editor()),
         )
     call_subprocess_mock.side_effect = self.side_effect
     self.reset_string_io()
     with systemtools.RedirectedStreams(stdout=self.string_io):
         with systemtools.TemporaryDirectoryChange(str(self.score_path)):
             try:
                 script(command)
             except SystemExit as e:
                 raise RuntimeError('SystemExit: {}'.format(e.code))
     self.compare_captured_output(r'''
     Staging segments:
         Reading test_score/segments/metadata.json ... OK!
         Writing test_score/segments/metadata.json
     Staged:
         segment_c
         segment_b
         segment_a
     '''.replace('/', os.path.sep))
     call_subprocess_mock.assert_called_with(
         '{} segments.txt'.format(abjad_configuration.get_text_editor()),
         )
Пример #24
0
def test_materials(material_name):
    materials = importlib.import_module('{}.materials'.format(root_name))
    material = getattr(materials, material_name, None)
    if not material:
        pytest.skip('No nominative material.')
    elif not hasattr(material, '__illustrate__'):
        pytest.skip('No illustratable material.')
    with systemtools.TemporaryDirectoryChange(str(test_path)):
        script = commandlinetools.ManageMaterialScript()
        command = ['--illustrate', material_name]
        with mock.patch('abjad.systemtools.IOManager.open_file'):
            script(command)
Пример #25
0
 def _is_up_to_date(self):
     if self._is_in_git_repository():
         command = 'git status --porcelain {}'
     elif self._is_svn_versioned():
         command = 'svn st {}'
     else:
         raise ValueError(self)
     command = command.format(self._path)
     with systemtools.TemporaryDirectoryChange(directory=self._path):
         process = self._io_manager.make_subprocess(command)
     first_line = self._io_manager._read_one_line_from_pipe(process.stdout)
     return first_line == ''
Пример #26
0
 def _is_git_versioned(self, path=None):
     path = path or self._path
     if not self._is_in_git_repository(path=path):
         return False
     command = 'git status --porcelain {}'
     command = command.format(path)
     with systemtools.TemporaryDirectoryChange(directory=self._path):
         process = self._io_manager.make_subprocess(command)
     first_line = self._io_manager._read_one_line_from_pipe(process.stdout)
     if first_line.startswith('?'):
         return False
     return True
Пример #27
0
 def get_xml_path(tag, test=False):
     data_directory = os.path.join(
         os.path.abspath(os.path.dirname(__file__)),
         '..',
         'data',
     )
     if Bootstrapper.is_test or test:
         glob_pattern = 'discogs_test_{}s.xml.gz'.format(tag)
     else:
         glob_pattern = 'discogs_2*_{}s.xml.gz'.format(tag)
     with systemtools.TemporaryDirectoryChange(data_directory):
         files = sorted(glob.glob(glob_pattern))
     return os.path.join(data_directory, files[-1])
Пример #28
0
 def test_list_materials_no_materials(self):
     self.create_score()
     script = commandlinetools.ManageMaterialScript()
     command = ['--list']
     with systemtools.RedirectedStreams(stdout=self.string_io):
         with systemtools.TemporaryDirectoryChange(str(self.score_path)):
             with self.assertRaises(SystemExit) as context_manager:
                 script(command)
             assert context_manager.exception.code == 2
     self.compare_captured_output(r'''
     Available materials:
         No materials available.
     ''')
Пример #29
0
 def test_success_filtered_segments(self, open_file_mock):
     self.create_score()
     self.create_segment('segment_one')
     self.create_segment('segment_two')
     self.create_segment('segment_three')
     script = commandlinetools.ManageSegmentScript()
     command = ['--illustrate', 'segment_t*']
     with systemtools.RedirectedStreams(stdout=self.string_io):
         with systemtools.TemporaryDirectoryChange(str(self.score_path)):
             try:
                 script(command)
             except SystemExit as e:
                 raise RuntimeError('SystemExit: {}'.format(e.code))
     self.compare_captured_output(r'''
         Illustration candidates: 'segment_t*' ...
             Reading test_score/segments/metadata.json ... OK!
         Illustrating test_score/segments/segment_two/
             Reading test_score/segments/metadata.json ... OK!
             Reading test_score/segments/segment_one/metadata.json ... JSON does not exist.
             Reading test_score/segments/segment_two/metadata.json ... JSON does not exist.
             Importing test_score.segments.segment_two.definition
             Writing test_score/segments/segment_two/metadata.json
                 Abjad runtime: ... second...
             Writing test_score/segments/segment_two/illustration.ly ... OK!
             Writing test_score/segments/segment_two/illustration.pdf ... OK!
                 LilyPond runtime: ... second...
             Illustrated test_score/segments/segment_two/
         Illustrating test_score/segments/segment_three/
             Reading test_score/segments/metadata.json ... OK!
             Reading test_score/segments/segment_two/metadata.json ... OK!
             Reading test_score/segments/segment_three/metadata.json ... JSON does not exist.
             Importing test_score.segments.segment_three.definition
             Writing test_score/segments/segment_three/metadata.json
                 Abjad runtime: ... second...
             Writing test_score/segments/segment_three/illustration.ly ... OK!
             Writing test_score/segments/segment_three/illustration.pdf ... OK!
                 LilyPond runtime: ... second...
             Illustrated test_score/segments/segment_three/
     '''.replace('/', os.path.sep))
     assert not self.segments_path.joinpath(
         'segment_one',
         'illustration.pdf',
     ).exists()
     assert self.segments_path.joinpath(
         'segment_two',
         'illustration.pdf',
     ).exists()
     assert self.segments_path.joinpath(
         'segment_three',
         'illustration.pdf',
     ).exists()
Пример #30
0
 def _run(self, input_=None):
     from scoremanager import idetools
     self._session._reinitialize()
     type(self).__init__(self, session=self._session)
     if input_:
         self._session._pending_input = input_
     controller = self._io_manager._controller(
         controller=self,
         consume_local_backtrack=True,
         on_exit_callbacks=(self._session._clean_up, ))
     path = self._configuration.score_manager_directory
     directory_change = systemtools.TemporaryDirectoryChange(path)
     state = systemtools.NullContextManager()
     wrangler_views = os.path.join(
         self._configuration.configuration_directory,
         'views',
         '__metadata__.py',
     )
     if self._session.is_test:
         paths_to_keep = []
         paths_to_keep.append(self._configuration.cache_file_path)
         paths_to_keep.append(wrangler_views)
         state = systemtools.FilesystemState(keep=paths_to_keep)
     interaction = self._io_manager._make_interaction(task=False)
     with controller, directory_change, state, interaction:
         self._session._pending_redraw = True
         if self._session.is_test:
             empty_views = os.path.join(
                 self._configuration.boilerplate_directory,
                 '__views_metadata__.py',
             )
             shutil.copyfile(empty_views, wrangler_views)
         while True:
             result = self._score_package_wrangler._get_sibling_score_path()
             if not result:
                 result = self._session.wrangler_navigation_directive
             if result:
                 self._score_package_wrangler._handle_input(result)
             elif not self._session.is_navigating_home:
                 self._score_package_wrangler._run()
             else:
                 menu = self._make_main_menu()
                 result = menu._run()
                 if result:
                     self._handle_input(result)
             self._update_session_variables()
             if self._session.is_quitting:
                 if not self._transcript[-1][-1] == '':
                     self._io_manager._display('')
                 return