def test_it_fails_with_a_bad_file_path(): """ApiSettings should raise an error non-default ini path doesn't exist.""" api_settings.ApiSettings() # defaulting to _DEFAULT_INI, no error api_settings.ApiSettings("looker.ini") # specifying _DEFAULT_INI, no error with pytest.raises(FileNotFoundError) as exc_info: api_settings.ApiSettings("/no/such/file.ini") assert exc_info.match("file.ini")
def _settings(config_file: str, section: Optional[str] = None): return api_settings.ApiSettings( filename=config_file, section=section, sdk_version=constants.sdk_version, env_prefix=constants.environment_prefix, )
def test_it_fails_when_env_variables_are_defined_but_empty(config_file, monkeypatch): """ApiSettings should throw an error if required settings are passed as empty env variables. """ monkeypatch.setenv("LOOKERSDK_BASE_URL", "") assert api_settings.ApiSettings(config_file, "BARE").is_configured() is False
def test_env_verify_ssl_maps_properly(monkeypatch, config_file, test_value, expected): """ApiSettings should map the various values that VERIFY_SSL can take to True/False accordingly. """ monkeypatch.setenv("LOOKERSDK_VERIFY_SSL", test_value) settings = api_settings.ApiSettings(config_file, section="BARE_MINIMUM") assert settings.verify_ssl == expected
def api() -> api_methods.APIMethods: settings = api_settings.ApiSettings("../looker.ini") transport = requests_transport.RequestsTransport.configure(settings) auth = auth_session.AuthSession(settings, transport, serialize.deserialize31, "3.1") return api_methods.APIMethods( auth, serialize.deserialize31, serialize.serialize, transport, "3.1" )
def api() -> api_methods.APIMethods: settings = api_settings.ApiSettings( filename="../looker.ini", env_prefix=constants.environment_prefix) transport = requests_transport.RequestsTransport.configure(settings) auth = auth_session.AuthSession(settings, transport, serialize.deserialize31, "3.1") return api_methods.APIMethods(auth, serialize.deserialize31, serialize.serialize31, transport, "3.1")
def test_it_retrieves_section_by_name(config_file, test_section, expected_url): """ApiSettings should return settings of specified section.""" settings = api_settings.ApiSettings(config_file, test_section) assert settings.base_url == expected_url assert settings.verify_ssl data = vars(settings) assert "client_id" not in data assert "client_secret" not in data
def oauth_interactive_roundtrip(): username = input("\nemail: ") password = getpass.getpass() settings = api_settings.ApiSettings() transport = requests_transport.RequestsTransport.configure(settings) session = auth_session.OAuthSession( settings=settings, transport=transport, deserialize=serialize.deserialize31, serialize=serialize.serialize, crypto=auth_session.CryptoHash(), version="3.1", ) auth_code_request_url = session.create_auth_code_request_url("api", "mystate") with requests.Session() as s: s.verify = False redirect_to_login = s.get(auth_code_request_url) csrf_token = urllib.parse.unquote(s.cookies["CSRF-TOKEN"]) redirect = s.post( redirect_to_login.url, data={"csrf-token": csrf_token, "email": username, "password": password}, allow_redirects=False, ) assert redirect.next.path_url != "/login", "Failed to login to looker." while redirect.next: try: # 1. redirect to /auth # 2. (if already authorized app) redirect to settings.redirect_uri redirect = s.send(redirect.next, allow_redirects=False, timeout=2) except requests.exceptions.ConnectTimeout: # yep, redirected to settings.redirect_uri which doesn't exist hence # the timeout error. skip the app approval else block below break else: # redirected to app approval redirect = s.post( redirect.url, data={"csrf-token": csrf_token, "approve": "true"}, allow_redirects=False, ) assert redirect.status_code != 403, "User not allowed to authorize app!" # whether we had to authorize or were already authorized, we've now # been redirected to settings.redirect_uri, grab the Location header # query string to parse out the "code" qs = urllib.parse.urlparse(redirect.headers["Location"]).query params = urllib.parse.parse_qs(qs) assert "code" in params session.redeem_auth_code(params["code"][0]) sdk = methods.Looker31SDK( session, serialize.deserialize31, serialize.serialize, transport, "3.1" ) me = sdk.me() print(f"Hi {me.first_name}, your user_id is {me.id}")
def oauth_session(config_file): settings = api_settings.ApiSettings(config_file) return auth.OAuthSession( settings=settings, transport=MockTransport.configure(settings), deserialize=serialize.deserialize31, serialize=serialize.serialize, crypto=auth.CryptoHash(), version="4.0", )
def test_settings_defaults_to_looker_section(config_file): """ApiSettings should retrieve settings from default (Looker) section if section is not specified during instantiation. """ settings = api_settings.ApiSettings(filename=config_file) assert settings.base_url == "https://host1.looker.com:19999" # API credentials are not set as attributes in ApiSettings data = vars(settings) assert "client_id" not in data assert "client_secret" not in data
def test_it_assigns_defaults_to_empty_settings(config_file): """ApiSettings assigns defaults to optional settings that are empty in the config file. """ settings = api_settings.ApiSettings(config_file, "BARE_MINIMUM") assert settings.base_url == "https://host3.looker.com:19999/" assert settings.verify_ssl data = vars(settings) assert "client_id" not in data assert "client_secret" not in data
def test_it_unquotes_quoted_env_var_values(monkeypatch): """ApiSettings should strip quotes from env variable values.""" monkeypatch.setenv("LOOKERSDK_BASE_URL", "'https://host1.looker.com:19999'") monkeypatch.setenv("LOOKERSDK_TIMEOUT", "100") monkeypatch.setenv("LOOKERSDK_VERIFY_SSL", '"false"') settings = api_settings.ApiSettings() # _DEFAULT_INI absence doesn't raise assert settings.base_url == "https://host1.looker.com:19999" assert settings.verify_ssl is False assert settings.timeout == 100
def test_it_fails_when_env_variables_are_defined_but_empty( config_file, monkeypatch): """ApiSettings should throw an error if required settings are passed as empty env variables. """ monkeypatch.setenv("LOOKERSDK_BASE_URL", "") with pytest.raises(error.SDKError): api_settings.ApiSettings(filename=config_file, section="BARE", env_prefix="LOOKERSDK").is_configured()
def test_configure_with_no_file(monkeypatch): """ApiSettings should be instantiated if required parameters all exist in env variables. """ monkeypatch.setenv("LOOKERSDK_BASE_URL", "https://host1.looker.com:19999") monkeypatch.setenv("LOOKERSDK_CLIENT_ID", "id123") monkeypatch.setenv("LOOKERSDK_CLIENT_SECRET", "secret123") settings = api_settings.ApiSettings("no-such-file") assert settings.base_url == "https://host1.looker.com:19999" data = vars(settings) assert "client_id" not in data assert "client_secret" not in data
def test_settings_from_env_variables_override_config_file( monkeypatch, config_file, test_section): """ApiSettings should read settings defined as env variables.""" monkeypatch.setenv("LOOKERSDK_BASE_URL", "https://host1.looker.com:19999") monkeypatch.setenv("LOOKERSDK_VERIFY_SSL", "0") monkeypatch.setenv("LOOKERSDK_CLIENT_ID", "id123") monkeypatch.setenv("LOOKERSDK_CLIENT_SECRET", "secret123") settings = api_settings.ApiSettings(config_file, section=test_section) assert settings.base_url == "https://host1.looker.com:19999" assert not settings.verify_ssl # API credentials are still not set as attributes when read from env variables data = vars(settings) assert "client_id" not in data assert "client_secret" not in data
def init40( config_file: str = "looker.ini", section: Optional[str] = None ) -> methods40.Looker40SDK: """Default dependency configuration """ settings = api_settings.ApiSettings(config_file, section) if not settings.is_configured(): raise InitError("Missing required configuration values.") transport = requests_transport.RequestsTransport.configure(settings) return methods40.Looker40SDK( auth_session.AuthSession(settings, transport, serialize.deserialize40, "4.0"), serialize.deserialize40, serialize.serialize, transport, "4.0", )
def test_it_fails_with_missing_credentials(config_file, monkeypatch, test_section, test_env_client_id, test_env_client_secret): monkeypatch.setenv("LOOKERSDK_CLIENT_ID", test_env_client_id) monkeypatch.setenv("LOOKERSDK_CLIENT_SECRET", test_env_client_secret) settings = api_settings.ApiSettings(config_file, test_section) settings.api_version = "3.1" auth_session = auth.AuthSession(settings, MockTransport.configure(settings), serialize.deserialize31, "3.1") with pytest.raises(error.SDKError) as exc_info: auth_session.authenticate() assert "auth credentials not found" in str(exc_info.value)
def configure_sdk(): try: settings = api_settings.ApiSettings() user_agent_tag = f"Themis v1.0" settings.headers = { "Content-Type": "application/json", "User-Agent": user_agent_tag, } settings.timeout = 480 transport = requests_transport.RequestsTransport.configure(settings) except Exception as e: logger.error('Issues generating SDK configuration: {}'.format(e)) return methods.Looker40SDK( auth_session.AuthSession(settings, transport, serialize.deserialize40, "4.0"), serialize.deserialize40, serialize.serialize, transport, "4.0")
def auth_session(config_file): settings = api_settings.ApiSettings(config_file) return auth.AuthSession(settings, MockTransport.configure(settings), serialize.deserialize31, "3.1")
def test_it_fails_with_a_bad_section_name(config_file): """ApiSettings should raise NoSectionError section is not found.""" with pytest.raises(configparser.NoSectionError) as exc_info: api_settings.ApiSettings(filename=config_file, section="NotAGoodLookForYou") assert exc_info.match("NotAGoodLookForYou")
def test_it_fails_with_a_bad_section_name(config_file): """ApiSettings should raise an error if section is not found.""" with pytest.raises(KeyError) as exc_info: api_settings.ApiSettings(config_file, "NotAGoodLookForYou") assert exc_info.match("NotAGoodLookForYou")
def test_it_fails_if_required_settings_are_not_found(config_file, test_section): """ApiSettings should throw an error if required settings are not found.""" assert api_settings.ApiSettings(config_file, test_section).is_configured() is False
def auth_session(config_file): settings = api_settings.ApiSettings(filename=config_file, env_prefix="LOOKERSDK") return auth.AuthSession(settings, MockTransport.configure(settings), serialize.deserialize31, "3.1")
def test_it_fails_if_required_settings_are_not_found(config_file, test_section): """ApiSettings should throw an error if required settings are not found.""" with pytest.raises(error.SDKError): api_settings.ApiSettings(filename=config_file, section=test_section).is_configured()
def test_it_unquotes_quoted_config_file_vars(config_file): """ApiSettings should strip quotes from config file variables.""" settings = api_settings.ApiSettings(filename=config_file, section="QUOTED_CONFIG_VARS") assert settings.base_url == "https://host4.looker.com:19999" assert settings.verify_ssl is False