Exemplo n.º 1
0
def _runsetup(setup, executable, *args):
    if os.path.isdir(setup):
        setup = os.path.join(setup, "setup.py")
    d = os.path.dirname(setup)

    args = list(args)
    args.insert(0, "-q")
    env = dict(os.environ)
    if executable == sys.executable:
        env["PYTHONPATH"] = setuptools_location
    # else pass an executable that has setuptools! See testselectingpython.py.

    here = os.getcwd()
    try:
        os.chdir(d)
        p = subprocess.Popen(
            [executable, setup] + args,
            stdout=subprocess.PIPE,
            stderr=subprocess.STDOUT,
            close_fds=MUST_CLOSE_FDS,
            env=env,
        )
        out = p.stdout.read()
        if p.wait():
            print out

        if os.path.exists("build"):
            rmtree("build")
    finally:
        os.chdir(here)
Exemplo n.º 2
0
def _runsetup(setup, executable, *args):
    if os.path.isdir(setup):
        setup = os.path.join(setup, 'setup.py')
    d = os.path.dirname(setup)

    args = list(args)
    args.insert(0, '-q')
    env = dict(os.environ)
    if executable == sys.executable:
        env['PYTHONPATH'] = setuptools_location
    # else pass an executable that has setuptools! See testselectingpython.py.

    here = os.getcwd()
    try:
        os.chdir(d)
        p = subprocess.Popen([executable, setup] + args,
                             stdout=subprocess.PIPE,
                             stderr=subprocess.STDOUT,
                             close_fds=MUST_CLOSE_FDS,
                             env=env)
        out = p.stdout.read()
        if p.wait():
            print out

        if os.path.exists('build'):
            rmtree('build')
    finally:
        os.chdir(here)
Exemplo n.º 3
0
def _runsetup(setup, executable, *args):
    if os.path.isdir(setup):
        setup = os.path.join(setup, 'setup.py')
    d = os.path.dirname(setup)

    args = [zc.buildout.easy_install._safe_arg(arg)
            for arg in args]
    args.insert(0, '-q')
    env = dict(os.environ)
    if executable == sys.executable:
        env['PYTHONPATH'] = setuptools_location
    # else pass an executable that has setuptools! See testselectingpython.py.

    here = os.getcwd()
    try:
        os.chdir(d)
        p = subprocess.Popen(
            [zc.buildout.easy_install._safe_arg(executable), setup] + args,
            stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
            close_fds=True, env=env)
        out = p.stdout.read()
        if p.wait():
            print out

        if os.path.exists('build'):
            rmtree('build')
    finally:
        os.chdir(here)
Exemplo n.º 4
0
def _runsetup(setup, *args):
    if os.path.isdir(setup):
        setup = os.path.join(setup, 'setup.py')
    args = list(args)
    args.insert(0, '-q')
    here = os.getcwd()
    try:
        os.chdir(os.path.dirname(setup))
        zc.buildout.easy_install.call_subprocess(
            [sys.executable, setup] + args,
            env=dict(os.environ, PYTHONPATH=setuptools_location))
        if os.path.exists('build'):
            rmtree('build')
    finally:
        os.chdir(here)
Exemplo n.º 5
0
def _runsetup(setup, *args):
    if os.path.isdir(setup):
        setup = os.path.join(setup, 'setup.py')
    args = list(args)
    args.insert(0, '-q')
    here = os.getcwd()
    try:
        os.chdir(os.path.dirname(setup))
        zc.buildout.easy_install.call_subprocess(
            [sys.executable, setup] + args,
            env=dict(os.environ, PYTHONPATH=setuptools_location))
        if os.path.exists('build'):
            rmtree('build')
    finally:
        os.chdir(here)
Exemplo n.º 6
0
def _runsetup(setup, executable, *args):
    if os.path.isdir(setup):
        setup = os.path.join(setup, 'setup.py')
    d = os.path.dirname(setup)

    args = [zc.buildout.easy_install._safe_arg(arg)
            for arg in args]
    args.insert(0, '-q')
    args.append(dict(os.environ, PYTHONPATH=setuptools_location))

    here = os.getcwd()
    try:
        os.chdir(d)
        os.spawnle(os.P_WAIT, executable,
                   zc.buildout.easy_install._safe_arg(executable),
                   setup, *args)
        if os.path.exists('build'):
            rmtree('build')
    finally:
        os.chdir(here)
Exemplo n.º 7
0
def _runsetup(setup, executable, *args):
    if os.path.isdir(setup):
        setup = os.path.join(setup, 'setup.py')
    d = os.path.dirname(setup)

    args = [zc.buildout.easy_install._safe_arg(arg) for arg in args]
    args.insert(0, '-q')
    env = dict(os.environ)
    if executable == sys.executable:
        env['PYTHONPATH'] = setuptools_location
    # else pass an executable that has setuptools! See testselectingpython.py.
    args.append(env)

    here = os.getcwd()
    try:
        os.chdir(d)
        os.spawnle(os.P_WAIT, executable,
                   zc.buildout.easy_install._safe_arg(executable), setup,
                   *args)
        if os.path.exists('build'):
            rmtree('build')
    finally:
        os.chdir(here)
