Skip to content

Commit

Permalink
rename PackageNotFoundError to PackagesNotFoundError and fix message …
Browse files Browse the repository at this point in the history
…formatting
  • Loading branch information
kalefranz committed Jun 26, 2017
1 parent 38b90dd commit d9d3317
Show file tree
Hide file tree
Showing 9 changed files with 60 additions and 66 deletions.
14 changes: 5 additions & 9 deletions conda/cli/install.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,11 @@
from ..core.solve import Solver
from ..exceptions import (CondaImportError, CondaOSError, CondaSystemExit, CondaValueError,
DirectoryNotFoundError, DryRunExit, EnvironmentLocationNotFound,
PackageNotFoundError, PackageNotInstalledError, TooManyArgumentsError,
PackageNotInstalledError, PackagesNotFoundError, TooManyArgumentsError,
UnsatisfiableError)
from ..misc import append_env, clone_env, explicit, touch_nonadmin
from ..plan import (revert_actions)
from ..resolve import ResolvePackageNotFound, dashlist
from ..resolve import ResolvePackageNotFound

log = getLogger(__name__)
stderr = getLogger('stderr')
Expand Down Expand Up @@ -221,18 +221,14 @@ def install(args, parser, command='install'):
progressive_fetch_extract = unlink_link_transaction.get_pfe()

except ResolvePackageNotFound as e:
pkg = e.bad_deps
pkg = dashlist(' -> '.join(map(str, q)) for q in pkg)
channel_priority_map = get_channel_priority_map(
channel_urls=index_args['channel_urls'],
prepend=index_args['prepend'],
platform=None,
use_local=index_args['use_local'],
)

channels_urls = tuple(channel_priority_map)

raise PackageNotFoundError(pkg, channels_urls)
raise PackagesNotFoundError(e.bad_deps, channels_urls)

except (UnsatisfiableError, SystemExit) as e:
# Unsatisfiable package specifications/no such revision/import error
Expand All @@ -247,8 +243,8 @@ def handle_txn(progressive_fetch_extract, unlink_link_transaction, prefix, args,
remove_op=False):
if unlink_link_transaction.nothing_to_do:
if remove_op:
error_message = "No packages found to remove from environment."
raise PackageNotFoundError(error_message)
# No packages found to remove from environment
raise PackagesNotFoundError(args.package_names)
elif not newenv:
if context.json:
common.stdout_json_success(message='All requested packages already installed.')
Expand Down
22 changes: 5 additions & 17 deletions conda/cli/main_search.py
Original file line number Diff line number Diff line change
Expand Up @@ -109,31 +109,19 @@ def configure_parser(sub_parsers):
def execute(args, parser):
from ..base.context import context
from ..core.index import get_channel_priority_map
from ..exceptions import PackageNotFoundError, ResolvePackageNotFound
from ..resolve import dashlist
from ..exceptions import PackagesNotFoundError, ResolvePackageNotFound

try:
execute_search(args, parser)
except ResolvePackageNotFound as e:
pkg = []
pkg.append(e.bad_deps)
pkg = dashlist(pkg)
index_args = {
'channel_urls': context.channels,
'prepend': not args.override_channels,
'use_local': args.use_local,
}

channel_priority_map = get_channel_priority_map(
channel_urls=index_args['channel_urls'],
prepend=index_args['prepend'],
channel_urls=context.channels,
prepend=not args.override_channels,
platform=None,
use_local=index_args['use_local'],
use_local=args.use_local,
)

channels_urls = tuple(channel_priority_map)

raise PackageNotFoundError(pkg, channels_urls)
raise PackagesNotFoundError(e.bad_deps, channels_urls)


