From eeb20bb8731286073fff821ae660446e183893f6 Mon Sep 17 00:00:00 2001 From: samkoebrich Date: Wed, 12 Feb 2025 10:36:15 -0700 Subject: [PATCH] do to expose credentials as persistent attributes --- tests/test_sdk.py | 12 ++++++++++++ watttime/api.py | 35 +++++++++++++++++++++++++++++++++-- 2 files changed, 45 insertions(+), 2 deletions(-) diff --git a/tests/test_sdk.py b/tests/test_sdk.py index e3df9e4c..e5adbb9c 100644 --- a/tests/test_sdk.py +++ b/tests/test_sdk.py @@ -125,6 +125,18 @@ def test_mock_register(self, mock_post): resp = self.base.register(email=os.getenv("WATTTIME_EMAIL")) self.assertEqual(len(mock_post.call_args_list), 1) + def test_get_password(self): + + with mock.patch.dict(os.environ, {}, clear=True), self.assertRaises(ValueError): + wt_base = WattTimeBase() + + with mock.patch.dict(os.environ, {}, clear=True): + wt_base = WattTimeBase( + username="WATTTIME_USERNAME", password="WATTTIME_PASSWORD" + ) + self.assertEqual(wt_base.username, "WATTTIME_USERNAME") + self.assertEqual(wt_base.password, "WATTTIME_PASSWORD") + class TestWattTimeHistorical(unittest.TestCase): def setUp(self): diff --git a/watttime/api.py b/watttime/api.py index 4d451dff..bbcba273 100644 --- a/watttime/api.py +++ b/watttime/api.py @@ -26,11 +26,42 @@ def __init__(self, username: Optional[str] = None, password: Optional[str] = Non username (Optional[str]): The username to use for authentication. If not provided, the value will be retrieved from the environment variable "WATTTIME_USER". password (Optional[str]): The password to use for authentication. If not provided, the value will be retrieved from the environment variable "WATTTIME_PASSWORD". """ - self.username = username or os.getenv("WATTTIME_USER") - self.password = password or os.getenv("WATTTIME_PASSWORD") + + # This only applies to the current session, is not stored persistently + if username and not os.getenv("WATTTIME_USER"): + os.environ["WATTTIME_USER"] = username + if password and not os.getenv("WATTTIME_PASSWORD"): + os.environ["WATTTIME_PASSWORD"] = password + + # Accessing attributes will raise exception if variables are not set + _ = self.password + _ = self.username + self.token = None self.token_valid_until = None + @property + def password(self): + password = os.getenv("WATTTIME_PASSWORD") + if not password: + raise ValueError( + "WATTTIME_PASSWORD env variable is not set." + + "Please set this variable, or pass in a password upon initialization," + + "which will store it as a variable only for the current session" + ) + return password + + @property + def username(self): + username = os.getenv("WATTTIME_USER") + if not username: + raise ValueError( + "WATTTIME_USER env variable is not set." + + "Please set this variable, or pass in a username upon initialization," + + "which will store it as a variable only for the current session" + ) + return username + def _login(self): """ Login to the WattTime API, which provides a JWT valid for 30 minutes