1
1
Fork 0
mirror of https://github.com/pypa/pip synced 2023-12-13 21:30:23 +01:00

more functional/unit tests restructure

This commit is contained in:
Marcus Smith 2013-05-28 14:58:08 -07:00
parent 2e2ce0f4e9
commit 28298c413d
31 changed files with 711 additions and 734 deletions

View file

@ -1,6 +1,6 @@
import zipfile
import textwrap
from os.path import join
from os.path import abspath, exists, join
from pip.download import path_to_url2
from tests.lib import tests_data, reset_env, run_pip, write_file
from tests.lib.path import Path
@ -31,3 +31,38 @@ def test_create_bundle():
assert 'src/FSPkg/' in files
assert 'src/initools/' in files
assert 'build/pip/' in files
def test_cleanup_after_create_bundle():
"""
Test clean up after making a bundle. Make sure (build|src)-bundle/ dirs are removed but not src/.
"""
env = reset_env()
# Install an editable to create a src/ dir.
args = ['install']
args.extend(['-e',
'%s#egg=pip-test-package' %
local_checkout('git+http://github.com/pypa/pip-test-package.git')])
run_pip(*args)
build = env.venv_path/"build"
src = env.venv_path/"src"
assert not exists(build), "build/ dir still exists: %s" % build
assert exists(src), "expected src/ dir doesn't exist: %s" % src
# Make the bundle.
fspkg = 'file://%s/FSPkg' %join(tests_data, 'packages')
pkg_lines = textwrap.dedent('''\
-e %s
-e %s#egg=initools-dev
pip''' % (fspkg, local_checkout('svn+http://svn.colorstudy.com/INITools/trunk')))
write_file('bundle-req.txt', pkg_lines)
run_pip('bundle', '-r', 'bundle-req.txt', 'test.pybundle')
build_bundle = env.scratch_path/"build-bundle"
src_bundle = env.scratch_path/"src-bundle"
assert not exists(build_bundle), "build-bundle/ dir still exists: %s" % build_bundle
assert not exists(src_bundle), "src-bundle/ dir still exists: %s" % src_bundle
env.assert_no_temp()
# Make sure previously created src/ from editable still exists
assert exists(src), "expected src dir doesn't exist: %s" % src

View file

@ -1,38 +0,0 @@
import textwrap
from tests.lib import reset_env, run_pip, pyversion, tests_data, write_file
def test_find_links_relative_path():
"""Test find-links as a relative path."""
e = reset_env()
result = run_pip(
'install',
'parent==0.1',
'--no-index',
'--find-links',
'packages/',
cwd=tests_data)
egg_info_folder = e.site_packages / 'parent-0.1-py%s.egg-info' % pyversion
initools_folder = e.site_packages / 'parent'
assert egg_info_folder in result.files_created, str(result)
assert initools_folder in result.files_created, str(result)
def test_find_links_requirements_file_relative_path():
"""Test find-links as a relative path to a reqs file."""
e = reset_env()
write_file('test-req.txt', textwrap.dedent("""
--no-index
--find-links=../../../../data/packages/
parent==0.1
"""))
result = run_pip(
'install',
'-r',
e.scratch_path / "test-req.txt",
cwd=tests_data)
egg_info_folder = e.site_packages / 'parent-0.1-py%s.egg-info' % pyversion
initools_folder = e.site_packages / 'parent'
assert egg_info_folder in result.files_created, str(result)
assert initools_folder in result.files_created, str(result)

View file

