Skip to content

Commit 594b455

Browse files
authored
Merge pull request lightspeed-core#1460 from tisnik/lcore-1608-more-fixes-of-docstrings
LCORE-1608: more fixes of docstrings in unit tests
2 parents 873f605 + 8830f88 commit 594b455

9 files changed

Lines changed: 263 additions & 38 deletions

tests/unit/cache/test_cache_factory.py

Lines changed: 23 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -129,15 +129,32 @@ def test_conversation_cache_noop(
129129
def test_conversation_cache_in_memory(
130130
memory_cache_config_fixture: ConversationHistoryConfiguration,
131131
) -> None:
132-
"""Check if InMemoryCache is returned by factory with proper configuration."""
132+
"""Check if InMemoryCache is returned by factory with proper configuration.
133+
134+
Verify CacheFactory returns an InMemoryCache when given an in-memory
135+
ConversationHistoryConfiguration.
136+
137+
Parameters:
138+
- memory_cache_config_fixture (ConversationHistoryConfiguration): a
139+
configuration with `type` set to the in-memory cache and a valid
140+
`memory` configuration.
141+
"""
133142
cache = CacheFactory.conversation_cache(memory_cache_config_fixture)
134143
assert cache is not None
135144
# check if the object has the right type
136145
assert isinstance(cache, InMemoryCache)
137146

138147

139148
def test_conversation_cache_in_memory_improper_config() -> None:
140-
"""Check if memory cache configuration is checked in cache factory."""
149+
"""Check if memory cache configuration is checked in cache factory.
150+
151+
Verify that CacheFactory.conversation_cache raises a ValueError when an
152+
in-memory cache configuration is missing.
153+
154+
Simulates an otherwise-valid in-memory configuration with its `memory`
155+
field set to None and asserts the factory raises ValueError with message
156+
containing "Expecting configuration for in-memory cache".
157+
"""
141158
cc = ConversationHistoryConfiguration(
142159
type=CACHE_TYPE_MEMORY, memory=InMemoryCacheConfig(max_entries=10)
143160
) # pyright: ignore[reportCallIssue]
@@ -192,7 +209,8 @@ def test_conversation_cache_postgres(
192209
def test_conversation_cache_postgres_improper_config() -> None:
193210
"""Check if PostgreSQL cache configuration is checked in cache factory.
194211
195-
Verify that the cache factory raises a ValueError when the PostgreSQL configuration is missing.
212+
Verify that the cache factory raises a ValueError when the PostgreSQL
213+
configuration is missing.
196214
197215
This test simulates an absent `postgres` config on a
198216
ConversationHistoryConfiguration with type `POSTGRES` and asserts that
@@ -216,7 +234,8 @@ def test_conversation_cache_postgres_improper_config() -> None:
216234
def test_conversation_cache_no_type() -> None:
217235
"""Check if wrong cache configuration is detected properly.
218236
219-
Verify that a ConversationHistoryConfiguration with no type causes the factory to reject it.
237+
Verify that a ConversationHistoryConfiguration with no type causes the
238+
factory to reject it.
220239
221240
Asserts that calling CacheFactory.conversation_cache with a configuration
222241
whose `type` is None raises a ValueError with message "Cache type must be

tests/unit/cache/test_noop_cache.py

Lines changed: 23 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,14 @@ def test_connect(cache_fixture: NoopCache) -> None:
4949

5050

5151
def test_insert_or_append(cache_fixture: NoopCache) -> None:
52-
"""Test the behavior of insert_or_append method."""
52+
"""Test the behavior of insert_or_append method.
53+
54+
Verify that inserting a CacheEntry for a user and conversation via
55+
`insert_or_append` completes without raising an exception.
56+
57+
This confirms the cache accepts the provided `cache_entry_1` for `USER_ID`
58+
and `CONVERSATION_ID`.
59+
"""
5360
cache_fixture.insert_or_append(
5461
USER_ID,
5562
CONVERSATION_ID,
@@ -124,7 +131,13 @@ def test_delete_improper_conversation_id(cache_fixture: NoopCache) -> None:
124131

125132

126133
def test_delete_skip_user_id_check(cache_fixture: NoopCache) -> None:
127-
"""Test deleting an existing conversation."""
134+
"""Test deleting an existing conversation.
135+
136+
Verify that deleting a conversation created with skip_user_id_check=True succeeds.
137+
138+
Inserts a cache entry for a non-UUID user ID using skip_user_id_check,
139+
deletes it with the same flag, and asserts the deletion returns True.
140+
"""
128141
skip_user_id_check = True
129142
cache_fixture.insert_or_append(
130143
USER_PROVIDED_USER_ID, CONVERSATION_ID, cache_entry_1, skip_user_id_check
@@ -201,7 +214,14 @@ def test_ready(cache_fixture: NoopCache) -> None:
201214

202215
@pytest.mark.parametrize("uuid", improper_user_uuids)
203216
def test_list_improper_user_id(cache_fixture: NoopCache, uuid: Optional[str]) -> None:
204-
"""Test list with invalid user ID."""
217+
"""Test list with invalid user ID.
218+
219+
Verify that listing conversations raises a ValueError for invalid user IDs.
220+
221+
Parameters:
222+
- uuid (Optional[str]): The invalid user-id value to test; the test
223+
asserts a ValueError with message "Invalid user ID {uuid}".
224+
"""
205225
with pytest.raises(ValueError, match=f"Invalid user ID {uuid}"):
206226
cache_fixture.list(uuid)
207227

tests/unit/cache/test_postgres_cache.py

Lines changed: 69 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -98,7 +98,7 @@ def postgres_cache_config() -> PostgreSQLDatabaseConfiguration:
9898
port, db, user, and a SecretStr password. Values are placeholders and
9999
not intended for real database connections.
100100
"""
101-
# can be any configuration, becuase tests won't really try to
101+
# can be any configuration, because tests won't really try to
102102
# connect to database
103103
return PostgreSQLDatabaseConfiguration(
104104
host="localhost",
@@ -122,7 +122,7 @@ def postgres_cache_config_wrong_namespace() -> PostgreSQLDatabaseConfiguration:
122122
spaces. Values are placeholders and not intended for real database
123123
connections.
124124
"""
125-
# can be any configuration, becuase tests won't really try to
125+
# can be any configuration, because tests won't really try to
126126
# connect to database
127127
return PostgreSQLDatabaseConfiguration(
128128
host="localhost",
@@ -147,7 +147,7 @@ def postgres_cache_config_too_long_namespace() -> PostgreSQLDatabaseConfiguratio
147147
characters. Values are placeholders and not intended for real database
148148
connections.
149149
"""
150-
# can be any configuration, becuase tests won't really try to
150+
# can be any configuration, because tests won't really try to
151151
# connect to database
152152
return PostgreSQLDatabaseConfiguration(
153153
host="localhost",
@@ -183,7 +183,14 @@ def test_cache_initialization_on_error(
183183
postgres_cache_config_fixture: PostgreSQLDatabaseConfiguration,
184184
mocker: MockerFixture,
185185
) -> None:
186-
"""Test the get operation when DB is not connected."""
186+
"""Test the get operation when DB is not connected.
187+
188+
Asserts that constructing PostgresCache propagates an exception raised
189+
while establishing the database connection.
190+
191+
This test patches the PostgreSQL connector to raise Exception("foo") and
192+
verifies that PostgresCache(...) raises the same exception.
193+
"""
187194
# prevent real connection to PG instance
188195
mocker.patch("psycopg2.connect", side_effect=Exception("foo"))
189196

@@ -265,7 +272,14 @@ def test_initialize_cache_when_connected(
265272
postgres_cache_config_fixture: PostgreSQLDatabaseConfiguration,
266273
mocker: MockerFixture,
267274
) -> None:
268-
"""Test the initialize_cache()."""
275+
"""Test the initialize_cache().
276+
277+
Ensure initialize_cache completes without error when a database connection is available.
278+
279+
Uses a mocked psycopg2.connect to simulate connectivity, constructs a
280+
PostgresCache with the provided configuration, and asserts that calling
281+
initialize_cache("public") does not raise an exception.
282+
"""
269283
# prevent real connection to PG instance
270284
mocker.patch("psycopg2.connect")
271285
cache = PostgresCache(postgres_cache_config_fixture)
@@ -291,7 +305,13 @@ def test_ready_method(
291305
postgres_cache_config_fixture: PostgreSQLDatabaseConfiguration,
292306
mocker: MockerFixture,
293307
) -> None:
294-
"""Test the ready() method."""
308+
"""Test the ready() method.
309+
310+
Verify that PostgresCache.ready() returns True when the cache has an active connection.
311+
312+
Patches psycopg2.connect to avoid a real database and constructs a
313+
PostgresCache; calling ready() must return True.
314+
"""
295315
# prevent real connection to PG instance
296316
mocker.patch("psycopg2.connect")
297317
cache = PostgresCache(postgres_cache_config_fixture)
@@ -326,7 +346,15 @@ def test_get_operation_when_connected(
326346
postgres_cache_config_fixture: PostgreSQLDatabaseConfiguration,
327347
mocker: MockerFixture,
328348
) -> None:
329-
"""Test the get() method."""
349+
"""Test the get() method.
350+
351+
Verify that calling get() on a connected PostgresCache does not raise and
352+
yields no entries for the given user and conversation.
353+
354+
The test patches psycopg2.connect to avoid a real database connection,
355+
constructs a PostgresCache using the provided fixture, calls get() with
356+
USER_ID_1 and CONVERSATION_ID_1, and asserts the returned list is empty.
357+
"""
330358
# prevent real connection to PG instance
331359
mocker.patch("psycopg2.connect")
332360
cache = PostgresCache(postgres_cache_config_fixture)
@@ -337,11 +365,23 @@ def test_get_operation_when_connected(
337365

338366

339367
def test_get_operation_returned_values() -> None:
340-
"""Test the get() method."""
368+
"""Test the get() method.
369+
370+
Verify that PostgresCache.get() reconstructs and returns CacheEntry objects
371+
from database rows.
372+
373+
This test should mock the database cursor to return rows representing
374+
stored cache entries (including JSON columns for referenced_documents,
375+
tool_calls, and tool_results) and assert that get(...) returns a list of
376+
CacheEntry instances whose fields match the original inserted data. The
377+
mock should emulate cursor.execute()/fetchall() behavior for realistic
378+
values and cover cases with and without optional JSON fields.
379+
"""
341380
# TODO: LCORE-721
342381
# TODO: Implement proper unit test for testing PostgreSQL cache 'get' operation
343382
# returning 'real' values
344383
# Need to mock the cursor.execute() method
384+
pytest.skip("Not yet implemented - see LCORE-721")
345385

346386

347387
def test_insert_or_append_when_disconnected(
@@ -412,7 +452,15 @@ def test_delete_operation_when_connected(
412452
postgres_cache_config_fixture: PostgreSQLDatabaseConfiguration,
413453
mocker: MockerFixture,
414454
) -> None:
415-
"""Test the delete() method."""
455+
"""Test the delete() method.
456+
457+
Verifies that delete() returns True when a database deletion affects one
458+
row and False when it affects zero rows.
459+
460+
The test uses a mocked database cursor to simulate `rowcount = 1` and
461+
`rowcount = 0` and asserts the corresponding boolean return values from
462+
`PostgresCache.delete`.
463+
"""
416464
# prevent real connection to PG instance
417465
mock_connect = mocker.patch("psycopg2.connect")
418466
cache = PostgresCache(postgres_cache_config_fixture)
@@ -457,7 +505,13 @@ def test_list_operation_when_disconnected(
457505
postgres_cache_config_fixture: PostgreSQLDatabaseConfiguration,
458506
mocker: MockerFixture,
459507
) -> None:
460-
"""Test the list() method."""
508+
"""Test the list() method.
509+
510+
Verifies that calling list on a PostgresCache with no active connection raises a CacheError.
511+
512+
Asserts that when the cache's connection is None (and connect is a no-op),
513+
invoking list(...) raises CacheError with message "cache is disconnected".
514+
"""
461515
# prevent real connection to PG instance
462516
mocker.patch("psycopg2.connect")
463517
cache = PostgresCache(postgres_cache_config_fixture)
@@ -543,6 +597,11 @@ def test_topic_summary_after_conversation_delete(
543597
deleted = cache.delete(USER_ID_1, CONVERSATION_ID_1, False)
544598
assert deleted is True
545599

600+
# Verify topic summary is no longer returned
601+
mock_cursor.fetchall.return_value = [] # Should be empty after deletion
602+
conversations = cache.list(USER_ID_1, False)
603+
assert len(conversations) == 0
604+
546605

547606
def test_topic_summary_when_disconnected(
548607
postgres_cache_config_fixture: PostgreSQLDatabaseConfiguration,

tests/unit/cache/test_sqlite_cache.py

Lines changed: 39 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,9 @@ def execute(self, command: Any) -> None:
4949
5050
Execute the provided SQL command on this cursor.
5151
52+
Parameters:
53+
command: The SQL command or statement to execute.
54+
5255
Raises:
5356
sqlite3.Error: Always raised with message "can not SELECT".
5457
"""
@@ -101,7 +104,13 @@ def create_cache(path: Path) -> SQLiteCache:
101104

102105

103106
def test_cache_initialization(tmpdir: Path) -> None:
104-
"""Test the get operation when DB is not connected."""
107+
"""Test the get operation when DB is not connected.
108+
109+
Verify a SQLiteCache can be created and has an active connection.
110+
111+
Asserts that creating a cache in the provided temporary directory returns a
112+
non-`None` cache object and that its `connection` attribute is not `None`.
113+
"""
105114
cache = create_cache(tmpdir)
106115
assert cache is not None
107116
assert cache.connection is not None
@@ -146,7 +155,13 @@ def test_connected_when_connection_error(tmpdir: Path) -> None:
146155

147156

148157
def test_initialize_cache_when_connected(tmpdir: Path) -> None:
149-
"""Test the initialize_cache()."""
158+
"""Test the initialize_cache().
159+
160+
Verify that initialize_cache completes successfully when the cache is connected.
161+
162+
Asserts that calling initialize_cache on a newly created, connected cache
163+
does not raise an exception.
164+
"""
150165
cache = create_cache(tmpdir)
151166
# should not fail
152167
cache.initialize_cache()
@@ -195,7 +210,14 @@ def test_get_operation_when_connected(tmpdir: Path) -> None:
195210

196211

197212
def test_insert_or_append_when_disconnected(tmpdir: Path) -> None:
198-
"""Test the insert_or_append() method."""
213+
"""Test the insert_or_append() method.
214+
215+
Verifies that insert_or_append raises a CacheError when the cache is disconnected.
216+
217+
Sets the cache connection to None and replaces the connect method with a
218+
no-op, then asserts that calling insert_or_append raises a CacheError with
219+
the message "cache is disconnected".
220+
"""
199221
cache = create_cache(tmpdir)
200222
cache.connection = None
201223
# no operation for @connection decorator
@@ -284,7 +306,10 @@ def test_get_operation_after_insert_or_append(tmpdir: Path) -> None:
284306

285307

286308
def test_get_operation_after_delete(tmpdir: Path) -> None:
287-
"""Test the get() method called after delete() one."""
309+
"""Test the get() method called after delete() one.
310+
311+
Verify that deleting a conversation removes its entries so subsequent get() returns empty.
312+
"""
288313
cache = create_cache(tmpdir)
289314

290315
cache.insert_or_append(USER_ID_1, CONVERSATION_ID_1, cache_entry_1, False)
@@ -330,7 +355,16 @@ def test_multiple_ids(tmpdir: Path) -> None:
330355

331356

332357
def test_list_with_conversations(tmpdir: Path) -> None:
333-
"""Test the list() method with actual conversations."""
358+
"""Test the list() method with actual conversations.
359+
360+
Verify that conversation metadata for a user is returned and ordered by
361+
last message timestamp.
362+
363+
Inserts two conversations for the same user, sets their topic summaries,
364+
calls `list(user_id, False)`, and asserts that the result contains exactly
365+
two `ConversationData` items, is ordered by `last_message_timestamp`
366+
descending, and includes both conversation IDs.
367+
"""
334368
cache = create_cache(tmpdir)
335369

336370
# Add some conversations

tests/unit/observability/test_splunk.py

Lines changed: 26 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,22 @@
1212

1313
@pytest.fixture(name="mock_splunk_config")
1414
def mock_splunk_config_fixture(tmp_path: Path, mocker: MockerFixture) -> Any:
15-
"""Create a mock SplunkConfiguration."""
15+
"""Create a mock SplunkConfiguration.
16+
17+
Create a mocked Splunk configuration object for tests.
18+
19+
The returned mock has attributes pre-populated to simulate a valid Splunk HEC configuration:
20+
- enabled = True
21+
- url = "https://splunk.example.com:8088/services/collector"
22+
- token_path = Path to a temporary file containing "test-hec-token"
23+
- index = "test_index"
24+
- source = "test-source"
25+
- timeout = 5
26+
- verify_ssl = True
27+
28+
Returns:
29+
mock_config: A MagicMock configured with the above Splunk fields.
30+
"""
1631
token_file = tmp_path / "token"
1732
token_file.write_text("test-hec-token")
1833

@@ -29,7 +44,16 @@ def mock_splunk_config_fixture(tmp_path: Path, mocker: MockerFixture) -> Any:
2944

3045
@pytest.fixture(name="mock_session")
3146
def mock_session_fixture(mocker: MockerFixture) -> Any:
32-
"""Create a mock aiohttp session with successful response."""
47+
"""Create a mock aiohttp session with successful response.
48+
49+
Parameters:
50+
- mocker (pytest_mock.MockerFixture): Fixture used to create AsyncMock objects.
51+
52+
Returns:
53+
AsyncMock: A mock session (`spec=aiohttp.ClientSession`) whose `post()`
54+
returns an async context manager that yields a response mock with
55+
`status = 200`.
56+
"""
3357
mock_response = mocker.AsyncMock()
3458
mock_response.status = 200
3559
session = mocker.AsyncMock(spec=aiohttp.ClientSession)

0 commit comments

Comments
 (0)