def test_repository_factory(self): self.maxDiff = None # Given store_url = "https://acme.com" config = Configuration(store_url=store_url, use_webservice=False) config.set_repositories_from_names(["enthought/foo"]) responses.add(responses.GET, config.indices[0][0], status=404) session = mocked_session_factory(self.tempdir) r_warning = textwrap.dedent("""\ Warning: Could not fetch the following indices: - 'neko' Those repositories do not exist (or you do not have the rights to access them). You should edit your configuration to remove those repositories. """) # When with mock_print() as m: with mock.patch("enstaller.cli.utils._display_store_name", return_value="neko"): repository = repository_factory(session, config.indices) # Then self.assertEqual(len(list(repository.iter_packages())), 0) self.assertMultiLineEqual(m.value, r_warning) # When/Then with self.assertRaises(requests.exceptions.HTTPError): repository_factory(session, config.indices, raise_on_error=True)
def test_from_configuration(self): # Given config = Configuration() # When/Then with Session.from_configuration(config) as session: self.assertTrue(session._raw.verify) self.assertIsInstance(session._authenticator, LegacyCanopyAuthManager) # When/Then config = Configuration() config.update(verify_ssl=False) with Session.from_configuration(config) as session: self.assertFalse(session._raw.verify) # Given config = Configuration() config.update(verify_ssl=False, use_webservice=False) # When/Then with Session.from_configuration(config) as session: self.assertFalse(session._raw.verify) self.assertIsInstance(session._authenticator, OldRepoAuthManager) # Given config = Configuration() config.update(store_url="brood+http://acme.com") # When/Then with Session.from_configuration(config) as session: self.assertIsInstance(session._authenticator, BroodAuthenticator)
def test_recursive_install_unavailable_dependency(self): config = Configuration() session = Session(DummyAuthenticator(), self.prefix) auth = ("nono", "le gros robot") session.authenticate(auth) config.update(auth=auth) r_output = textwrap.dedent(""" Cannot install 'scipy', as this package (or some of its requirements) are not available at your subscription level 'Canopy / EPD Free' (You are logged in as 'nono'). """) self.maxDiff = None numpy = dummy_repository_package_factory("numpy", "1.7.1", 1) numpy.available = False scipy = dummy_repository_package_factory("scipy", "0.12.0", 1) scipy.packages = ["numpy 1.7.1"] remote_entries = [numpy, scipy] with mock.patch("enstaller.main.Enpkg.execute"): enpkg = create_prefix_with_eggs(config, self.prefix, [], remote_entries) with mock_print() as m: with self.assertRaises(SystemExit): install_req(enpkg, config, "scipy", FakeOptions()) self.assertMultiLineEqual(m.value, r_output)
def test_install_pypi_before_non_pypi(self): # Given config = Configuration() config.update(auth=("nono", "le petit robot")) session = Session.from_configuration(config) session.authenticate(config.auth) repository = repository_factory(session, config.indices) enpkg = Enpkg(repository, session, [self.prefix]) enpkg.execute = mock.Mock() # When with mock_print() as mocked_print: with mock_raw_input("yes"): install_req(enpkg, config, "swig 2.0.2", FakeOptions()) # Then self._assert_ask_for_pypi(mocked_print) # When with mock_print() as mocked_print: with mock_raw_input("yes"): install_req(enpkg, config, "swig 2.0.2-1", FakeOptions()) # Then self._assert_ask_for_pypi(mocked_print)
def test_set_repository_cache(self): homedir = os.path.normpath(os.path.expanduser("~")) config = Configuration() config.update(repository_cache="~/.env/LOCAL-REPO") self.assertEqual(config.repository_cache, os.path.join(homedir, ".env", "LOCAL-REPO"))
def test_recursive_install_unavailable_dependency(self): config = Configuration() config.set_auth("None", "None") r_output = textwrap.dedent("""\ Error: could not resolve "numpy 1.7.1" required by "scipy-0.12.0-1.egg" You may be able to force an install of just this egg by using the --no-deps enpkg commandline argument after installing another version of the dependency. Available versions of the required package 'numpy' are: 1.7.1 (no subscription) No package found to fulfill your requirement at your subscription level: You are logged in as None. Subscription level: EPD """) self.maxDiff = None numpy = dummy_enpkg_entry_factory("numpy", "1.7.1", 1) numpy.available = False scipy = dummy_enpkg_entry_factory("scipy", "0.12.0", 1) scipy.packages = [Dependency.from_spec_string("numpy 1.7.1")] remote_entries = [numpy, scipy] with mock.patch("enstaller.main.Enpkg.execute"): enpkg = _create_prefix_with_eggs(config, self.prefix, [], remote_entries) with mock_print() as m: with self.assertRaises(SystemExit): install_req(enpkg, "scipy", FakeOptions()) self.assertMultiLineEqual(m.value, r_output)
def test_not_available(self): config = Configuration() config.use_webservice = False r_output = textwrap.dedent("""\ Name Versions Product Note ================================================================================ another_package 2.0.0-1 commercial not subscribed to dummy 0.9.8-1 commercial {0} 1.0.1-1 commercial {0} """.format("")) another_entry = dummy_enpkg_entry_factory("another_package", "2.0.0", 1) another_entry.available = False entries = [dummy_enpkg_entry_factory("dummy", "1.0.1", 1), dummy_enpkg_entry_factory("dummy", "0.9.8", 1), another_entry] with mock.patch("enstaller.main.subscription_message") as mocked_subscription_message: mocked_subscription_message.return_value = "" with mkdtemp() as d: with mock_print() as m: enpkg = _create_prefix_with_eggs(config, d, remote_entries=entries) search(enpkg) self.assertMultiLineEqual(m.value, r_output) self.assertTrue(mocked_subscription_message.called)
def test_set_prefix(self): homedir = os.path.normpath(os.path.expanduser("~")) config = Configuration() config.update(prefix=os.path.normpath("~/.env")) self.assertEqual(config.prefix, os.path.join(homedir, ".env"))
def test_use_webservice_valid_user(self): config = Configuration() config.set_auth(FAKE_USER, FAKE_PASSWORD) with mock.patch("enstaller.config.web_auth") as mocked_auth: authenticate(config) self.assertTrue(mocked_auth.called)
def test_parse_simple_unsupported_entry(self): # XXX: ideally, we would like something like with self.assertWarns to # check for the warning, but backporting the python 3.3 code to # unittest2 is a bit painful. with mock.patch("enstaller.config.warnings.warn") as m: Configuration.from_file(StringIO("nono = 'le petit robot'")) m.assert_called_with('Unsupported configuration setting nono, ignored')
def test_api_token_authentication(self): # Given yaml_string = textwrap.dedent("""\ authentication: kind: token api_token: ulysse """) # When config = Configuration.from_yaml_filename(StringIO(yaml_string)) # Then self.assertFalse(config.use_webservice) self.assertEqual(config.auth, APITokenAuth("ulysse")) # Given yaml_string = textwrap.dedent("""\ authentication: api_token: ulysse """) # When config = Configuration.from_yaml_filename(StringIO(yaml_string)) # Then self.assertFalse(config.use_webservice) self.assertEqual(config.auth, APITokenAuth("ulysse"))
def test_simple_no_webservice(self): output_template = textwrap.dedent("""\ Python version: {pyver} enstaller version: {version} sys.prefix: {sys_prefix} platform: {platform} architecture: {arch} use_webservice: False keyring backend: {keyring_backend} settings: prefix = {{prefix}} repository_cache = {{repository_cache}} noapp = False proxy = None IndexedRepos: 'http://acme.com/' No valid auth information in configuration, cannot authenticate. You are not logged in. To log in, type 'enpkg --userpass'. """).format(pyver=PY_VER, sys_prefix=sys.prefix, version=__version__, platform=platform.platform(), arch=platform.architecture()[0], keyring_backend=_keyring_backend_name()) prefix = sys.prefix repository_cache = os.path.join(prefix, "LOCAL-REPO") r_output = output_template.format(prefix=os.path.normpath(prefix), repository_cache=repository_cache) config = Configuration() config.update(indexed_repositories=["http://acme.com"], use_webservice=False) with mock_print() as m: print_config(config, config.prefix, Session(DummyAuthenticator(), self.prefix)) self.assertMultiLineEqual(m.value, r_output)
def test_max_retries_setup(self): # When config = Configuration() # Then self.assertEqual(config.max_retries, 0) # Given data = StringIO("max_retries = 1") # When config = Configuration.from_file(data) # Then self.assertEqual(config.max_retries, 1) # Given data = StringIO("max_retries = 0") # When config = Configuration.from_file(data) # Then self.assertEqual(config.max_retries, 0) # Given data = StringIO("max_retries = 'a'") # When/Then with self.assertRaises(InvalidConfiguration): Configuration.from_file(data)
def test_files_cache(self): # Given yaml_string = textwrap.dedent("""\ files_cache: "/foo/bar" """) # When config = Configuration.from_yaml_filename(StringIO(yaml_string)) # Then self.assertFalse(config.use_webservice) self.assertEqual(config.repository_cache, "/foo/bar") # Given yaml_string = textwrap.dedent("""\ files_cache: "~/foo/bar/{PLATFORM}" """) # When config = Configuration.from_yaml_filename(StringIO(yaml_string)) # Then self.assertFalse(config.use_webservice) self.assertEqual( config.repository_cache, os.path.expanduser("~/foo/bar/{0}".format(custom_plat)))
def test_ensure_authenticated_config(self): # Given r_message = textwrap.dedent("""\ Could not authenticate as 'nono' Please check your credentials/configuration and try again (original error is: 'Authentication error: Invalid user login.'). You can change your authentication details with 'enpkg --userpass'. """) store_url = "https://acme.com" responses.add(responses.GET, store_url + "/accounts/user/info/", body=json.dumps(R_JSON_NOAUTH_RESP)) config = Configuration() config.update(store_url=store_url, auth=("nono", "le petit robot")) session = Session.from_configuration(config) # When/Then with mock_print() as m: with self.assertRaises(SystemExit) as e: ensure_authenticated_config(config, "", session) self.assertEqual(exception_code(e), -1) self.assertMultiLineEqual(m.value, r_message)
def test_installed(self): config = Configuration() config.update(use_webservice=False) with mkdtemp() as d: r_output = textwrap.dedent("""\ Name Versions Product Note ================================================================================ dummy 0.9.8-1 commercial {0} * 1.0.1-1 commercial {0} """.format("")) entries = [ dummy_repository_package_factory("dummy", "1.0.1", 1), dummy_repository_package_factory("dummy", "0.9.8", 1) ] installed_entries = [ dummy_installed_package_factory("dummy", "1.0.1", 1) ] enpkg = create_prefix_with_eggs(config, d, installed_entries, entries) with mock_print() as m: search(enpkg._remote_repository, enpkg._installed_repository, config, UserInfo(True)) self.assertMultiLineEqual(m.value, r_output)
def test_no_installed(self): config = Configuration() config.update(use_webservice=False) with mkdtemp() as d: # XXX: isn't there a better way to ensure ws at the end of a line # are not eaten away ? r_output = textwrap.dedent("""\ Name Versions Product Note ================================================================================ another_dummy 2.0.0-1 commercial {0} dummy 0.9.8-1 commercial {0} 1.0.0-1 commercial {0} """.format("")) entries = [ dummy_repository_package_factory("dummy", "1.0.0", 1), dummy_repository_package_factory("dummy", "0.9.8", 1), dummy_repository_package_factory("another_dummy", "2.0.0", 1) ] enpkg = create_prefix_with_eggs(config, d, remote_entries=entries) with mock_print() as m: search(enpkg._remote_repository, enpkg._top_installed_repository, config, UserInfo(True)) self.assertMultiLineEqual(m.value, r_output)
def test_indices_property_platform(self): # Given platform = "win-32" r_indices = tuple([ ("https://api.enthought.com/eggs/{0}/index.json?pypi=true". format(platform), "https://api.enthought.com/eggs/{0}/index.json".format(platform)), ]) # When config = Configuration() config._platform = platform # Then self.assertEqual(config.indices, r_indices) # Given platform = "osx-32" r_indices = tuple([ ("https://api.enthought.com/eggs/{0}/index.json?pypi=true". format(platform), "https://api.enthought.com/eggs/{0}/index.json".format(platform)), ]) # When config = Configuration() config._platform = "osx-32" # Then self.assertEqual(config.indices, r_indices)
def test_set_local(self): homedir = os.path.normpath(os.path.expanduser("~")) config = Configuration() config.local = os.path.normpath("~/.env/LOCAL-REPO") self.assertEqual(config.local, os.path.join(homedir, ".env", "LOCAL-REPO"))
def test_use_webservice_false_brood_repository(self): # Given use_webservice = False store_url = "https://acme.com" repositories = [ 'enthought/commercial', 'enthought/free', 'file:///foo/bar', ] python_tag = PythonImplementation.from_running_python().pep425_tag r_indices = ( ("{0}/api/v0/json/indices/enthought/commercial/{1}/{2}/eggs". format(store_url, custom_plat, python_tag)), ("{0}/api/v0/json/indices/enthought/free/{1}/{2}/eggs". format(store_url, custom_plat, python_tag)), "file:///foo/bar/index.json", ) # When config = Configuration(use_webservice=use_webservice, store_url=store_url) config.set_repositories_from_names(repositories) # Then self.assertEqual(len(config.repositories), 3) self.assertIsInstance(config.repositories[0], IBroodRepositoryInfo) self.assertIsInstance(config.repositories[1], IBroodRepositoryInfo) self.assertIsInstance(config.repositories[2], IBroodRepositoryInfo) self.assertEqual(r_indices, tuple(repository.index_url for repository in config.repositories))
def test_files_cache(self): # Given yaml_string = textwrap.dedent("""\ files_cache: "/foo/bar" """) # When config = Configuration.from_yaml_filename(StringIO(yaml_string)) # Then self.assertFalse(config.use_webservice) self.assertEqual(config.repository_cache, "/foo/bar") # Given yaml_string = textwrap.dedent("""\ files_cache: "~/foo/bar/{PLATFORM}" """) # When config = Configuration.from_yaml_filename(StringIO(yaml_string)) # Then self.assertFalse(config.use_webservice) self.assertEqual(config.repository_cache, os.path.expanduser("~/foo/bar/{0}".format(custom_plat)))
def test_insecure_flag(self): # Given responses.add(responses.GET, "https://acme.com/accounts/user/info/", body=json.dumps(R_JSON_AUTH_RESP)) config = Configuration() config.update(store_url="https://acme.com") config.update(auth=("nono", "le gros robot")) # When with self.assertRaises(SystemExit) as e: with mock.patch("enstaller.main._ensure_config_or_die", return_value=config): with mock.patch( "enstaller.main.ensure_authenticated_config" ): main_noexc(["-s", "fubar"]) # Then self.assertEqual(e.exception.code, 0) # When with self.assertRaises(SystemExit) as e: with mock.patch("enstaller.main._ensure_config_or_die", return_value=config): with mock.patch( "enstaller.main.ensure_authenticated_config" ): main_noexc(["-ks", "fubar"]) # Then self.assertEqual(e.exception.code, 0)
def test_api_token_authentication(self): # Given yaml_string = textwrap.dedent("""\ authentication: kind: token api_token: ulysse """) # When config = Configuration.from_yaml_filename(StringIO(yaml_string)) # Then self.assertFalse(config.use_webservice) self.assertEqual(config.auth, APITokenAuth("ulysse")) # Given yaml_string = textwrap.dedent("""\ authentication: api_token: ulysse """) # When config = Configuration.from_yaml_filename(StringIO(yaml_string)) # Then self.assertFalse(config.use_webservice) self.assertEqual(config.auth, APITokenAuth("ulysse"))
def test_install_pypi_before_non_pypi(self): # Given config = Configuration() config.update(auth=("nono", "le petit robot")) session = Session.from_configuration(config) session.authenticate(config.auth) repository = repository_factory(session, config.indices) enpkg = Enpkg(repository, session, [self.prefix]) enpkg.execute = mock.Mock() # When with mock_print() as mocked_print: with mock_raw_input("yes"): install_req(enpkg, config, "swig 2.0.2", FakeOptions()) # Then self._assert_ask_for_pypi(mocked_print) # When with mock_print() as mocked_print: with mock_raw_input("yes"): install_req(enpkg, config, "swig 2.0.2-1", FakeOptions()) # Then self._assert_ask_for_pypi(mocked_print)
def test_max_retries_setup(self): # When config = Configuration() # Then self.assertEqual(config.max_retries, 0) # Given data = StringIO("max_retries = 1") # When config = Configuration.from_file(data) # Then self.assertEqual(config.max_retries, 1) # Given data = StringIO("max_retries = 0") # When config = Configuration.from_file(data) # Then self.assertEqual(config.max_retries, 0) # Given data = StringIO("max_retries = 'a'") # When/Then with self.assertRaises(InvalidConfiguration): Configuration.from_file(data)
def test_use_webservice_false_brood_repository(self): # Given use_webservice = False store_url = "https://acme.com" repositories = [ 'enthought/commercial', 'enthought/free', 'file:///foo/bar', ] r_indices = ( "{0}/repo/enthought/commercial/{1}/index.json".format(store_url, custom_plat), "{0}/repo/enthought/free/{1}/index.json".format(store_url, custom_plat), "file:///foo/bar/index.json", ) # When config = Configuration(use_webservice=use_webservice, store_url=store_url) config.set_repositories_from_names(repositories) # Then self.assertEqual(len(config.repositories), 3) self.assertIsInstance(config.repositories[0], IBroodRepositoryInfo) self.assertIsInstance(config.repositories[1], IBroodRepositoryInfo) self.assertIsInstance(config.repositories[2], IBroodRepositoryInfo) self.assertEqual(r_indices, tuple(repository.index_url for repository in config.repositories))
def test_recursive_install_unavailable_dependency(self): config = Configuration() session = Session(DummyAuthenticator(), self.prefix) auth = ("nono", "le gros robot") session.authenticate(auth) config.update(auth=auth) r_output = textwrap.dedent(""" Cannot install 'scipy', as this package (or some of its requirements) are not available at your subscription level 'Canopy / EPD Free' (You are logged in as 'nono'). """) self.maxDiff = None numpy = dummy_repository_package_factory("numpy", "1.7.1", 1) numpy.available = False scipy = dummy_repository_package_factory("scipy", "0.12.0", 1) scipy.packages = ["numpy 1.7.1"] remote_entries = [numpy, scipy] with mock.patch("enstaller.main.Enpkg.execute"): enpkg = create_prefix_with_eggs(config, self.prefix, [], remote_entries) with mock_print() as m: with self.assertRaises(SystemExit): install_req(enpkg, config, "scipy", FakeOptions()) self.assertMultiLineEqual(m.value, r_output)
def test_not_available(self): responses.add(responses.GET, "https://acme.com/accounts/user/info/", body=json.dumps(R_JSON_AUTH_FREE_RESP)) config = Configuration() config.update(store_url="https://acme.com") r_output = textwrap.dedent("""\ Name Versions Product Note ================================================================================ another_package 2.0.0-1 commercial not subscribed to dummy 0.9.8-1 commercial {0} 1.0.1-1 commercial {0} Note: some of those packages are not available at your current subscription level ('Canopy / EPD Free'). """.format("")) another_entry = dummy_repository_package_factory("another_package", "2.0.0", 1) another_entry.available = False entries = [dummy_repository_package_factory("dummy", "1.0.1", 1), dummy_repository_package_factory("dummy", "0.9.8", 1), another_entry] with Session.from_configuration(config) as session: with mkdtemp() as d: with mock_print() as m: enpkg = create_prefix_with_eggs(config, d, remote_entries=entries) search(enpkg._remote_repository, enpkg._installed_repository, config, session) self.assertMultiLineEqual(m.value, r_output)
def test_ensure_authenticated_config(self): # Given r_message = textwrap.dedent("""\ Could not authenticate as 'nono' Please check your credentials/configuration and try again (original error is: 'Authentication error: Invalid user login.'). You can change your authentication details with 'enpkg --userpass'. """) store_url = "https://acme.com" responses.add(responses.GET, store_url + "/accounts/user/info/", body=json.dumps(R_JSON_NOAUTH_RESP)) config = Configuration() config.update(store_url=store_url, auth=("nono", "le petit robot")) session = Session.from_configuration(config) # When/Then with mock_print() as m: with self.assertRaises(SystemExit) as e: ensure_authenticated_config(config, "", session) self.assertEqual(exception_code(e), -1) self.assertMultiLineEqual(m.value, r_message)
def test_pattern(self): config = Configuration() config.update(use_webservice=False) with mkdtemp() as d: r_output = textwrap.dedent("""\ Name Versions Product Note ================================================================================ dummy 0.9.8-1 commercial {0} * 1.0.1-1 commercial {0} """.format("")) entries = [dummy_repository_package_factory("dummy", "1.0.1", 1), dummy_repository_package_factory("dummy", "0.9.8", 1), dummy_repository_package_factory("another_package", "2.0.0", 1)] installed_entries = [dummy_installed_package_factory("dummy", "1.0.1", 1)] enpkg = create_prefix_with_eggs(config, d, installed_entries, entries) with mock_print() as m: search(enpkg._remote_repository, enpkg._top_installed_repository, config, UserInfo(True), pat=re.compile("dummy")) self.assertMultiLineEqual(m.value, r_output) r_output = textwrap.dedent("""\ Name Versions Product Note ================================================================================ another_package 2.0.0-1 commercial {0} dummy 0.9.8-1 commercial {0} * 1.0.1-1 commercial {0} """.format("")) with mock_print() as m: search(enpkg._remote_repository, enpkg._top_installed_repository, config, UserInfo(True), pat=re.compile(".*")) self.assertMultiLineEqual(m.value, r_output)
def test__from_legacy_locations_non_existing_path(self): # When/Then with mock.patch( "enstaller.config.legacy_configuration_read_search_order", return_value=[self.prefix]): with self.assertRaises(InvalidConfiguration): Configuration._from_legacy_locations()
def test_reset_auth_with_keyring_failure(self): """Ensure reset_auth failed with keyring if no user is set up.""" with make_keyring_available_context(): config = Configuration() with self.assertRaises(ValueError): config.reset_auth()
def test_set_prefix(self): homedir = os.path.normpath(os.path.expanduser("~")) config = Configuration() config.update(prefix=os.path.normpath("~/.env")) self.assertEqual(config.prefix, os.path.join(homedir, ".env"))
def setUp(self): self.prefix = tempfile.mkdtemp() self.config = Configuration() self.config.update(use_webservice=False, indexed_repositories=["http://acme.com"]) self.session = Session(self.klass.from_configuration(self.config), self.prefix)
def test_with_keyring(self): with make_keyring_available_context() as mocked_keyring: config = Configuration() config.update(auth=(FAKE_USER, FAKE_PASSWORD)) self.assertEqual(config.auth, UserPasswordAuth(FAKE_USER, FAKE_PASSWORD)) self.assertFalse(mocked_keyring.set_password.called)
def test_use_remote(self): config = Configuration() config.use_webservice = False config.set_auth(FAKE_USER, FAKE_PASSWORD) remote = mock.Mock() user = authenticate(config, remote) self.assertEqual(user, {"is_authenticated": True})
def test_non_writable_repository_cache(self): fake_dir = "/some/dummy_dir/hopefully/doesnt/exists" config = Configuration() with mock.patch("os.makedirs", side_effect=OSError("mocked makedirs")): config.update(repository_cache=fake_dir) self.assertNotEqual(config.repository_cache, fake_dir)
def test_reset_auth_with_keyring(self): with make_keyring_available_context(): config = Configuration() config.update(auth=(FAKE_USER, FAKE_PASSWORD)) config.reset_auth() self.assertIsNone(config.auth)
def test_non_writable_repository_cache(self): fake_dir = "/some/dummy_dir/hopefully/doesnt/exists" config = Configuration() with mock.patch("os.makedirs", side_effect=OSError("mocked makedirs")): config.update(repository_cache=fake_dir) self.assertNotEqual(config.repository_cache, fake_dir)
def test_with_keyring(self): with make_keyring_available_context() as mocked_keyring: config = Configuration() config.update(auth=(FAKE_USER, FAKE_PASSWORD)) self.assertEqual(config.auth, UserPasswordAuth(FAKE_USER, FAKE_PASSWORD)) self.assertFalse(mocked_keyring.set_password.called)
def test_parse_simple_unsupported_entry(self): # XXX: ideally, we would like something like with self.assertWarns to # check for the warning, but backporting the python 3.3 code to # unittest2 is a bit painful. with mock.patch("enstaller.config.warnings.warn") as m: Configuration.from_file(StringIO("nono = 'le petit robot'")) m.assert_called_with( 'Unsupported configuration setting nono, ignored')
def test_simple_install(self): remote_entries = [dummy_repository_package_factory("nose", "1.3.0", 1)] with mock.patch("enstaller.main.Enpkg.execute") as m: enpkg = create_prefix_with_eggs(Configuration(), self.prefix, [], remote_entries) install_req(enpkg, Configuration(), "nose", FakeOptions()) m.assert_called_with([('fetch', 'nose-1.3.0-1.egg'), ('install', 'nose-1.3.0-1.egg')])
def test_with_keyring(self): with make_keyring_available_context() as mocked_keyring: config = Configuration() config.set_auth(FAKE_USER, FAKE_PASSWORD) self.assertEqual(config.get_auth(), (FAKE_USER, FAKE_PASSWORD)) mocked_keyring.set_password.assert_called_with("Enthought.com", FAKE_USER, FAKE_PASSWORD)
def test_deprecated_get_auth(self): with mkdtemp() as d: f = os.path.join(d, "enstaller4rc") config = Configuration() config.set_auth(FAKE_USER, FAKE_PASSWORD) config.write(f) with mock.patch("enstaller.config.get_path", lambda: f): self.assertEqual(get_auth(), (FAKE_USER, FAKE_PASSWORD))
def test_use_webservice_invalid_user(self): config = Configuration() config.set_auth(FAKE_USER, FAKE_PASSWORD) with mock.patch("enstaller.config.web_auth") as mocked_auth: mocked_auth.return_value = {"is_authenticated": False} with self.assertRaises(AuthFailedError): authenticate(config)
def test_reset_auth_without_keyring(self): config = Configuration() config.set_auth(FAKE_USER, FAKE_PASSWORD) config.reset_auth() self.assertIsNone(config._username) self.assertIsNone(config._password) self.assertFalse(config.is_auth_configured)
def test_simple_with_proxy(self): proxystr = "http://acme.com:3128" config = Configuration() config.proxy = proxystr config.write(self.f) config = Configuration.from_file(self.f) self.assertEqual(config.proxy, proxystr)
def test_proxy_setup(self): # Given proxy_string = "http://acme.com" # When config = Configuration() config.update(proxy=proxy_string) # Then self.assertEqual(str(config.proxy), "http://acme.com:3128")
def test_remote_success(self): write_default_config(self.f) config = Configuration() auth = ("usr", "password") session = Session(DummyAuthenticator(old_auth_user), self.d) with session: usr = config._checked_change_auth(auth, session, self.f) self.assertEqual(usr, UserInfo(True))
def test_invalid_format(self): # Given yaml_string = textwrap.dedent("""\ repositoriess: - enthought/commercial """) # When/Then with self.assertRaises(InvalidConfiguration): Configuration.from_yaml_filename(StringIO(yaml_string))
def test_indices_property_no_webservice(self): # Given r_indices = tuple( (("https://acme.com/{0}/index.json".format(custom_plat), "https://acme.com/{0}/index.json".format(custom_plat)), )) config = Configuration() config.update(use_webservice=False, indexed_repositories=["https://acme.com/{PLATFORM}/"]) # When/Then self.assertEqual(config.indices, r_indices)
def test_both_auth_set(self): # Given data = "EPD_auth = '{0}'\napi_token = 'token'" data = StringIO(data.format(FAKE_CREDS)) msg = "Both 'EPD_auth' and 'api_token' set in configuration." \ "\nYou should remove one of those for consistent " \ "behaviour." # When with self.assertWarnsRegex(Warning, msg): Configuration.from_file(data)
def test_change_existing_config_file_empty_username(self): with tempfile.NamedTemporaryFile(delete=False, mode="wt") as fp: fp.write("EPD_auth = '{0}'".format(FAKE_CREDS)) config = Configuration.from_file(fp.name) self.assertEqual(config.auth, FAKE_AUTH) config.reset_auth() config._change_auth(fp.name) new_config = Configuration.from_file(fp.name) self.assertIsNone(new_config.auth)
def authenticated_config(f): config = Configuration() config.update(auth=("dummy", "dummy")) m = mock.Mock() m.return_value = config m.from_file.return_value = config wrapper = mock.patch("enstaller.main.Configuration", m) mock_authenticated_config = mock.patch( "enstaller.main.ensure_authenticated_config", mock.Mock()) return mock_authenticated_config(wrapper(f))
def test_indices_property_no_pypi(self): # Given r_indices = tuple([ ("https://api.enthought.com/eggs/{0}/index.json?pypi=false".format( custom_plat), "https://api.enthought.com/eggs/{0}/index.json".format( custom_plat)), ]) config = Configuration() config.update(use_pypi=False) # When/Then self.assertEqual(config.indices, r_indices)
def test_invalid_syntax(self): # Given data = "store_url = http://acme.com" r_message = "Could not parse configuration file (invalid python " \ "syntax at line 1: expression 'store_url = " \ "http://acme.com')" # When with self.assertRaises(InvalidConfiguration) as e: Configuration.from_file(StringIO(data)) # Then self.assertMultiLineEqual(str(e.exception), r_message)
def test_max_retries(self): # Given config = Configuration() # When/Then with Session.from_configuration(config) as session: for prefix in ("http://", "https://"): self.assertEqual(session._raw.adapters[prefix].max_retries, 0) # When/Then config.update(max_retries=3) with Session.from_configuration(config) as session: for prefix in ("http://", "https://"): self.assertEqual(session._raw.adapters[prefix].max_retries, 3)
def test_change_existing_config_file(self): r_new_password = "******" with tempfile.NamedTemporaryFile(delete=False, mode="wt") as fp: fp.write("EPD_auth = '{0}'".format(FAKE_CREDS)) config = Configuration.from_file(fp.name) self.assertEqual(config.auth, FAKE_AUTH) config.update(auth=(FAKE_USER, r_new_password)) config._change_auth(fp.name) new_config = Configuration.from_file(fp.name) self.assertEqual(new_config.auth, UserPasswordAuth(FAKE_USER, r_new_password))
def test_unsupported_syntax(self): # Given data = textwrap.dedent("""\ store_url = 'http://acme' store_url += '.com' """) r_message = "Could not parse configuration file (error at line 2: " \ "expression \"store_url += '.com'\" not supported)" # When with self.assertRaises(InvalidConfiguration) as e: Configuration.from_file(StringIO(data)) # Then self.assertMultiLineEqual(str(e.exception), r_message)
class AuthManagerBase(unittest.TestCase): klass = None def setUp(self): self.prefix = tempfile.mkdtemp() self.config = Configuration() self.config.update(use_webservice=False, indexed_repositories=["http://acme.com"]) self.session = Session(self.klass.from_configuration(self.config), self.prefix) def tearDown(self): shutil.rmtree(self.prefix) self.session.close()