@ -1,79 +1,15 @@
import re
import os
import filecmp
import textwrap
import sys
import textwrap
from os.path import abspath, join, curdir, pardir
from nose.tools import assert_raises
from nose import SkipTest
from mock import patch
from pip.util import rmtree, find_command
from pip.exceptions import BadCommand
from tests.lib import (tests_data, reset_env, run_pip, pyversion, mkdir, pip_install_local,
src_folder, write_file, path_to_url, find_links)
from pip.util import rmtree
from tests.lib import tests_data, reset_env, run_pip, pyversion, mkdir, pip_install_local, write_file, find_links
from tests.lib.local_repos import local_checkout
from tests.lib.path import Path
def test_correct_pip_version():
"""
Check we are running proper version of pip in run_pip.
"""
reset_env()
# output is like:
# pip PIPVERSION from PIPDIRECTORY (python PYVERSION)
result = run_pip('--version')
# compare the directory tree of the invoked pip with that of this source distribution
dir = re.match(r'pip \d(\.[\d])+(\.?(rc|dev|pre|post)\d+)? from (.*) \(python \d(.[\d])+\)$',
result.stdout).group(4)
pip_folder = join(src_folder, 'pip')
pip_folder_outputed = join(dir, 'pip')
diffs = filecmp.dircmp(pip_folder, pip_folder_outputed)
# If any non-matching .py files exist, we have a problem: run_pip
# is picking up some other version! N.B. if this project acquires
# primary resources other than .py files, this code will need
# maintenance
mismatch_py = [x for x in diffs.left_only + diffs.right_only + diffs.diff_files if x.endswith('.py')]
assert not mismatch_py, 'mismatched source files in %r and %r: %r'% (pip_folder, pip_folder_outputed, mismatch_py)
def test_pip_second_command_line_interface_works():
"""
Check if ``pip-<PYVERSION>`` commands behaves equally
"""
e = reset_env()
args = ['pip-%s' % pyversion]
args.extend(['install', 'INITools==0.2'])
result = e.run(*args)
egg_info_folder = e.site_packages / 'INITools-0.2-py%s.egg-info' % pyversion
initools_folder = e.site_packages / 'initools'
assert egg_info_folder in result.files_created, str(result)
assert initools_folder in result.files_created, str(result)
#def test_distutils_configuration_setting():
# """
# Test the distutils-configuration-setting command (which is distinct from other commands).
# """
#print run_pip('-vv', '--distutils-cfg=easy_install:index_url:http://download.zope.org/ppix/', expect_error=True)
#Script result: python ../../poacheggs.py -E .../poacheggs-tests/test-scratch -vv --distutils-cfg=easy_install:index_url:http://download.zope.org/ppix/
#-- stdout: --------------------
#Distutils config .../poacheggs-tests/test-scratch/lib/python.../distutils/distutils.cfg is writable
#Replaced setting index_url
#Updated .../poacheggs-tests/test-scratch/lib/python.../distutils/distutils.cfg
#<BLANKLINE>
#-- updated: -------------------
# lib/python2.4/distutils/distutils.cfg (346 bytes)
def test_install_from_pypi():
"""
Test installing a package from PyPI.
@ -86,30 +22,6 @@ def test_install_from_pypi():
assert initools_folder in result.files_created, str(result)
def test_install_from_mirrors():
"""
Test installing a package from the PyPI mirrors.
"""
e = reset_env()
result = run_pip('install', '-vvv', '--use-mirrors', '--no-index', 'INITools==0.2')
egg_info_folder = e.site_packages / 'INITools-0.2-py%s.egg-info' % pyversion
initools_folder = e.site_packages / 'initools'
assert egg_info_folder in result.files_created, str(result)
assert initools_folder in result.files_created, str(result)
def test_install_from_mirrors_with_specific_mirrors():
"""
Test installing a package from a specific PyPI mirror.
"""
e = reset_env()
result = run_pip('install', '-vvv', '--use-mirrors', '--mirrors', "http://a.pypi.python.org/", '--no-index', 'INITools==0.2')
egg_info_folder = e.site_packages / 'INITools-0.2-py%s.egg-info' % pyversion
initools_folder = e.site_packages / 'initools'
assert egg_info_folder in result.files_created, str(result)
assert initools_folder in result.files_created, str(result)
def test_editable_install():
"""
Test editable installation.
@ -330,56 +242,6 @@ def test_install_as_egg():
assert join(egg_folder, 'fspkg') in result.files_created, str(result)
def test_install_from_wheel():
"""
Test installing from a wheel.
"""
env = reset_env(use_distribute=True)
result = run_pip('install', 'simple.dist', '--use-wheel',
'--no-index', '--find-links='+find_links,
expect_error=False)
dist_info_folder = env.site_packages/'simple.dist-0.1.dist-info'
assert dist_info_folder in result.files_created, (dist_info_folder,
result.files_created,
result.stdout)
def test_install_from_wheel_with_extras():
"""
Test installing from a wheel.
"""
try:
import ast
except ImportError:
raise SkipTest("Need ast module to interpret wheel extras")
env = reset_env(use_distribute=True)
result = run_pip('install', 'complex-dist[simple]', '--use-wheel',
'--no-index', '--find-links='+find_links,
expect_error=False)
dist_info_folder = env.site_packages/'complex_dist-0.1.dist-info'
assert dist_info_folder in result.files_created, (dist_info_folder,
result.files_created,
result.stdout)
dist_info_folder = env.site_packages/'simple.dist-0.1.dist-info'
assert dist_info_folder in result.files_created, (dist_info_folder,
result.files_created,
result.stdout)
def test_install_from_wheel_file():
"""
Test installing directly from a wheel file.
"""
env = reset_env(use_distribute=True)
package = abspath(join(tests_data,
'packages',
'headers.dist-0.1-py2.py3-none-any.whl'))
result = run_pip('install', package, '--no-index', expect_error=False)
dist_info_folder = env.site_packages/'headers.dist-0.1.dist-info'
assert dist_info_folder in result.files_created, (dist_info_folder,
result.files_created,
result.stdout)
def test_install_curdir():
"""
@ -546,18 +408,6 @@ def test_install_package_with_target():
assert Path('scratch')/'target'/'initools' in result.files_created, str(result)
def test_install_wheel_with_target():
"""
Test installing a wheel using pip install --target
"""
env = reset_env(use_distribute=True)
pip_install_local('wheel')
target_dir = env.scratch_path/'target'
result = run_pip('install', 'simple.dist==0.1', '-t', target_dir, '--use-wheel',
'--no-index', '--find-links='+find_links)
assert Path('scratch')/'target'/'simpledist' in result.files_created, str(result)
def test_install_package_with_root():
"""
Test installing a package using pip install --root
@ -572,79 +422,50 @@ def test_install_package_with_root():
assert root_path in result.files_created, str(result)
def test_find_command_folder_in_path():
def test_install_package_that_emits_unicode():
"""
If a folder named e.g. 'git' is in PATH, and find_command is looking for
the 'git' executable, it should not match the folder, but rather keep
looking.
Install a package with a setup.py that emits UTF-8 output and then fails.
This works fine in Python 2, but fails in Python 3 with:
Traceback (most recent call last):
...
File "/Users/marc/python/virtualenvs/py3.1-phpserialize/lib/python3.2/site-packages/pip-1.0.2-py3.2.egg/pip/__init__.py", line 230, in call_subprocess
line = console_to_str(stdout.readline())
File "/Users/marc/python/virtualenvs/py3.1-phpserialize/lib/python3.2/site-packages/pip-1.0.2-py3.2.egg/pip/backwardcompat.py", line 60, in console_to_str
return s.decode(console_encoding)
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 17: ordinal not in range(128)
Refs https://github.com/pypa/pip/issues/326
"""
#skip on win/py3 for now, see issue #782
if sys.platform == 'win32' and sys.version_info >= (3,):
raise SkipTest()
env = reset_env()
to_install = os.path.abspath(os.path.join(tests_data, 'packages', 'BrokenEmitsUTF8'))
result = run_pip('install', to_install, expect_error=True, expect_temp=True, quiet=True)
assert 'FakeError: this package designed to fail on install' in result.stdout
assert 'UnicodeDecodeError' not in result.stdout
def test_url_req_case_mismatch():
"""
tar ball url requirements (with no egg fragment), that happen to have upper case project names,
should be considered equal to later requirements that reference the project name using lower case.
tests/packages contains Upper-1.0.tar.gz and Upper-2.0.tar.gz
'requiresupper' has install_requires = ['upper']
"""
env = reset_env()
mkdir('path_one')
path_one = env.scratch_path/'path_one'
mkdir(path_one/'foo')
mkdir('path_two')
path_two = env.scratch_path/'path_two'
write_file(path_two/'foo', '# nothing')
found_path = find_command('foo', map(str, [path_one, path_two]))
assert found_path == path_two/'foo'
Upper = os.path.join(find_links, 'Upper-1.0.tar.gz')
result = run_pip('install', '--no-index', '-f', find_links, Upper, 'requiresupper')
def test_does_not_find_command_because_there_is_no_path():
"""
Test calling `pip.utils.find_command` when there is no PATH env variable
"""
environ_before = os.environ
os.environ = {}
try:
try:
find_command('anycommand')
except BadCommand:
e = sys.exc_info()[1]
assert e.args == ("Cannot find command 'anycommand'",)
else:
raise AssertionError("`find_command` should raise `BadCommand`")
finally:
os.environ = environ_before
@patch('os.pathsep', ':')
@patch('pip.util.get_pathext')
@patch('os.path.isfile')
def test_find_command_trys_all_pathext(mock_isfile, getpath_mock):
"""
If no pathext should check default list of extensions, if file does not
exist.
"""
mock_isfile.return_value = False
getpath_mock.return_value = os.pathsep.join([".COM", ".EXE"])
paths = [os.path.join('path_one', f) for f in ['foo.com', 'foo.exe', 'foo']]
expected = [((p,),) for p in paths]
assert_raises(BadCommand, find_command, 'foo', 'path_one')
assert mock_isfile.call_args_list == expected, "Actual: %s\nExpected %s" % (mock_isfile.call_args_list, expected)
assert getpath_mock.called, "Should call get_pathext"
@patch('os.pathsep', ':')
@patch('pip.util.get_pathext')
@patch('os.path.isfile')
def test_find_command_trys_supplied_pathext(mock_isfile, getpath_mock):
"""
If pathext supplied find_command should use all of its list of extensions to find file.
"""
mock_isfile.return_value = False
getpath_mock.return_value = ".FOO"
pathext = os.pathsep.join([".RUN", ".CMD"])
paths = [os.path.join('path_one', f) for f in ['foo.run', 'foo.cmd', 'foo']]
expected = [((p,),) for p in paths]
assert_raises(BadCommand, find_command, 'foo', 'path_one', pathext)
assert mock_isfile.call_args_list == expected, "Actual: %s\nExpected %s" % (mock_isfile.call_args_list, expected)
assert not getpath_mock.called, "Should not call get_pathext"
#only Upper-1.0.tar.gz should get installed.
egg_folder = env.site_packages / 'Upper-1.0-py%s.egg-info' % pyversion
assert egg_folder in result.files_created, str(result)
egg_folder = env.site_packages / 'Upper-2.0-py%s.egg-info' % pyversion
assert egg_folder not in result.files_created, str(result)
def test_dont_install_distribute_in_py3():
@ -657,3 +478,20 @@ def test_dont_install_distribute_in_py3():
result = run_pip('install', 'distribute')
assert "Skipping distribute: Can not install distribute due to bootstrap issues" in result.stdout
assert not result.files_updated
def test_pip_second_command_line_interface_works():
"""
Check if ``pip-<PYVERSION>`` commands behaves equally
"""
e = reset_env()
args = ['pip-%s' % pyversion]
args.extend(['install', 'INITools==0.2'])
result = e.run(*args)
egg_info_folder = e.site_packages / 'INITools-0.2-py%s.egg-info' % pyversion
initools_folder = e.site_packages / 'initools'
assert egg_info_folder in result.files_created, str(result)
assert initools_folder in result.files_created, str(result)