Exemplo n.º 8
0
def _runsetup(setup, executable, *args):
    if os.path.isdir(setup):
        setup = os.path.join(setup, 'setup.py')
    d = os.path.dirname(setup)

    args = [zc.buildout.easy_install._safe_arg(arg)
            for arg in args]
    args.insert(0, '-q')
    env = dict(os.environ)
    if executable == sys.executable:
        env['PYTHONPATH'] = setuptools_location
    # else pass an executable that has setuptools! See testselectingpython.py.
    args.append(env)

    here = os.getcwd()
    try:
        os.chdir(d)
        os.spawnle(os.P_WAIT, executable,
                   zc.buildout.easy_install._safe_arg(executable),
                   setup, *args)
        if os.path.exists('build'):
            rmtree('build')
    finally:
        os.chdir(here)
Exemplo n.º 9
0
def buildoutSetUp(test):

    test.globs['__tear_downs'] = __tear_downs = []
    test.globs['register_teardown'] = register_teardown = __tear_downs.append

    installer_values = get_installer_values()
    register_teardown(lambda: set_installer_values(installer_values))

    here = os.getcwd()
    register_teardown(lambda: os.chdir(here))

    handlers_before_set_up = logging.getLogger().handlers[:]

    def restore_root_logger_handlers():
        root_logger = logging.getLogger()
        for handler in root_logger.handlers[:]:
            root_logger.removeHandler(handler)
        for handler in handlers_before_set_up:
            root_logger.addHandler(handler)

    register_teardown(restore_root_logger_handlers)

    base = tempfile.mkdtemp('buildoutSetUp')
    base = os.path.realpath(base)
    register_teardown(lambda base=base: rmtree(base))

    old_home = os.environ.get('HOME')
    os.environ['HOME'] = os.path.join(base, 'bbbBadHome')

    def restore_home():
        if old_home is None:
            del os.environ['HOME']
        else:
            os.environ['HOME'] = old_home

    register_teardown(restore_home)

    base = os.path.join(base, '_TEST_')
    os.mkdir(base)

    tmp = tempfile.mkdtemp('buildouttests')
    register_teardown(lambda: rmtree(tmp))

    zc.buildout.easy_install.default_index_url = 'file://' + tmp
    os.environ['buildout-testing-index-url'] = (
        zc.buildout.easy_install.default_index_url)
    os.environ.pop('PYTHONPATH', None)

    def tmpdir(name):
        path = os.path.join(base, name)
        mkdir(path)
        return path

    sample = tmpdir('sample-buildout')

    os.chdir(sample)
    make_buildout()

    def start_server(path):
        port, thread = _start_server(path, name=path)
        url = 'http://localhost:%s/' % port
        register_teardown(lambda: stop_server(url, thread))
        return url

    def make_py(initialization=''):
        """Returns paths to new executable and to its site-packages.
        """
        buildout = tmpdir('executable_buildout')
        site_packages_dir = os.path.join(buildout, 'site-packages')
        mkdir(site_packages_dir)
        old_wd = os.getcwd()
        os.chdir(buildout)
        make_buildout()
        # Normally we don't process .pth files in extra-paths.  We want to
        # in this case so that we can test with setuptools system installs
        # (--single-version-externally-managed), which use .pth files.
        initialization = (
            ('import sys\n'
             'import site\n'
             'known_paths = set(sys.path)\n'
             'site_packages_dir = %r\n'
             'site.addsitedir(site_packages_dir, known_paths)\n') %
            (site_packages_dir, )) + initialization
        initialization = '\n'.join('  ' + line
                                   for line in initialization.split('\n'))
        install_develop('zc.recipe.egg', os.path.join(buildout,
                                                      'develop-eggs'))
        install_develop('z3c.recipe.scripts',
                        os.path.join(buildout, 'develop-eggs'))
        write(
            'buildout.cfg',
            textwrap.dedent('''\
            [buildout]
            parts = py
            include-site-packages = false
            exec-sitecustomize = false

            [py]
            recipe = z3c.recipe.scripts
            interpreter = py
            initialization =
            %(initialization)s
            extra-paths = %(site-packages)s
            eggs = setuptools
            ''') % {
                'initialization': initialization,
                'site-packages': site_packages_dir
            })
        system(os.path.join(buildout, 'bin', 'buildout'))
        os.chdir(old_wd)
        return (os.path.join(buildout, 'bin', 'py'), site_packages_dir)

    cdpaths = []

    def cd(*path):
        path = os.path.join(*path)
        cdpaths.append(os.path.abspath(os.getcwd()))
        os.chdir(path)

    def uncd():
        os.chdir(cdpaths.pop())

    test.globs.update(
        dict(
            sample_buildout=sample,
            ls=ls,
            cat=cat,
            mkdir=mkdir,
            rmdir=rmdir,
            remove=remove,
            tmpdir=tmpdir,
            write=write,
            system=system,
            call_py=call_py,
            get=get,
            cd=cd,
            uncd=uncd,
            join=os.path.join,
            sdist=sdist,
            bdist_egg=bdist_egg,
            start_server=start_server,
            buildout=os.path.join(sample, 'bin', 'buildout'),
            wait_until=wait_until,
            make_py=make_py,
            clean_up_pyc=clean_up_pyc,
        ))
