From 3903338d8c921a7c882880dac28a1a705e4da71f Mon Sep 17 00:00:00 2001 From: Andrew Teixeira Date: Fri, 13 Mar 2026 16:41:32 -0400 Subject: [PATCH] feat: Add the ability to pass a requests Session to Client fixes #254 --- cert_manager/client.py | 5 ++++- tests/test_client.py | 19 +++++++++++++++++++ 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/cert_manager/client.py b/cert_manager/client.py index b5b0785..9c04f1d 100644 --- a/cert_manager/client.py +++ b/cert_manager/client.py @@ -40,6 +40,8 @@ def __init__(self, **kwargs): auth_url: The full URL to the Sectigo OAuth2 token endpoint; the default is "https://auth.sso.sectigo.com/auth/realms/apiclients/protocol/openid-connect/token" client_id: The Client ID to use for OAuth2 authentication client_secret: The Client Secret to use for OAuth2 authentication + session: A requests.Session object to use instead of creating a new one; the default is None, + which will create a new session """ # Initialize class variables self._base_url = None @@ -51,7 +53,8 @@ def __init__(self, **kwargs): self._user_key_file = None self._username = None - self._session = requests.Session() + self._session = kwargs.get("session", requests.Session()) + # Set the default HTTP headers self._headers = { "Accept": "application/json", diff --git a/tests/test_client.py b/tests/test_client.py index 3d2ba9d..bdc4797 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -11,6 +11,7 @@ from unittest import mock import pytest +import requests import responses from requests.exceptions import HTTPError from testtools import TestCase @@ -138,6 +139,24 @@ def test_versioning(self): self.assertEqual(client.headers["User-Agent"], user_agent) self.assertEqual(client._session.headers["User-Agent"], user_agent) + def test_session_passed(self): + """Test that a passed session is used.""" + session = requests.Session() + client = Client( + base_url=self.cfixt.base_url, + login_uri=self.cfixt.login_uri, + username=self.cfixt.username, + password=self.cfixt.password, + session=session, + ) + self.assertIs(client._session, session) + + def test_session_created(self): + """Test that a session is created if not passed.""" + # The setUp method already creates a client without a session passed + self.assertIsInstance(self.client._session, requests.Session) + self.assertIsNotNone(self.client._session) + def test_need_crt(self): """Raise an exception without a cert file if cert_auth=True.""" self.assertRaises(KeyError, Client, base_url=self.cfixt.base_url, login_uri=self.cfixt.login_uri,