View file

@ -29,17 +29,6 @@ def test_no_clean_option_blocks_cleaning_after_install():
assert exists(build), "build/simple should still exist %s" % str(result)
def test_no_clean_option_blocks_cleaning_after_wheel():
"""
Test --no-clean option blocks cleaning after wheel build
"""
env = reset_env(use_distribute=True)
pip_install_local('wheel')
result = run_pip('wheel', '--no-clean', '--no-index', '--find-links=%s' % find_links, 'simple')
build = env.venv_path/'build'/'simple'
assert exists(build), "build/simple should still exist %s" % str(result)
def test_cleanup_after_install_editable_from_hg():
"""
Test clean up after cloning from Mercurial.
@ -73,41 +62,6 @@ def test_cleanup_after_install_from_local_directory():
env.assert_no_temp()
def test_cleanup_after_create_bundle():
"""
Test clean up after making a bundle. Make sure (build|src)-bundle/ dirs are removed but not src/.
"""
env = reset_env()
# Install an editable to create a src/ dir.
args = ['install']
args.extend(['-e',
'%s#egg=pip-test-package' %
local_checkout('git+http://github.com/pypa/pip-test-package.git')])
run_pip(*args)
build = env.venv_path/"build"
src = env.venv_path/"src"
assert not exists(build), "build/ dir still exists: %s" % build
assert exists(src), "expected src/ dir doesn't exist: %s" % src
# Make the bundle.
fspkg = 'file://%s/FSPkg' %join(tests_data, 'packages')
pkg_lines = textwrap.dedent('''\
-e %s
-e %s#egg=initools-dev
pip''' % (fspkg, local_checkout('svn+http://svn.colorstudy.com/INITools/trunk')))
write_file('bundle-req.txt', pkg_lines)
run_pip('bundle', '-r', 'bundle-req.txt', 'test.pybundle')
build_bundle = env.scratch_path/"build-bundle"
src_bundle = env.scratch_path/"src-bundle"
assert not exists(build_bundle), "build-bundle/ dir still exists: %s" % build_bundle
assert not exists(src_bundle), "src-bundle/ dir still exists: %s" % src_bundle
env.assert_no_temp()
# Make sure previously created src/ from editable still exists
assert exists(src), "expected src dir doesn't exist: %s" % src
def test_no_install_and_download_should_not_leave_build_dir():
"""
It should remove build/ dir if it was pip that created

View file

@ -1,17 +1,7 @@
import os
import textwrap
import pip
from pip.download import _get_response_from_url as _get_response_from_url_original
from mock import patch
from shutil import rmtree
from tempfile import mkdtemp
from pip.download import path_to_url2, unpack_http_url
from pip.index import Link
from tests.lib import reset_env, run_pip, write_file, tests_data
from tests.lib import reset_env, run_pip, write_file
from tests.lib.path import Path
from pip.download import URLOpener
def test_download_if_requested():
@ -79,28 +69,3 @@ def test_download_should_skip_existing_files():
assert Path('scratch')/ 'INITools-0.1.tar.gz' not in result.files_created
assert env.site_packages/ 'initools' not in result.files_created
assert env.site_packages/ 'openid' not in result.files_created
def test_unpack_http_url_with_urllib_response_without_content_type():
"""
It should download and unpack files even if no Content-Type header exists
"""
def _get_response_from_url_mock(*args, **kw):
resp = _get_response_from_url_original(*args, **kw)
del resp.info()['content-type']
return resp
with patch('pip.download._get_response_from_url', _get_response_from_url_mock) as mocked:
uri = path_to_url2(os.path.join(tests_data, 'packages', 'simple-1.0.tar.gz'))
link = Link(uri)
temp_dir = mkdtemp()
try:
unpack_http_url(link, temp_dir, download_cache=None, download_dir=None)
assert set(os.listdir(temp_dir)) == set(['PKG-INFO', 'setup.cfg', 'setup.py', 'simple', 'simple.egg-info'])
finally:
rmtree(temp_dir)
def test_user_agent():
opener = URLOpener().get_opener()
user_agent = [x for x in opener.addheaders if x[0].lower() == "user-agent"][0]
assert user_agent[1].startswith("pip/%s" % pip.__version__)

View file

@ -0,0 +1,87 @@
import os
import textwrap
from pip.backwardcompat import urllib
from tests.lib import (reset_env, run_pip, pyversion, tests_data, write_file,
path_to_url)
def test_find_links_relative_path():
"""Test find-links as a relative path."""
e = reset_env()
result = run_pip(
'install',
'parent==0.1',
'--no-index',
'--find-links',
'packages/',
cwd=tests_data)
egg_info_folder = e.site_packages / 'parent-0.1-py%s.egg-info' % pyversion
initools_folder = e.site_packages / 'parent'
assert egg_info_folder in result.files_created, str(result)
assert initools_folder in result.files_created, str(result)
def test_find_links_requirements_file_relative_path():
"""Test find-links as a relative path to a reqs file."""
e = reset_env()
write_file('test-req.txt', textwrap.dedent("""
--no-index
--find-links=../../../../data/packages/
parent==0.1
"""))
result = run_pip(
'install',
'-r',
e.scratch_path / "test-req.txt",
cwd=tests_data)
egg_info_folder = e.site_packages / 'parent-0.1-py%s.egg-info' % pyversion
initools_folder = e.site_packages / 'parent'
assert egg_info_folder in result.files_created, str(result)
assert initools_folder in result.files_created, str(result)
def test_install_from_mirrors():
"""
Test installing a package from the PyPI mirrors.
"""
e = reset_env()
result = run_pip('install', '-vvv', '--use-mirrors', '--no-index', 'INITools==0.2')
egg_info_folder = e.site_packages / 'INITools-0.2-py%s.egg-info' % pyversion
initools_folder = e.site_packages / 'initools'
assert egg_info_folder in result.files_created, str(result)
assert initools_folder in result.files_created, str(result)
def test_install_from_mirrors_with_specific_mirrors():
"""
Test installing a package from a specific PyPI mirror.
"""
e = reset_env()
result = run_pip('install', '-vvv', '--use-mirrors', '--mirrors', "http://a.pypi.python.org/", '--no-index', 'INITools==0.2')
egg_info_folder = e.site_packages / 'INITools-0.2-py%s.egg-info' % pyversion
initools_folder = e.site_packages / 'initools'
assert egg_info_folder in result.files_created, str(result)
assert initools_folder in result.files_created, str(result)
def test_install_from_file_index_hash_link():
"""
Test that a pkg can be installed from a file:// index using a link with a hash
"""
env = reset_env()
index_url = path_to_url(os.path.join(tests_data, 'indexes', 'simple'))
result = run_pip('install', '-i', index_url, 'simple==1.0')
egg_info_folder = env.site_packages / 'simple-1.0-py%s.egg-info' % pyversion
assert egg_info_folder in result.files_created, str(result)
def test_file_index_url_quoting():
"""
Test url quoting of file index url with a space
"""
index_url = path_to_url(os.path.join(tests_data, 'indexes', urllib.quote('in dex')))
env = reset_env()
result = run_pip('install', '-vvv', '--index-url', index_url, 'simple', expect_error=False)
assert (env.site_packages/'simple') in result.files_created, str(result.stdout)
assert (env.site_packages/'simple-1.0-py%s.egg-info' % pyversion) in result.files_created, str(result)