def make_icon_url(info): # pragma: no cover
Expand Down
4 changes: 2 additions & 2 deletions conda/core/solve.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
from ..common.constants import NULL
from ..common.io import spinner
from ..common.path import paths_equal
from ..exceptions import PackageNotFoundError
from ..exceptions import PackagesNotFoundError
from ..history import History
from ..models.channel import Channel
from ..models.dag import PrefixDag
Expand Down Expand Up @@ -174,7 +174,7 @@ def solve_final_state(self, deps_modifier=NULL, prune=NULL, ignore_pinned=NULL,
solution = tuple(Dist(rec) for rec in dag.records)

if not removed_records and not prune:
raise PackageNotFoundError("No packages found to remove from environment.")
raise PackagesNotFoundError(tuple(spec.name for spec in specs_to_remove))

# We handle as best as possible environments in inconsistent states. To do this,
# we remove now from consideration the set of packages causing inconsistencies,
Expand Down
42 changes: 25 additions & 17 deletions conda/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,8 @@
class ResolvePackageNotFound(CondaError): # change back to Exception in conda 4.4
def __init__(self, bad_deps):
# bad_deps is a list of lists
self.bad_deps = bad_deps
message = '\n' + '\n'.join((' - %s' % dep) for deps in bad_deps for dep in deps if dep)
self.bad_deps = tuple(dep for deps in bad_deps for dep in deps if dep)
message = '\n' + '\n'.join((' - %s' % dep) for dep in self.bad_deps)
super(ResolvePackageNotFound, self).__init__(message)
NoPackagesFound = NoPackagesFoundError = ResolvePackageNotFound # NOQA

Expand Down Expand Up @@ -390,25 +390,33 @@ class AuthenticationError(CondaError):
pass


class PackageNotFoundError(CondaError):
class PackagesNotFoundError(CondaError):

def __init__(self, bad_pkg, channel_urls=()):
from .resolve import dashlist
channels = dashlist(channel_urls)
def __init__(self, packages, channel_urls=()):
format_list = lambda iterable: ' - ' + '\n - '.join(text_type(x) for x in iterable)

if not channel_urls:
msg = """Package(s) is missing from the environment:
%(pkg)s
"""
else:
msg = """Packages missing in current channels:
%(pkg)s
if channel_urls:
message = dals("""
The following packages are not available from current channels:
%(packages_formatted)s
We have searched for the packages in the following channels:
%(channels)s
"""
Current channels:
%(channels_formatted)s
""")
packages_formatted = format_list(packages)
channels_formatted = format_list(channel_urls)
else:
message = dals("""
The following packages are missing from the target environment:
%(packages_formatted)s
""")
packages_formatted = format_list(packages)
channels_formatted = ()

super(PackageNotFoundError, self).__init__(msg, pkg=bad_pkg, channels=channels)
super(PackagesNotFoundError, self).__init__(
message, packages=packages, packages_formatted=packages_formatted,
channel_urls=channel_urls, channels_formatted=channels_formatted
)


class UnsatisfiableError(CondaError):
Expand Down
5 changes: 2 additions & 3 deletions conda/misc.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
from .core.link import PrefixSetup, UnlinkLinkTransaction
from .core.linked_data import PrefixData, linked_data
from .core.package_cache import PackageCache, ProgressiveFetchExtract
from .exceptions import PackageNotFoundError, ParseError
from .exceptions import PackagesNotFoundError, ParseError
from .gateways.disk.delete import rm_rf
from .gateways.disk.link import islink
from .models.dist import Dist
Expand Down Expand Up @@ -222,8 +222,7 @@ def clone_env(prefix1, prefix2, verbose=True, quiet=False, index_args=None):
else:
notfound.append(fn)
if notfound:
what = "Package%s " % ('' if len(notfound) == 1 else 's')
raise PackageNotFoundError(what)
raise PackagesNotFoundError(notfound)

# Assemble the URL and channel list
urls = {}
Expand Down
4 changes: 2 additions & 2 deletions conda/resolve.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,8 @@
ResolvePackageNotFound = ResolvePackageNotFound


def dashlist(iter):
return ''.join('\n - ' + str(x) for x in iter)
def dashlist(iterable):
return ''.join('\n - ' + str(x) for x in iterable)


class Resolve(object):
Expand Down
17 changes: 10 additions & 7 deletions tests/test_create.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
from unittest import TestCase
from uuid import uuid4

from conda._vendor.auxlib.ish import dals
import pytest
import requests

Expand All @@ -38,7 +39,7 @@
linked as install_linked, linked_data
from conda.core.package_cache import PackageCache
from conda.core.repodata import create_cache_dir
from conda.exceptions import CondaHTTPError, DryRunExit, PackageNotFoundError, RemoveError, \
from conda.exceptions import CondaHTTPError, DryRunExit, PackagesNotFoundError, RemoveError, \
conda_exception_handler
from conda.gateways.anaconda_client import read_binstar_tokens
from conda.gateways.disk.create import mkdir_p
Expand Down Expand Up @@ -1018,7 +1019,7 @@ def test_create_dry_run(self):

def test_packages_not_found(self):
with make_temp_env() as prefix:
with pytest.raises(PackageNotFoundError) as exc:
with pytest.raises(PackagesNotFoundError) as exc:
run_command(Commands.INSTALL, prefix, "not-a-real-package")
assert "not-a-real-package" in text_type(exc.value)

