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_download(self): # Given url = "http://acme.com/foo.bin" responses.add(responses.GET, url, body=b"some data") config = Configuration() # When with Session.from_configuration(config) as session: target = session.download(url) # Then try: self.assertTrue(os.path.exists(target)) with open(target, "rb") as fp: self.assertEqual(fp.read(), b"some data") finally: os.unlink(target) self.assertEqual(target, "foo.bin") # When with Session.from_configuration(config) as session: target = session.download(url, "foo.baz") # Then try: self.assertTrue(os.path.exists(target)) with open(target, "rb") as fp: self.assertEqual(fp.read(), b"some data") finally: os.unlink(target) self.assertEqual(target, "foo.baz")
def test_simple_scenario(self): egg = DUMMY_EGG r_actions = {1: [], 0: [("remove", os.path.basename(egg))]} config = Configuration() repository = Repository() package = RepositoryPackageMetadata.from_egg(egg) package.python = PY_VER repository.add_package(package) with open(egg, "rb") as fp: responses.add(responses.GET, package.source_url, body=fp.read(), status=200, content_type='application/json') session = Session(DummyAuthenticator(), config.repository_cache) enpkg = Enpkg(repository, session, prefixes=self.prefixes) actions = [("fetch", os.path.basename(egg)), ("install", os.path.basename(egg))] enpkg.execute(actions) name, version = egg_name_to_name_version(egg) enpkg._installed_repository.find_package(name, version) for state in [0, 1]: actions = enpkg.revert_actions(state) self.assertEqual(actions, r_actions[state])
def test_bearer_token(self): # Given responses.add(responses.POST, self.token_url, status=200, body=json.dumps({"token": "dummy_token"})) r_auth = BroodBearerTokenAuth("dummy_token") # When self.session.authenticate((FAKE_USER, FAKE_PASSWORD)) # Then self.assertIsInstance(self.session._raw.auth, BroodBearerTokenAuth) self.assertEqual(self.session._raw.auth._token, r_auth._token) # Given headers = {} def callback(request): headers.update(request.headers) return (200, {}, b"") responses.add_callback(responses.GET, "https://acme.com/fubar", callback) # When self.session.fetch("https://acme.com/fubar") # Then self.assertEqual(headers["Authorization"], "Bearer dummy_token")
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.convert_auth_if_required"): 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.convert_auth_if_required"): main_noexc(["-ks", "fubar"]) # Then self.assertEqual(e.exception.code, 0)
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 _mock_index(self, entries): index = dict((entry.key, entry.s3index_data) for entry in entries) responses.add(responses.GET, "https://api.enthought.com/eggs/{0}/index.json".format(custom_plat), body=json.dumps(index), status=200, content_type='application/json')
def test_simple(self): # Given responses.add(responses.GET, self.config.api_url, status=200, body=json.dumps(R_JSON_AUTH_RESP)) # When # Then no exception self.session.authenticate((FAKE_USER, FAKE_PASSWORD))
def test_http_failure(self): # Given responses.add(responses.POST, self.token_url, body="", status=403, content_type='application/json') # When/Then with self.assertRaises(AuthFailedError): self.session.authenticate((FAKE_USER, FAKE_PASSWORD))
def test_unauthenticated_user(self): # Given responses.add(responses.GET, self.config.api_url, body=json.dumps(R_JSON_NOAUTH_RESP), content_type='application/json') # When/Then with self.assertRaises(AuthFailedError): self.session.authenticate((FAKE_USER, FAKE_PASSWORD))
def test_http_failure(self): # Given config = Configuration() responses.add(responses.GET, config.api_url, body="", status=404, content_type='application/json') # When/Then with self.assertRaises(AuthFailedError): self.session.authenticate((FAKE_USER, FAKE_PASSWORD))
def test_auth_failure_50x(self): # Given auth = ("nono", "le petit robot") responses.add(responses.HEAD, self.config.indices[0][0], status=503, content_type='application/json') # When/Given with self.assertRaises(AuthFailedError): self.session.authenticate(auth)
def wrapped(*a, **kw): responses.add(responses.GET, "{0}/accounts/user/info/".format(store_url), body=json.dumps(R_JSON_AUTH_RESP)) url = "{0}/eggs/{1}/index.json" responses.add(responses.GET, url.format(store_url, custom_plat), body=json.dumps(index_data)) return f(*a, **kw)
def _mock_index(self, entries): index = dict((entry.key, entry.s3index_data) for entry in entries) responses.add(responses.GET, "https://api.enthought.com/eggs/{0}/index.json".format( custom_plat), body=json.dumps(index), status=200, content_type='application/json')
def test_from_configuration(self): # Given responses.add(responses.GET, self.config.api_url, status=200, body=json.dumps(R_JSON_AUTH_RESP)) authenticator = LegacyCanopyAuthManager.from_configuration(self.config) session = Session(authenticator, self.prefix) # When with session: # Then no exception session.authenticate((FAKE_USER, FAKE_PASSWORD))
def test_simple(self): # Given responses.add(responses.POST, self.token_url, status=200, body=json.dumps({"token": "dummy token"})) r_auth = BroodBearerTokenAuth("dummy token") # When self.session.authenticate((FAKE_USER, FAKE_PASSWORD)) # Then self.assertIsInstance(self.session._raw.auth, BroodBearerTokenAuth) self.assertEqual(self.session._raw.auth._token, r_auth._token)
def test_agent(self): # Given url = "http://acme.com" responses.add(responses.GET, url) config = Configuration() r_user_agent = "enstaller/{0}".format(enstaller.__version__) # When/Then with Session.from_configuration(config) as session: resp = session._raw_get(url) self.assertTrue(resp.request.headers["user-agent"]. startswith(r_user_agent))
def test_use_webservice_invalid_user(self): # Given config = Configuration() responses.add(responses.GET, config.api_url, body=json.dumps(R_JSON_NOAUTH_RESP), content_type='application/json') # When/Then session = Session(LegacyCanopyAuthManager(config.api_url), self.prefix) with session: with self.assertRaises(AuthFailedError): session.authenticate((FAKE_USER, FAKE_PASSWORD))
def test_agent(self): # Given url = "http://acme.com" responses.add(responses.GET, url) config = Configuration() r_user_agent = "enstaller/{0}".format(enstaller.__version__) # When/Then with Session.from_configuration(config) as session: resp = session._raw_get(url) self.assertTrue( resp.request.headers["user-agent"].startswith(r_user_agent))
def test_authenticated_from_configuration_wo_auth(self): # Given url = "http://acme.com" responses.add(responses.GET, url) responses.add(responses.GET, url + "/accounts/user/info/", body=json.dumps(R_JSON_AUTH_RESP)) config = Configuration() config.update(store_url=url) # When/Then with self.assertRaises(EnstallerException): with Session.authenticated_from_configuration(config): pass
def test_from_configuration(self): # Given responses.add(responses.POST, self.token_url, status=200, body=json.dumps({"token": "dummy token"})) authenticator = BroodAuthenticator.from_configuration(self.config) session = Session(authenticator, self.prefix) r_auth = BroodBearerTokenAuth("dummy token") # When with session: session.authenticate((FAKE_USER, FAKE_PASSWORD)) # Then self.assertIsInstance(session._raw.auth, BroodBearerTokenAuth) self.assertEqual(session._raw.auth._token, r_auth._token)
def test_from_configuration(self): # Given responses.add(responses.HEAD, self.config.indices[0][0], status=200, body=json.dumps(R_JSON_AUTH_RESP)) authenticator = OldRepoAuthManager.from_configuration(self.config) session = Session(authenticator, self.prefix) # When with session: session.authenticate((FAKE_USER, FAKE_PASSWORD)) # Then self.assertIsInstance(session._raw.auth, requests.auth.HTTPBasicAuth) self.assertEqual(session._raw.auth.username, FAKE_USER) self.assertEqual(session._raw.auth.password, FAKE_PASSWORD)
def test_authenticated_from_configuration(self): # Given url = "http://acme.com" responses.add(responses.GET, url) responses.add(responses.GET, url + "/accounts/user/info/", body=json.dumps(R_JSON_AUTH_RESP)) config = Configuration() config.update(store_url=url, auth=("yoyo", "yeye")) # When with Session.authenticated_from_configuration(config) as session: resp = session._raw_get(url) # Then self.assertTrue(resp.status_code, 200)
def test_simple(self): # Given path = os.path.join(self.prefix, "enstaller.yaml") responses.add(responses.POST, "http://acme.com/api/v0/json/auth/tokens/auth", body=json.dumps({"token": "dummy token"})) with open(path, "wt") as fp: fp.write(textwrap.dedent("""\ store_url: "http://acme.com" authentication: kind: "simple" username: "******" password: "******" """)) # When # Then No exception main(["-s", "numpy", "-c", path])
def test_simple_old_legacy(self): # Given url = "https://acme.com" config = Configuration() config.update(use_webservice=False, auth=FAKE_AUTH) config.update(indexed_repositories=[url]) responses.add(responses.HEAD, config.indices[0][0], status=200) session = Session.from_configuration(config) session.authenticate(config.auth) # When user_info = UserInfo.from_session(session) # Then self.assertTrue(user_info.is_authenticated)
def test_simple_legacy_canopy(self): # Given url = "https://api.enthought.com" config = Configuration() config.update(store_url=url, auth=FAKE_AUTH) responses.add(responses.GET, url + "/accounts/user/info/", status=200, body=json.dumps(R_JSON_AUTH_RESP)) session = Session.from_configuration(config) session.authenticate(config.auth) # When user_info = UserInfo.from_session(session) # Then self.assertEqual(user_info.first_name, R_JSON_AUTH_RESP["first_name"])
def test_print_config(self): self.maxDiff = None # Given config = Configuration() config.update(prefix=sys.prefix) template = textwrap.dedent("""\ Python version: {pyver} enstaller version: {version} sys.prefix: {sys_prefix} platform: {platform} architecture: {arch} use_webservice: True keyring backend: {keyring_backend} settings: prefix = {prefix} repository_cache = {repository_cache} noapp = False proxy = None You are logged in as 'dummy' (David Cournapeau). Subscription level: Canopy / EPD Basic or above """) r_output = template.format(pyver=PY_VER, sys_prefix=os.path.normpath(sys.prefix), version=__version__, platform=platform.platform(), arch=platform.architecture()[0], keyring_backend=_keyring_backend_name(), prefix=os.path.normpath(config.prefix), repository_cache=config.repository_cache) responses.add(responses.GET, "https://api.enthought.com/accounts/user/info/", body=json.dumps(R_JSON_AUTH_RESP)) # When with self.assertRaises(SystemExit) as e: with mock_print() as m: main_noexc(["--config"]) # Then self.assertEqual(e.exception.code, 0) self.assertMultiLineEqual(m.value, r_output)
def test_simple_brood_auth(self): # Given url = "https://acme.com" token_url = url + "/api/v0/json/auth/tokens/auth" config = Configuration() config.update(store_url="brood+" + url, auth=FAKE_AUTH) responses.add(responses.POST, token_url, status=200, body=json.dumps({"token": "dummy token"})) session = Session.from_configuration(config) session.authenticate(config.auth) # When user_info = UserInfo.from_session(session) # Then self.assertTrue(user_info.is_authenticated)
def test_fetch_unauthorized(self): # Given filename = "nose-1.3.0-1.egg" url = "http://api.enthought.com/eggs/yoyo/" repository = Repository() path = os.path.join(_EGGINST_COMMON_DATA, filename) package = RepositoryPackageMetadata.from_egg(path, url) repository.add_package(package) responses.add(responses.GET, url + filename, body='{"error": "forbidden"}', status=403) downloader = _DownloadManager(mocked_session_factory(self.tempdir), repository) # When/Then with self.assertRaises(requests.exceptions.HTTPError): downloader.fetch(filename)
def test_simple(self): # Given path = os.path.join(self.prefix, "enstaller.yaml") responses.add(responses.POST, "http://acme.com/api/v0/json/auth/tokens/auth", body=json.dumps({"token": "dummy token"})) with open(path, "wt") as fp: fp.write( textwrap.dedent("""\ store_url: "http://acme.com" authentication: kind: "simple" username: "******" password: "******" """)) # When # Then No exception main(["-s", "numpy", "-c", path])
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 _add_response_for_path(self, path): with open(path, "rb") as fp: responses.add(responses.GET, path_to_uri(path), body=fp.read(), status=200, content_type='application/octet-stream')
def _mock_auth(self): responses.add(responses.GET, "https://api.enthought.com/accounts/user/info/", body=json.dumps(R_JSON_AUTH_RESP), status=200, content_type='application/json')