View file

@ -29,14 +29,6 @@ def test_requirements_file():
fn = '%s-%s-py%s.egg-info' % (other_lib_name, other_lib_version, pyversion)
assert result.files_created[env.site_packages/fn].dir
def test_remote_reqs_parse():
"""
Test parsing a simple remote requirements file
"""
# this requirements file just contains a comment
# previously this has failed in py3 (https://github.com/pypa/pip/issues/760)
for req in parse_requirements('https://raw.github.com/pypa/pip-test-package/master/tests/req_just_comment.txt'):
pass
def test_schema_check_in_requirements_file():
"""
@ -107,83 +99,6 @@ def test_respect_order_in_requirements_file():
'be "simple" but was "%s"' % downloaded[2]
def test_requirements_data_structure_keeps_order():
requirements = Requirements()
requirements['pip'] = 'pip'
requirements['nose'] = 'nose'
requirements['coverage'] = 'coverage'
assert ['pip', 'nose', 'coverage'] == list(requirements.values())
assert ['pip', 'nose', 'coverage'] == list(requirements.keys())
def test_requirements_data_structure_implements__repr__():
requirements = Requirements()
requirements['pip'] = 'pip'
requirements['nose'] = 'nose'
assert "Requirements({'pip': 'pip', 'nose': 'nose'})" == repr(requirements)
def test_requirements_data_structure_implements__contains__():
requirements = Requirements()
requirements['pip'] = 'pip'
assert 'pip' in requirements
assert 'nose' not in requirements
@patch('os.path.normcase')
@patch('pip.req.os.getcwd')
@patch('pip.req.os.path.exists')
@patch('pip.req.os.path.isdir')
def test_parse_editable_local(isdir_mock, exists_mock, getcwd_mock, normcase_mock):
exists_mock.return_value = isdir_mock.return_value = True
# mocks needed to support path operations on windows tests
normcase_mock.return_value = getcwd_mock.return_value = "/some/path"
assert_equal(
parse_editable('.', 'git'),
(None, 'file:///some/path', None)
)
normcase_mock.return_value = "/some/path/foo"
assert_equal(
parse_editable('foo', 'git'),
(None, 'file:///some/path/foo', None)
)
def test_parse_editable_default_vcs():
assert_equal(
parse_editable('https://foo#egg=foo', 'git'),
('foo', 'git+https://foo#egg=foo', None)
)
def test_parse_editable_explicit_vcs():
assert_equal(
parse_editable('svn+https://foo#egg=foo', 'git'),
('foo', 'svn+https://foo#egg=foo', None)
)
def test_parse_editable_vcs_extras():
assert_equal(
parse_editable('svn+https://foo#egg=foo[extras]', 'git'),
('foo[extras]', 'svn+https://foo#egg=foo[extras]', None)
)
@patch('os.path.normcase')
@patch('pip.req.os.getcwd')
@patch('pip.req.os.path.exists')
@patch('pip.req.os.path.isdir')
def test_parse_editable_local_extras(isdir_mock, exists_mock, getcwd_mock, normcase_mock):
exists_mock.return_value = isdir_mock.return_value = True
normcase_mock.return_value = getcwd_mock.return_value = "/some/path"
assert_equal(
parse_editable('.[extras]', 'git'),
(None, 'file://' + "/some/path", ('extras',))
)
normcase_mock.return_value = "/some/path/foo"
assert_equal(
parse_editable('foo[bar,baz]', 'git'),
(None, 'file:///some/path/foo', ('bar', 'baz'))
)
def test_install_local_editable_with_extras():
env = reset_env()
@ -194,23 +109,5 @@ def test_install_local_editable_with_extras():
assert env.site_packages/'simple' in res.files_created, str(result)
def test_url_req_case_mismatch():
"""
tar ball url requirements (with no egg fragment), that happen to have upper case project names,
should be considered equal to later requirements that reference the project name using lower case.
tests/packages contains Upper-1.0.tar.gz and Upper-2.0.tar.gz
'requiresupper' has install_requires = ['upper']
"""
env = reset_env()
Upper = os.path.join(find_links, 'Upper-1.0.tar.gz')
result = run_pip('install', '--no-index', '-f', find_links, Upper, 'requiresupper')
#only Upper-1.0.tar.gz should get installed.
egg_folder = env.site_packages / 'Upper-1.0-py%s.egg-info' % pyversion
assert egg_folder in result.files_created, str(result)
egg_folder = env.site_packages / 'Upper-2.0-py%s.egg-info' % pyversion
assert egg_folder not in result.files_created, str(result)

View file

@ -1,10 +0,0 @@
from pip.req import InstallRequirement
def test_url_with_query():
"""InstallRequirement should strip the fragment, but not the query."""
url = 'http://foo.com/?p=bar.git;a=snapshot;h=v0.1;sf=tgz'
fragment = '#egg=bar'
req = InstallRequirement.from_line(url + fragment)
assert req.url == url, req.url

View file

@ -142,3 +142,5 @@ def test_git_works_with_editable_non_origin_repo():
assert "Error when trying to get requirement" in result.stderr
assert "Could not determine repository location" in result.stdout
assert "version-pkg==0.1" in result.stdout

View file

@ -0,0 +1,68 @@
from os.path import abspath, join
from nose import SkipTest
from tests.lib import tests_data, reset_env, run_pip, pip_install_local, find_links
from tests.lib.path import Path
def test_install_from_wheel():
"""
Test installing from a wheel.
"""
env = reset_env(use_distribute=True)
result = run_pip('install', 'simple.dist', '--use-wheel',
'--no-index', '--find-links='+find_links,
expect_error=False)
dist_info_folder = env.site_packages/'simple.dist-0.1.dist-info'
assert dist_info_folder in result.files_created, (dist_info_folder,
result.files_created,
result.stdout)
def test_install_from_wheel_with_extras():
"""
Test installing from a wheel.
"""
try:
import ast
except ImportError:
raise SkipTest("Need ast module to interpret wheel extras")
env = reset_env(use_distribute=True)
result = run_pip('install', 'complex-dist[simple]', '--use-wheel',
'--no-index', '--find-links='+find_links,
expect_error=False)
dist_info_folder = env.site_packages/'complex_dist-0.1.dist-info'
assert dist_info_folder in result.files_created, (dist_info_folder,
result.files_created,
result.stdout)
dist_info_folder = env.site_packages/'simple.dist-0.1.dist-info'
assert dist_info_folder in result.files_created, (dist_info_folder,
result.files_created,
result.stdout)
def test_install_from_wheel_file():
"""
Test installing directly from a wheel file.
"""
env = reset_env(use_distribute=True)
package = abspath(join(tests_data,
'packages',
'headers.dist-0.1-py2.py3-none-any.whl'))
result = run_pip('install', package, '--no-index', expect_error=False)
dist_info_folder = env.site_packages/'headers.dist-0.1.dist-info'
assert dist_info_folder in result.files_created, (dist_info_folder,
result.files_created,
result.stdout)
def test_install_wheel_with_target():
"""
Test installing a wheel using pip install --target
"""
env = reset_env(use_distribute=True)
pip_install_local('wheel')
target_dir = env.scratch_path/'target'
result = run_pip('install', 'simple.dist==0.1', '-t', target_dir, '--use-wheel',
'--no-index', '--find-links='+find_links)
assert Path('scratch')/'target'/'simpledist' in result.files_created, str(result)

View file

@ -1,31 +0,0 @@
import os
import sys
from nose import SkipTest
from tests.lib import tests_data, reset_env, run_pip
def test_install_package_that_emits_unicode():
"""
Install a package with a setup.py that emits UTF-8 output and then fails.
This works fine in Python 2, but fails in Python 3 with:
Traceback (most recent call last):
...
File "/Users/marc/python/virtualenvs/py3.1-phpserialize/lib/python3.2/site-packages/pip-1.0.2-py3.2.egg/pip/__init__.py", line 230, in call_subprocess
line = console_to_str(stdout.readline())
File "/Users/marc/python/virtualenvs/py3.1-phpserialize/lib/python3.2/site-packages/pip-1.0.2-py3.2.egg/pip/backwardcompat.py", line 60, in console_to_str
return s.decode(console_encoding)
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 17: ordinal not in range(128)
Refs https://github.com/pypa/pip/issues/326
"""
#skip on win/py3 for now, see issue #782
if sys.platform == 'win32' and sys.version_info >= (3,):
raise SkipTest()
env = reset_env()
to_install = os.path.abspath(os.path.join(tests_data, 'packages', 'BrokenEmitsUTF8'))
result = run_pip('install', to_install, expect_error=True, expect_temp=True, quiet=True)
assert 'FakeError: this package designed to fail on install' in result.stdout
assert 'UnicodeDecodeError' not in result.stdout

View file

@ -1,225 +1,96 @@
"""Tests for wheel binary packages and .dist-info."""
"""'pip wheel' tests"""
import os
import pkg_resources
import sys
import textwrap
from mock import patch
from os.path import exists
from mock import patch
from nose import SkipTest
from pip.exceptions import InstallationError
from pip.index import PackageFinder
from pip import wheel
from pip.download import path_to_url as path_to_url_d
from tests.lib import (tests_data, reset_env, run_pip, pyversion_nodot, write_file,
path_to_url, assert_raises_regexp, find_links, pip_install_local)
from tests.lib import tests_data, reset_env, run_pip, pyversion_nodot, write_file, path_to_url, find_links, pip_install_local
def test_pip_wheel_fails_without_wheel():
"""
Test 'pip wheel' fails without wheel
"""
env = reset_env(use_distribute=True)
result = run_pip('wheel', '--no-index', '-f', find_links, 'simple==3.0', expect_error=True)
assert "'pip wheel' requires bdist_wheel" in result.stdout
def test_uninstallation_paths():
class dist(object):
def get_metadata_lines(self, record):
return ['file.py,,',
'file.pyc,,',
'file.so,,',
'nopyc.py']
location = ''
def test_pip_wheel_setuptools_fails():
"""
Test 'pip wheel' fails with setuptools
"""
if sys.version_info >= (3, 0):
# virtualenv installs distribute in py3
raise SkipTest()
env = reset_env(use_distribute=False)
pip_install_local('wheel')
result = run_pip('wheel', '--no-index', '-f', find_links, 'simple==3.0', expect_error=True)
assert "'pip wheel' requires %s" % wheel.distribute_requirement in result.stdout, result.stdout
d = dist()
paths = list(wheel.uninstallation_paths(d))
expected = ['file.py',
'file.pyc',
'file.so',
'nopyc.py',
'nopyc.pyc']
assert paths == expected
# Avoid an easy 'unique generator' bug
paths2 = list(wheel.uninstallation_paths(d))
assert paths2 == paths
def test_pip_wheel_success():
"""
Test 'pip wheel' success.
"""
env = reset_env(use_distribute=True)
pip_install_local('wheel')
result = run_pip('wheel', '--no-index', '-f', find_links, 'simple==3.0')
wheel_file_name = 'simple-3.0-py%s-none-any.whl' % pyversion_nodot
wheel_file_path = env.scratch/'wheelhouse'/wheel_file_name
assert wheel_file_path in result.files_created, result.stdout
assert "Successfully built simple" in result.stdout, result.stdout
class TestPipWheel:
def test_pip_wheel_fails_without_wheel(self):
"""
Test 'pip wheel' fails without wheel
"""
env = reset_env(use_distribute=True)
result = run_pip('wheel', '--no-index', '-f', find_links, 'simple==3.0', expect_error=True)
assert "'pip wheel' requires bdist_wheel" in result.stdout
def test_pip_wheel_setuptools_fails(self):
"""
Test 'pip wheel' fails with setuptools
"""
if sys.version_info >= (3, 0):
# virtualenv installs distribute in py3
raise SkipTest()
env = reset_env(use_distribute=False)
pip_install_local('wheel')
result = run_pip('wheel', '--no-index', '-f', find_links, 'simple==3.0', expect_error=True)
assert "'pip wheel' requires %s" % wheel.distribute_requirement in result.stdout, result.stdout
def test_pip_wheel_success(self):
"""
Test 'pip wheel' success.
"""
env = reset_env(use_distribute=True)
pip_install_local('wheel')
result = run_pip('wheel', '--no-index', '-f', find_links, 'simple==3.0')
wheel_file_name = 'simple-3.0-py%s-none-any.whl' % pyversion_nodot
wheel_file_path = env.scratch/'wheelhouse'/wheel_file_name
assert wheel_file_path in result.files_created, result.stdout
assert "Successfully built simple" in result.stdout, result.stdout
def test_pip_wheel_fail():
"""
Test 'pip wheel' failure.
"""
env = reset_env(use_distribute=True)
pip_install_local('wheel')
result = run_pip('wheel', '--no-index', '-f', find_links, 'wheelbroken==0.1')
wheel_file_name = 'wheelbroken-0.1-py%s-none-any.whl' % pyversion_nodot
wheel_file_path = env.scratch/'wheelhouse'/wheel_file_name
assert wheel_file_path not in result.files_created, (wheel_file_path, result.files_created)
assert "FakeError" in result.stdout, result.stdout
assert "Failed to build wheelbroken" in result.stdout, result.stdout
def test_pip_wheel_fail(self):
"""
Test 'pip wheel' failure.
"""
env = reset_env(use_distribute=True)
pip_install_local('wheel')
result = run_pip('wheel', '--no-index', '-f', find_links, 'wheelbroken==0.1')
wheel_file_name = 'wheelbroken-0.1-py%s-none-any.whl' % pyversion_nodot
wheel_file_path = env.scratch/'wheelhouse'/wheel_file_name
assert wheel_file_path not in result.files_created, (wheel_file_path, result.files_created)
assert "FakeError" in result.stdout, result.stdout
assert "Failed to build wheelbroken" in result.stdout, result.stdout
def test_pip_wheel_ignore_wheels_editables():
"""
Test 'pip wheel' ignores editables and *.whl files in requirements
"""
env = reset_env(use_distribute=True)
pip_install_local('wheel')
local_wheel = '%s/simple.dist-0.1-py2.py3-none-any.whl' % find_links
local_editable = os.path.abspath(os.path.join(tests_data, 'packages', 'FSPkg'))
write_file('reqs.txt', textwrap.dedent("""\
%s
-e %s
simple
""" % (local_wheel, local_editable)))
result = run_pip('wheel', '--no-index', '-f', find_links, '-r', env.scratch_path / 'reqs.txt')
wheel_file_name = 'simple-3.0-py%s-none-any.whl' % pyversion_nodot
wheel_file_path = env.scratch/'wheelhouse'/wheel_file_name
assert wheel_file_path in result.files_created, (wheel_file_path, result.files_created)
assert "Successfully built simple" in result.stdout, result.stdout
assert "Failed to build" not in result.stdout, result.stdout
assert "ignoring %s" % local_wheel in result.stdout
ignore_editable = "ignoring %s" % path_to_url(local_editable)
#TODO: understand this divergence
if sys.platform == 'win32':
ignore_editable = "ignoring %s" % path_to_url_d(local_editable)
assert ignore_editable in result.stdout, result.stdout
def test_pip_wheel_ignore_wheels_editables(self):
"""
Test 'pip wheel' ignores editables and *.whl files in requirements
"""
env = reset_env(use_distribute=True)
pip_install_local('wheel')
local_wheel = '%s/simple.dist-0.1-py2.py3-none-any.whl' % find_links
local_editable = os.path.abspath(os.path.join(tests_data, 'packages', 'FSPkg'))
write_file('reqs.txt', textwrap.dedent("""\
%s
-e %s
simple
""" % (local_wheel, local_editable)))
result = run_pip('wheel', '--no-index', '-f', find_links, '-r', env.scratch_path / 'reqs.txt')
wheel_file_name = 'simple-3.0-py%s-none-any.whl' % pyversion_nodot
wheel_file_path = env.scratch/'wheelhouse'/wheel_file_name
assert wheel_file_path in result.files_created, (wheel_file_path, result.files_created)
assert "Successfully built simple" in result.stdout, result.stdout
assert "Failed to build" not in result.stdout, result.stdout
assert "ignoring %s" % local_wheel in result.stdout
ignore_editable = "ignoring %s" % path_to_url(local_editable)
#TODO: understand this divergence
if sys.platform == 'win32':
ignore_editable = "ignoring %s" % path_to_url_d(local_editable)
assert ignore_editable in result.stdout, result.stdout
class TestWheelSupported(object):
def raise_not_found(self, dist):
raise pkg_resources.DistributionNotFound()
def set_use_wheel_true(self, finder):
finder.use_wheel = True
@patch("pip.wheel.pkg_resources.get_distribution")
def test_wheel_supported_true(self, mock_get_distribution):
"""
Test wheel_supported returns true, when distribute is installed and requirement is met
"""
mock_get_distribution.return_value = pkg_resources.Distribution(project_name='distribute', version='0.6.34')
assert wheel.wheel_distribute_support()
@patch("pip.wheel.pkg_resources.get_distribution")
def test_wheel_supported_false_no_install(self, mock_get_distribution):
"""
Test wheel_supported returns false, when distribute not installed
"""
mock_get_distribution.side_effect = self.raise_not_found
assert not wheel.wheel_distribute_support()
@patch("pip.wheel.pkg_resources.get_distribution")
def test_wheel_supported_false_req_fail(self, mock_get_distribution):
"""
Test wheel_supported returns false, when distribute is installed, but req is not met
"""
mock_get_distribution.return_value = pkg_resources.Distribution(project_name='distribute', version='0.6.28')
assert not wheel.wheel_distribute_support()
@patch("pip.wheel.pkg_resources.get_distribution")
def test_finder_raises_error(self, mock_get_distribution):
"""
Test the PackageFinder raises an error when wheel is not supported
"""
mock_get_distribution.side_effect = self.raise_not_found
# on initialization
assert_raises_regexp(InstallationError, 'wheel support', PackageFinder, [], [], use_wheel=True)
# when setting property later
p = PackageFinder([], [])
assert_raises_regexp(InstallationError, 'wheel support', self.set_use_wheel_true, p)
@patch("pip.wheel.pkg_resources.get_distribution")
def test_finder_no_raises_error(self, mock_get_distribution):
"""
Test the PackageFinder doesn't raises an error when use_wheel is False, and wheel is supported
"""
mock_get_distribution.return_value = pkg_resources.Distribution(project_name='distribute', version='0.6.34')
p = PackageFinder( [], [], use_wheel=False)
p = PackageFinder([], [])
p.use_wheel = False
class TestWheelFile(object):
@patch('pip.wheel.supported_tags', [('py2', 'none', 'any')])
def test_supported_single_version(self):
"""
Test single-version wheel is known to be supported
"""
w = wheel.Wheel('simple-0.1-py2-none-any.whl')
assert w.supported()
@patch('pip.wheel.supported_tags', [('py3', 'none', 'any')])
def test_supported_multi_version(self):
"""
Test multi-version wheel is known to be supported
"""
w = wheel.Wheel('simple-0.1-py2.py3-none-any.whl')
assert w.supported()
@patch('pip.wheel.supported_tags', [('py1', 'none', 'any')])
def test_not_supported_version(self):
"""
Test unsupported wheel is known to be unsupported
"""
w = wheel.Wheel('simple-0.1-py2-none-any.whl')
assert not w.supported()
@patch('pip.wheel.supported_tags', [
('py2', 'none', 'TEST'),
('py2', 'TEST', 'any'),
('py2', 'none', 'any'),
])
def test_support_index_min(self):
"""
Test results from `support_index_min`
"""
w = wheel.Wheel('simple-0.1-py2-none-any.whl')
assert w.support_index_min() == 2
w = wheel.Wheel('simple-0.1-py2-none-TEST.whl')
assert w.support_index_min() == 0
@patch('pip.wheel.supported_tags', [])
def test_support_index_min_none(self):
"""
Test `support_index_min` returns None, when wheel not supported
"""
w = wheel.Wheel('simple-0.1-py2-none-any.whl')
assert w.support_index_min() == None
def test_no_clean_option_blocks_cleaning_after_wheel():
"""
Test --no-clean option blocks cleaning after wheel build
"""
env = reset_env(use_distribute=True)
pip_install_local('wheel')
result = run_pip('wheel', '--no-clean', '--no-index', '--find-links=%s' % find_links, 'simple')
build = env.venv_path/'build'/'simple'
assert exists(build), "build/simple should still exist %s" % str(result)

View file

@ -1,7 +1,6 @@
import os
import pip.backwardcompat
from pip.backwardcompat import urllib, string_types, b, u, emailmessage
from tests.lib import tests_cache
urlopen_original = pip.backwardcompat.urllib2.urlopen
@ -86,6 +85,8 @@ class CachedResponse(object):
class PyPIProxy(object):
CACHE_PATH = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'tests_cache')
@classmethod
def setup(cls):
instance = cls()
@ -94,12 +95,12 @@ class PyPIProxy(object):
def _monkey_patch_urllib2_to_cache_everything(self):
def urlopen(url):
return CachedResponse(url, self.tests_cache)
return CachedResponse(url, self.CACHE_PATH)
pip.backwardcompat.urllib2.urlopen = urlopen
def _create_cache_folder(self):
if not os.path.exists(self.tests_cache):
os.mkdir(self.tests_cache)
if not os.path.exists(self.CACHE_PATH):
os.mkdir(self.CACHE_PATH)
def assert_equal(a, b):

View file

@ -1,13 +1,14 @@
"""Test the test support."""
import filecmp
import imp
import sys
import os
from os.path import abspath, join, curdir, isdir, isfile
import re
import sys
from os.path import join, isdir
from nose import SkipTest
from tests.lib.local_repos import local_checkout
from tests.lib import tests_lib, reset_env, run_pip, pyversion
from pip.backwardcompat import uses_pycache
from tests.lib import tests_lib, reset_env, run_pip, src_folder
patch_urlopen = """
@ -106,7 +107,7 @@ def test_add_patch_to_sitecustomize():
src_mtime = os.stat(env.lib_path / 'sitecustomize.py').st_mtime
cache_mtime = os.stat(cache_path).st_mtime
debug_content += "src mtime: %s, cache mtime: %s" % (src_mtime, cache_mtime)
assert "sitecustomize" == result.stdout.strip(), debug_content
assert "sitecustomize" == result.stdout.strip(), result.stdout
def test_sitecustomize_not_growing_in_fast_environment():
@ -145,3 +146,30 @@ def test_tmp_dir_exists_in_fast_env():
env.assert_no_temp() #this fails if env.tmp_path doesn't exist
assert env.environ['TMPDIR'] == env.temp_path
assert isdir(env.temp_path)
def test_correct_pip_version():
"""
Check we are running proper version of pip in run_pip.
"""
reset_env()
# output is like:
# pip PIPVERSION from PIPDIRECTORY (python PYVERSION)
result = run_pip('--version')
# compare the directory tree of the invoked pip with that of this source distribution
dir = re.match(r'pip \d(\.[\d])+(\.?(rc|dev|pre|post)\d+)? from (.*) \(python \d(.[\d])+\)$',
result.stdout).group(4)
pip_folder = join(src_folder, 'pip')
pip_folder_outputed = join(dir, 'pip')
diffs = filecmp.dircmp(pip_folder, pip_folder_outputed)
# If any non-matching .py files exist, we have a problem: run_pip
# is picking up some other version! N.B. if this project acquires
# primary resources other than .py files, this code will need
# maintenance
mismatch_py = [x for x in diffs.left_only + diffs.right_only + diffs.diff_files if x.endswith('.py')]
assert not mismatch_py, 'mismatched source files in %r and %r: %r'% (pip_folder, pip_folder_outputed, mismatch_py)

