Ejemplo n.º 1
0
def test_args_backward(tmpdir):
    tmpdir.chdir()
    enable_coverage()
    requirements('')

    with pytest.raises(CalledProcessError) as excinfo:
        venv_update('venv=', 'requirements.txt')

    # py26 doesn't have a consistent exit code:
    #   http://bugs.python.org/issue15033
    assert excinfo.value.returncode != 0
    out, err = excinfo.value.result
    err = strip_coverage_warnings(err)
    err = strip_pip_warnings(err)
    assert err == ''
    out = uncolor(out)
    assert out.rsplit('\n', 4)[-4:] == [
        '> virtualenv requirements.txt',
        'ERROR: File already exists and is not a directory.',
        'Please provide a different path or delete the file.',
        '',
    ]

    assert Path('requirements.txt').isfile()
    assert Path('requirements.txt').read() == ''
    assert not Path('myvenv').exists()
Ejemplo n.º 2
0
def venv_update_symlink_pwd():
    # I wish I didn't need this =/
    # surely there's a better way -.-
    # NOTE: `pip install TOP` causes an infinite copyfiles loop, under tox >.<
    from venv_update import __file__ as venv_update_path, dotpy

    # symlink so that we get coverage, where possible
    venv_update_path = Path(dotpy(venv_update_path))
    local_vu = Path(venv_update_path.basename)
    local_vu.mksymlinkto(venv_update_path)
Ejemplo n.º 3
0
def test_override_requirements_file(tmpdir):
    tmpdir.chdir()
    enable_coverage()
    requirements('')
    Path('.').join('requirements-bootstrap.txt').write('''\
venv-update==%s
pure_python_package
''' % __version__)
    out, err = venv_update(
        'bootstrap-deps=',
        '-r',
        'requirements-bootstrap.txt',
    )
    err = strip_pip_warnings(err)
    assert err == ('You must give at least one requirement to install '
                   '(see "pip help install")\n')

    out = uncolor(out)
    assert '\n> pip install -r requirements-bootstrap.txt\n' in out
    assert (
        '\nSuccessfully installed pure-python-package-0.2.1 venv-update-%s' %
        __version__) in out
    assert '\n  Successfully uninstalled pure-python-package-0.2.1\n' in out

    expected = '\n'.join(
        ('appdirs==1.4.0', 'packaging==16.8', 'pip==9.0.1',
         'pyparsing==2.1.10', 'setuptools==34.1.1', 'six==1.10.0',
         'venv-update==' + __version__, 'wheel==0.29.0', ''))
    assert pip_freeze() == expected
Ejemplo n.º 4
0
def pipe_output(read, write):
    from os import environ
    environ = environ.copy()
    environ['HOME'] = str(Path('.').realpath())

    from subprocess import Popen
    vupdate = Popen(
        ('venv-update', '--version'),
        env=environ,
        stdout=write,
        close_fds=True,
    )

    from os import close
    from testing.capture_subprocess import read_all
    close(write)
    result = read_all(read)
    vupdate.wait()

    result = result.decode('US-ASCII')
    uncolored = uncolor(result)
    assert uncolored.startswith('> ')
    # FIXME: Sometimes this is 'python -m', sometimes 'python2.7 -m'. Weird.
    assert uncolored.endswith('''\
 -m virtualenv virtualenv_run --version
1.11.6
''')

    return result, uncolored
Ejemplo n.º 5
0
def test_override_requirements_file(tmpdir):
    tmpdir.chdir()
    enable_coverage()
    requirements('')
    Path('.').ensure_dir('requirements.d').join('venv-update.txt').write('''\
venv-update==%s
pure_python_package
''' % __version__)
    out, err = venv_update()
    err = strip_pip_warnings(err)
    assert err == ''

    out = uncolor(out)
    assert (
        '\n> pip install --find-links=file://%s/home/.cache/pip-faster/wheelhouse -r requirements.d/venv-update.txt\n' % tmpdir
    ) in out
    assert (
        '\nSuccessfully installed pip-1.5.6 pure-python-package-0.2.0 venv-update-%s' % __version__
    ) in out
    assert '\n  Successfully uninstalled pure-python-package\n' in out

    expected = '\n'.join((
        'venv-update==%s' % __version__,
        'wheel==0.29.0',
        ''
    ))
    assert pip_freeze() == expected
Ejemplo n.º 6
0
def test_override_requirements_file(tmpdir):
    tmpdir.chdir()
    requirements('')
    Path('.').ensure_dir('requirements.d').join('venv-update.txt').write('''\
pip-faster==%s
pure_python_package
''' % __version__)
    out, err = venv_update()
    err = strip_pip_warnings(err)
    assert err == ''

    out = uncolor(out)
    assert ' '.join((
        '\n> venv/bin/python -m pip.__main__ install',
        '-r requirements.d/venv-update.txt\n',
    )) in out
    expected = ('\nSuccessfully installed pip-1.5.6 pip-faster-%s pure-python-package-0.2.0 virtualenv-1.11.6' % __version__)
    assert expected in out
    assert '\n  Successfully uninstalled pure-python-package\n' in out

    expected = '\n'.join((
        'pip-faster==%s' % __version__,
        'virtualenv==1.11.6',
        'wheel==0.29.0',
        ''
    ))
    assert pip_freeze() == expected
