Skip to content

Commit

Permalink
refactore settings
Browse files Browse the repository at this point in the history
  • Loading branch information
loechel committed Apr 30, 2024
1 parent 74d977c commit 7e6a7db
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 22 deletions.
45 changes: 30 additions & 15 deletions src/edutap/wallet_google/session.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@
from requests.adapters import HTTPAdapter

import json
import os
import threading


Expand All @@ -29,39 +28,49 @@ class GoogleWalletSettings(BaseSettings):
"""Settings for Google Wallet Preferences."""

model_config = SettingsConfigDict(
env_file=".env",
env_file_encoding="utf-8",
# env_file=".env",
# env_file_encoding="utf-8",
env_prefix="EDUTAP_WALLET_GOOGLE_",
case_sensitive=False,
# extra="ignore",
extra="allow",
)

record_api_calls_dir: Path | None = None
record_api_calls_dir: Path | None = ROOT_DIR / "tests" / "data"
base_url: HttpUrl = HttpUrl("https://walletobjects.googleapis.com/walletobjects/v1")
save_url: HttpUrl = HttpUrl("https://pay.google.com/gp/v/save")
scopes: list[HttpUrl] = [
HttpUrl("https://www.googleapis.com/auth/wallet_object.issuer")
]

credentials_path: Path = ROOT_DIR
# credentials_dir: Path = Field(alias="EDUTAP_WALLET_PATH_CREDENTIAL_DIR", default=ROOT_DIR)

# credentials_file: str = "credentials.json"
credentials_file: Path = ROOT_DIR / "credentials.json"

credentials_file: str = "credentials.json"
issuer_account_email: EmailStr | None = None
issuer_id: str | None = Field(min_length=19, max_length=20)
issuer_id: str | None = Field(min_length=19, max_length=20, default=None)


class HTTPRecorder(HTTPAdapter):
"""Record the HTTP requests and responses to a file."""

def __init__(self, settings: GoogleWalletSettings):
super().__init__()
self.settings = settings

def send(self, request, *args, **kwargs):
req_record = {
"method": request.method,
"url": request.url,
"headers": dict(request.headers),
"body": json.loads(request.body.decode("utf-8")),
}
target_directory = os.environ.get("EDUTAP_WALLET_GOOGLE_RECORD_API_CALLS_DIR")
target_directory = (
self.settings.record_api_calls_dir
) # os.environ.get("EDUTAP_WALLET_GOOGLE_RECORD_API_CALLS_DIR")
if target_directory.is_dir() and not target_directory.exists():
target_directory
filename = f"{target_directory}/{request.method}-{request.url.replace('/', '_')}.REQUEST.json"
with open(filename, "w") as fp:
json.dump(req_record, fp, indent=4)
Expand All @@ -79,6 +88,9 @@ def send(self, request, *args, **kwargs):
class SessionManager:
"""Manages the session to the Google Wallet API and provides helper methods."""

def __init__(self):
self.settings = GoogleWalletSettings()

@property
def base_url(self) -> str:
return str(self.settings.base_url)
Expand All @@ -97,9 +109,8 @@ def save_url(self) -> str:
def credentials_file(self) -> Path | None:
if getattr(self, "_credentials_file", None) is None:
self._credentials_file = None
path = self.settings.credentials_path / self.settings.credentials_file
if path.exists():
self._credentials_file = path
if self.settings.credentials_file.exists():
self._credentials_file = self.settings.credentials_file
# if os.environ.get("EDUTAP_WALLET_GOOGLE_CREDENTIALS_FILE"):
# path = Path(os.environ.get("CREDENTIAL_PATH", ".")) / Path(
# os.environ.get(
Expand All @@ -124,15 +135,19 @@ def credentials_info(self) -> dict[str, str]:
return self._credentials_info

def _make_session(self) -> AuthorizedSession:
self.settings = GoogleWalletSettings()
# self.settings = GoogleWalletSettings()
if not self.credentials_file:
raise ValueError("EDUTAP_WALLET_GOOGLE_CREDENTIALS_FILE not set")
credentials = Credentials.from_service_account_file(
self.credentials_file, scopes=SCOPES
str(self.credentials_file), scopes=SCOPES
)
session = AuthorizedSession(credentials)
if os.environ.get("EDUTAP_WALLET_GOOGLE_RECORD_API_CALLS_DIR", None):
session.mount("https://", HTTPRecorder())
if (
self.settings.record_api_calls_dir is not None
and self.settings.credentials_file.exists()
):
# if os.environ.get("EDUTAP_WALLET_GOOGLE_RECORD_API_CALLS_DIR", None):
session.mount("https://", HTTPRecorder(settings=self.settings))
return session

@property
Expand Down
8 changes: 4 additions & 4 deletions tests/test_session.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
from edutap.wallet_google.session import ROOT_DIR


def test_session_manager_url(clean_registry): # noqa: F811
from edutap.wallet_google.registry import register_model

Expand Down Expand Up @@ -33,13 +36,10 @@ class Foo2:

def test_session_creation(monkeypatch):
from edutap.wallet_google.session import SessionManager
from pathlib import Path

monkeypatch.setenv("CREDENTIAL_PATH", str(Path(__file__).parent / "data"))

monkeypatch.setenv(
"EDUTAP_WALLET_GOOGLE_CREDENTIALS_FILE",
"credentials_fake.json",
ROOT_DIR / "tests" / "data" / "credentials_fake.json",
)
manager = SessionManager()
session = manager.session
Expand Down
8 changes: 5 additions & 3 deletions tests/test_settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ def test_settings():
== "https://walletobjects.googleapis.com/walletobjects/v1"
)
assert str(settings.save_url) == "https://pay.google.com/gp/v/save"
assert settings.scopes == ["https://www.googleapis.com/auth/wallet_object.issuer"]
assert settings.issuer_id
assert settings.credentials_file
assert [str(s) for s in settings.scopes] == [
"https://www.googleapis.com/auth/wallet_object.issuer"
]
assert settings.issuer_id is not None
assert settings.credentials_file.exists()

0 comments on commit 7e6a7db

Please sign in to comment.