View file

@ -0,0 +1,36 @@
import os
from shutil import rmtree
from tempfile import mkdtemp
import pip
from mock import patch
from pip.download import (_get_response_from_url as _get_response_from_url_original,
path_to_url2, unpack_http_url, URLOpener)
from pip.index import Link
from tests.lib import tests_data
def test_unpack_http_url_with_urllib_response_without_content_type():
"""
It should download and unpack files even if no Content-Type header exists
"""
def _get_response_from_url_mock(*args, **kw):
resp = _get_response_from_url_original(*args, **kw)
del resp.info()['content-type']
return resp
with patch('pip.download._get_response_from_url', _get_response_from_url_mock) as mocked:
uri = path_to_url2(os.path.join(tests_data, 'packages', 'simple-1.0.tar.gz'))
link = Link(uri)
temp_dir = mkdtemp()
try:
unpack_http_url(link, temp_dir, download_cache=None, download_dir=None)
assert set(os.listdir(temp_dir)) == set(['PKG-INFO', 'setup.cfg', 'setup.py', 'simple', 'simple.egg-info'])
finally:
rmtree(temp_dir)
def test_user_agent():
opener = URLOpener().get_opener()
user_agent = [x for x in opener.addheaders if x[0].lower() == "user-agent"][0]
assert user_agent[1].startswith("pip/%s" % pip.__version__)