Ejemplo n.º 7
0
def test_override_requirements_file(tmpdir):
    tmpdir.chdir()
    enable_coverage()
    requirements('')
    Path('.').join('requirements-bootstrap.txt').write('''\
venv-update==%s
pure_python_package
''' % __version__)
    out, err = venv_update(
        'bootstrap-deps=', '-r', 'requirements-bootstrap.txt',
    )
    err = strip_pip_warnings(err)
    # pip>=10 doesn't complain about installing an empty requirements file.
    assert err == ''

    out = uncolor(out)
    assert '\n> pip install -r requirements-bootstrap.txt\n' in out
    assert (
        '\nSuccessfully installed pure-python-package-0.2.1 venv-update-%s' % __version__
    ) in out
    assert '\n  Successfully uninstalled pure-python-package-0.2.1\n' in out

    expected = '\n'.join((
        'venv-update==' + __version__,
        ''
    ))
    assert pip_freeze() == expected
Ejemplo n.º 8
0
        def venv_setup():
            # First just set up a blank virtualenv, this'll bypass the
            # bootstrap when we're actually testing for speed
            if not Path('venv').exists():
                requirements('')
                venv_update()
            install_coverage()

            # Now the actual requirements we'll install
            requirements('\n'.join(
                ('project_with_c', 'pure_python_package==0.2.1',
                 'slow_python_package==0.1.0', 'dependant_package',
                 'many_versions_package>=2,<3', '')))

            yield

            expected = '\n'.join(
                ('appdirs==1.4.3', 'dependant-package==1',
                 'implicit-dependency==1', 'many-versions-package==2.1',
                 'packaging==16.8', 'pip==9.0.1', 'project-with-c==0.1.0',
                 'pure-python-package==0.2.1', 'pyparsing==2.2.0',
                 'setuptools==35.0.2', 'six==1.10.0',
                 'slow-python-package==0.1.0', 'venv-update==%s' % __version__,
                 'wheel==0.29.0', ''))
            assert pip_freeze() == expected
Ejemplo n.º 9
0
 def pgdir(self):
     """Retrieve the set playground directory"""
     for parent in search_parent_directories():
         pgdir = Path(parent).join(self.pgconf['pgdir'], abs=1)
         if pgdir.check(dir=True):
             return pgdir
     raise NoPlayground("could not find any directory named '%s'" %
                        self.pgconf['pgdir'])
Ejemplo n.º 10
0
def venv_update_script(pyscript, venv='venv'):
    """Run a python script that imports venv_update"""

    # symlink so that we get coverage, where possible
    venv_update_symlink_pwd()

    # write it to a file so we get more-reasonable stack traces
    testscript = Path('testscript.py')
    testscript.write(pyscript)
    return run('%s/bin/python' % venv, testscript.strpath)
Ejemplo n.º 11
0
def test_args_backward(tmpdir):
    tmpdir.chdir()
    requirements('')

    from subprocess import CalledProcessError
    with pytest.raises(CalledProcessError) as excinfo:
        venv_update('requirements.txt', 'myvenv')

    # py26 doesn't have a consistent exit code:
    #   http://bugs.python.org/issue15033
    assert excinfo.value.returncode != 0
    _, err = excinfo.value.result
    lasterr = strip_coverage_warnings(err).rsplit('\n', 2)[-2]
    errname = 'NotADirectoryError' if PY33 else 'OSError'
    assert lasterr.startswith(errname + ': [Errno 20] Not a directory'), err

    assert Path('requirements.txt').isfile()
    assert Path('requirements.txt').read() == ''
    assert not Path('myvenv').exists()
Ejemplo n.º 12
0
 def service_by_name(self, service_name):
     """Return an instantiated Service, by name."""
     if os.path.isabs(service_name):
         path = Path(service_name)
     else:
         path = self.pgdir.join(service_name, abs=1)
     return Service(
         path,
         self.pghome.join(path.relto(str('/')), abs=1),
         self.pgconf['timeout'],
     )
Ejemplo n.º 13
0
def assert_timestamps(*reqs):
    firstreq = Path(reqs[0])
    lastreq = Path(reqs[-1])
    args = ['install='] + sum([['-r', req] for req in reqs], [])

    venv_update(*args)

    assert firstreq.mtime() < Path('venv').mtime()

    # garbage, to cause a failure
    lastreq.write('-w wat')

    with pytest.raises(CalledProcessError) as excinfo:
        venv_update(*args)

    assert excinfo.value.returncode == 1
    assert firstreq.mtime() > Path('venv').mtime()

    # blank requirements should succeed
    lastreq.write('')

    venv_update(*args)
    assert firstreq.mtime() < Path('venv').mtime()
Ejemplo n.º 14
0
def test_scripts_left_behind(tmpdir):
    tmpdir.chdir()
    requirements('')

    venv_update()

    # an arbitrary small package with a script: pep8
    script_path = Path('venv/bin/pep8')
    assert not script_path.exists()

    run('venv/bin/pip', 'install', 'pep8')
    assert script_path.exists()

    venv_update()
    assert not script_path.exists()