Exemplo n.º 10
0
def buildoutSetUp(test):

    test.globs['__tear_downs'] = __tear_downs = []
    test.globs['register_teardown'] = register_teardown = __tear_downs.append

    prefer_final = zc.buildout.easy_install.prefer_final()
    register_teardown(
        lambda: zc.buildout.easy_install.prefer_final(prefer_final))

    here = os.getcwd()
    register_teardown(lambda: os.chdir(here))

    handlers_before_set_up = logging.getLogger().handlers[:]

    def restore_root_logger_handlers():
        root_logger = logging.getLogger()
        for handler in root_logger.handlers[:]:
            root_logger.removeHandler(handler)
        for handler in handlers_before_set_up:
            root_logger.addHandler(handler)
        bo_logger = logging.getLogger('zc.buildout')
        for handler in bo_logger.handlers[:]:
            bo_logger.removeHandler(handler)

    register_teardown(restore_root_logger_handlers)

    base = tempfile.mkdtemp('buildoutSetUp')
    base = os.path.realpath(base)
    register_teardown(lambda base=base: rmtree(base))

    old_home = os.environ.get('HOME')
    os.environ['HOME'] = os.path.join(base, 'bbbBadHome')

    def restore_home():
        if old_home is None:
            del os.environ['HOME']
        else:
            os.environ['HOME'] = old_home

    register_teardown(restore_home)

    base = os.path.join(base, '_TEST_')
    os.mkdir(base)

    tmp = tempfile.mkdtemp('buildouttests')
    register_teardown(lambda: rmtree(tmp))

    zc.buildout.easy_install.default_index_url = 'file://' + tmp
    os.environ['buildout_testing_index_url'] = (
        zc.buildout.easy_install.default_index_url)

    def tmpdir(name):
        path = os.path.join(base, name)
        mkdir(path)
        return path

    sample = tmpdir('sample-buildout')

    os.chdir(sample)

    # Create a basic buildout.cfg to avoid a warning from buildout:
    with open('buildout.cfg', 'w') as f:
        f.write("[buildout]\nparts =\n")

    # Use the buildout bootstrap command to create a buildout
    zc.buildout.buildout.Buildout(
        'buildout.cfg',
        [
            ('buildout', 'log-level', 'WARNING'),
            # trick bootstrap into putting the buildout develop egg
            # in the eggs dir.
            ('buildout', 'develop-eggs-directory', 'eggs'),
        ]).bootstrap([])

    # Create the develop-eggs dir, which didn't get created the usual
    # way due to the trick above:
    os.mkdir('develop-eggs')

    path_to_coveragerc = os.getenv("COVERAGE_PROCESS_START", None)
    if path_to_coveragerc is not None:

        # Before we return to the current directory and destroy the
        # temporary working directory, we need to copy all the coverage files
        # back so that they can be `coverage combine`d.
        def copy_coverage_files():
            coveragedir = os.path.dirname(path_to_coveragerc)
            import glob
            for f in glob.glob('.coverage*'):
                shutil.copy(f, coveragedir)

        __tear_downs.insert(0, copy_coverage_files)

        # Now we must modify the newly created bin/buildout to
        # actually begin coverage.
        with open('bin/buildout') as f:
            import textwrap
            lines = f.read().splitlines()
            assert lines[1] == '', lines
            lines[1] = 'import coverage; coverage.process_startup()'

        with open('bin/buildout', 'w') as f:
            f.write('\n'.join(lines))

    def start_server(path):
        port, thread = _start_server(path, name=path)
        url = 'http://localhost:%s/' % port
        register_teardown(lambda: stop_server(url, thread))
        return url

    cdpaths = []

    def cd(*path):
        path = os.path.join(*path)
        cdpaths.append(os.path.abspath(os.getcwd()))
        os.chdir(path)

    def uncd():
        os.chdir(cdpaths.pop())

    test.globs.update(
        dict(
            sample_buildout=sample,
            ls=ls,
            cat=cat,
            mkdir=mkdir,
            rmdir=rmdir,
            remove=remove,
            tmpdir=tmpdir,
            write=write,
            system=system,
            get=get,
            cd=cd,
            uncd=uncd,
            join=os.path.join,
            sdist=sdist,
            bdist_egg=bdist_egg,
            start_server=start_server,
            stop_server=stop_server,
            buildout=os.path.join(sample, 'bin', 'buildout'),
            wait_until=wait_until,
            print_=print_,
            clean_up_pyc=clean_up_pyc,
        ))

    zc.buildout.easy_install.prefer_final(prefer_final)
 def tearDown(self):
     os.chdir(self.here)
     rmtree.rmtree(self.location)
    def test_install(self):
        """"""
        from ..recipes import Recipe
        from ..recipes import mappings

        buildout = self.buildout
        recipe_options = self.recipe_options.copy()
        recipe_options.update(
            {
                "black-enabled": "1",
                "black-args": "--line-length 88",
                "black-path": "$project_path/bin/black",
                "flake8-enabled": "True",
                "flake8-args": "--max-line-length 88",
                "flake8-path": "${buildout:directory}/bin/flake8",
                "isort-enabled": "True",
                "isort-path": "${buildout:directory}/bin/isort",
                "generate-envfile": "True",
            }
        )
        buildout["vscode"] = recipe_options
        recipe = Recipe(buildout, "vscode", buildout["vscode"])
        recipe.install()

        generated_settings = json.loads(
            read(os.path.join(self.location, ".vscode", "settings.json"))
        )
        # should be two, zc,recipe.egg, python site-package path
        self.assertEqual(
            2, len(generated_settings[mappings["autocomplete-extrapaths"]])
        )
        self.assertEqual(
            generated_settings[mappings["flake8-path"]], self.location + "/bin/flake8"
        )

        # Isort executable should get automatically
        self.assertEqual(
            generated_settings[mappings["isort-path"]],
            self.location + "/bin/isort"
        )

        # Test existence and configuration of env file
        envfile_path = os.path.join(self.location, ".vscode", ".env")
        self.assertEqual(generated_settings["python.envFile"], envfile_path)
        self.assertTrue(os.path.isfile(envfile_path))

        # Test with custom location with package
        buildout["vscode"].update({
            "packages": "/fake/path",
            "project-root": os.path.join(tempfile.gettempdir(), "hshdshgdrts"),
        })

        recipe = Recipe(buildout, "vscode", buildout["vscode"])
        recipe.install()

        generated_settings = json.loads(
            read(
                os.path.join(
                    buildout["vscode"]["project-root"], ".vscode", "settings.json"
                )
            )
        )

        # Now should three (two+one) links
        self.assertEqual(
            3, len(generated_settings[mappings["autocomplete-extrapaths"]])
        )

        # restore
        rmtree.rmtree(buildout["vscode"]["project-root"])
        del buildout["vscode"]["project-root"]
        del buildout["vscode"]["packages"]

        # Test ignores
        buildout["buildout"].update({"develop": "."})
        buildout["vscode"].update({"ignores": "zc.buildout", "ignore-develop": "True"})
        recipe = Recipe(buildout, "vscode", buildout["vscode"])
        recipe.install()

        generated_settings = json.loads(
            read(os.path.join(self.location, ".vscode", "settings.json"))
        )

        # should be two, zc.buildout is ignored
        self.assertEqual(
            2, len(generated_settings[mappings["autocomplete-extrapaths"]])
        )

        # Failed Test: existing project file with invalid json
        write(
            os.path.join(self.location, ".vscode"), "settings.json", """I am invalid"""
        )
        try:
            recipe.update()
            raise AssertionError(
                "Code should not come here, as invalid json inside existing project"
                "file! ValueError raised by UserError"
            )
        except UserError:
            pass

        # Failed Test: exception rasied by zc.recipe.Egg
        recipe.options.update(
            {
                # Invalid Egg
                "eggs": "\\"
            }
        )
        try:
            recipe.install()
            raise AssertionError(
                "Code should not come here, as should raised execption "
                "because of invalid eggs"
            )
        except UserError:
            pass