View file

@ -78,28 +78,6 @@ def test_sort_locations_file_not_find_link():
assert urls and not files, "urls, but not files should have been found"
def test_install_from_file_index_hash_link():
"""
Test that a pkg can be installed from a file:// index using a link with a hash
"""
env = reset_env()
index_url = path_to_url(os.path.join(tests_data, 'indexes', 'simple'))
result = run_pip('install', '-i', index_url, 'simple==1.0')
egg_info_folder = env.site_packages / 'simple-1.0-py%s.egg-info' % pyversion
assert egg_info_folder in result.files_created, str(result)
def test_file_index_url_quoting():
"""
Test url quoting of file index url with a space
"""
index_url = path_to_url(os.path.join(tests_data, 'indexes', urllib.quote('in dex')))
env = reset_env()
result = run_pip('install', '-vvv', '--index-url', index_url, 'simple', expect_error=False)
assert (env.site_packages/'simple') in result.files_created, str(result.stdout)
assert (env.site_packages/'simple-1.0-py%s.egg-info' % pyversion) in result.files_created, str(result)
def test_inflink_greater():
"""Test InfLink compares greater."""
assert InfLink > Link("some link")

View file

@ -28,7 +28,6 @@ def test_correct_pip_version():
Check we are importing pip from the right place.
"""
base = os.path.dirname(tests_data)
assert pip.__file__.startswith(src_folder), pip.__file__

View file

@ -2,11 +2,13 @@ import os
import shutil
import tempfile
from mock import Mock
from mock import Mock, patch
from nose.tools import assert_equal, assert_raises
from pip.exceptions import PreviousBuildDirError
from pip.index import PackageFinder
from pip.log import logger
from pip.req import InstallRequirement, RequirementSet
from pip.req import (InstallRequirement, RequirementSet, parse_editable,
Requirements, parse_requirements)
from tests.lib import path_to_url, assert_raises_regexp, find_links
@ -66,3 +68,100 @@ class TestRequirementSet(object):
assert True == reqset.add_requirement(req)
reqset = self.basic_reqset(skip_reqs={'simple':''})
assert False == reqset.add_requirement(req)
def test_url_with_query():
"""InstallRequirement should strip the fragment, but not the query."""
url = 'http://foo.com/?p=bar.git;a=snapshot;h=v0.1;sf=tgz'
fragment = '#egg=bar'
req = InstallRequirement.from_line(url + fragment)
assert req.url == url, req.url
def test_requirements_data_structure_keeps_order():
requirements = Requirements()
requirements['pip'] = 'pip'
requirements['nose'] = 'nose'
requirements['coverage'] = 'coverage'
assert ['pip', 'nose', 'coverage'] == list(requirements.values())
assert ['pip', 'nose', 'coverage'] == list(requirements.keys())
def test_requirements_data_structure_implements__repr__():
requirements = Requirements()
requirements['pip'] = 'pip'
requirements['nose'] = 'nose'
assert "Requirements({'pip': 'pip', 'nose': 'nose'})" == repr(requirements)
def test_requirements_data_structure_implements__contains__():
requirements = Requirements()
requirements['pip'] = 'pip'
assert 'pip' in requirements
assert 'nose' not in requirements
@patch('os.path.normcase')
@patch('pip.req.os.getcwd')
@patch('pip.req.os.path.exists')
@patch('pip.req.os.path.isdir')
def test_parse_editable_local(isdir_mock, exists_mock, getcwd_mock, normcase_mock):
exists_mock.return_value = isdir_mock.return_value = True
# mocks needed to support path operations on windows tests
normcase_mock.return_value = getcwd_mock.return_value = "/some/path"
assert_equal(
parse_editable('.', 'git'),
(None, 'file:///some/path', None)
)
normcase_mock.return_value = "/some/path/foo"
assert_equal(
parse_editable('foo', 'git'),
(None, 'file:///some/path/foo', None)
)
def test_parse_editable_default_vcs():
assert_equal(
parse_editable('https://foo#egg=foo', 'git'),
('foo', 'git+https://foo#egg=foo', None)
)
def test_parse_editable_explicit_vcs():
assert_equal(
parse_editable('svn+https://foo#egg=foo', 'git'),
('foo', 'svn+https://foo#egg=foo', None)
)
def test_parse_editable_vcs_extras():
assert_equal(
parse_editable('svn+https://foo#egg=foo[extras]', 'git'),
('foo[extras]', 'svn+https://foo#egg=foo[extras]', None)
)
@patch('os.path.normcase')
@patch('pip.req.os.getcwd')
@patch('pip.req.os.path.exists')
@patch('pip.req.os.path.isdir')
def test_parse_editable_local_extras(isdir_mock, exists_mock, getcwd_mock, normcase_mock):
exists_mock.return_value = isdir_mock.return_value = True
normcase_mock.return_value = getcwd_mock.return_value = "/some/path"
assert_equal(
parse_editable('.[extras]', 'git'),
(None, 'file://' + "/some/path", ('extras',))
)
normcase_mock.return_value = "/some/path/foo"
assert_equal(
parse_editable('foo[bar,baz]', 'git'),
(None, 'file:///some/path/foo', ('bar', 'baz'))
)
def test_remote_reqs_parse():
"""
Test parsing a simple remote requirements file
"""
# this requirements file just contains a comment
# previously this has failed in py3 (https://github.com/pypa/pip/issues/760)
for req in parse_requirements('https://raw.github.com/pypa/pip-test-package/master/tests/req_just_comment.txt'):
pass

View file

@ -3,11 +3,12 @@ util tests
"""
import os
import pkg_resources
import sys
from mock import Mock, patch
from nose.tools import eq_
from tests.lib.path import Path
from pip.util import egg_link_path, Inf, get_installed_distributions, dist_is_editable
from nose.tools import eq_, assert_raises
from pip.exceptions import BadCommand
from pip.util import egg_link_path, Inf, get_installed_distributions, find_command
class Tests_EgglinkPath:
@ -196,6 +197,64 @@ class Tests_get_installed_distributions:
assert len(dists) == 3
def test_does_not_find_command_because_there_is_no_path():
"""
Test calling `pip.utils.find_command` when there is no PATH env variable
"""
environ_before = os.environ
os.environ = {}
try:
try:
find_command('anycommand')
except BadCommand:
e = sys.exc_info()[1]
assert e.args == ("Cannot find command 'anycommand'",)
else:
raise AssertionError("`find_command` should raise `BadCommand`")
finally:
os.environ = environ_before
@patch('os.pathsep', ':')
@patch('pip.util.get_pathext')
@patch('os.path.isfile')
def test_find_command_trys_all_pathext(mock_isfile, getpath_mock):
"""
If no pathext should check default list of extensions, if file does not
exist.
"""
mock_isfile.return_value = False
getpath_mock.return_value = os.pathsep.join([".COM", ".EXE"])
paths = [os.path.join('path_one', f) for f in ['foo.com', 'foo.exe', 'foo']]
expected = [((p,),) for p in paths]
assert_raises(BadCommand, find_command, 'foo', 'path_one')
assert mock_isfile.call_args_list == expected, "Actual: %s\nExpected %s" % (mock_isfile.call_args_list, expected)
assert getpath_mock.called, "Should call get_pathext"
@patch('os.pathsep', ':')
@patch('pip.util.get_pathext')
@patch('os.path.isfile')
def test_find_command_trys_supplied_pathext(mock_isfile, getpath_mock):
"""
If pathext supplied find_command should use all of its list of extensions to find file.
"""
mock_isfile.return_value = False
getpath_mock.return_value = ".FOO"
pathext = os.pathsep.join([".RUN", ".CMD"])
paths = [os.path.join('path_one', f) for f in ['foo.run', 'foo.cmd', 'foo']]
expected = [((p,),) for p in paths]
assert_raises(BadCommand, find_command, 'foo', 'path_one', pathext)
assert mock_isfile.call_args_list == expected, "Actual: %s\nExpected %s" % (mock_isfile.call_args_list, expected)
assert not getpath_mock.called, "Should not call get_pathext"

