def test_configuration():
    print('Conda configuration')
    print('-------------------')
    spec_manager = CondaKernelSpecManager()
    conda_info = spec_manager._conda_info
    if conda_info is None:
        print('ERROR: Could not find conda find conda.')
        exit(-1)
    print(u'Current prefix: {}'.format(prefix))
    print(u'Root prefix: {}'.format(conda_info['root_prefix']))
    print(u'Conda version: {}'.format(conda_info['conda_version']))
    print(u'Environments:')
    for env in conda_info['envs']:
        print(u'  - {}'.format(env))
    checks = {}
    print('Kernels included in get_all_specs')
    print('---------------------------------')
    for key, value in spec_manager.get_all_specs().items():
        if value['spec']['argv'][:3] == RUNNER_COMMAND:
            long_env = value['spec']['argv'][4]
        else:
            long_env = prefix
        print(u'  - {}: {}'.format(key, long_env))
        if key.startswith('conda-'):
            if long_env == prefix:
                checks['env_current'] = True
            if key.startswith('conda-root-'):
                checks['root_py'] = True
            if key.startswith('conda-env-'):
                if key.endswith('-py'):
                    checks['env_py'] = True
                if key.endswith('-r'):
                    checks['env_r'] = True
            if ' ' in long_env:
                checks['env_space'] = True
            try:
                long_env.encode('ascii')
            except UnicodeEncodeError:
                checks['env_unicode'] = True
        elif key.lower().startswith('python'):
            checks['default_py'] = True
    print('Scenarios required for proper testing')
    print('-------------------------------------')
    print('  - Python kernel in test environment: {}'.format(
        bool(checks.get('default_py'))))
    print('  - ... included in the conda kernel list: {}'.format(
        bool(checks.get('env_current'))))
    print('  - Python kernel in root environment: {}'.format(
        bool(checks.get('root_py'))))
    print('  - Python kernel in other environment: {}'.format(
        bool(checks.get('env_py'))))
    print('  - R kernel in non-test environment: {}'.format(
        bool(checks.get('env_r'))))
    print('  - Environment with non-ASCII name: {}'.format(
        bool(checks.get('env_unicode'))))
    print('  - Environment with space in name: {}'.format(
        bool(checks.get('env_space'))))
    # In some conda build scenarios, the test environment is not returned by conda
    # in the listing of conda environments.
    assert len(checks) >= 7 - ('conda-bld' in prefix)
Example #2
0
def test_kernel_name_format(monkeypatch, tmp_path, name_format, expected):
    kernelspec = {
        "display_name": "Python 3 (XPython)",
        "argv":
        ["@XPYTHON_KERNELSPEC_PATH@xpython", "-f", "{connection_file}"],
        "language": "python",
        "metadata": {
            "debugger": True
        }
    }
    mock_info = {'conda_prefix': '/'}
    env_name = "dummy_env"

    def envs(*args):
        return {env_name: str(tmp_path)}

    kernel_file = tmp_path / 'share' / 'jupyter' / 'kernels' / 'xpython' / 'kernel.json'
    kernel_file.parent.mkdir(parents=True, exist_ok=True)
    if sys.version_info >= (3, 0):
        kernel_file.write_text(json.dumps(kernelspec))
    else:
        kernel_file.write_bytes(json.dumps(kernelspec))

    monkeypatch.setattr(CondaKernelSpecManager, "_conda_info", mock_info)
    monkeypatch.setattr(CondaKernelSpecManager, "_all_envs", envs)

    manager = CondaKernelSpecManager(name_format=name_format)
    specs = manager._all_specs()

    assert len(specs) == 1
    for spec in specs.values():
        assert spec["display_name"] == expected.format(env_name=env_name)
Example #3
0
def test_kernel_metadata(monkeypatch, tmp_path, kernelspec):

    mock_info = {'conda_prefix': '/'}

    def envs(*args):
        return {'env_name': str(tmp_path)}

    kernel_file = tmp_path / 'share' / 'jupyter' / 'kernels' / 'my_kernel' / 'kernel.json'
    kernel_file.parent.mkdir(parents=True, exist_ok=True)
    if sys.version_info >= (3, 0):
        kernel_file.write_text(json.dumps(kernelspec))
    else:
        kernel_file.write_bytes(json.dumps(kernelspec))

    monkeypatch.setattr(CondaKernelSpecManager, "_conda_info", mock_info)
    monkeypatch.setattr(CondaKernelSpecManager, "_all_envs", envs)

    manager = CondaKernelSpecManager()
    specs = manager._all_specs()

    assert len(specs) == 1
    for spec in specs.values():
        metadata = spec['metadata']
        for key, value in kernelspec['metadata'].items():
            assert key in metadata
            assert metadata[key] == value
