Пример #1
0
    def from_notebook_node(self, nb, resources=None, **kw):
        latex, resources = super(PDFExporter, self).from_notebook_node(
            nb, resources=resources, **kw
        )
        # set texinputs directory, so that local files will be found
        if resources and resources.get('metadata', {}).get('path'):
            self.texinputs = resources['metadata']['path']
        else:
            self.texinputs = getcwd()

        self._captured_outputs = []
        with TemporaryWorkingDirectory():
            notebook_name = 'notebook'
            resources['output_extension'] = '.tex'
            tex_file = self.writer.write(latex, resources, notebook_name=notebook_name)
            self.log.info("Building PDF")
            self.run_latex(tex_file)
            if self.run_bib(tex_file):
                self.run_latex(tex_file)

            pdf_file = notebook_name + '.pdf'
            if not os.path.isfile(pdf_file):
                raise LatexFailed('\n'.join(self._captured_output))
            self.log.info('PDF successfully created')
            with open(pdf_file, 'rb') as f:
                pdf_data = f.read()
        
        # convert output extension to pdf
        # the writer above required it to be tex
        resources['output_extension'] = '.pdf'
        # clear figure outputs, extracted by latex export,
        # so we don't claim to be a multi-file export.
        resources.pop('outputs', None)
        
        return pdf_data, resources
Пример #2
0
def test_console_example():
    responses.add_callback(
        'GET',
        re.compile(r'https://www.python.org/ftp/.*'),
        callback=respond_python_zip,
        content_type='application/zip',
    )

    with TemporaryWorkingDirectory() as td:
        for src in example_dir.iterdir():
            copy(str(src), td)


        with modified_env({CACHE_ENV_VAR: td}), \
             MockCommand('makensis') as makensis:
            ec = main(['installer.cfg'])

        assert ec == 0
        assert makensis.get_calls()[0]['argv'][1].endswith('installer.nsi')

        build_dir = Path(td, 'build', 'nsis')
        assert_isdir(build_dir)
        assert_isfile(build_dir / 'Python' / 'python.exe')
        assert_isfile(build_dir / 'pkgs' / 'guessnumber.py')
        assert_isfile(build_dir / 'Guess_the_Number.launch.py')
Пример #3
0
    def create_temp_cwd(self, copy_filenames=None):
        temp_dir = TemporaryWorkingDirectory()

        #Copy the files if requested.
        if copy_filenames is not None:
            self.copy_files_to(copy_filenames, dest=temp_dir.name)

        #Return directory handler
        return temp_dir
Пример #4
0
def test_save(sim_server):
    with TemporaryWorkingDirectory() as td:
        glimpse.main(['--save', sim_server.endpoint])
        files = os.listdir(td)
        assert len(files) == 1
        path = os.path.join(td, files[0])
        with h5py.File(path, 'r') as f:
            trainId = f['SPB_DET_AGIPD1M-1/DET/0CH0:xtdf/image.trainId'][:]
            assert trainId[0] == 10000000000
Пример #5
0
    def test_cli(self):
        from testpath.tempdir import TemporaryWorkingDirectory

        source_path = self._get_filepath('tests/notebooks/notebook.ipynb')

        with TemporaryWorkingDirectory():
            app = nblineage.extensionapp.ExtensionApp()
            app.initialize(['new-root-meme', source_path, 'output.ipynb'])
            app.start()

            with io.open('output.ipynb') as f:
                newnb = self._read_notebook_from_stream(f)

            self.assertEqual(1, len(newnb.cells[0].metadata['lc_cell_meme']['history']))
            self.assertEqual(1, len(newnb.cells[1].metadata['lc_cell_meme']['history']))
            self.assertEqual(1, len(newnb.cells[2].metadata['lc_cell_meme']['history']))

            self.assertNotEqual(
                newnb.cells[0].metadata['lc_cell_meme']['current'],
                newnb.cells[0].metadata['lc_cell_meme']['history'][0]['current'])
            self.assertNotEqual(
                newnb.cells[1].metadata['lc_cell_meme']['current'],
                newnb.cells[1].metadata['lc_cell_meme']['history'][0]['current'])
            self.assertNotEqual(
                newnb.cells[2].metadata['lc_cell_meme']['current'],
                newnb.cells[2].metadata['lc_cell_meme']['history'][0]['current'])

            self.assertIsNone(
                newnb.cells[0].metadata['lc_cell_meme']['history'][0]['previous'])
            self.assertEqual(
                newnb.cells[1].metadata['lc_cell_meme']['history'][0]['current'],
                newnb.cells[0].metadata['lc_cell_meme']['history'][0]['next'])
            self.assertEqual(
                newnb.cells[0].metadata['lc_cell_meme']['history'][0]['current'],
                newnb.cells[1].metadata['lc_cell_meme']['history'][0]['previous'])
            self.assertEqual(
                newnb.cells[2].metadata['lc_cell_meme']['history'][0]['current'],
                newnb.cells[1].metadata['lc_cell_meme']['history'][0]['next'])
            self.assertEqual(
                newnb.cells[1].metadata['lc_cell_meme']['history'][0]['current'],
                newnb.cells[2].metadata['lc_cell_meme']['history'][0]['previous'])
            self.assertIsNone(
                newnb.cells[2].metadata['lc_cell_meme']['history'][0]['next'])

            self.assertEqual(1, len(newnb.metadata['lc_notebook_meme']['root_cells_history']))
            self.assertEqual(3, len(newnb.metadata['lc_notebook_meme']['root_cells_history'][0]))
            for i in range(3):
                self.assertEqual(
                    newnb.metadata['lc_notebook_meme']['root_cells_history'][0][i],
                    [
                        newnb.cells[i].metadata['lc_cell_meme']['history'][0]['current'],
                        newnb.cells[i].metadata['lc_cell_meme']['current']
                    ]
                )
