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

Make invocation contexts more reliable in testing scenarios. #69

Merged
merged 1 commit into from
Feb 6, 2024
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
6 changes: 6 additions & 0 deletions .changes/unreleased/Fixes-20240206-160231.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
kind: Fixes
body: Make invocation contexts more reliable in testing scenarios.
time: 2024-02-06T16:02:31.81842-05:00
custom:
Author: peterallenwebb
Issue: "52"
19 changes: 16 additions & 3 deletions dbt_common/context.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from contextvars import ContextVar
from contextvars import ContextVar, copy_context
from typing import List, Mapping, Optional

from dbt_common.constants import SECRET_ENV_PREFIX
Expand Down Expand Up @@ -26,10 +26,23 @@ def env_secrets(self) -> List[str]:
_INVOCATION_CONTEXT_VAR: ContextVar[InvocationContext] = ContextVar("DBT_INVOCATION_CONTEXT_VAR")


def _reliably_get_invocation_var() -> ContextVar:
invocation_var: Optional[ContextVar] = next(
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This ensures that the ContextVar is identified by name, which works around some fancy async stuff pytest does which cause this module to be loaded multiple times.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Huh, nice discovery with this!

(cv for cv in copy_context() if cv.name == _INVOCATION_CONTEXT_VAR.name), None
)

if invocation_var is None:
invocation_var = _INVOCATION_CONTEXT_VAR

return invocation_var


def set_invocation_context(env: Mapping[str, str]) -> None:
_INVOCATION_CONTEXT_VAR.set(InvocationContext(env))
invocation_var = _reliably_get_invocation_var()
invocation_var.set(InvocationContext(env))


def get_invocation_context() -> InvocationContext:
ctx = _INVOCATION_CONTEXT_VAR.get()
invocation_var = _reliably_get_invocation_var()
ctx = invocation_var.get()
return ctx
Loading