Example #4
0
def test_configuration():
    print('\nConda configuration')
    print('-------------------')
    spec_manager = CondaKernelSpecManager()
    conda_info = spec_manager._conda_info
    if conda_info is None:
        print('ERROR: Could not find conda find conda.')
        exit(-1)
    print(u'Current prefix: {}'.format(prefix))
    print(u'Root prefix: {}'.format(conda_info['root_prefix']))
    print(u'Conda version: {}'.format(conda_info['conda_version']))
    print(u'Environments:')
    for env in conda_info['envs']:
        print(u'  - {}'.format(env))
    checks = {}
    print('Kernels included in get_all_specs')
    print('---------------------------------')
    for key, value in spec_manager.get_all_specs().items():
        if value['spec']['argv'][:3] == RUNNER_COMMAND:
            long_env = value['spec']['argv'][4]
            assert long_env == value['spec']['metadata']['conda_env_path']
        else:
            long_env = prefix
        print(u'  - {}: {}'.format(key, long_env))
        if key.startswith('conda-'):
            if long_env == prefix:
                checks['env_current'] = True
            if key.startswith('conda-root-'):
                checks['root_py'] = True
            if key.startswith('conda-env-'):
                if len(key.split('-')) >= 5:
                    checks['env_project'] = True
                if key.endswith('-py'):
                    checks['env_py'] = True
                if key.endswith('-r'):
                    checks['env_r'] = True
            try:
                long_env.encode('ascii')
            except UnicodeEncodeError:
                checks['env_unicode'] = True
        elif key.lower().startswith('python'):
            checks['default_py'] = True
    print('Scenarios required for proper testing')
    print('-------------------------------------')
    print('  - Python kernel in test environment: {}'.format(bool(checks.get('default_py'))))
    print('  - ... included in the conda kernel list: {}'.format(bool(checks.get('env_current'))))
    print('  - Python kernel in root environment: {}'.format(bool(checks.get('root_py'))))
    print('  - Python kernel in other environment: {}'.format(bool(checks.get('env_py'))))
    print('  - R kernel in non-test environment: {}'.format(bool(checks.get('env_r'))))
    print('  - Environment with non-ASCII name: {}'.format(bool(checks.get('env_unicode'))))
    print('  - External project environment: {}'.format(bool(checks.get('env_project'))))
    # In some conda build scenarios, the test environment is not returned by conda
    # in the listing of conda environments.
    if 'conda-bld' in prefix:
        checks.setdefault('env_current', False)
    # It is difficult to get AppVeyor to handle Unicode environments well, but manual testing
    # on Windows works fine. So it is likely related to the way AppVeyor captures output
    if sys.platform.startswith('win'):
        checks.setdefault('env_unicode', False)
    assert len(checks) >= 7
Example #5
0
def jupyter_manager(tmp_path):
    jupyter_data_dir = tmp_path / "share" / "jupyter"
    jupyter_data_dir.mkdir(parents=True, exist_ok=True)
    manager = CondaKernelSpecManager(kernelspec_path=str(tmp_path))
    # Install the kernel specs
    manager.find_kernel_specs()

    return KernelSpecManager(kernel_dirs=[str(jupyter_data_dir / "kernels")])
Example #6
0
def test_kernelspec_path(tmp_path, kernelspec_path, user, prefix, expected):
    config = Config({"CondaKernelSpecManager": {"kernelspec_path": kernelspec_path}})
    with patch("nb_conda_kernels.manager.CondaKernelSpecManager.install_kernel_spec") as install:
        install.return_value = str(tmp_path)        
        if isinstance(expected, type) and issubclass(expected, Exception):
            with pytest.raises(expected):
                CondaKernelSpecManager(config=config)
        else:
            spec_manager = CondaKernelSpecManager(config=config)
            assert spec_manager.kernelspec_path == expected
            assert spec_manager.conda_only == (spec_manager.kernelspec_path is not None)
            for call_ in install.call_args_list:
                assert call_[1]["user"] == user
                assert call_[1]["prefix"] ==prefix