Ejemplo n.º 15
0
def test_arguments_system_packages(tmpdir):
    """Show that we can pass arguments through to virtualenv"""
    tmpdir.chdir()
    requirements('')

    venv_update('venv=', '--system-site-packages', 'venv')

    out, err = run('venv/bin/python', '-c', '''\
import sys
for p in sys.path:
    if p.startswith(sys.real_prefix) and p.endswith("-packages"):
        print(p)
        break
''')
    assert err == ''
    out = out.rstrip('\n')
    assert out and Path(out).isdir()
Ejemplo n.º 16
0
    def log(self, interactive=None):
        """Displays the stdout and stderr for a service or group of services"""
        # TODO(p3): -n: send the value to tail -n
        # TODO(p3): -f: force iteractive behavior
        # TODO(p3): -F: force iteractive behavior off
        tail = ('tail', '--verbose')  # show file headers

        if interactive is None:
            import sys
            interactive = sys.stdout.isatty()
        if interactive:
            # we're interactive; give a continuous log
            # TODO-TEST: pgctl log | pb should be non-interactive
            tail += ('--follow=name', '--retry')

        pwd = Path()
        logfiles = []
        for service in self.services:
            service.ensure_logs()
            logfiles.append(service.path.join('stdout.log').relto(pwd))
            logfiles.append(service.path.join('stderr.log').relto(pwd))
        exec_(tail + tuple(logfiles))  # never returns
Ejemplo n.º 17
0
def assert_timestamps(*reqs):
    firstreq = Path(reqs[0])
    lastreq = Path(reqs[-1])

    venv_update('--python=python', 'virtualenv_run', *reqs)

    assert firstreq.mtime() < Path('virtualenv_run').mtime()

    # garbage, to cause a failure
    lastreq.write('-w wat')

    from subprocess import CalledProcessError
    with pytest.raises(CalledProcessError) as excinfo:
        venv_update('virtualenv_run', *reqs)

    assert excinfo.value.returncode == 1
    assert firstreq.mtime() > Path('virtualenv_run').mtime()

    # blank requirements should succeed
    lastreq.write('')

    venv_update('virtualenv_run', *reqs)
    assert Path(reqs[0]).mtime() < Path('virtualenv_run').mtime()
Ejemplo n.º 18
0
def scratch_dir(pghome_dir, service_name, in_example_dir):
    yield pghome_dir.join(Path().join('playground',
                                      service_name).relto(str('/')),
                          abs=1)
Ejemplo n.º 19
0
    def pghome(self):
        """Retrieve the set pgctl home directory.

        By default, this is "$XDG_RUNTIME_DIR/pgctl".
        """
        return Path(self.pgconf['pghome'], expanduser=True)
Ejemplo n.º 20
0
def mylang_compile(*args, **env):
    # we get coverage for free via the (patched) pytest-cov plugin
    return run('mylang-compile', *args, HOME=str(Path('.').realpath()), **env)
Ejemplo n.º 21
0
def venv_update(*args, **env):
    # we get coverage for free via the (patched) pytest-cov plugin
    return run('venv-update', *args, HOME=str(Path('.').realpath()), **env)
Ejemplo n.º 22
0
def test_timestamps_multiple(tmpdir):
    tmpdir.chdir()
    requirements('')
    Path('requirements2.txt').write('')
    assert_timestamps('requirements.txt', 'requirements2.txt')
Ejemplo n.º 23
0
def it_removes_down_file():
    path = Path(os.getcwd()).join('playground/slow-startup/down')
    path.ensure()
    assert path.check()
    it_can_succeed()
    assert not path.check()
Ejemplo n.º 24
0
def test_str_and_repr():
    service = Service(Path('/tmp/magic-service'),
                      Path('/tmp/magic-service-scratch'), None)
    assert str(service) == 'magic-service'
Ejemplo n.º 25
0
# NOTE WELL: No side-effects are allowed in __init__ files. This means you!
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals

import os
from re import compile as Regex
from re import DOTALL
from re import MULTILINE

from pip._internal.wheel import Wheel
from py._path.local import LocalPath as Path

TOP = Path(__file__) / '../../..'
COVERAGE_REQS = TOP.join('requirements.d/coverage.txt')


def requirements(reqs, path='requirements.txt'):
    """Write a requirements.txt file to the current working directory."""
    Path(path).write(reqs)


def run(*cmd, **env):
    if env:
        from os import environ
        tmp = env
        env = environ.copy()
        env.update(tmp)
    else:
        env = None
Ejemplo n.º 26
0
def install_coverage(venv='venv'):
    venv = Path(venv)
    if not venv.exists():
        run('virtualenv', str(venv))
    run(str(venv.join('bin/python')), '-m', 'pip.__main__', 'install', '-r',
        str(COVERAGE_REQS))
Ejemplo n.º 27
0
def requirements(reqs, path='requirements.txt'):
    """Write a requirements.txt file to the current working directory."""
    Path(path).write(reqs)