Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: improve logging dbt client #94

Merged
merged 2 commits into from
Sep 30, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 26 additions & 26 deletions src/preset_cli/api/clients/dbt.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,9 @@

# pylint: disable=invalid-name, too-few-public-methods

import logging
from enum import Enum
from typing import Any, Dict, List, Type, TypedDict
from typing import Any, Dict, List, Optional, Type, TypedDict

from marshmallow import INCLUDE, Schema, fields
from python_graphql_client import GraphqlClient
Expand All @@ -20,6 +21,8 @@
from preset_cli import __version__
from preset_cli.auth.main import Auth

_logger = logging.getLogger(__name__)

REST_ENDPOINT = URL("https://cloud.getdbt.com/")
GRAPHQL_ENDPOINT = URL("https://metadata.cloud.getdbt.com/graphql")

Expand Down Expand Up @@ -575,33 +578,31 @@ class DBTClient: # pylint: disable=too-few-public-methods
"""

def __init__(self, auth: Auth):
self.auth = auth
self.auth.headers.update(
{
"User-Agent": "Preset CLI",
"X-Client-Version": __version__,
},
)
self.graphql_client = GraphqlClient(endpoint=GRAPHQL_ENDPOINT)
self.baseurl = REST_ENDPOINT

self.session = auth.get_session()
self.session.headers.update(auth.get_headers())
self.session.headers["User-Agent"] = "Preset CLI"
self.session.headers["X-Client-Version"] = __version__

def execute(self, query: str, **variables: Any) -> DataResponse:
"""
Run a GraphQL query.
"""
return self.graphql_client.execute(
query=query,
variables=variables,
headers=self.auth.get_headers(),
headers=self.session.headers,
)

def get_accounts(self) -> List[AccountSchema]:
"""
List all accounts.
"""
session = self.auth.get_session()
headers = self.auth.get_headers()
response = session.get(self.baseurl / "api/v2/accounts/", headers=headers)
url = self.baseurl / "api/v2/accounts/"
_logger.debug("GET %s", url)
response = self.session.get(url)

payload = response.json()

Expand All @@ -612,12 +613,9 @@ def get_projects(self, account_id: int) -> List[ProjectSchema]:
"""
List all projects.
"""
session = self.auth.get_session()
headers = self.auth.get_headers()
response = session.get(
self.baseurl / "api/v2/accounts" / str(account_id) / "projects/",
headers=headers,
)
url = self.baseurl / "api/v2/accounts" / str(account_id) / "projects/"
_logger.debug("GET %s", url)
response = self.session.get(url)

payload = response.json()

Expand All @@ -626,16 +624,18 @@ def get_projects(self, account_id: int) -> List[ProjectSchema]:

return projects

def get_jobs(self, account_id: int) -> List[JobSchema]:
def get_jobs(
self,
account_id: int,
project_id: Optional[int] = None,
) -> List[JobSchema]:
"""
List all jobs.
List all jobs, optionally for a project.
"""
session = self.auth.get_session()
headers = self.auth.get_headers()
response = session.get(
self.baseurl / "api/v2/accounts" / str(account_id) / "jobs/",
headers=headers,
)
url = self.baseurl / "api/v2/accounts" / str(account_id) / "jobs/"
params = {"project_id": project_id} if project_id is not None else {}
_logger.debug("GET %s", url % params)
response = self.session.get(url, params=params)

payload = response.json()

Expand Down
134 changes: 129 additions & 5 deletions tests/api/clients/dbt_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
Tests for the dbt client.
"""

# pylint: disable=missing-class-docstring, invalid-name, line-too-long
# pylint: disable=missing-class-docstring, invalid-name, line-too-long, too-many-lines

import datetime
from enum import Enum
Expand Down Expand Up @@ -60,10 +60,7 @@ def test_dbt_client_execute(mocker: MockerFixture) -> None:
GraphqlClient().execute.assert_called_with(
query=query,
variables={"jobId": 1},
headers={
"User-Agent": "Preset CLI",
"X-Client-Version": __version__,
},
headers=client.session.headers,
)


Expand Down Expand Up @@ -768,6 +765,133 @@ def test_dbt_client_get_jobs(requests_mock: Mocker) -> None:
]


def test_dbt_client_get_jobs_for_project(requests_mock: Mocker) -> None:
"""
Test the ``get_jobs`` method when passing a project.
"""
requests_mock.get(
"https://cloud.getdbt.com/api/v2/accounts/72449/jobs/",
json={
"status": {
"code": 200,
"is_success": True,
"user_message": "Success!",
"developer_message": "",
},
"data": [
{
"execution": {"timeout_seconds": 0},
"generate_docs": True,
"run_generate_sources": False,
"id": 108380,
"account_id": 72449,
"project_id": 134905,
"environment_id": 107605,
"name": "Test job",
"dbt_version": "1.0.0",
"created_at": "2022-07-25T22:00:11.943460+00:00",
"updated_at": "2022-07-26T22:36:23.862370+00:00",
"execute_steps": ["dbt run", "dbt test"],
"state": 1,
"deactivated": False,
"run_failure_count": 0,
"deferring_job_definition_id": None,
"lifecycle_webhooks": False,
"lifecycle_webhooks_url": None,
"triggers": {
"github_webhook": False,
"git_provider_webhook": False,
"custom_branch_only": False,
"schedule": True,
},
"settings": {"threads": 4, "target_name": "default"},
"schedule": {
"cron": "0 * * * *",
"date": {"type": "every_day"},
"time": {"type": "every_hour", "interval": 1},
},
"is_deferrable": False,
"generate_sources": False,
"cron_humanized": "Every hour",
"next_run": "2022-07-26T23:00:00+00:00",
"next_run_humanized": "2 weeks, 2 days",
},
],
"extra": {
"filters": {"limit": 100, "offset": 0, "account_id": 72449},
"order_by": "id",
"pagination": {"count": 1, "total_count": 1},
},
},
)
auth = Auth()
client = DBTClient(auth)
assert client.get_jobs(72449, project_id=134905) == [
{
"id": 108380,
"deactivated": False,
"triggers": {
"custom_branch_only": False,
"git_provider_webhook": False,
"github_webhook": False,
"schedule": True,
},
"next_run_humanized": "2 weeks, 2 days",
"generate_sources": False,
"execution": {"timeout_seconds": 0},
"environment_id": 107605,
"created_at": datetime.datetime(
2022,
7,
25,
22,
0,
11,
943460,
tzinfo=datetime.timezone(datetime.timedelta(0), "+0000"),
),
"account_id": 72449,
"state": 1,
"deferring_job_definition_id": None,
"generate_docs": True,
"cron_humanized": "Every hour",
"next_run": datetime.datetime(
2022,
7,
26,
23,
0,
tzinfo=datetime.timezone(datetime.timedelta(0), "+0000"),
),
"run_failure_count": 0,
"lifecycle_webhooks": False,
"settings": {"threads": 4, "target_name": "default"},
"execute_steps": ["dbt run", "dbt test"],
"project_id": 134905,
"is_deferrable": False,
"schedule": {
"cron": "0 * * * *",
"time": {"interval": 1, "type": "every_hour"},
"date": {"type": "every_day"},
},
"run_generate_sources": False,
"dbt_version": "1.0.0",
"updated_at": datetime.datetime(
2022,
7,
26,
22,
36,
23,
862370,
tzinfo=datetime.timezone(datetime.timedelta(0), "+0000"),
),
"lifecycle_webhooks_url": None,
"name": "Test job",
},
]


def test_dbt_client_get_models(mocker: MockerFixture) -> None:
"""
Test the ``get_models`` method.
Expand Down