Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def test_invalid_format_should_raise_value_error():
with pytest.raises(SpectaclesException):
selector_to_pattern("model_a.explore_a")
with pytest.raises(SpectaclesException):
selector_to_pattern("model_a/")
with pytest.raises(SpectaclesException):
selector_to_pattern("explore_a")
def test_no_data_tests_should_raise_error(validator):
with pytest.raises(SpectaclesException):
validator.build_project(exclusions=["*/*"])
validator.validate()
validator._running_queries = [
Query(
query_id="12345",
lookml_ref=None,
query_task_id="abc",
explore_url="https://example.looker.com/x/12345",
)
]
mock_create_queries = create_autospec(validator._create_queries)
mock_create_queries.side_effect = KeyboardInterrupt()
validator._create_queries = mock_create_queries
mock_cancel_queries = create_autospec(validator._cancel_queries)
validator._cancel_queries = mock_cancel_queries
try:
validator._create_and_run(mode="batch")
except SpectaclesException:
mock_cancel_queries.assert_called_once_with(query_task_ids=["abc"])
def raise_exception():
if exception == SpectaclesException:
raise exception(
name="exception-name",
title="An exception occurred.",
detail="Couldn't handle the truth. Please try again.",
)
elif exception == GenericValidationError:
raise GenericValidationError
else:
raise exception(f"This is a {exception.__class__.__name__}.")
f"\n{error}\n\n"
+ printer.dim(
"Run in verbose mode (-v) or check your log file to see the full "
"response from the Looker API. "
"For support, please create an issue at "
"https://github.com/spectacles-ci/spectacles/issues"
)
+ "\n"
)
looker_api_response = json.dumps(error.looker_api_response, indent=2)
logger.debug(
f"Spectacles received a {error.status} response code from "
f"the Looker API with the following details: {looker_api_response}\n"
)
sys.exit(error.exit_code)
except SpectaclesException as error:
logger.error(
f"\n{error}\n\n"
+ printer.dim(
"For support, please create an issue at "
"https://github.com/spectacles-ci/spectacles/issues"
)
+ "\n"
)
sys.exit(error.exit_code)
except KeyboardInterrupt as error:
logger.debug(error, exc_info=True)
logger.info("Spectacles was manually interrupted.")
sys.exit(1)
except Exception as error:
logger.debug(error, exc_info=True)
logger.error(
"""
config = self.parse_config(path=values)
for dest, value in config.items():
for action in parser._actions:
if dest == action.dest:
"""Required actions that are fulfilled by config are no longer
required from the command line."""
action.required = False
# Override default if not previously set by an environment variable.
if not isinstance(action, EnvVarAction) or not os.environ.get(
action.env_var
):
setattr(namespace, dest, value)
break
else:
raise SpectaclesException(
name="invalid-config-file-param",
title="Invalid configuration file parameter.",
detail=f"Parameter '{dest}' in {values} is not valid.",
)
parser.set_defaults(**config)
def __init__(
self,
base_url: str,
client_id: str,
client_secret: str,
port: int = 19999,
api_version: float = 3.1,
):
supported_api_versions = [3.1]
if api_version not in supported_api_versions:
raise SpectaclesException(
name="unsupported-api-version",
title="Specified API version is not supported.",
detail=(
f"Version '{api_version}' is not supported. "
"Please use one of these supported versions instead: "
f"{', '.join(str(ver) for ver in sorted(supported_api_versions))}"
),
)
self.base_url: str = base_url.rstrip("/")
self.api_url: str = f"{self.base_url}:{port}/api/{api_version}/"
self.client_id: str = client_id
self.client_secret: str = client_secret
self.api_version: float = api_version
self.access_token: Optional[AccessToken] = None
self.session: requests.Session = requests.Session()
title="Encountered an unexpected query result status.",
detail=(
f"Query result status '{status}' was returned "
"by the Looker API."
),
)
logger.debug(f"Query task {query_task_id} status is: {status}")
query_result = QueryResult(query_task_id, status)
if status == "error":
try:
error_details = self._extract_error_details(result)
except (KeyError, TypeError, IndexError) as error:
logger.debug(
f"Exiting because of unexpected query result format: {result}"
)
raise SpectaclesException(
name="unexpected-query-result-format",
title="Encountered an unexpected query result format.",
detail="Unable to extract error details. The unexpected result has been logged.",
) from error
else:
query_result.error = error_details
query_results.append(query_result)
return query_results
def __init__(self, env_var, required=False, default=False, **kwargs):
self.env_var = env_var
if env_var in os.environ:
value = os.environ[env_var].lower()
if value not in ("true", "false"):
raise SpectaclesException(
name="invalid-env-var-value",
title="Invalid value for environment variable.",
detail=(
f"Allowed values for {env_var} are 'true' or 'false' "
f"(case-insensitive), received '{value}'"
),
)
default = True if value == "true" else False
if required and default:
required = False
super().__init__(default=default, required=required, **kwargs)
class SpectaclesException(Exception):
exit_code = 100
def __init__(self, name: str, title: str, detail: str):
self.type: str = "/errors/" + name
self.title = title
self.detail = detail
def __repr__(self) -> str:
return self.title
def __str__(self) -> str:
return self.title + " " + self.detail
class LookMlNotFound(SpectaclesException):
...
class LookerApiError(SpectaclesException):
"""Exception raised when an error is returned by the Looker API.
Args:
name: A lowercase, hyphenated, unique ID for the error type.
title: A short, human-readable summary of the problem.
status: The HTTP status code returned by the Looker API.
detail: A human-readable explanation with any helpful tips for
solving the issue.
response: The response object returned by the Looker API.
"""
exit_code = 101