139
tests/unit/test_wheel.py Normal file
View file

@ -0,0 +1,139 @@
"""Tests for wheel binary packages and .dist-info."""
import pkg_resources
from mock import patch
from pip import wheel
from pip.exceptions import InstallationError
from pip.index import PackageFinder
from tests.lib import assert_raises_regexp
def test_uninstallation_paths():
class dist(object):
def get_metadata_lines(self, record):
return ['file.py,,',
'file.pyc,,',
'file.so,,',
'nopyc.py']
location = ''
d = dist()
paths = list(wheel.uninstallation_paths(d))
expected = ['file.py',
'file.pyc',
'file.so',
'nopyc.py',
'nopyc.pyc']
assert paths == expected
# Avoid an easy 'unique generator' bug
paths2 = list(wheel.uninstallation_paths(d))
assert paths2 == paths
class TestWheelSupported(object):
def raise_not_found(self, dist):
raise pkg_resources.DistributionNotFound()
def set_use_wheel_true(self, finder):
finder.use_wheel = True
@patch("pip.wheel.pkg_resources.get_distribution")
def test_wheel_supported_true(self, mock_get_distribution):
"""
Test wheel_supported returns true, when distribute is installed and requirement is met
"""
mock_get_distribution.return_value = pkg_resources.Distribution(project_name='distribute', version='0.6.34')
assert wheel.wheel_distribute_support()
@patch("pip.wheel.pkg_resources.get_distribution")
def test_wheel_supported_false_no_install(self, mock_get_distribution):
"""
Test wheel_supported returns false, when distribute not installed
"""
mock_get_distribution.side_effect = self.raise_not_found
assert not wheel.wheel_distribute_support()
@patch("pip.wheel.pkg_resources.get_distribution")
def test_wheel_supported_false_req_fail(self, mock_get_distribution):
"""
Test wheel_supported returns false, when distribute is installed, but req is not met
"""
mock_get_distribution.return_value = pkg_resources.Distribution(project_name='distribute', version='0.6.28')
assert not wheel.wheel_distribute_support()
@patch("pip.wheel.pkg_resources.get_distribution")
def test_finder_raises_error(self, mock_get_distribution):
"""
Test the PackageFinder raises an error when wheel is not supported
"""
mock_get_distribution.side_effect = self.raise_not_found
# on initialization
assert_raises_regexp(InstallationError, 'wheel support', PackageFinder, [], [], use_wheel=True)
# when setting property later
p = PackageFinder([], [])
assert_raises_regexp(InstallationError, 'wheel support', self.set_use_wheel_true, p)
@patch("pip.wheel.pkg_resources.get_distribution")
def test_finder_no_raises_error(self, mock_get_distribution):
"""
Test the PackageFinder doesn't raises an error when use_wheel is False, and wheel is supported
"""
mock_get_distribution.return_value = pkg_resources.Distribution(project_name='distribute', version='0.6.34')
p = PackageFinder( [], [], use_wheel=False)
p = PackageFinder([], [])
p.use_wheel = False
class TestWheelFile(object):
@patch('pip.wheel.supported_tags', [('py2', 'none', 'any')])
def test_supported_single_version(self):
"""
Test single-version wheel is known to be supported
"""
w = wheel.Wheel('simple-0.1-py2-none-any.whl')
assert w.supported()
@patch('pip.wheel.supported_tags', [('py3', 'none', 'any')])
def test_supported_multi_version(self):
"""
Test multi-version wheel is known to be supported
"""
w = wheel.Wheel('simple-0.1-py2.py3-none-any.whl')
assert w.supported()
@patch('pip.wheel.supported_tags', [('py1', 'none', 'any')])
def test_not_supported_version(self):
"""
Test unsupported wheel is known to be unsupported
"""
w = wheel.Wheel('simple-0.1-py2-none-any.whl')
assert not w.supported()
@patch('pip.wheel.supported_tags', [
('py2', 'none', 'TEST'),
('py2', 'TEST', 'any'),
('py2', 'none', 'any'),
])
def test_support_index_min(self):
"""
Test results from `support_index_min`
"""
w = wheel.Wheel('simple-0.1-py2-none-any.whl')
assert w.support_index_min() == 2
w = wheel.Wheel('simple-0.1-py2-none-TEST.whl')
assert w.support_index_min() == 0
@patch('pip.wheel.supported_tags', [])
def test_support_index_min_none(self):
"""
Test `support_index_min` returns None, when wheel not supported
"""
w = wheel.Wheel('simple-0.1-py2-none-any.whl')
assert w.support_index_min() == None