2020from datetime import datetime
2121from gzip import GzipFile
2222from pathlib import Path
23+ from typing import List
2324
2425import pytest
26+ from httpx import Request , Response
27+ from pytest_mock import MockerFixture
2528
2629from structurizr .api .structurizr_client import StructurizrClient
30+ from structurizr .api .structurizr_client_exception import StructurizrClientException
31+ from structurizr .workspace import Workspace
2732
2833
2934MockSettings = namedtuple (
@@ -47,7 +52,7 @@ def mock_settings():
4752
4853
4954@pytest .fixture (scope = "function" )
50- def client (mock_settings ):
55+ def client (mock_settings ) -> StructurizrClient :
5156 """Provide a client instance with the mock settings."""
5257 return StructurizrClient (settings = mock_settings )
5358
@@ -131,3 +136,52 @@ def test_add_headers_authentication(client: StructurizrClient, mocker):
131136 headers = client ._add_headers (request , content = "Hello" , content_type = "World" )
132137 assert headers ["Content-MD5" ] == "OGIxYTk5NTNjNDYxMTI5NmE4MjdhYmY4YzQ3ODA0ZDc="
133138 assert headers ["Content-Type" ] == "World"
139+
140+
141+ def test_get_workspace_handles_error_responses (
142+ client : StructurizrClient , mocker : MockerFixture
143+ ):
144+ """Test that response code other than 200 raise an exception."""
145+ mocker .patch .object (client ._client , "send" , return_value = Response (403 ))
146+ with pytest .raises (
147+ StructurizrClientException ,
148+ match = "Failed .* workspace 19.\n Response 403 - Forbidden" ,
149+ ):
150+ client .get_workspace ()
151+
152+
153+ def test_put_workspace_handles_error_responses (
154+ client : StructurizrClient , mocker : MockerFixture
155+ ):
156+ """Test that response code other than 200 raise an exception."""
157+ mocker .patch .object (client ._client , "send" , return_value = Response (403 ))
158+ workspace = Workspace (name = "Workspace 1" , description = "" , id = 19 )
159+ with pytest .raises (
160+ StructurizrClientException ,
161+ match = "Failed .* workspace 19.\n Response 403 - Forbidden" ,
162+ ):
163+ client .put_workspace (workspace )
164+
165+
166+ def test_locking_and_unlocking (client : StructurizrClient , mocker : MockerFixture ):
167+ """Ensure that using the client in a with block locks and unlocks."""
168+ requests : List [Request ] = []
169+
170+ def fake_send (request : Request ):
171+ nonlocal requests
172+ requests .append (request )
173+ return Response (
174+ 200 ,
175+ content = '{"success": true, "message": "OK"}' .encode ("ascii" ),
176+ request = request ,
177+ )
178+
179+ mocker .patch .object (client ._client , "send" , new = fake_send )
180+ with client :
181+ pass
182+
183+ assert len (requests ) == 2
184+ assert requests [0 ].method == "PUT"
185+ assert requests [0 ].url .path == "/workspace/19/lock"
186+ assert requests [1 ].method == "DELETE"
187+ assert requests [1 ].url .path == "/workspace/19/lock"
0 commit comments