-
Notifications
You must be signed in to change notification settings - Fork 119
Expand file tree
/
Copy pathtest_tokenize.py
More file actions
512 lines (463 loc) · 19.3 KB
/
test_tokenize.py
File metadata and controls
512 lines (463 loc) · 19.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
"""Integration tests for the tokenization module.
These tests cover the client's responsibilities:
- Correct serialization of inputs (enums, TextAnalyzerConfigCreate, StopwordsCreate)
- Correct deserialization of responses into the TokenizeResult object
- Client-side validation (TextAnalyzerConfigCreate, stopwords/stopword_presets mutex)
- Version gate (>= 1.37.0)
- Both sync and async client paths
Server-side behavior this client relies on:
- Word tokenization defaults to preset "en" when no stopword config is sent.
- Both endpoints return only ``indexed`` and ``query``.
- ``stopwords`` and ``stopword_presets`` are mutually exclusive on the generic
endpoint — the server rejects requests that set both.
"""
from typing import AsyncGenerator, Generator
import pytest
import pytest_asyncio
import weaviate
from weaviate.classes.tokenization import (
StopwordsCreate,
StopwordsPreset,
TextAnalyzerConfigCreate,
Tokenization,
TokenizeResult,
)
from weaviate.config import AdditionalConfig
from weaviate.exceptions import WeaviateUnsupportedFeatureError
@pytest.fixture(scope="module")
def client() -> Generator[weaviate.WeaviateClient, None, None]:
c = weaviate.connect_to_local(
additional_config=AdditionalConfig(timeout=(60, 120)),
)
yield c
c.close()
@pytest.fixture(autouse=False)
def require_1_37(client: weaviate.WeaviateClient) -> None:
if client._connection._weaviate_version.is_lower_than(1, 37, 0):
pytest.skip("Tokenization requires Weaviate >= 1.37.0")
@pytest_asyncio.fixture
async def async_client() -> AsyncGenerator[weaviate.WeaviateAsyncClient, None]:
c = weaviate.use_async_with_local(
additional_config=AdditionalConfig(timeout=(60, 120)),
)
await c.connect()
yield c
await c.close()
@pytest.fixture
def recipe_collection(client: weaviate.WeaviateClient) -> Generator:
"""Collection with a `recipe` word-tokenized property and an en + ["quick"] stopwords config."""
name = "TestTokenizeRecipe"
client.collections.delete(name)
client.collections.create_from_dict(
{
"class": name,
"vectorizer": "none",
"invertedIndexConfig": {
"stopwords": {"preset": "en", "additions": ["quick"]},
},
"properties": [
{"name": "recipe", "dataType": ["text"], "tokenization": "word"},
],
}
)
try:
yield client.collections.get(name)
finally:
client.collections.delete(name)
# ---------------------------------------------------------------------------
# Serialization
# ---------------------------------------------------------------------------
@pytest.mark.usefixtures("require_1_37")
class TestSerialization:
"""Verify the client correctly serializes different input forms."""
@pytest.mark.parametrize(
"tokenization,text,expected_indexed,expected_query",
[
# "the" is an English stopword — filtered from the query output
# by the server's default "en" preset for word tokenization.
(
Tokenization.WORD,
"The quick brown fox",
["the", "quick", "brown", "fox"],
["quick", "brown", "fox"],
),
# Non-word tokenizations do not apply the default "en" preset.
(
Tokenization.LOWERCASE,
"Hello World Test",
["hello", "world", "test"],
["hello", "world", "test"],
),
(
Tokenization.WHITESPACE,
"Hello World Test",
["Hello", "World", "Test"],
["Hello", "World", "Test"],
),
(Tokenization.FIELD, " Hello World ", ["Hello World"], ["Hello World"]),
(Tokenization.TRIGRAM, "Hello", ["hel", "ell", "llo"], ["hel", "ell", "llo"]),
],
)
def test_tokenization_enum(
self,
client: weaviate.WeaviateClient,
tokenization: Tokenization,
text: str,
expected_indexed: list,
expected_query: list,
) -> None:
result = client.tokenization.text(text=text, tokenization=tokenization)
assert isinstance(result, TokenizeResult)
assert result.indexed == expected_indexed
assert result.query == expected_query
@pytest.mark.parametrize(
"call_kwargs,expected_indexed,expected_query",
[
(
{"text": "The quick brown fox"},
["the", "quick", "brown", "fox"],
["quick", "brown", "fox"],
),
(
{
"text": "The quick brown fox",
"analyzer_config": TextAnalyzerConfigCreate(
stopword_preset=StopwordsPreset.NONE
),
},
["the", "quick", "brown", "fox"],
["the", "quick", "brown", "fox"],
),
(
{
"text": "L'école est fermée",
"analyzer_config": TextAnalyzerConfigCreate(ascii_fold=True),
},
["l", "ecole", "est", "fermee"],
["l", "ecole", "est", "fermee"],
),
(
{
"text": "L'école est fermée",
"analyzer_config": TextAnalyzerConfigCreate(
ascii_fold=True, ascii_fold_ignore=["é"]
),
},
["l", "école", "est", "fermée"],
["l", "école", "est", "fermée"],
),
(
{
"text": "The quick brown fox",
"analyzer_config": TextAnalyzerConfigCreate(stopword_preset=StopwordsPreset.EN),
},
["the", "quick", "brown", "fox"],
["quick", "brown", "fox"],
),
(
{
"text": "The quick brown fox",
"analyzer_config": TextAnalyzerConfigCreate(stopword_preset="en"),
},
["the", "quick", "brown", "fox"],
["quick", "brown", "fox"],
),
(
{
"text": "The école est fermée",
"analyzer_config": TextAnalyzerConfigCreate(
ascii_fold=True,
ascii_fold_ignore=["é"],
stopword_preset=StopwordsPreset.EN,
),
},
["the", "école", "est", "fermée"],
["école", "est", "fermée"],
),
(
{
"text": "the quick brown fox",
"stopwords": StopwordsCreate(
preset=StopwordsPreset.EN, additions=["quick"], removals=None
),
},
["the", "quick", "brown", "fox"],
["brown", "fox"],
),
(
{
"text": "the quick hello world",
"stopwords": StopwordsCreate(preset=None, additions=["hello"], removals=None),
},
["the", "quick", "hello", "world"],
["quick", "world"],
),
(
{
"text": "the quick is fast",
"stopwords": StopwordsCreate(preset=None, additions=None, removals=["the"]),
},
["the", "quick", "is", "fast"],
["the", "quick", "fast"],
),
(
{
"text": "hello world test",
"analyzer_config": TextAnalyzerConfigCreate(stopword_preset="custom"),
"stopword_presets": {"custom": ["test"]},
},
["hello", "world", "test"],
["hello", "world"],
),
(
{
"text": "the quick hello world",
"stopword_presets": {"en": ["hello"]},
},
["the", "quick", "hello", "world"],
["the", "quick", "world"],
),
],
ids=[
"default_en_applied_for_word",
"opt_out_of_default_en",
"ascii_fold",
"ascii_fold_with_ignore",
"stopword_preset_enum",
"stopword_preset_string",
"ascii_fold_combined_with_stopwords",
"stopwords_fallback",
"stopwords_additions_default_preset_to_en",
"stopwords_removals_default_preset_to_en",
"stopword_presets_named_reference",
"stopword_presets_override_builtin_en",
],
)
def test_text_tokenize(
self,
client: weaviate.WeaviateClient,
call_kwargs: dict,
expected_indexed: list,
expected_query: list,
) -> None:
result = client.tokenization.text(tokenization=Tokenization.WORD, **call_kwargs)
assert isinstance(result, TokenizeResult)
assert result.indexed == expected_indexed
assert result.query == expected_query
def test_text_from_collection_config(
self, client: weaviate.WeaviateClient, recipe_collection
) -> None:
"""Values round-tripped through config.get() feed back into tokenization.text()."""
config = recipe_collection.config.get()
recipe = next(p for p in config.properties if p.name == "recipe")
stopwords = config.inverted_index_config.stopwords
result = client.tokenization.text(
text="the quick brown fox",
tokenization=recipe.tokenization,
stopwords=stopwords,
)
assert result.indexed == ["the", "quick", "brown", "fox"]
assert result.query == ["brown", "fox"]
def test_property_and_generic_endpoints_agree(
self, client: weaviate.WeaviateClient, recipe_collection
) -> None:
"""Property endpoint (server resolves config from schema) produces the same indexed/query as the generic endpoint fed the same config."""
config = recipe_collection.config.get()
recipe = next(p for p in config.properties if p.name == "recipe")
stopwords = config.inverted_index_config.stopwords
text = "the quick brown fox"
via_property = client.tokenization.for_property(
collection=recipe_collection.name, property_name="recipe", text=text
)
via_generic = client.tokenization.text(
text=text,
tokenization=recipe.tokenization,
stopwords=stopwords,
)
assert via_property.indexed == via_generic.indexed
assert via_property.query == via_generic.query
# ---------------------------------------------------------------------------
# Deserialization
# ---------------------------------------------------------------------------
@pytest.mark.usefixtures("require_1_37")
class TestDeserialization:
"""Verify the client correctly deserializes response fields into TokenizeResult."""
def test_property_result_shape(self, client: weaviate.WeaviateClient) -> None:
"""Property endpoint response deserializes into TokenizeResult — server resolves tokenization from the property's schema."""
client.collections.delete("TestDeserPropTypes")
try:
client.collections.create_from_dict(
{
"class": "TestDeserPropTypes",
"vectorizer": "none",
"properties": [
{
"name": "tag",
"dataType": ["text"],
"tokenization": "field",
},
],
}
)
result = client.tokenization.for_property(
collection="TestDeserPropTypes", property_name="tag", text=" Hello World "
)
assert isinstance(result, TokenizeResult)
assert result.indexed == ["Hello World"]
finally:
client.collections.delete("TestDeserPropTypes")
# ---------------------------------------------------------------------------
# Client-side validation
# ---------------------------------------------------------------------------
class TestClientSideValidation:
"""Verify that client-side validation rejects invalid input before hitting the server."""
@pytest.mark.parametrize(
"kwargs",
[
{"ascii_fold": False, "ascii_fold_ignore": ["é"]},
{"ascii_fold_ignore": ["é"]},
],
ids=["explicit_false", "default"],
)
def test_ascii_fold_ignore_without_fold_raises(self, kwargs: dict) -> None:
with pytest.raises(ValueError, match="asciiFoldIgnore"):
TextAnalyzerConfigCreate(**kwargs)
@pytest.mark.parametrize(
"kwargs,expected",
[
(
{"ascii_fold": True, "ascii_fold_ignore": ["é", "ñ"]},
{"asciiFold": True, "asciiFoldIgnore": ["é", "ñ"]},
),
(
{"ascii_fold": True},
{"asciiFold": True, "asciiFoldIgnore": None},
),
(
{"stopword_preset": "en"},
{"stopwordPreset": "en"},
),
(
{},
{"asciiFold": None, "asciiFoldIgnore": None, "stopwordPreset": None},
),
],
ids=["fold_with_ignore", "fold_without_ignore", "stopword_preset_only", "empty"],
)
def test_valid_config(self, kwargs: dict, expected: dict) -> None:
cfg = TextAnalyzerConfigCreate(**kwargs)
for attr, value in expected.items():
assert getattr(cfg, attr) == value
def test_stopwords_and_stopword_presets_mutex(self, client: weaviate.WeaviateClient) -> None:
"""Client rejects the mutex violation locally with ValueError, before sending the request (which the server would also reject with 422)."""
if client._connection._weaviate_version.is_lower_than(1, 37, 0):
pytest.skip("Tokenization requires Weaviate >= 1.37.0")
with pytest.raises(ValueError, match="mutually exclusive"):
client.tokenization.text(
text="hello",
tokenization=Tokenization.WORD,
stopwords=StopwordsCreate(preset=StopwordsPreset.EN, additions=None, removals=None),
stopword_presets={"custom": ["hello"]},
)
@pytest.mark.parametrize(
"stopword_presets,match",
[
({"custom": "hello"}, "must be a list of strings"),
(
{
"custom": StopwordsCreate(
preset=StopwordsPreset.EN, additions=None, removals=None
),
},
"must be a list of strings",
),
({"custom": ["hello", 123]}, "must contain only strings"),
],
ids=["str_value", "pydantic_model_value", "non_string_element"],
)
def test_stopword_presets_invalid_shape_raises(
self,
client: weaviate.WeaviateClient,
stopword_presets: dict,
match: str,
) -> None:
"""Client rejects malformed stopword_presets values locally before sending — str would silently split into characters; a pydantic model would serialize to field tuples."""
if client._connection._weaviate_version.is_lower_than(1, 37, 0):
pytest.skip("Tokenization requires Weaviate >= 1.37.0")
with pytest.raises(ValueError, match=match):
client.tokenization.text(
text="hello",
tokenization=Tokenization.WORD,
stopword_presets=stopword_presets,
)
# ---------------------------------------------------------------------------
# Version gate
# ---------------------------------------------------------------------------
class TestVersionGate:
"""On Weaviate < 1.37 the client must raise before sending the request."""
def test_text_raises_on_old_server(self, client: weaviate.WeaviateClient) -> None:
if client._connection._weaviate_version.is_at_least(1, 37, 0):
pytest.skip("Version gate only applies to Weaviate < 1.37.0")
with pytest.raises(WeaviateUnsupportedFeatureError):
client.tokenization.text(text="hello", tokenization=Tokenization.WORD)
def test_tokenize_property_raises_on_old_server(self, client: weaviate.WeaviateClient) -> None:
if client._connection._weaviate_version.is_at_least(1, 37, 0):
pytest.skip("Version gate only applies to Weaviate < 1.37.0")
with pytest.raises(WeaviateUnsupportedFeatureError):
client.tokenization.for_property(collection="Any", property_name="title", text="hello")
# ---------------------------------------------------------------------------
# Async client
# ---------------------------------------------------------------------------
@pytest.mark.usefixtures("require_1_37")
class TestAsyncClient:
"""Verify tokenization.text() and tokenization.for_property() work through the async client."""
@pytest.mark.asyncio
async def test_text_tokenize(self, async_client: weaviate.WeaviateAsyncClient) -> None:
result = await async_client.tokenization.text(
text="The quick brown fox",
tokenization=Tokenization.WORD,
)
assert isinstance(result, TokenizeResult)
assert result.indexed == ["the", "quick", "brown", "fox"]
# default "en" applied server-side.
assert result.query == ["quick", "brown", "fox"]
@pytest.mark.asyncio
async def test_text_with_stopwords_fallback(
self, async_client: weaviate.WeaviateAsyncClient
) -> None:
sw = StopwordsCreate(preset=StopwordsPreset.EN, additions=["quick"], removals=None)
result = await async_client.tokenization.text(
text="the quick brown fox",
tokenization=Tokenization.WORD,
stopwords=sw,
)
assert result.indexed == ["the", "quick", "brown", "fox"]
assert result.query == ["brown", "fox"]
@pytest.mark.asyncio
async def test_property_tokenize(self, async_client: weaviate.WeaviateAsyncClient) -> None:
await async_client.collections.delete("TestAsyncPropTokenize")
try:
await async_client.collections.create_from_dict(
{
"class": "TestAsyncPropTokenize",
"vectorizer": "none",
"properties": [
{
"name": "title",
"dataType": ["text"],
"tokenization": "word",
"textAnalyzer": {"stopwordPreset": "en"},
},
],
}
)
result = await async_client.tokenization.for_property(
collection="TestAsyncPropTokenize",
property_name="title",
text="The quick brown fox",
)
assert isinstance(result, TokenizeResult)
assert result.indexed == ["the", "quick", "brown", "fox"]
assert result.query == ["quick", "brown", "fox"]
finally:
await async_client.collections.delete("TestAsyncPropTokenize")