Exemplo n.º 13
0
    def test_install(self):
        """"""
        from ..recipes import Recipe

        buildout = self.buildout
        recipe_options = self.recipe_options.copy()
        recipe_options.update({
            'jedi-enabled': '1',
            'sublimelinter-enabled': '1',
            'sublimelinter-pylint-enabled': 'True',
            'anaconda-enabled': 'True',
        })
        buildout['sublimetext'] = recipe_options
        recipe = Recipe(buildout, 'sublimetext', buildout['sublimetext'])
        recipe.install()

        generated_settings = json.loads(
            read(
                os.path.join(
                    self.location,
                    recipe_options['project-name'] + '.sublime-project')), )
        # should be three, zc.buildout, zc,recipe.egg, python site-package path
        self.assertEqual(
            3, len(generated_settings['settings']['python_package_paths']))
        self.assertEqual(3, len(generated_settings['settings']['extra_paths']))
        self.assertIsInstance(
            generated_settings['settings']['python_interpreter'], str_)
        self.assertIn(
            recipe.buildout['buildout']['directory'] + '/bin/python',
            generated_settings['build_systems'][0]['shell_cmd'],
        )

        # Test with custom location with package
        buildout['sublimetext'].update({
            'packages':
            '/fake/path',
            'location':
            os.path.join(tempfile.gettempdir(), 'hshdshgdrts'),
        })

        recipe = Recipe(buildout, 'sublimetext', buildout['sublimetext'])
        recipe.install()

        generated_settings = json.loads(
            read(
                os.path.join(
                    buildout['sublimetext']['location'],
                    recipe_options['project-name'] + '.sublime-project',
                )), )

        # Now should four links
        self.assertEqual(
            4, len(generated_settings['settings']['python_package_paths']))

        # Make sure settings file is created at custom location
        self.assertTrue(
            os.path.exists(
                os.path.join(
                    buildout['sublimetext']['location'],
                    buildout['sublimetext']['project-name'] +
                    '.sublime-project',
                )))

        # restore
        rmtree.rmtree(buildout['sublimetext']['location'])
        del buildout['sublimetext']['location']
        del buildout['sublimetext']['packages']

        # Test ignores
        buildout['buildout'].update({
            'develop': '.',
        })
        buildout['sublimetext'].update({
            'ignores': 'zc.buildout',
            'ignore-develop': 'True',
        })
        recipe = Recipe(buildout, 'sublimetext', buildout['sublimetext'])
        recipe.install()

        generated_settings = json.loads(
            read(
                os.path.join(
                    self.location,
                    recipe_options['project-name'] + '.sublime-project')), )

        # should be two, zc.buildout is ignored
        self.assertEqual(
            2, len(generated_settings['settings']['python_package_paths']))

        # Failed Test: existing project file with invalid json
        write(
            self.location,
            recipe_options['project-name'] + '.sublime-project',
            """I am invalid""",
        )
        try:
            recipe.update()
            raise AssertionError(
                'Code should not come here, as invalid json inside existing project'
                'file! ValueError raised by UserError', )
        except UserError:
            pass

        # Failed Test: exception rasied by zc.recipe.Egg
        recipe.options.update({
            # Invalid Egg
            'eggs': '\\',
        })
        try:
            recipe.install()
            raise AssertionError(
                'Code should not come here, as should raised execption because of invalied eggs'
            )
        except UserError:
            pass
Exemplo n.º 14
0
def buildoutSetUp(test):

    test.globs['__tear_downs'] = __tear_downs = []
    test.globs['register_teardown'] = register_teardown = __tear_downs.append

    installer_values = get_installer_values()
    register_teardown(
        lambda: set_installer_values(installer_values)
        )

    here = os.getcwd()
    register_teardown(lambda: os.chdir(here))

    handlers_before_set_up = logging.getLogger().handlers[:]
    def restore_root_logger_handlers():
        root_logger = logging.getLogger()
        for handler in root_logger.handlers[:]:
            root_logger.removeHandler(handler)
        for handler in handlers_before_set_up:
            root_logger.addHandler(handler)
    register_teardown(restore_root_logger_handlers)

    base = tempfile.mkdtemp('buildoutSetUp')
    base = os.path.realpath(base)
    register_teardown(lambda base=base: rmtree(base))

    old_home = os.environ.get('HOME')
    os.environ['HOME'] = os.path.join(base, 'bbbBadHome')
    def restore_home():
        if old_home is None:
            del os.environ['HOME']
        else:
            os.environ['HOME'] = old_home
    register_teardown(restore_home)

    base = os.path.join(base, '_TEST_')
    os.mkdir(base)

    tmp = tempfile.mkdtemp('buildouttests')
    register_teardown(lambda: rmtree(tmp))

    zc.buildout.easy_install.default_index_url = 'file://'+tmp
    os.environ['buildout-testing-index-url'] = (
        zc.buildout.easy_install.default_index_url)

    def tmpdir(name):
        path = os.path.join(base, name)
        mkdir(path)
        return path

    sample = tmpdir('sample-buildout')

    os.chdir(sample)
    make_buildout()

    def start_server(path):
        port, thread = _start_server(path, name=path)
        url = 'http://localhost:%s/' % port
        register_teardown(lambda: stop_server(url, thread))
        return url

    def make_py(initialization=''):
        """Returns paths to new executable and to its site-packages.
        """
        buildout = tmpdir('executable_buildout')
        site_packages_dir = os.path.join(buildout, 'site-packages')
        mkdir(site_packages_dir)
        old_wd = os.getcwd()
        os.chdir(buildout)
        make_buildout()
        # Normally we don't process .pth files in extra-paths.  We want to
        # in this case so that we can test with setuptools system installs
        # (--single-version-externally-managed), which use .pth files.
        initialization = (
            ('import sys\n'
             'import site\n'
             'known_paths = set(sys.path)\n'
             'site_packages_dir = %r\n'
             'site.addsitedir(site_packages_dir, known_paths)\n'
            ) % (site_packages_dir,)) + initialization
        initialization = '\n'.join(
            '  ' + line for line in initialization.split('\n'))
        install_develop(
            'zc.recipe.egg', os.path.join(buildout, 'develop-eggs'))
        install_develop(
            'z3c.recipe.scripts', os.path.join(buildout, 'develop-eggs'))
        write('buildout.cfg', textwrap.dedent('''\
            [buildout]
            parts = py

            [py]
            recipe = z3c.recipe.scripts
            interpreter = py
            initialization =
            %(initialization)s
            extra-paths = %(site-packages)s
            eggs = setuptools
            ''') % {
                'initialization': initialization,
                'site-packages': site_packages_dir})
        system(os.path.join(buildout, 'bin', 'buildout'))
        os.chdir(old_wd)
        return (
            os.path.join(buildout, 'bin', 'py'), site_packages_dir)

    test.globs.update(dict(
        sample_buildout = sample,
        ls = ls,
        cat = cat,
        mkdir = mkdir,
        rmdir = rmdir,
        remove = remove,
        tmpdir = tmpdir,
        write = write,
        system = system,
        call_py = call_py,
        get = get,
        cd = (lambda *path: os.chdir(os.path.join(*path))),
        join = os.path.join,
        sdist = sdist,
        bdist_egg = bdist_egg,
        start_server = start_server,
        buildout = os.path.join(sample, 'bin', 'buildout'),
        wait_until = wait_until,
        make_py = make_py
        ))
Exemplo n.º 15
0
def buildoutSetUp(test):

    test.globs["__tear_downs"] = __tear_downs = []
    test.globs["register_teardown"] = register_teardown = __tear_downs.append

    installer_values = get_installer_values()
    register_teardown(lambda: set_installer_values(installer_values))

    here = os.getcwd()
    register_teardown(lambda: os.chdir(here))

    handlers_before_set_up = logging.getLogger().handlers[:]

    def restore_root_logger_handlers():
        root_logger = logging.getLogger()
        for handler in root_logger.handlers[:]:
            root_logger.removeHandler(handler)
        for handler in handlers_before_set_up:
            root_logger.addHandler(handler)

    register_teardown(restore_root_logger_handlers)

    base = tempfile.mkdtemp("buildoutSetUp")
    base = os.path.realpath(base)
    register_teardown(lambda base=base: rmtree(base))

    old_home = os.environ.get("HOME")
    os.environ["HOME"] = os.path.join(base, "bbbBadHome")

    def restore_home():
        if old_home is None:
            del os.environ["HOME"]
        else:
            os.environ["HOME"] = old_home

    register_teardown(restore_home)

    base = os.path.join(base, "_TEST_")
    os.mkdir(base)

    tmp = tempfile.mkdtemp("buildouttests")
    register_teardown(lambda: rmtree(tmp))

    zc.buildout.easy_install.default_index_url = "file://" + tmp
    os.environ["buildout-testing-index-url"] = zc.buildout.easy_install.default_index_url
    os.environ.pop("PYTHONPATH", None)

    def tmpdir(name):
        path = os.path.join(base, name)
        mkdir(path)
        return path

    sample = tmpdir("sample-buildout")

    os.chdir(sample)
    make_buildout()

    def start_server(path):
        port, thread = _start_server(path, name=path)
        url = "http://localhost:%s/" % port
        register_teardown(lambda: stop_server(url, thread))
        return url

    def make_py(initialization=""):
        """Returns paths to new executable and to its site-packages.
        """
        buildout = tmpdir("executable_buildout")
        site_packages_dir = os.path.join(buildout, "site-packages")
        mkdir(site_packages_dir)
        old_wd = os.getcwd()
        os.chdir(buildout)
        make_buildout()
        # Normally we don't process .pth files in extra-paths.  We want to
        # in this case so that we can test with setuptools system installs
        # (--single-version-externally-managed), which use .pth files.
        initialization = (
            (
                "import sys\n"
                "import site\n"
                "known_paths = set(sys.path)\n"
                "site_packages_dir = %r\n"
                "site.addsitedir(site_packages_dir, known_paths)\n"
            )
            % (site_packages_dir,)
        ) + initialization
        initialization = "\n".join("  " + line for line in initialization.split("\n"))
        install_develop("zc.recipe.egg", os.path.join(buildout, "develop-eggs"))
        install_develop("z3c.recipe.scripts", os.path.join(buildout, "develop-eggs"))
        write(
            "buildout.cfg",
            textwrap.dedent(
                """\
            [buildout]
            parts = py
            include-site-packages = false
            exec-sitecustomize = false

            [py]
            recipe = z3c.recipe.scripts
            interpreter = py
            initialization =
            %(initialization)s
            extra-paths = %(site-packages)s
            eggs = setuptools
            """
            )
            % {"initialization": initialization, "site-packages": site_packages_dir},
        )
        system(os.path.join(buildout, "bin", "buildout"))
        os.chdir(old_wd)
        return (os.path.join(buildout, "bin", "py"), site_packages_dir)

    cdpaths = []

    def cd(*path):
        path = os.path.join(*path)
        cdpaths.append(os.path.abspath(os.getcwd()))
        os.chdir(path)

    def uncd():
        os.chdir(cdpaths.pop())

    test.globs.update(
        dict(
            sample_buildout=sample,
            ls=ls,
            cat=cat,
            mkdir=mkdir,
            rmdir=rmdir,
            remove=remove,
            tmpdir=tmpdir,
            write=write,
            system=system,
            call_py=call_py,
            get=get,
            cd=cd,
            uncd=uncd,
            join=os.path.join,
            sdist=sdist,
            bdist_egg=bdist_egg,
            start_server=start_server,
            buildout=os.path.join(sample, "bin", "buildout"),
            wait_until=wait_until,
            make_py=make_py,
            clean_up_pyc=clean_up_pyc,
        )
    )