Пример #6
0
def test_build_wheel_relpath():
    hooks = get_hooks('pkg1')
    with TemporaryWorkingDirectory() as builddir:
        with modified_env({'PYTHONPATH': BUILDSYS_PKGS}):
            whl_file = hooks.build_wheel('.', {})

        assert whl_file.endswith('.whl')
        assert os.sep not in whl_file

        whl_file = pjoin(builddir, whl_file)
        assert_isfile(whl_file)
        assert zipfile.is_zipfile(whl_file)
Пример #7
0
    def from_notebook_node(self, nb, resources=None, **kw):
        """ Generate a PDF from a given parsed notebook node
        """
        output, resources = super(PDFQtExporter,
                                  self).from_notebook_node(nb,
                                                           resources=resources,
                                                           **kw)

        with TemporaryWorkingDirectory() as td:
            for path, res in resources.get("outputs", {}).items():
                dest = os.path.join(td, os.path.basename(path))
                shutil.copyfile(path, dest)

            index_html = os.path.join(td, "index.html")

            with open(index_html, "w+") as fp:
                fp.write(output)

            ipynb = "notebook.ipynb"

            with open(os.path.join(td, ipynb), "w") as fp:
                nbformat.write(nb, fp)

            self.log.info("Building PDF...")

            subprocess.check_call(
                [sys.executable, "-m", "nbconvert_pdfqt.printer", td],
                env=dict(
                    **os.environ,
                    QTWEBENGINE_DISABLE_SANDBOX="1",
                    QT_WEBENGINE_DISABLE_GPU="1",
                    QTWEBENGINE_CHROMIUM_FLAGS=
                    "--headless --disable-gpu --no-sandbox --single-process --enable-logging --log-level=0"
                ))

            pdf_file = "notebook.pdf"

            if not os.path.isfile(pdf_file):
                raise IOError("PDF creating failed")

            self.log.info("PDF successfully created")

            with open(pdf_file, 'rb') as f:
                pdf_data = f.read()

        # convert output extension to pdf
        # the writer above required it to be tex
        resources['output_extension'] = '.pdf'
        # clear figure outputs, extracted by pdf export,
        # so we don't claim to be a multi-file export.
        resources.pop('outputs', None)

        return pdf_data, resources
Пример #8
0
    def from_notebook_node(self, nb, resources=None, **kw):
        # ********************************************** #
        # From LatexExporter
        # https://github.com/jupyter/nbconvert/blob/master/nbconvert/exporters/latex.py
        langinfo = nb.metadata.get("language_info", {})
        lexer = langinfo.get("pygments_lexer", langinfo.get("name", None))
        highlight_code = self.filters.get(
            "highlight_code", Highlight2Latex(pygments_lexer=lexer, parent=self)
        )
        self.register_filter("highlight_code", highlight_code)
        # ********************************************** #

        # ***************** CUSTOM CODE **************** #
        # call the overridden from_notebook_node
        latex, resources = super()._from_notebook_node_override(
            nb, resources=resources, **kw
        )
        # ********************************************** #

        # ********************************************** #
        # From PDFExporter
        # set texinputs directory, so that local files will be found
        if resources and resources.get("metadata", {}).get("path"):
            self.texinputs = resources["metadata"]["path"]
        else:
            self.texinputs = getcwd()

        self._captured_outputs = []
        with TemporaryWorkingDirectory():
            notebook_name = "notebook"
            resources["output_extension"] = ".tex"
            tex_file = self.writer.write(latex, resources, notebook_name=notebook_name)
            self.log.info("Building PDF")
            self.run_latex(tex_file)
            if self.run_bib(tex_file):
                self.run_latex(tex_file)

            pdf_file = notebook_name + ".pdf"
            if not os.path.isfile(pdf_file):
                raise LatexFailed("\n".join(self._captured_output))
            self.log.info("PDF successfully created")
            with open(pdf_file, "rb") as f:
                pdf_data = f.read()

        # convert output extension to pdf
        # the writer above required it to be tex
        resources["output_extension"] = ".pdf"
        # clear figure outputs, extracted by latex export,
        # so we don't claim to be a multi-file export.
        resources.pop("outputs", None)

        return pdf_data, resources
Пример #9
0
    def test_cli_file_already_exists(self):
        from testpath.tempdir import TemporaryWorkingDirectory

        source_path = self._get_filepath('tests/notebooks/notebook.ipynb')

        with TemporaryWorkingDirectory():
            with io.open('output.ipynb', 'w') as f:
                pass

            app = nblineage.extensionapp.ExtensionApp()
            app.initialize(['new-root-meme', source_path, 'output.ipynb'])

            with self.assertRaises(SystemExit):
                app.start()
Пример #10
0
def test_tomlify():
    with TemporaryWorkingDirectory() as td:
        copy(str(samples_dir / 'entrypoints_valid.ini'),
             os.path.join(td, 'flit.ini'))
        copy(str(samples_dir / 'some_entry_points.txt'), td)
        tomlify.main(argv=[])

        pyproject_toml = Path(td, 'pyproject.toml')
        assert_isfile(pyproject_toml)

        with pyproject_toml.open(encoding='utf-8') as f:
            content = pytoml.load(f)

        assert 'build-system' in content
        assert 'tool' in content
        assert 'flit' in content['tool']
        flit_table = content['tool']['flit']
        assert 'metadata' in flit_table
        assert 'scripts' in flit_table
        assert 'entrypoints' in flit_table
Пример #11
0
 def create_temp_cwd(self, copy_filenames=None):
     return TemporaryWorkingDirectory()