Expand Down Expand Up @@ -1214,7 +1215,7 @@ def side_effect(self, url, **kwargs):
mock_method.side_effect = side_effect

# Fails because flask dependencies are not retrievable.
with pytest.raises(PackageNotFoundError):
with pytest.raises(PackagesNotFoundError):
run_command(Commands.INSTALL, prefix, "-c", channel,
"flask", "--json", "--offline")

Expand Down Expand Up @@ -1400,12 +1401,14 @@ def test_remove_spellcheck(self):
assert exists(join(prefix, PYTHON_BINARY))
assert_package_is_installed(prefix, 'numpy')

with pytest.raises(PackageNotFoundError) as exc:
with pytest.raises(PackagesNotFoundError) as exc:
run_command(Commands.REMOVE, prefix, 'numpi')

exc_string = '%r' % exc.value
assert exc_string.strip() == """PackageNotFoundError: Package(s) is missing from the environment:
numpi """.strip()
assert exc_string.strip() == dals("""
PackagesNotFoundError: The following packages are missing from the target environment:
- numpi
""").strip()
assert_package_is_installed(prefix, 'numpy')

def test_conda_list_json(self):
Expand Down Expand Up @@ -1516,7 +1519,7 @@ def test_install_dep_uninstall_base(self, prefix_specified):
assert not package_is_installed(self.prefix, "spiffy-test-app")
assert not package_is_installed(self.prefix, "uses-spiffy-test-app")

with pytest.raises(PackageNotFoundError):
with pytest.raises(PackagesNotFoundError):
run_command(Commands.REMOVE, self.prefix, "spiffy-test-app")
assert package_is_installed(self.preferred_env_prefix, "spiffy-test-app")
assert isfile(self.exe_file(self.preferred_env_prefix, 'spiffy-test-app'))
Expand Down
14 changes: 7 additions & 7 deletions tests/test_exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
from conda.common.io import captured, env_var
from conda.exceptions import BasicClobberError, BinaryPrefixReplacementError, CommandNotFoundError, \
CondaHTTPError, CondaKeyError, CondaRevisionError, DirectoryNotFoundError, \
KnownPackageClobberError, MD5MismatchError, PackageNotFoundError, PathNotFoundError, \
KnownPackageClobberError, MD5MismatchError, PackagesNotFoundError, PathNotFoundError, \
SharedLinkPathClobberError, TooFewArgumentsError, TooManyArgumentsError, \
UnknownPackageClobberError, conda_exception_handler, print_unexpected_error_message

Expand Down Expand Up @@ -221,12 +221,12 @@ def test_PackageNotFoundError(self):
package = "Potato"
with env_var("CONDA_JSON", "yes", reset_context):
with captured() as c:
exc = PackageNotFoundError(package)
exc = PackagesNotFoundError((package,))
conda_exception_handler(_raise_helper, exc)

json_obj = json.loads(c.stdout)
assert not c.stderr
assert json_obj['exception_type'] == "<class 'conda.exceptions.PackageNotFoundError'>"
assert json_obj['exception_type'] == "<class 'conda.exceptions.PackagesNotFoundError'>"
assert json_obj['message'] == text_type(exc)
assert json_obj['error'] == repr(exc)

Expand All @@ -235,10 +235,10 @@ def test_PackageNotFoundError(self):
conda_exception_handler(_raise_helper, exc)

assert not c.stdout
assert c.stderr.strip() == """
PackageNotFoundError: Package(s) is missing from the environment:
Potato
""".strip()
assert c.stderr.strip() == dals("""
PackagesNotFoundError: The following packages are missing from the target environment:
- Potato
""").strip()

def test_CondaRevisionError(self):
message = "Potato"
Expand Down
4 changes: 2 additions & 2 deletions tests/test_plan.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
from conda.cli.python_api import Commands, run_command
from conda.common.io import env_var
from conda.core.solve import get_pinned_specs
from conda.exceptions import PackageNotFoundError
from conda.exceptions import PackagesNotFoundError
from conda.gateways.disk.create import mkdir_p
import conda.instructions as inst
from conda.models.dist import Dist
Expand Down Expand Up @@ -876,7 +876,7 @@ def get_dists_for_spec(spec, emptyok=False):
# Here, spec should be a MatchSpec
res = groups[spec.name]
if not res and not emptyok:
raise PackageNotFoundError([(spec,)])
raise PackagesNotFoundError((spec,))
return res

def get_explicit(spec):
Expand Down

0 comments on commit d9d3317

Please sign in to comment.