Exemplo n.º 16
0
def buildoutSetUp(test):

    test.globs['__tear_downs'] = __tear_downs = []
    test.globs['register_teardown'] = register_teardown = __tear_downs.append

    prefer_final = zc.buildout.easy_install.prefer_final()
    register_teardown(
        lambda: zc.buildout.easy_install.prefer_final(prefer_final)
        )

    here = os.getcwd()
    register_teardown(lambda: os.chdir(here))

    handlers_before_set_up = logging.getLogger().handlers[:]
    def restore_root_logger_handlers():
        root_logger = logging.getLogger()
        for handler in root_logger.handlers[:]:
            root_logger.removeHandler(handler)
        for handler in handlers_before_set_up:
            root_logger.addHandler(handler)
        bo_logger = logging.getLogger('zc.buildout')
        for handler in bo_logger.handlers[:]:
            bo_logger.removeHandler(handler)
    register_teardown(restore_root_logger_handlers)

    base = tempfile.mkdtemp('buildoutSetUp')
    base = os.path.realpath(base)
    register_teardown(lambda base=base: rmtree(base))

    old_home = os.environ.get('HOME')
    os.environ['HOME'] = os.path.join(base, 'bbbBadHome')
    def restore_home():
        if old_home is None:
            del os.environ['HOME']
        else:
            os.environ['HOME'] = old_home
    register_teardown(restore_home)

    base = os.path.join(base, '_TEST_')
    os.mkdir(base)

    tmp = tempfile.mkdtemp('buildouttests')
    register_teardown(lambda: rmtree(tmp))

    zc.buildout.easy_install.default_index_url = 'file://'+tmp
    os.environ['buildout-testing-index-url'] = (
        zc.buildout.easy_install.default_index_url)

    def tmpdir(name):
        path = os.path.join(base, name)
        mkdir(path)
        return path

    sample = tmpdir('sample-buildout')

    os.chdir(sample)

    # Create a basic buildout.cfg to avoid a warning from buildout:
    with open('buildout.cfg', 'w') as f:
        f.write("[buildout]\nparts =\n")

    # Use the buildout bootstrap command to create a buildout
    zc.buildout.buildout.Buildout(
        'buildout.cfg',
        [('buildout', 'log-level', 'WARNING'),
         # trick bootstrap into putting the buildout develop egg
         # in the eggs dir.
         ('buildout', 'develop-eggs-directory', 'eggs'),
         ]
        ).bootstrap([])



    # Create the develop-eggs dir, which didn't get created the usual
    # way due to the trick above:
    os.mkdir('develop-eggs')

    if os.getenv("COVERAGE_PROCESS_START"):
        # The user has requested subprocess code coverage. Since we will be changing
        # directories, we need to make sure this path is absolute, which means
        # we need to temporarily return to our starting directory.
        os.chdir(here)
        path_to_coveragerc = os.path.abspath(os.environ['COVERAGE_PROCESS_START'])
        os.chdir(sample)
        assert os.path.isfile(path_to_coveragerc), path_to_coveragerc
        os.environ['COVERAGE_PROCESS_START'] = path_to_coveragerc

        # Before we return to the current directory and destroy the
        # temporary working directory, we need to copy all the coverage files
        # back so that they can be `coverage combine`d.
        def copy_coverage_files():
            coveragedir = os.path.dirname(path_to_coveragerc)
            import glob
            for f in glob.glob('.coverage*'):
                shutil.copy(f, coveragedir)
        __tear_downs.insert(0, copy_coverage_files)


        # Now we must modify the newly created bin/buildout to
        # actually begin coverage.
        with open('bin/buildout') as f:
            import textwrap
            lines = f.read().splitlines()
            assert lines[1] == '', lines
            lines[1] = 'import coverage; coverage.process_startup()'

        with open('bin/buildout', 'w') as f:
            f.write('\n'.join(lines))

    def start_server(path):
        port, thread = _start_server(path, name=path)
        url = 'http://localhost:%s/' % port
        register_teardown(lambda: stop_server(url, thread))
        return url

    cdpaths = []
    def cd(*path):
        path = os.path.join(*path)
        cdpaths.append(os.path.abspath(os.getcwd()))
        os.chdir(path)

    def uncd():
        os.chdir(cdpaths.pop())

    test.globs.update(dict(
        sample_buildout = sample,
        ls = ls,
        cat = cat,
        mkdir = mkdir,
        rmdir = rmdir,
        remove = remove,
        tmpdir = tmpdir,
        write = write,
        system = system,
        get = get,
        cd = cd, uncd = uncd,
        join = os.path.join,
        sdist = sdist,
        bdist_egg = bdist_egg,
        start_server = start_server,
        buildout = os.path.join(sample, 'bin', 'buildout'),
        wait_until = wait_until,
        print_ = print_,
        clean_up_pyc = clean_up_pyc,
        ))

    zc.buildout.easy_install.prefer_final(prefer_final)