Example #7
0
def test_install_kernelspec(tmp_path, kernelspec_path):
    config = Config({"CondaKernelSpecManager": {"kernelspec_path": kernelspec_path}})
    with patch("nb_conda_kernels.manager.CondaKernelSpecManager.install_kernel_spec") as install:
        install.return_value = str(tmp_path)
        CondaKernelSpecManager(config=config)
        
        assert install.called == (kernelspec_path is not None)
def test_configuration():
    print('Conda configuration')
    print('-------------------')
    spec_manager = CondaKernelSpecManager()
    conda_info = spec_manager._conda_info
    if conda_info is None:
        print('ERROR: Could not find conda find conda.')
        exit(-1)
    print('Current prefix: {}'.format(prefix))
    print('Root prefix: {}'.format(conda_info['root_prefix']))
    print('Conda version: {}'.format(conda_info['conda_version']))
    print('Environments:')
    for env in conda_info['envs']:
        print('  - {}'.format(env))
    checks = {}
    print('Kernels included in get_all_specs')
    print('---------------------------------')
    for key, value in spec_manager.get_all_specs().items():
        long_env = value['spec']['argv'][4] if key.startswith(
            'conda-') else prefix
        print('  - {}: {}'.format(key, long_env))
        key = key.lower()
        if key.startswith('python'):
            checks['default_py'] = True
        if key.startswith('ir'):
            checks['default_r'] = True
        if key.startswith('conda-root-py'):
            checks['root_py'] = True
        if key.startswith('conda-env-'):
            if key.endswith('-py'):
                checks['env_py'] = True
            if key.endswith('-r'):
                checks['env_r'] = True
    if len(checks) < 5:
        print('The environment is not properly configured for testing:')
        if not checks.get('default_py'):
            print('  - Default Python kernel missing')
        if not checks.get('default_r'):
            print('  - Default R kernel missing')
        if not checks.get('root_py'):
            print('  - Root Python kernel missing')
        if not checks.get('env_py'):
            print('  - Environment Python kernel missing')
        if not checks.get('env_r'):
            print('  - Environment R kernel missing')
        assert False
Example #9
0
def test_remove_kernelspec(tmp_path, kernel_name, expected):
    config = Config({"CondaKernelSpecManager": {"kernelspec_path": ""}})
    kernel_spec = tmp_path / kernel_name / "kernel.json"
    kernel_spec.parent.mkdir()
    kernel_spec.write_bytes(b"{}")
    with patch("nb_conda_kernels.manager.CondaKernelSpecManager.install_kernel_spec") as install:
        install.return_value = str(tmp_path)
        with patch("nb_conda_kernels.manager.CondaKernelSpecManager._get_destination_dir") as destination:
            destination.return_value = str(tmp_path)
            with patch("shutil.rmtree") as remove:
                CondaKernelSpecManager(config=config)
                
                assert remove.called == expected
Example #10
0
def test_runner():
    if os.environ.get('CONDA_BUILD'):
        # The current version of conda build manually adds the activation
        # directories to the PATH---and then calls the standard conda
        # activation script, which does it again. This frustrates conda's
        # ability to deactivate this environment. Most package builds are
        # not affected by this, but we are, because our tests need to do
        # environment activation and deactivation. To fix this, we remove
        # the duplicate PATH entries conda-build added.
        print('BEFORE: {}'.format(os.environ['PATH']))
        path_list = os.environ['PATH'].split(os.pathsep)
        path_dups = set()
        path_list = [
            p for p in path_list if not p.startswith(sys.prefix)
            or p not in path_dups and not path_dups.add(p)
        ]
        os.environ['PATH'] = os.pathsep.join(path_list)
        print('AFTER: {}'.format(os.environ['PATH']))
    spec_manager = CondaKernelSpecManager()
    for key, value in spec_manager._all_specs().items():
        if key.endswith('-py') or key.endswith('-r'):
            yield check_exec_in_env, key, value['argv']