def test_TooManyArgumentsError(self): expected = 2 received = 5 offending_arguments = "groot" exc = TooManyArgumentsError(expected, received, offending_arguments) with env_var("CONDA_JSON", "yes", stack_callback=conda_tests_ctxt_mgmt_def_pol): with captured() as c: conda_exception_handler(_raise_helper, exc) json_obj = json.loads(c.stdout) assert not c.stderr assert json_obj['exception_type'] == "<class 'conda.exceptions.TooManyArgumentsError'>" assert json_obj['exception_name'] == 'TooManyArgumentsError' assert json_obj['message'] == text_type(exc) assert json_obj['error'] == repr(exc) assert json_obj['expected'] == 2 assert json_obj['received'] == 5 assert json_obj['offending_arguments'] == "groot" with env_var("CONDA_JSON", "no", stack_callback=conda_tests_ctxt_mgmt_def_pol): with captured() as c: conda_exception_handler(_raise_helper, exc) assert not c.stdout assert c.stderr.strip() == "TooManyArgumentsError: Got 5 arguments (g, r, o, o, t) but expected 2."
def test_attach_stderr_handler(): name = 'abbacadabba' logr = getLogger(name) assert len(logr.handlers) == 0 assert logr.level is NOTSET debug_message = "debug message 1329-485" with captured() as c: attach_stderr_handler(WARN, name) logr.warn('test message') logr.debug(debug_message) assert len(logr.handlers) == 1 assert logr.handlers[0].name == 'stderr' assert logr.handlers[0].level is NOTSET assert logr.level is WARN assert c.stdout == '' assert 'test message' in c.stderr assert debug_message not in c.stderr # round two, with debug with captured() as c: attach_stderr_handler(DEBUG, name) logr.warn('test message') logr.debug(debug_message) logr.info('info message') assert len(logr.handlers) == 1 assert logr.handlers[0].name == 'stderr' assert logr.handlers[0].level is NOTSET assert logr.level is DEBUG assert c.stdout == '' assert 'test message' in c.stderr assert debug_message in c.stderr
def test_MD5MismatchError(self): url = "https://download.url/path/to/file.tar.bz2" target_full_path = "/some/path/on/disk/another-name.tar.bz2" expected_md5sum = "abc123" actual_md5sum = "deadbeef" exc = MD5MismatchError(url, target_full_path, expected_md5sum, actual_md5sum) with env_var("CONDA_JSON", "yes", stack_callback=conda_tests_ctxt_mgmt_def_pol): with captured() as c: conda_exception_handler(_raise_helper, exc) json_obj = json.loads(c.stdout) assert not c.stderr assert json_obj['exception_type'] == "<class 'conda.exceptions.MD5MismatchError'>" assert json_obj['exception_name'] == 'MD5MismatchError' assert json_obj['message'] == text_type(exc) assert json_obj['error'] == repr(exc) assert json_obj['url'] == url assert json_obj['target_full_path'] == target_full_path assert json_obj['expected_sum'] == expected_md5sum assert json_obj['actual_sum'] == actual_md5sum assert json_obj['checksum_type'] == 'md5' with env_var("CONDA_JSON", "no", stack_callback=conda_tests_ctxt_mgmt_def_pol): with captured() as c: conda_exception_handler(_raise_helper, exc) assert not c.stdout assert c.stderr.strip() == dals(""" MD5MismatchError: Conda detected a mismatch between the expected content and downloaded content for url 'https://download.url/path/to/file.tar.bz2'. download saved to: /some/path/on/disk/another-name.tar.bz2 expected md5 sum: abc123 actual md5 sum: deadbeef """).strip()
def test_CondaHTTPError(self): msg = "Potato" url = "https://download.url/path/to/Potato.tar.gz" status_code = "Potato" reason = "COULD NOT CONNECT" elapsed_time = 1.24 exc = CondaHTTPError(msg, url, status_code, reason, elapsed_time) with env_var("CONDA_JSON", "yes", stack_callback=conda_tests_ctxt_mgmt_def_pol): with captured() as c: conda_exception_handler(_raise_helper, exc) json_obj = json.loads(c.stdout) assert not c.stderr assert json_obj['exception_type'] == "<class 'conda.exceptions.CondaHTTPError'>" assert json_obj['exception_name'] == 'CondaHTTPError' assert json_obj['message'] == text_type(exc) assert json_obj['error'] == repr(exc) assert json_obj['url'] == url assert json_obj['status_code'] == status_code assert json_obj['reason'] == reason assert json_obj['elapsed_time'] == elapsed_time with env_var("CONDA_JSON", "no", stack_callback=conda_tests_ctxt_mgmt_def_pol): with captured() as c: conda_exception_handler(_raise_helper, exc) assert not c.stdout assert dals(""" CondaHTTPError: HTTP Potato COULD NOT CONNECT for url <https://download.url/path/to/Potato.tar.gz> Elapsed: 1.24 Potato """).strip() in c.stderr.strip()
def run_conda_command(command, prefix, *arguments): """ Run conda command, Args: command: conda create, list, info prefix: The prefix or the name of environment *arguments: Extra arguments """ p = generate_parser() prefix = escape_for_winpath(prefix) if arguments: arguments = list(map(escape_for_winpath, arguments)) if command is Commands.INFO: # INFO command_line = "{0} {1}".format(command, " ".join(arguments)) elif command is Commands.LIST: # LIST command_line = "{0} -n {1} {2}".format(command, prefix, " ".join(arguments)) else: # CREATE command_line = "{0} -y -q -n {1} {2}".format(command, prefix, " ".join(arguments)) from conda._vendor.auxlib.compat import shlex_split_unicode commands = shlex_split_unicode(command_line) args = p.parse_args(commands) context._set_argparse_args(args) with captured() as c: do_call(args, p) return c.stdout, c.stderr
def run_env_command(command, prefix, *arguments): """ Run conda env commands Args: command: The command, create, remove, export prefix: The prefix, for remove and create *arguments: The extra arguments """ arguments = massage_arguments(arguments) arguments.insert(0, command) if command is Commands.ENV_EXPORT: arguments[1:1] = ['-n', prefix] elif command is Commands.ENV_CREATE: # CREATE if prefix: arguments[1:1] = ['-f', prefix] elif command is Commands.ENV_REMOVE: # REMOVE arguments[1:1] = ['--yes', '-n', prefix] elif command is Commands.ENV_UPDATE: arguments[1:1] = ['-n', prefix] else: command_line = " --help " p = create_parser() args = p.parse_args(arguments) context._set_argparse_args(args) with captured() as c: do_call_conda_env(args, p) return c.stdout, c.stderr
def test_initialize_dev_cmd_exe(self): with env_vars({'CONDA_DRY_RUN': 'true', 'CONDA_VERBOSITY': '0'}, reset_context): with tempdir() as conda_temp_prefix: new_py = abspath(join(conda_temp_prefix, get_python_short_path())) mkdir_p(dirname(new_py)) create_link(abspath(sys.executable), new_py, LinkType.hardlink if on_win else LinkType.softlink) with captured() as c: initialize_dev('cmd.exe', dev_env_prefix=conda_temp_prefix, conda_source_root=dirname(CONDA_PACKAGE_ROOT)) print(c.stdout) print(c.stderr, file=sys.stderr) if on_win: modified_files = ( 'conda.exe', 'conda-env.exe', 'conda-script.py', 'conda-env-script.py', 'conda.bat', '_conda_activate.bat', 'conda_auto_activate.bat', 'conda_hook.bat', 'activate.bat', 'activate.bat', 'deactivate.bat', 'activate', 'deactivate', 'conda.sh', 'conda.fish', 'conda.xsh', 'conda.csh', 'site-packages', # remove conda in site-packages dir 'conda.egg-link', 'easy-install.pth', 'conda.egg-info', ) else: modified_files = ( 'conda', 'conda-env', 'activate', 'deactivate', 'conda.sh', 'conda.fish', 'conda.xsh', 'conda.csh', 'site-packages', # remove conda in site-packages dir 'conda.egg-link', 'easy-install.pth', 'conda.egg-info', ) stderr = c.stderr.replace('no change', 'modified') assert stderr.count('modified') == len(modified_files) for fn in modified_files: line = next(line for line in stderr.splitlines() if line.strip().endswith(fn)) assert line.strip().startswith('modified'), line
def run_env_command(command, prefix, *arguments): """ Run conda env commands Args: command: The command, create, remove, export prefix: The prefix, for remove and create *arguments: The extra arguments """ p = create_parser() prefix = escape_for_winpath(prefix) if arguments: arguments = list(map(escape_for_winpath, arguments)) if command is Commands.ENV_EXPORT: command_line = "{0} -n {1} {2}".format(command, prefix, " ".join(arguments)) elif command is Commands.ENV_CREATE: # CREATE if prefix : command_line = "{0} -f {1} {2}".format(command, prefix, " ".join(arguments)) else: command_line = "{0} ".format(command) elif command is Commands.ENV_REMOVE: # REMOVE command_line = "{0} --yes -n {1} {2}".format(command, prefix, " ".join(arguments)) elif command is Commands.ENV_UPDATE: command_line = "{0} -n {1} {2}".format(command, prefix, " ".join(arguments)) else: command_line = " --help " args = p.parse_args(split(command_line)) context._add_argparse_args(args) with captured() as c: args.func(args, p) return c.stdout, c.stderr
def run_command(command, prefix, *arguments, **kwargs): use_exception_handler = kwargs.get('use_exception_handler', False) arguments = list(arguments) p, sub_parsers = generate_parser() parser_config[command](sub_parsers) if command is Commands.CONFIG: arguments.append("--file {0}".format(join(prefix, 'condarc'))) if command in (Commands.LIST, Commands.CREATE, Commands.INSTALL, Commands.REMOVE, Commands.UPDATE): arguments.append("-p {0}".format(prefix)) if command in (Commands.CREATE, Commands.INSTALL, Commands.REMOVE, Commands.UPDATE): arguments.extend(["-y", "-q"]) arguments = list(map(escape_for_winpath, arguments)) command_line = "{0} {1}".format(command, " ".join(arguments)) args = p.parse_args(split(command_line)) context._add_argparse_args(args) print("executing command >>>", command_line) with captured() as c, replace_log_streams(): if use_exception_handler: conda_exception_handler(args.func, args, p) else: args.func(args, p) print(c.stderr, file=sys.stderr) print(c.stdout) if command is Commands.CONFIG: reload_config(prefix) return c.stdout, c.stderr
def run_conda_command(command, prefix, *arguments): """ Run conda command, Args: command: conda create , list, info prefix: The prefix or the name of environment *arguments: Extra arguments """ p, sub_parsers = generate_parser() assert command in parser_config, "Wrong command for conda {0}".format(command) parser_config[command](sub_parsers) prefix = escape_for_winpath(prefix) if arguments: arguments = list(map(escape_for_winpath, arguments)) if command is Commands.INFO: # INFO command_line = "{0} {1}".format(command, " ".join(arguments)) elif command is Commands.LIST: # LIST command_line = "{0} -n {1} {2}".format(command, prefix, " ".join(arguments)) else: # CREATE command_line = "{0} -y -q -n {1} {2}".format(command, prefix, " ".join(arguments)) args = p.parse_args(split(command_line)) context._add_argparse_args(args) with captured() as c: args.func(args, p) return c.stdout, c.stderr
def test_print_unexpected_error_message_opt_out_2(self, isatty_mock, input_mock, post_mock): with captured() as c: ExceptionHandler()(_raise_helper, AssertionError()) assert input_mock.call_count == 1 assert post_mock.call_count == 0 assert c.stdout == '' assert "conda version" in c.stderr
def test_print_unexpected_error_message_upload_1(self, post_mock): with env_var('CONDA_REPORT_ERRORS', 'true', stack_callback=conda_tests_ctxt_mgmt_def_pol): with captured() as c: ExceptionHandler()(_raise_helper, AssertionError()) assert post_mock.call_count == 2 assert c.stdout == '' assert "conda version" in c.stderr
def test_print_unexpected_error_message_upload_2(self, post_mock): with env_var('CONDA_JSON', 'true', stack_callback=conda_tests_ctxt_mgmt_def_pol): with env_var('CONDA_YES', 'yes', stack_callback=conda_tests_ctxt_mgmt_def_pol): with captured() as c: ExceptionHandler()(_raise_helper, AssertionError()) assert post_mock.call_count == 3 assert len(json.loads(c.stdout)['conda_info']['channels']) >= 2 assert not c.stderr
def test_confirm_yn_yes(self, stdin_mock): args = AttrDict({ 'dry_run': False, }) from conda.cli.common import confirm_yn with captured() as c: choice = confirm_yn() assert choice is True assert "Invalid choice" in c.stdout
def run_inprocess_conda_command(command): reset_context(()) with argv(split(command)), captured() as c: initialize_logging() try: exit_code = cli.main() except SystemExit: pass print(c.stderr, file=sys.stderr) print(c.stdout) return c.stdout, c.stderr, exit_code
def test_CondaFileNotFoundError(self): filename = "Groot" exc = PathNotFoundError(filename) with env_var("CONDA_JSON", "yes", stack_callback=conda_tests_ctxt_mgmt_def_pol): with captured() as c: conda_exception_handler(_raise_helper, exc) json_obj = json.loads(c.stdout) assert not c.stderr assert json_obj['exception_type'] == "<class 'conda.exceptions.PathNotFoundError'>" assert json_obj['exception_name'] == 'PathNotFoundError' assert json_obj['message'] == text_type(exc) assert json_obj['error'] == repr(exc) with env_var("CONDA_JSON", "no", stack_callback=conda_tests_ctxt_mgmt_def_pol): with captured() as c: conda_exception_handler(_raise_helper, exc) assert not c.stdout assert c.stderr.strip() == "PathNotFoundError: Groot"
def test_CondaRevisionError(self): message = "Potato" exc = CondaRevisionError(message) with env_var("CONDA_JSON", "yes", stack_callback=conda_tests_ctxt_mgmt_def_pol): with captured() as c: conda_exception_handler(_raise_helper, exc) json_obj = json.loads(c.stdout) assert not c.stderr assert json_obj['exception_type'] == "<class 'conda.exceptions.CondaRevisionError'>" assert json_obj['exception_name'] == 'CondaRevisionError' assert json_obj['message'] == text_type(exc) assert json_obj['error'] == repr(exc) with env_var("CONDA_JSON", "no", stack_callback=conda_tests_ctxt_mgmt_def_pol): with captured() as c: conda_exception_handler(_raise_helper, exc) assert not c.stdout assert c.stderr.strip() == "CondaRevisionError: Potato."
def test_print_unexpected_error_message_opt_out_1(self, input_mock, post_mock): with env_var('CONDA_REPORT_ERRORS', 'false', stack_callback=conda_tests_ctxt_mgmt_def_pol): e = AssertionError() with captured() as c: ExceptionHandler()(_raise_helper, AssertionError()) assert input_mock.call_count == 0 assert post_mock.call_count == 0 assert c.stdout == '' print(c.stderr, file=sys.stderr) assert "conda version" in c.stderr
def test_CommandNotFoundError_conda_build(self): cmd = "build" exc = CommandNotFoundError(cmd) with env_var("CONDA_JSON", "yes", stack_callback=conda_tests_ctxt_mgmt_def_pol): with captured() as c: conda_exception_handler(_raise_helper, exc) json_obj = json.loads(c.stdout) assert not c.stderr assert json_obj['exception_type'] == "<class 'conda.exceptions.CommandNotFoundError'>" assert json_obj['message'] == text_type(exc) assert json_obj['error'] == repr(exc) with env_var("CONDA_JSON", "no", stack_callback=conda_tests_ctxt_mgmt_def_pol): with captured() as c: conda_exception_handler(_raise_helper, exc) assert not c.stdout assert c.stderr.strip() == ("CommandNotFoundError: To use 'conda build', install conda-build.")
def run_inprocess_conda_command(command, disallow_stderr=True): # anything that uses this function is an integration test reset_context(()) with argv(split(command)), captured(disallow_stderr) as c: initialize_logging() try: exit_code = cli.main() except SystemExit: pass print(c.stderr, file=sys.stderr) print(c.stdout) return c.stdout, c.stderr, exit_code
def test_DirectoryNotFoundError(self): directory = "Groot" exc = DirectoryNotFoundError(directory) with env_var("CONDA_JSON", "yes", reset_context): with captured() as c: conda_exception_handler(_raise_helper, exc) json_obj = json.loads(c.stdout) assert not c.stderr assert json_obj['exception_type'] == "<class 'conda.exceptions.DirectoryNotFoundError'>" assert json_obj['exception_name'] == 'DirectoryNotFoundError' assert json_obj['message'] == text_type(exc) assert json_obj['error'] == repr(exc) assert json_obj['path'] == "Groot" with env_var("CONDA_JSON", "no", reset_context): with captured() as c: conda_exception_handler(_raise_helper, exc) assert not c.stdout assert c.stderr.strip() == "DirectoryNotFoundError: Groot"
def test_CommandNotFoundError_simple(self): cmd = "instate" exc = CommandNotFoundError(cmd) with env_var("CONDA_JSON", "yes", stack_callback=conda_tests_ctxt_mgmt_def_pol): with captured() as c: conda_exception_handler(_raise_helper, exc) json_obj = json.loads(c.stdout) assert not c.stderr assert json_obj['exception_type'] == "<class 'conda.exceptions.CommandNotFoundError'>" assert json_obj['message'] == text_type(exc) assert json_obj['error'] == repr(exc) with env_var("CONDA_JSON", "no", stack_callback=conda_tests_ctxt_mgmt_def_pol): with captured() as c: conda_exception_handler(_raise_helper, exc) assert not c.stdout assert c.stderr.strip() == ("CommandNotFoundError: No command 'conda instate'.\n" "Did you mean 'conda install'?")
def test_init_cmd_exe_registry(self): def _read_windows_registry_mock(target_path, value=None): if not value: value = "yada\\yada\\conda_hook.bat" return 'echo hello & "{}" & echo "world"'.format(value), None from conda.core import initialize orig_read_windows_registry = initialize._read_windows_registry initialize._read_windows_registry = _read_windows_registry_mock orig_join = initialize.join initialize.join = ntpath.join try: target_path = r'HKEY_CURRENT_USER\Software\Microsoft\Command Processor\AutoRun' conda_prefix = "c:\\Users\\Lars\\miniconda" with env_var('CONDA_DRY_RUN', 'true', conda_tests_ctxt_mgmt_def_pol): with captured() as c: initialize.init_cmd_exe_registry(target_path, conda_prefix) finally: initialize._read_windows_registry = orig_read_windows_registry initialize.join = orig_join expected = "echo hello & \"c:\\Users\\Lars\\miniconda\\condabin\\conda_hook.bat\" & echo \"world\"" assert c.stdout.strip().splitlines()[-1][1:] == expected # test the reverse (remove the key) initialize._read_windows_registry = lambda x: _read_windows_registry_mock(x, value=join(conda_prefix, 'condabin', 'conda_hook.bat')) initialize.join = ntpath.join try: target_path = r'HKEY_CURRENT_USER\Software\Microsoft\Command Processor\AutoRun' conda_prefix = "c:\\Users\\Lars\\miniconda" with env_var('CONDA_DRY_RUN', 'true', conda_tests_ctxt_mgmt_def_pol): with captured() as c: initialize.init_cmd_exe_registry(target_path, conda_prefix, reverse=True) finally: initialize._read_windows_registry = orig_read_windows_registry initialize.join = orig_join expected = "echo hello & echo \"world\"" assert c.stdout.strip().splitlines()[-1][1:] == expected
def run_inprocess_conda_command(command, disallow_stderr=True): # anything that uses this function is an integration test reset_context(()) # May want to do this to command: with argv(encode_arguments(shlex_split_unicode(command))), captured(disallow_stderr) as c: initialize_logging() try: exit_code = cli.main(*sys.argv) except SystemExit: pass print(c.stderr, file=sys.stderr) print(c.stdout) return c.stdout, c.stderr, exit_code
def test_PackageNotFoundError(self): package = "Potato" with env_var("CONDA_JSON", "yes", reset_context): with captured() as c: 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.PackagesNotFoundError'>" assert json_obj['message'] == text_type(exc) assert json_obj['error'] == repr(exc) with env_var("CONDA_JSON", "no", reset_context): with captured() as c: conda_exception_handler(_raise_helper, exc) assert not c.stdout assert c.stderr.strip() == dals(""" PackagesNotFoundError: The following packages are missing from the target environment: - Potato """).strip()
def test_search_0(self): with captured(): res = capture_json_with_argv('conda search --json') self.assertIsInstance(res, dict) self.assertIsInstance(res['conda'], list) self.assertIsInstance(res['conda'][0], dict) keys = ('build', 'channel', 'fn', 'version') for key in keys: self.assertIn(key, res['conda'][0]) stdout, stderr, rc = run_inprocess_conda_command('conda search * --json') assert stderr == '' assert rc is None
def test_CommandNotFoundError_conda_build(self): cmd = "build" exc = CommandNotFoundError(cmd) with env_var("CONDA_JSON", "yes", reset_context): with captured() as c, replace_log_streams(): conda_exception_handler(_raise_helper, exc) json_obj = json.loads(c.stdout) assert not c.stderr assert json_obj[ 'exception_type'] == "<class 'conda.exceptions.CommandNotFoundError'>" assert json_obj['message'] == text_type(exc) assert json_obj['error'] == repr(exc) with env_var("CONDA_JSON", "no", reset_context): with captured() as c, replace_log_streams(): conda_exception_handler(_raise_helper, exc) assert not c.stdout assert c.stderr.strip() == ("CommandNotFoundError: You need to install conda-build in order to\n" \ "use the 'conda build' command.")
def PackageNotFoundError(self): package = "Groot" exc = PackageNotFoundError(package) with env_var("CONDA_JSON", "yes", reset_context): with captured() as c, replace_log_streams(): 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['message'] == text_type(exc) assert json_obj['package_name'] == package assert json_obj['error'] == repr(exc) with env_var("CONDA_JSON", "no", reset_context): with captured() as c, replace_log_streams(): conda_exception_handler(_raise_helper, exc) assert not c.stdout assert c.stderr.strip( ) == "Package not found: Conda could not find Groot"
def test_CondaFileNotFoundError(self): filename = "Groot" exc = CondaFileNotFoundError(filename) with env_var("CONDA_JSON", "yes", reset_context): with captured() as c, replace_log_streams(): conda_exception_handler(_raise_helper, exc) json_obj = json.loads(c.stdout) assert not c.stderr assert json_obj[ 'exception_type'] == "<class 'conda.exceptions.CondaFileNotFoundError'>" assert json_obj['exception_name'] == 'CondaFileNotFoundError' assert json_obj['message'] == text_type(exc) assert json_obj['error'] == repr(exc) with env_var("CONDA_JSON", "no", reset_context): with captured() as c, replace_log_streams(): conda_exception_handler(_raise_helper, exc) assert not c.stdout assert c.stderr.strip( ) == "CondaFileNotFoundError: File not found: 'Groot'."
def test_MD5MismatchError(self): url = "https://download.url/path/to/file.tar.bz2" target_full_path = "/some/path/on/disk/another-name.tar.bz2" expected_md5sum = "abc123" actual_md5sum = "deadbeef" exc = ChecksumMismatchError(url, target_full_path, "md5", expected_md5sum, actual_md5sum) with env_var("CONDA_JSON", "yes", stack_callback=conda_tests_ctxt_mgmt_def_pol): with captured() as c: conda_exception_handler(_raise_helper, exc) json_obj = json.loads(c.stdout) assert not c.stderr assert json_obj[ 'exception_type'] == "<class 'conda.exceptions.ChecksumMismatchError'>" assert json_obj['exception_name'] == 'ChecksumMismatchError' assert json_obj['message'] == text_type(exc) assert json_obj['error'] == repr(exc) assert json_obj['url'] == url assert json_obj['target_full_path'] == target_full_path assert json_obj['expected_checksum'] == expected_md5sum assert json_obj['actual_checksum'] == actual_md5sum with env_var("CONDA_JSON", "no", stack_callback=conda_tests_ctxt_mgmt_def_pol): with captured() as c: conda_exception_handler(_raise_helper, exc) assert not c.stdout assert c.stderr.strip() == dals(""" ChecksumMismatchError: Conda detected a mismatch between the expected content and downloaded content for url 'https://download.url/path/to/file.tar.bz2'. download saved to: /some/path/on/disk/another-name.tar.bz2 expected md5: abc123 actual md5: deadbeef """).strip()
def test_CommandNotFoundError_simple(self): cmd = "instate" exc = CommandNotFoundError(cmd) with env_var("CONDA_JSON", "yes", reset_context): with captured() as c, replace_log_streams(): conda_exception_handler(_raise_helper, exc) json_obj = json.loads(c.stdout) assert not c.stderr assert json_obj[ 'exception_type'] == "<class 'conda.exceptions.CommandNotFoundError'>" assert json_obj['message'] == text_type(exc) assert json_obj['error'] == repr(exc) with env_var("CONDA_JSON", "no", reset_context): with captured() as c, replace_log_streams(): conda_exception_handler(_raise_helper, exc) assert not c.stdout assert c.stderr.strip( ) == "CommandNotFoundError: Conda could not find the command: 'instate'"
def test_BinaryPrefixReplacementError(self): new_data_length = 1104 original_data_length = 1404 new_prefix = "some/where/on/goodwin.ave" path = "some/where/by/boneyard/creek" placeholder = "save/my/spot/in/374" exc = BinaryPrefixReplacementError(path, placeholder, new_prefix, original_data_length, new_data_length) with env_var("CONDA_JSON", "yes", reset_context): with captured() as c, replace_log_streams(): conda_exception_handler(_raise_helper, exc) json_obj = json.loads(c.stdout) assert not c.stderr assert json_obj[ 'exception_type'] == "<class 'conda.exceptions.BinaryPrefixReplacementError'>" assert json_obj['exception_name'] == 'BinaryPrefixReplacementError' assert json_obj['message'] == text_type(exc) assert json_obj['error'] == repr(exc) assert json_obj['new_data_length'] == 1104 assert json_obj['original_data_length'] == 1404 assert json_obj['new_prefix'] == new_prefix assert json_obj['path'] == path assert json_obj['placeholder'] == placeholder with env_var("CONDA_JSON", "no", reset_context): with captured() as c, replace_log_streams(): conda_exception_handler(_raise_helper, exc) assert not c.stdout assert c.stderr.strip() == dals(""" BinaryPrefixReplacementError: Refusing to replace mismatched data length in binary file. path: some/where/by/boneyard/creek placeholder: save/my/spot/in/374 new prefix: some/where/on/goodwin.ave original data Length: 1404 new data length: 1104 """).strip()
def test_PackageNotFoundError(self): package = "Potato" with env_var("CONDA_JSON", "yes", stack_callback=conda_tests_ctxt_mgmt_def_pol): with captured() as c: 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.PackagesNotFoundError'>" assert json_obj['message'] == text_type(exc) assert json_obj['error'] == repr(exc) with env_var("CONDA_JSON", "no", stack_callback=conda_tests_ctxt_mgmt_def_pol): with captured() as c: conda_exception_handler(_raise_helper, exc) assert not c.stdout assert c.stderr.strip() == dals(""" PackagesNotFoundError: The following packages are missing from the target environment: - Potato """).strip()
def test_DirectoryNotFoundError(self): directory = "Groot" exc = DirectoryNotFoundError(directory) with env_var("CONDA_JSON", "yes", reset_context): with captured() as c, replace_log_streams(): conda_exception_handler(_raise_helper, exc) json_obj = json.loads(c.stdout) assert not c.stderr assert json_obj[ 'exception_type'] == "<class 'conda.exceptions.DirectoryNotFoundError'>" assert json_obj['exception_name'] == 'DirectoryNotFoundError' assert json_obj['message'] == text_type(exc) assert json_obj['error'] == repr(exc) assert json_obj['path'] == "Groot" with env_var("CONDA_JSON", "no", reset_context): with captured() as c, replace_log_streams(): conda_exception_handler(_raise_helper, exc) assert not c.stdout assert c.stderr.strip() == "DirectoryNotFoundError: Groot"
def test_CondaHTTPError(self): msg = "Potato" url = "https://download.url/path/to/Potato.tar.gz" status_code = "Potato" reason = "COULD NOT CONNECT" elapsed_time = 1.24 exc = CondaHTTPError(msg, url, status_code, reason, elapsed_time) with env_var("CONDA_JSON", "yes", stack_callback=conda_tests_ctxt_mgmt_def_pol): with captured() as c: conda_exception_handler(_raise_helper, exc) json_obj = json.loads(c.stdout) assert not c.stderr assert json_obj[ 'exception_type'] == "<class 'conda.exceptions.CondaHTTPError'>" assert json_obj['exception_name'] == 'CondaHTTPError' assert json_obj['message'] == text_type(exc) assert json_obj['error'] == repr(exc) assert json_obj['url'] == url assert json_obj['status_code'] == status_code assert json_obj['reason'] == reason assert json_obj['elapsed_time'] == elapsed_time with env_var("CONDA_JSON", "no", stack_callback=conda_tests_ctxt_mgmt_def_pol): with captured() as c: conda_exception_handler(_raise_helper, exc) assert not c.stdout assert dals(""" CondaHTTPError: HTTP Potato COULD NOT CONNECT for url <https://download.url/path/to/Potato.tar.gz> Elapsed: 1.24 Potato """).strip() in c.stderr.strip()
def test_CondaKeyError(self): key = "Potato" message = "Potato is not a key." exc = CondaKeyError(key, message) with env_var("CONDA_JSON", "yes", reset_context): with captured() as c: conda_exception_handler(_raise_helper, exc) json_obj = json.loads(c.stdout) assert not c.stderr assert json_obj['exception_type'] == "<class 'conda.exceptions.CondaKeyError'>" assert json_obj['exception_name'] == 'CondaKeyError' assert json_obj['message'] == text_type(exc) assert json_obj['error'] == repr(exc) assert json_obj['key'] == "Potato" with env_var("CONDA_JSON", "no", reset_context): with captured() as c: conda_exception_handler(_raise_helper, exc) assert not c.stdout assert c.stderr.strip() == "CondaKeyError: 'Potato': Potato is not a key."
def test_install_1(self): with env_vars({'CONDA_DRY_RUN': 'true', 'CONDA_VERBOSITY': '0'}, stack_callback=conda_tests_ctxt_mgmt_def_pol): with tempdir() as conda_temp_prefix: with captured() as c: install(conda_temp_prefix) assert "WARNING: Cannot install xonsh wrapper" in c.stderr if on_win: modified_files = ( 'conda.exe', 'conda-env.exe', 'conda-script.py', 'conda-env-script.py', 'conda.bat', # condabin/conda.bat 'conda.bat', # Library/bin/conda.bat '_conda_activate.bat', 'rename_tmp.bat', 'conda_auto_activate.bat', 'conda_hook.bat', 'activate.bat', 'activate.bat', 'deactivate.bat', 'activate', 'deactivate', 'conda.sh', 'conda.fish', 'Conda.psm1', 'conda-hook.ps1', 'conda.csh', ) else: modified_files = ( 'conda', # condabin/conda 'conda', # bin/conda 'conda-env', 'activate', 'deactivate', 'conda.sh', 'conda.fish', 'Conda.psm1', 'conda-hook.ps1', 'conda.csh', ) print(c.stdout) print(c.stderr, file=sys.stderr) assert c.stdout.count('modified') == len(modified_files) for fn in modified_files: line = next(line for line in c.stdout.splitlines() if line.strip().endswith(fn)) assert line.strip().startswith('modified'), line
def test_install_1(self): with env_vars({'CONDA_DRY_RUN': 'true', 'CONDA_VERBOSITY': '0'}, conda_tests_ctxt_mgmt_def_pol): with tempdir() as conda_temp_prefix: with captured() as c: install(conda_temp_prefix) assert "WARNING: Cannot install xonsh wrapper" in c.stderr if on_win: modified_files = ( 'conda.exe', 'conda-env.exe', 'conda-script.py', 'conda-env-script.py', 'conda.bat', # condabin/conda.bat 'conda.bat', # Library/bin/conda.bat '_conda_activate.bat', 'rename_tmp.bat', 'conda_auto_activate.bat', 'conda_hook.bat', 'activate.bat', 'activate.bat', 'deactivate.bat', 'activate', 'deactivate', 'conda.sh', 'conda.fish', 'Conda.psm1', 'conda-hook.ps1', 'conda.csh', ) else: modified_files = ( 'conda', # condabin/conda 'conda', # bin/conda 'conda-env', 'activate', 'deactivate', 'conda.sh', 'conda.fish', 'Conda.psm1', 'conda-hook.ps1', 'conda.csh', ) print(c.stdout) print(c.stderr, file=sys.stderr) assert c.stdout.count('modified') == len(modified_files) for fn in modified_files: line = next(line for line in c.stdout.splitlines() if line.strip().endswith(fn)) assert line.strip().startswith('modified'), line
def test_print_unexpected_error_message_upload_username_with_unicode( self, pwuid, post_mock): with env_var('CONDA_REPORT_ERRORS', 'true', stack_callback=conda_tests_ctxt_mgmt_def_pol): with captured() as c: ExceptionHandler()(_raise_helper, AssertionError()) error_data = json.loads(post_mock.call_args[1].get("data")) assert error_data.get("has_spaces") == False assert error_data.get("is_ascii") == False assert post_mock.call_count == 2 assert c.stdout == '' assert "conda version" in c.stderr
def test_SharedLinkPathClobberError(self): target_path = "some/where/in/shampoo/banana" incompatible_package_dists = "Groot" exc = SharedLinkPathClobberError(target_path, incompatible_package_dists, context) with env_var("CONDA_PATH_CONFLICT", "prevent", reset_context): with captured() as c: conda_exception_handler(_raise_helper, exc) assert not c.stdout assert c.stderr.strip() == dals(""" ClobberError: This transaction has incompatible packages due to a shared path. packages: G, r, o, o, t path: 'some/where/in/shampoo/banana' """).strip()
def test_CommandNotFoundError_simple(self): cmd = "instate" exc = CommandNotFoundError(cmd) with env_var("CONDA_JSON", "yes", conda_tests_ctxt_mgmt_def_pol): with captured() as c: conda_exception_handler(_raise_helper, exc) json_obj = json.loads(c.stdout) assert not c.stderr assert json_obj[ 'exception_type'] == "<class 'conda.exceptions.CommandNotFoundError'>" assert json_obj['message'] == text_type(exc) assert json_obj['error'] == repr(exc) with env_var("CONDA_JSON", "no", conda_tests_ctxt_mgmt_def_pol): with captured() as c: conda_exception_handler(_raise_helper, exc) assert not c.stdout assert c.stderr.strip() == ( "CommandNotFoundError: No command 'conda instate'.\n" "Did you mean 'conda install'?")
def get_info(): from conda.cli import conda_argparse from conda.cli.main_info import configure_parser from shlex import split from conda.common.io import captured p = conda_argparse.ArgumentParser() sub_parsers = p.add_subparsers(metavar='command', dest='cmd') configure_parser(sub_parsers) args = p.parse_args(split("info")) with captured() as c: args.func(args, p) return c.stdout, c.stderr
def test_BasicClobberError(self): source_path = "some/path/on/goodwin.ave" target_path = "some/path/to/wright.st" exc = BasicClobberError(source_path, target_path, context) with env_var("CONDA_PATH_CONFLICT", "prevent", reset_context): with captured() as c, replace_log_streams(): conda_exception_handler(_raise_helper, exc) assert not c.stdout assert c.stderr.strip() == dals(""" ClobberError: Conda was asked to clobber an existing path. source path: some/path/on/goodwin.ave target path: some/path/to/wright.st """).strip()
def test_print_unexpected_error_message_opt_out_2(self, isatty_mock, input_mock, post_mock): try: assert 0 except AssertionError: pass e = AssertionError() with captured() as c: print_unexpected_error_message(e) assert input_mock.call_count == 1 assert post_mock.call_count == 0 assert c.stdout == '' assert "conda version" in c.stderr
def test_TooFewArgumentsError(self): expected = 5 received = 2 exc = TooFewArgumentsError(expected, received) with env_var("CONDA_JSON", "yes", reset_context): with captured() as c: conda_exception_handler(_raise_helper, exc) json_obj = json.loads(c.stdout) assert not c.stderr assert json_obj['exception_type'] == "<class 'conda.exceptions.TooFewArgumentsError'>" assert json_obj['exception_name'] == 'TooFewArgumentsError' assert json_obj['message'] == text_type(exc) assert json_obj['error'] == repr(exc) assert json_obj['expected'] == 5 assert json_obj['received'] == 2 with env_var("CONDA_JSON", "no", reset_context): with captured() as c: conda_exception_handler(_raise_helper, exc) assert not c.stdout assert c.stderr.strip() == "TooFewArgumentsError: Got 2 arguments but expected 5."
def test_SharedLinkPathClobberError(self): target_path = "some/where/in/shampoo/banana" incompatible_package_dists = "Groot" exc = SharedLinkPathClobberError(target_path, incompatible_package_dists, context) with env_var("CONDA_PATH_CONFLICT", "prevent", stack_callback=conda_tests_ctxt_mgmt_def_pol): with captured() as c: conda_exception_handler(_raise_helper, exc) assert not c.stdout assert c.stderr.strip() == dals(""" ClobberError: This transaction has incompatible packages due to a shared path. packages: G, r, o, o, t path: 'some/where/in/shampoo/banana' """).strip()
def test_search_0(self): with captured(): res = capture_json_with_argv("conda search --json") self.assertIsInstance(res, dict) self.assertIsInstance(res["conda"], list) self.assertIsInstance(res["conda"][0], dict) keys = ("build", "channel", "fn", "version") for key in keys: self.assertIn(key, res["conda"][0]) stdout, stderr, rc = run_inprocess_conda_command( "conda search * --json") assert stderr == "" assert rc is None
def test_print_unexpected_error_message_upload_2(self, post_mock): try: assert 0 except AssertionError: pass with env_var('CONDA_JSON', 'true', reset_context): with env_var('CONDA_YES', 'yes', reset_context): e = AssertionError() with captured() as c: print_unexpected_error_message(e) assert post_mock.call_count == 3 assert len(json.loads(c.stdout)['conda_info']['channels']) >= 2 assert not c.stderr
def test_TooFewArgumentsError(self): expected = 5 received = 2 exc = TooFewArgumentsError(expected, received) with env_var("CONDA_JSON", "yes", stack_callback=conda_tests_ctxt_mgmt_def_pol): with captured() as c: conda_exception_handler(_raise_helper, exc) json_obj = json.loads(c.stdout) assert not c.stderr assert json_obj['exception_type'] == "<class 'conda.exceptions.TooFewArgumentsError'>" assert json_obj['exception_name'] == 'TooFewArgumentsError' assert json_obj['message'] == text_type(exc) assert json_obj['error'] == repr(exc) assert json_obj['expected'] == 5 assert json_obj['received'] == 2 with env_var("CONDA_JSON", "no", stack_callback=conda_tests_ctxt_mgmt_def_pol): with captured() as c: conda_exception_handler(_raise_helper, exc) assert not c.stdout assert c.stderr.strip() == "TooFewArgumentsError: Got 2 arguments but expected 5."
def test_print_unexpected_error_message_opt_out_1(self, input_mock, post_mock): try: assert 0 except AssertionError: pass with env_var('CONDA_REPORT_ERRORS', 'false', reset_context): e = AssertionError() with captured() as c: print_unexpected_error_message(e) assert input_mock.call_count == 0 assert post_mock.call_count == 0 assert c.stdout == '' assert "conda version" in c.stderr
def test_confirm_yn_yes(monkeypatch): monkeypatch.setattr('sys.stdin', StringIO('blah\ny\n')) with env_var('CONDA_ALWAYS_YES', 'false', stack_callback=conda_tests_ctxt_mgmt_def_pol): with env_var('CONDA_DRY_RUN', 'false', stack_callback=conda_tests_ctxt_mgmt_def_pol): assert not context.always_yes args = AttrDict({ 'dry_run': False, }) with captured() as cap: choice = confirm_yn(args) assert choice is True assert "Invalid choice" in cap.stdout
def test_UnknownPackageClobberError(self): target_path = "siebel/center/for/c.s" colliding_dist_being_linked = "Groot" exc = UnknownPackageClobberError(target_path, colliding_dist_being_linked, context) with env_var("CONDA_PATH_CONFLICT", "prevent", reset_context): with captured() as c: conda_exception_handler(_raise_helper, exc) assert not c.stdout assert c.stderr.strip() == dals(""" ClobberError: The package 'Groot' cannot be installed due to a path collision for 'siebel/center/for/c.s'. This path already exists in the target prefix, and it won't be removed by an uninstall action in this transaction. The path is one that conda doesn't recognize. It may have been created by another package manager. """).strip()
def test_KnownPackageClobberError(self): target_path = "some/where/on/goodwin.ave" colliding_dist_being_linked = "Groot" colliding_linked_dist = "Liquid" exc = KnownPackageClobberError(target_path, colliding_dist_being_linked, colliding_linked_dist, context) with env_var("CONDA_PATH_CONFLICT", "prevent", reset_context): with captured() as c: conda_exception_handler(_raise_helper, exc) assert not c.stdout assert c.stderr.strip() == dals(""" ClobberError: The package 'Groot' cannot be installed due to a path collision for 'some/where/on/goodwin.ave'. This path already exists in the target prefix, and it won't be removed by an uninstall action in this transaction. The path appears to be coming from the package 'Liquid', which is already installed in the prefix. """).strip()
def test_BasicClobberError(self): source_path = "some/path/on/goodwin.ave" target_path = "some/path/to/wright.st" exc = BasicClobberError(source_path, target_path, context) t = repr(exc) with env_var("CONDA_PATH_CONFLICT", "prevent", stack_callback=conda_tests_ctxt_mgmt_def_pol): with captured() as c: conda_exception_handler(_raise_helper, exc) assert not c.stdout assert c.stderr.strip() == dals(""" ClobberError: Conda was asked to clobber an existing path. source path: some/path/on/goodwin.ave target path: some/path/to/wright.st """).strip()
def test_search_0(self): with captured(): res = capture_json_with_argv('conda search --json') self.assertIsInstance(res, dict) self.assertIsInstance(res['conda'], list) self.assertIsInstance(res['conda'][0], dict) keys = ('build', 'channel', 'extracted', 'features', 'fn', 'installed', 'version') for key in keys: self.assertIn(key, res['conda'][0]) stdout, stderr, rc = run_inprocess_conda_command('conda search * --json') assert json.loads(stdout.strip())['exception_name'] == 'CommandArgumentError' assert stderr == '' assert rc > 0 res = capture_json_with_argv('conda search --canonical --json') self.assertIsInstance(res, list) self.assertIsInstance(res[0], text_type)