Exemplo n.º 17
0
def buildoutSetUp(test):

    test.globs['__tear_downs'] = __tear_downs = []
    test.globs['register_teardown'] = register_teardown = __tear_downs.append

    prefer_final = zc.buildout.easy_install.prefer_final()
    register_teardown(
        lambda: zc.buildout.easy_install.prefer_final(prefer_final)
        )

    here = os.getcwd()
    register_teardown(lambda: os.chdir(here))

    handlers_before_set_up = logging.getLogger().handlers[:]
    def restore_root_logger_handlers():
        root_logger = logging.getLogger()
        for handler in root_logger.handlers[:]:
            root_logger.removeHandler(handler)
        for handler in handlers_before_set_up:
            root_logger.addHandler(handler)
    register_teardown(restore_root_logger_handlers)

    base = tempfile.mkdtemp('buildoutSetUp')
    base = os.path.realpath(base)
    register_teardown(lambda base=base: rmtree(base))

    old_home = os.environ.get('HOME')
    os.environ['HOME'] = os.path.join(base, 'bbbBadHome')
    def restore_home():
        if old_home is None:
            del os.environ['HOME']
        else:
            os.environ['HOME'] = old_home
    register_teardown(restore_home)

    base = os.path.join(base, '_TEST_')
    os.mkdir(base)

    tmp = tempfile.mkdtemp('buildouttests')
    register_teardown(lambda: rmtree(tmp))

    zc.buildout.easy_install.default_index_url = 'file://'+tmp
    os.environ['buildout-testing-index-url'] = (
        zc.buildout.easy_install.default_index_url)

    def tmpdir(name):
        path = os.path.join(base, name)
        mkdir(path)
        return path

    sample = tmpdir('sample-buildout')

    os.chdir(sample)

    # Create a basic buildout.cfg to avoid a warning from buildout:
    with open('buildout.cfg', 'w') as f:
        f.write("[buildout]\nparts =\n")

    # Use the buildout bootstrap command to create a buildout
    zc.buildout.buildout.Buildout(
        'buildout.cfg',
        [('buildout', 'log-level', 'WARNING'),
         # trick bootstrap into putting the buildout develop egg
         # in the eggs dir.
         ('buildout', 'develop-eggs-directory', 'eggs'),
         ]
        ).bootstrap([])



    # Create the develop-eggs dir, which didn't get created the usual
    # way due to the trick above:
    os.mkdir('develop-eggs')

    def start_server(path):
        port, thread = _start_server(path, name=path)
        url = 'http://localhost:%s/' % port
        register_teardown(lambda: stop_server(url, thread))
        return url

    cdpaths = []
    def cd(*path):
        path = os.path.join(*path)
        cdpaths.append(os.path.abspath(os.getcwd()))
        os.chdir(path)

    def uncd():
        os.chdir(cdpaths.pop())

    test.globs.update(dict(
        sample_buildout = sample,
        ls = ls,
        cat = cat,
        mkdir = mkdir,
        rmdir = rmdir,
        remove = remove,
        tmpdir = tmpdir,
        write = write,
        system = system,
        get = get,
        cd = cd, uncd = uncd,
        join = os.path.join,
        sdist = sdist,
        bdist_egg = bdist_egg,
        start_server = start_server,
        buildout = os.path.join(sample, 'bin', 'buildout'),
        wait_until = wait_until,
        print_ = print_,
        clean_up_pyc = clean_up_pyc,
        ))

    zc.buildout.easy_install.prefer_final(prefer_final)
Exemplo n.º 18
0
def buildoutSetUp(test):

    test.globs['__tear_downs'] = __tear_downs = []
    test.globs['register_teardown'] = register_teardown = __tear_downs.append

    prefer_final = zc.buildout.easy_install.prefer_final()
    register_teardown(
        lambda: zc.buildout.easy_install.prefer_final(prefer_final))

    here = os.getcwd()
    register_teardown(lambda: os.chdir(here))

    handlers_before_set_up = logging.getLogger().handlers[:]

    def restore_root_logger_handlers():
        root_logger = logging.getLogger()
        for handler in root_logger.handlers[:]:
            root_logger.removeHandler(handler)
        for handler in handlers_before_set_up:
            root_logger.addHandler(handler)

    register_teardown(restore_root_logger_handlers)

    base = tempfile.mkdtemp('buildoutSetUp')
    base = os.path.realpath(base)
    register_teardown(lambda base=base: rmtree(base))

    old_home = os.environ.get('HOME')
    os.environ['HOME'] = os.path.join(base, 'bbbBadHome')

    def restore_home():
        if old_home is None:
            del os.environ['HOME']
        else:
            os.environ['HOME'] = old_home

    register_teardown(restore_home)

    base = os.path.join(base, '_TEST_')
    os.mkdir(base)

    tmp = tempfile.mkdtemp('buildouttests')
    register_teardown(lambda: rmtree(tmp))

    zc.buildout.easy_install.default_index_url = 'file://' + tmp
    os.environ['buildout-testing-index-url'] = (
        zc.buildout.easy_install.default_index_url)

    def tmpdir(name):
        path = os.path.join(base, name)
        mkdir(path)
        return path

    sample = tmpdir('sample-buildout')

    os.chdir(sample)

    # Create a basic buildout.cfg to avoid a warning from buildout:
    with open('buildout.cfg', 'w') as f:
        f.write("[buildout]\nparts =\n")

    # Use the buildout bootstrap command to create a buildout
    zc.buildout.buildout.Buildout(
        'buildout.cfg',
        [
            ('buildout', 'log-level', 'WARNING'),
            # trick bootstrap into putting the buildout develop egg
            # in the eggs dir.
            ('buildout', 'develop-eggs-directory', 'eggs'),
        ]).bootstrap([])

    # Create the develop-eggs dir, which didn't get created the usual
    # way due to the trick above:
    os.mkdir('develop-eggs')

    def start_server(path):
        port, thread = _start_server(path, name=path)
        url = 'http://localhost:%s/' % port
        register_teardown(lambda: stop_server(url, thread))
        return url

    cdpaths = []

    def cd(*path):
        path = os.path.join(*path)
        cdpaths.append(os.path.abspath(os.getcwd()))
        os.chdir(path)

    def uncd():
        os.chdir(cdpaths.pop())

    test.globs.update(
        dict(
            sample_buildout=sample,
            ls=ls,
            cat=cat,
            mkdir=mkdir,
            rmdir=rmdir,
            remove=remove,
            tmpdir=tmpdir,
            write=write,
            system=system,
            get=get,
            cd=cd,
            uncd=uncd,
            join=os.path.join,
            sdist=sdist,
            bdist_egg=bdist_egg,
            start_server=start_server,
            buildout=os.path.join(sample, 'bin', 'buildout'),
            wait_until=wait_until,
            print_=print_,
            clean_up_pyc=clean_up_pyc,
        ))

    zc.buildout.easy_install.prefer_final(prefer_final)