diff --git a/.changes/unreleased/Added-20240921-220814.yaml b/.changes/unreleased/Added-20240921-220814.yaml new file mode 100644 index 00000000..bce061cf --- /dev/null +++ b/.changes/unreleased/Added-20240921-220814.yaml @@ -0,0 +1,5 @@ +kind: Added +body: Added a new `RESTClient` method to refresh the session token +time: 2024-09-21T22:08:14.334533-06:00 +custom: + Issue: "1190" diff --git a/src/citric/_rest/client.py b/src/citric/_rest/client.py index ff8155ab..64ddd48f 100644 --- a/src/citric/_rest/client.py +++ b/src/citric/_rest/client.py @@ -47,14 +47,16 @@ def __init__( self.url = url self._session = requests_session or requests.session() self._session.headers["User-Agent"] = self.USER_AGENT - self._session_id: str | None + self.__session_id: str | None = None - self.authenticate( - username=username, - password=password, - ) + self.authenticate(username=username, password=password) self._session.auth = self._auth + @property + def session_id(self) -> str | None: + """Session ID.""" + return self.__session_id + def authenticate(self, username: str, password: str) -> None: """Authenticate with the REST API. @@ -72,6 +74,12 @@ def authenticate(self, username: str, password: str) -> None: response.raise_for_status() self.__session_id = response.json() + def refresh_token(self) -> None: + """Refresh the session token.""" + response = self._session.put(url=f"{self.url}/rest/v1/session") + response.raise_for_status() + self.__session_id = response.json()["token"] + def close(self) -> None: """Delete the session.""" response = self._session.delete(f"{self.url}/rest/v1/session") diff --git a/tests/integration/test_rest_client.py b/tests/integration/test_rest_client.py index 0573128f..8abf498e 100644 --- a/tests/integration/test_rest_client.py +++ b/tests/integration/test_rest_client.py @@ -30,6 +30,14 @@ def rest_client( yield client +@pytest.mark.integration_test +def test_refresh_token(rest_client: RESTClient) -> None: + """Test refreshing the token.""" + session_id = rest_client.session_id + rest_client.refresh_token() + assert session_id != rest_client.session_id + + @pytest.mark.integration_test def test_get_surveys(rest_client: RESTClient, survey_id: int) -> None: """Test getting surveys.""" diff --git a/tests/test_rest.py b/tests/test_rest.py index cf73bfeb..46a1aa87 100644 --- a/tests/test_rest.py +++ b/tests/test_rest.py @@ -123,11 +123,8 @@ def rest_client( httpserver.expect_request( "/rest/v1/session", method="POST", - json={ - "username": username, - "password": password, - }, - ).respond_with_json('"my-session-id"') + json={"username": username, "password": password}, + ).respond_with_json("my-session-id") httpserver.expect_request("/rest/v1/session", method="DELETE").respond_with_data("") with RESTClient(httpserver.url_for("").rstrip("/"), username, password) as client: