-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy pathtest_search_api.py
More file actions
2290 lines (1944 loc) · 90.3 KB
/
test_search_api.py
File metadata and controls
2290 lines (1944 loc) · 90.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
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import logging
import os
import tempfile
import pandas as pd
import pytest
from fastapi.testclient import TestClient
from feast import Entity, FeatureService, FeatureView, Field, FileSource, RequestSource
from feast.api.registry.rest.rest_registry_server import RestRegistryServer
from feast.feature_store import FeatureStore
from feast.infra.offline_stores.file_source import SavedDatasetFileStorage
from feast.on_demand_feature_view import on_demand_feature_view
from feast.project import Project
from feast.repo_config import RepoConfig
from feast.saved_dataset import SavedDataset
from feast.types import Float64, Int64, String
from feast.value_type import ValueType
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
@pytest.fixture
def search_test_app():
"""Test fixture that sets up a Feast environment with multiple resources for search testing"""
# Create temp registry and data directory
tmp_dir = tempfile.TemporaryDirectory()
registry_path = os.path.join(tmp_dir.name, "registry.db")
# Create dummy parquet files for different data sources
user_data_path = os.path.join(tmp_dir.name, "user_data.parquet")
product_data_path = os.path.join(tmp_dir.name, "product_data.parquet")
transaction_data_path = os.path.join(tmp_dir.name, "transaction_data.parquet")
# Create user data
user_df = pd.DataFrame(
{
"user_id": [1, 2, 3],
"age": [25, 30, 22],
"income": [50000.0, 60000.0, 45000.0],
"event_timestamp": pd.to_datetime(
["2024-01-01", "2024-01-02", "2024-01-03"]
),
}
)
user_df.to_parquet(user_data_path)
# Create product data
product_df = pd.DataFrame(
{
"product_id": [101, 102, 103],
"price": [29.99, 15.99, 99.99],
"category": ["electronics", "books", "electronics"],
"event_timestamp": pd.to_datetime(
["2024-01-01", "2024-01-02", "2024-01-03"]
),
}
)
product_df.to_parquet(product_data_path)
# Create transaction data
transaction_df = pd.DataFrame(
{
"transaction_id": [1001, 1002, 1003],
"amount": [100.0, 50.0, 200.0],
"payment_method": ["credit", "debit", "credit"],
"event_timestamp": pd.to_datetime(
["2024-01-01", "2024-01-02", "2024-01-03"]
),
}
)
transaction_df.to_parquet(transaction_data_path)
# Setup repo config
config = {
"registry": registry_path,
"project": "test_project",
"provider": "local",
"offline_store": {"type": "file"},
"online_store": {"type": "sqlite", "path": ":memory:"},
}
# Create data sources
user_source = FileSource(
name="user_source",
path=user_data_path,
event_timestamp_column="event_timestamp",
)
product_source = FileSource(
name="product_source",
path=product_data_path,
event_timestamp_column="event_timestamp",
)
transaction_source = FileSource(
name="transaction_source",
path=transaction_data_path,
event_timestamp_column="event_timestamp",
)
# Create feature store
store = FeatureStore(config=RepoConfig.model_validate(config))
# Create entities
user_entity = Entity(
name="user",
value_type=ValueType.INT64,
description="User entity for customer data",
tags={"team": "data", "environment": "test"},
)
product_entity = Entity(
name="product",
value_type=ValueType.INT64,
description="Product entity for catalog data",
tags={"team": "product", "environment": "test"},
)
transaction_entity = Entity(
name="transaction",
value_type=ValueType.INT64,
description="Transaction entity for payment data",
tags={"team": "finance", "environment": "test"},
)
# Create feature views
user_features = FeatureView(
name="user_features",
entities=[user_entity],
ttl=None,
schema=[
Field(name="age", dtype=Int64),
Field(name="income", dtype=Float64),
],
source=user_source,
description="User demographic features",
tags={"team": "data", "version": "v1"},
)
product_features = FeatureView(
name="product_features",
entities=[product_entity],
ttl=None,
schema=[
Field(name="price", dtype=Float64),
Field(name="category", dtype=String),
],
source=product_source,
description="Product catalog features",
tags={"team": "product", "version": "v2"},
)
transaction_features = FeatureView(
name="transaction_features",
entities=[transaction_entity],
ttl=None,
schema=[
Field(name="amount", dtype=Float64),
Field(name="payment_method", dtype=String),
],
source=transaction_source,
description="Transaction payment features",
tags={"team": "finance", "version": "v1"},
)
# Create feature services
user_service = FeatureService(
name="user_service",
features=[user_features],
description="Service for user-related features",
tags={"team": "data", "type": "serving"},
)
product_service = FeatureService(
name="product_service",
features=[product_features],
description="Service for product catalog features",
tags={"team": "product", "type": "serving"},
)
# Create an on-demand feature view
request_source = RequestSource(
name="user_request_source",
schema=[
Field(name="user_id", dtype=Int64),
Field(name="conversion_rate", dtype=Float64),
],
)
@on_demand_feature_view(
sources=[user_features, request_source],
schema=[
Field(name="age_conversion_score", dtype=Float64),
],
description="On-demand features combining user features with real-time data",
tags={"team": "data", "type": "real_time", "environment": "test"},
)
def user_on_demand_features(inputs: dict):
# Access individual feature columns directly from inputs
age = inputs["age"] # from user_features feature view
conversion_rate = inputs["conversion_rate"] # from request source
# Create age-based conversion score
age_conversion_score = age * conversion_rate
return pd.DataFrame(
{
"age_conversion_score": age_conversion_score,
}
)
# Create saved datasets
user_dataset_storage = SavedDatasetFileStorage(path=user_data_path)
user_dataset = SavedDataset(
name="user_training_dataset",
features=["user_features:age", "user_features:income"],
join_keys=["user"],
storage=user_dataset_storage,
tags={"environment": "test", "purpose": "training", "team": "data"},
)
# Apply all objects
store.apply(
[
user_entity,
product_entity,
transaction_entity,
user_features,
product_features,
transaction_features,
user_service,
product_service,
user_on_demand_features,
]
)
store.registry.apply_saved_dataset(user_dataset, "test_project")
global global_store
global_store = store
# Build REST app
rest_server = RestRegistryServer(store)
client = TestClient(rest_server.app)
yield client
tmp_dir.cleanup()
@pytest.fixture
def multi_project_search_test_app():
"""Test fixture that sets up multiple projects with overlapping resource names for comprehensive multi-project search testing"""
# Create temp registry and data directory
tmp_dir = tempfile.TemporaryDirectory()
registry_path = os.path.join(tmp_dir.name, "registry.db")
# Create dummy parquet files for different projects with proper entity columns
data_paths = {}
entity_data = {
"project_a": {
"user_id": [1, 2, 3],
"driver_id": [11, 12, 13],
"trip_id": [21, 22, 23],
},
"project_b": {
"user_id": [4, 5, 6],
"restaurant_id": [14, 15, 16],
"order_id": [24, 25, 26],
},
"project_c": {
"customer_id": [7, 8, 9],
"product_id": [17, 18, 19],
"transaction_id": [27, 28, 29],
},
}
for project in ["project_a", "project_b", "project_c"]:
data_paths[project] = os.path.join(tmp_dir.name, f"{project}_data.parquet")
# Create comprehensive data with all entity IDs and feature columns for this project
base_data = {
"event_timestamp": pd.to_datetime(
["2024-01-01", "2024-01-02", "2024-01-03"]
)
}
# Add entity columns for this project
for entity_col, values in entity_data[project].items():
base_data[entity_col] = values
# Add feature columns that will be used by feature views
feature_columns = {
"user_features_value": [10.0, 20.0, 30.0],
"feature_1_value": [11.0, 21.0, 31.0],
"feature_2_value": [12.0, 22.0, 32.0],
"driver_features_value": [13.0, 23.0, 33.0],
"restaurant_features_value": [14.0, 24.0, 34.0],
"customer_analytics_value": [15.0, 25.0, 35.0],
"product_analytics_value": [16.0, 26.0, 36.0],
"sales_features_value": [17.0, 27.0, 37.0],
}
for feature_col, values in feature_columns.items():
base_data[feature_col] = values
df = pd.DataFrame(base_data)
df.to_parquet(data_paths[project])
# Setup projects with overlapping resource names
projects_data = {
"project_a": {
"description": "Ride sharing platform project",
"domain": "transportation",
"entities": [
{"name": "user", "desc": "User entity for ride sharing"},
{"name": "driver", "desc": "Driver entity for ride sharing"},
{"name": "trip", "desc": "Trip entity for ride tracking"},
],
"feature_views": [
{
"name": "user_features",
"desc": "User demographic and rating features for rides",
},
{"name": "driver_features", "desc": "Driver performance and ratings"},
{"name": "trip_features", "desc": "Trip duration and cost features"},
],
"feature_services": [
{
"name": "user_service",
"desc": "Service for user features in ride sharing",
},
{"name": "driver_service", "desc": "Service for driver matching"},
],
"data_sources": [
{"name": "user_data", "desc": "User data source for ride sharing"},
{"name": "common_analytics", "desc": "Common analytics data source"},
],
},
"project_b": {
"description": "Food delivery platform project",
"domain": "food_delivery",
"entities": [
{
"name": "user",
"desc": "User entity for food delivery",
}, # Same name as project_a
{"name": "restaurant", "desc": "Restaurant entity for food delivery"},
{"name": "order", "desc": "Order entity for food tracking"},
],
"feature_views": [
{
"name": "user_features",
"desc": "User preferences and order history for food",
}, # Same name as project_a
{
"name": "restaurant_features",
"desc": "Restaurant ratings and cuisine types",
},
{
"name": "order_features",
"desc": "Order value and delivery time features",
},
],
"feature_services": [
{
"name": "user_service",
"desc": "Service for user features in food delivery",
}, # Same name as project_a
{
"name": "recommendation_service",
"desc": "Service for restaurant recommendations",
},
],
"data_sources": [
{
"name": "restaurant_data",
"desc": "Restaurant data source for food delivery",
},
{
"name": "common_analytics",
"desc": "Common analytics data source",
}, # Same name as project_a
],
},
"project_c": {
"description": "E-commerce analytics project",
"domain": "ecommerce",
"entities": [
{"name": "customer", "desc": "Customer entity for e-commerce"},
{"name": "product", "desc": "Product entity for catalog"},
{"name": "transaction", "desc": "Transaction entity for purchases"},
],
"feature_views": [
{"name": "customer_analytics", "desc": "Customer behavior analytics"},
{"name": "product_analytics", "desc": "Product performance metrics"},
{"name": "sales_features", "desc": "Sales and revenue features"},
],
"feature_services": [
{"name": "analytics_service", "desc": "Service for customer analytics"},
{
"name": "product_service",
"desc": "Service for product recommendations",
},
],
"data_sources": [
{"name": "sales_data", "desc": "Sales transaction data"},
{"name": "inventory_data", "desc": "Product inventory data"},
],
},
}
# Create a single registry to hold all projects
base_config = {
"registry": registry_path,
"provider": "local",
"offline_store": {"type": "file"},
"online_store": {"type": "sqlite", "path": ":memory:"},
}
# Create a master FeatureStore instance for managing the shared registry
master_config = {**base_config, "project": "project_a"} # Use project_a as base
master_store = FeatureStore(config=RepoConfig.model_validate(master_config))
# First, create the Project objects in the registry
for project_name, project_data in projects_data.items():
project_obj = Project(
name=project_name,
description=project_data["description"],
tags={"domain": project_data["domain"]},
)
master_store.registry.apply_project(project_obj)
# Create resources for each project and apply them to the shared registry
for project_name, project_data in projects_data.items():
# Create data sources for this project
data_sources = []
for ds in project_data["data_sources"]:
# Make data source names unique across projects to avoid conflicts
unique_name = (
f"{project_name}_{ds['name']}"
if ds["name"] == "common_analytics"
else ds["name"]
)
source = FileSource(
name=unique_name,
path=data_paths[project_name],
event_timestamp_column="event_timestamp",
)
# Ensure the data source has the correct project set
if hasattr(source, "project"):
source.project = project_name
data_sources.append(source)
# Create entities for this project with proper join keys
entities = []
entity_mapping = {
"project_a": {"user": "user_id", "driver": "driver_id", "trip": "trip_id"},
"project_b": {
"user": "user_id",
"restaurant": "restaurant_id",
"order": "order_id",
},
"project_c": {
"customer": "customer_id",
"product": "product_id",
"transaction": "transaction_id",
},
}
for ent in project_data["entities"]:
join_key = entity_mapping[project_name][ent["name"]]
entity = Entity(
name=ent["name"],
join_keys=[join_key],
value_type=ValueType.INT64, # Add required value_type
description=ent["desc"],
tags={
"project": project_name,
"domain": project_data["domain"],
"environment": "test",
},
)
# Ensure the entity has the correct project set
entity.project = project_name
entities.append(entity)
# Create feature views for this project with proper entity relationships
feature_views = []
# Map feature view names to their corresponding feature columns
feature_column_mapping = {
"user_features": "user_features_value",
"driver_features": "driver_features_value",
"trip_features": "feature_1_value",
"restaurant_features": "restaurant_features_value",
"order_features": "feature_2_value",
"customer_analytics": "customer_analytics_value",
"product_analytics": "product_analytics_value",
"sales_features": "sales_features_value",
}
for i, fv in enumerate(project_data["feature_views"]):
# Alternate between data sources and entities
source = data_sources[i % len(data_sources)]
entity = entities[i % len(entities)] # Use different entities
# Get the correct feature column name for this feature view
feature_column = feature_column_mapping.get(
fv["name"], f"feature_{i}_value"
)
# Get the entity's join key for the schema
entity_join_key = entity.join_key
feature_view = FeatureView(
name=fv["name"],
entities=[entity],
ttl=None,
schema=[
# Include entity column in schema
Field(name=entity_join_key, dtype=Int64),
# Include feature column in schema
Field(name=feature_column, dtype=Float64),
],
source=source,
description=fv["desc"],
tags={
"project": project_name,
"domain": project_data["domain"],
"team": f"team_{project_name}",
"version": f"v{i + 1}",
},
)
# Ensure the feature view has the correct project set
feature_view.project = project_name
feature_views.append(feature_view)
# Create feature services for this project
feature_services = []
for i, fs in enumerate(project_data["feature_services"]):
# Use different feature views for each service
fv_subset = (
feature_views[i : i + 2]
if i + 1 < len(feature_views)
else [feature_views[i]]
)
service = FeatureService(
name=fs["name"],
features=fv_subset,
description=fs["desc"],
tags={
"project": project_name,
"domain": project_data["domain"],
"service_type": "real_time",
},
)
# Ensure the feature service has the correct project set
service.project = project_name
feature_services.append(service)
# Apply all objects for this project directly to the registry
for entity in entities:
master_store.registry.apply_entity(entity, project_name)
for data_source in data_sources:
master_store.registry.apply_data_source(data_source, project_name)
for feature_view in feature_views:
master_store.registry.apply_feature_view(feature_view, project_name)
for feature_service in feature_services:
master_store.registry.apply_feature_service(feature_service, project_name)
# Ensure registry is committed
master_store.registry.commit()
# Build REST app using the master store's registry (contains all projects)
rest_server = RestRegistryServer(master_store)
client = TestClient(rest_server.app)
yield client
tmp_dir.cleanup()
@pytest.fixture
def shared_search_responses(search_test_app):
"""Pre-computed responses for common search scenarios to reduce API calls"""
return {
"user_query": search_test_app.get("/search?query=user").json(),
"empty_query": search_test_app.get("/search?query=").json(),
"nonexistent_query": search_test_app.get("/search?query=xyz_12345").json(),
"paginated_basic": search_test_app.get("/search?query=&page=1&limit=5").json(),
"paginated_page2": search_test_app.get("/search?query=&page=2&limit=3").json(),
"sorted_by_name": search_test_app.get(
"/search?query=&sort_by=name&sort_order=asc"
).json(),
"sorted_by_match_score": search_test_app.get(
"/search?query=user&sort_by=match_score&sort_order=desc"
).json(),
"with_tags": search_test_app.get("/search?query=&tags=team:data").json(),
"feature_name_query": search_test_app.get("/search?query=age").json(),
}
class TestSearchAPI:
"""Test class for the comprehensive search API"""
def test_search_user_query_comprehensive(self, shared_search_responses):
"""Comprehensive test for user query validation - combines multiple test scenarios"""
data = shared_search_responses["user_query"]
# Test response structure (replaces test_search_all_resources_with_query)
assert "results" in data
assert "pagination" in data
assert "query" in data
assert "projects_searched" in data
assert "errors" in data
assert data["query"] == "user"
# Test pagination structure
pagination = data["pagination"]
assert pagination["totalCount"] > 0
assert pagination["totalPages"] > 0
assert pagination["page"] == 1
assert pagination["limit"] == 50
# Test results content
results = data["results"]
assert len(results) > 0
result = results[0]
required_result_fields = [
"type",
"name",
"description",
"project",
"match_score",
]
for field in required_result_fields:
assert field in result
# Log for debugging
type_counts = {}
for r in results:
result_type = r.get("type", "unknown")
type_counts[result_type] = type_counts.get(result_type, 0) + 1
logger.debug(f"Found {len(results)} results:")
for r in results:
logger.debug(
f" - {r['type']}: {r['name']} (score: {r.get('match_score', 'N/A')})"
)
# Test that we found expected resources
resource_names = [r["name"] for r in results]
assert "user" in resource_names # user entity
# Test feature views
feature_view_names = [r["name"] for r in results if r["type"] == "featureView"]
if feature_view_names:
assert "user_features" in feature_view_names
else:
logging.warning(
"No feature views found in search results - this may indicate a search API issue"
)
# Test cross-project functionality (replaces test_search_cross_project_when_no_project_specified)
assert len(data["projects_searched"]) >= 1
assert "test_project" in data["projects_searched"]
def test_search_with_project_filter(self, search_test_app):
"""Test searching within a specific project"""
response = search_test_app.get("/search?query=user&projects=test_project")
assert response.status_code == 200
data = response.json()
assert data["projects_searched"] == ["test_project"]
results = data["results"]
# All results should be from test_project
for result in results:
if "project" in result:
assert result["project"] == "test_project"
def test_search_by_description(self, search_test_app):
"""Test searching by description content"""
response = search_test_app.get("/search?query=demographic")
assert response.status_code == 200
data = response.json()
results = data["results"]
# Debug: Show what we found
logger.debug(f"Search for 'demographic' returned {len(results)} results:")
for r in results:
logger.debug(
f" - {r['type']}: {r['name']} - '{r.get('description', '')}' (score: {r.get('match_score', 'N/A')})"
)
# Should find user_features which has "demographic" in description
feature_view_names = [r["name"] for r in results if r["type"] == "featureView"]
if len(feature_view_names) > 0:
assert "user_features" in feature_view_names
else:
# If no feature views found, check if any resources have "demographic" in description
demographic_resources = [
r for r in results if "demographic" in r.get("description", "").lower()
]
if len(demographic_resources) == 0:
logger.warning(
"No resources found with 'demographic' in description - search may not be working properly"
)
def test_search_by_tags(self, shared_search_responses):
"""Test searching by tag content"""
# Get tags filtered results
tags_data = shared_search_responses["with_tags"]
logger.debug(f"Tags data: {tags_data}")
results = tags_data["results"]
assert len(results) > 0
# Should find user-related resources that also have "team": "data" tag
expected_resources = {"user", "user_features", "user_service"}
found_resources = {r["name"] for r in results}
# Check intersection rather than strict subset (more flexible)
found_expected = expected_resources.intersection(found_resources)
assert len(found_expected) > 0, (
f"Expected to find some of {expected_resources} but found none in {found_resources}"
)
def test_search_matched_tags_exact_match(self, search_test_app):
"""Test that matched_tags field is present when a tag matches exactly"""
# Search for "data" which should match tag key "team" with value "data"
response = search_test_app.get("/search?query=data")
assert response.status_code == 200
data = response.json()
results = data["results"]
# Find results that matched via tags (match_score = 60)
tag_matched_results = [
r for r in results if r.get("match_score") == 60 and "matched_tags" in r
]
assert len(tag_matched_results) > 0, (
"Expected to find at least one result with matched_tags from tag matching"
)
# Verify matched_tags is present and has a valid dictionary value
for result in tag_matched_results:
matched_tags = result.get("matched_tags")
assert matched_tags is not None, (
f"matched_tags should not be None for result {result['name']}"
)
assert isinstance(matched_tags, dict), (
f"matched_tags should be a dictionary, got {type(matched_tags)}"
)
# matched_tags should be a non-empty dict for tag-matched results
assert len(matched_tags) > 0, (
"matched_tags should not be empty for tag matches"
)
logger.debug(
f"Found {len(tag_matched_results)} results with matched_tags: {[r['name'] + ' -> ' + str(r.get('matched_tags', 'N/A')) for r in tag_matched_results]}"
)
def test_search_matched_tags_multiple_tags(self, search_test_app):
"""Test that multiple matching tags are returned in matched_tags"""
# Search for "a" which should match:
# - Names containing "a" (e.g., user_training_dataset, data sources)
# - Tags where key/value contains "a": "team" (key), "data" (value), "training" (value)
response = search_test_app.get("/search?query=a")
logger.info(response.json())
assert response.status_code == 200
data = response.json()
results = data["results"]
# Find user_training_dataset which has tags: {"environment": "test", "purpose": "training", "team": "data"}
# "team" contains "a", "data" contains "a", "training" contains "a"
# So matched_tags should have at least 2 entries: "purpose" and "team"
dataset_results = [
r for r in results if r.get("name") == "user_training_dataset"
]
assert len(dataset_results) > 0, (
"Expected to find user_training_dataset in results"
)
dataset_result = dataset_results[0]
matched_tags = dataset_result.get("matched_tags", {})
assert isinstance(matched_tags, dict), (
f"matched_tags should be a dictionary, got {type(matched_tags)}"
)
# Should have multiple matching tags: "purpose" and "team"
assert len(matched_tags) >= 2, (
f"Expected at least 2 matching tags for 'a' query, got {len(matched_tags)}: {matched_tags}"
)
# Verify the expected tags are present
assert "team" in matched_tags and "purpose" in matched_tags, (
f"Expected 'team' and 'purpose' in matched_tags, got: {matched_tags}"
)
logger.debug(f"user_training_dataset matched_tags: {matched_tags}")
def test_search_matched_tags_fuzzy_match(self, search_test_app):
"""Test that matched_tags field is present when a tag matches via fuzzy matching"""
# Search for "te" which should fuzzy match tag key "team"
# "te" vs "team": overlap={'t','e'}/union={'t','e','a','m'} = 2/4 = 50% (below threshold)
# Try "tea" which should fuzzy match "team" better
# "tea" vs "team": overlap={'t','e','a'}/union={'t','e','a','m'} = 3/4 = 75% (above threshold)
response = search_test_app.get("/search?query=tea")
assert response.status_code == 200
data = response.json()
results = data["results"]
# Find results that matched via fuzzy tag matching (match_score < 60 but >= 40)
fuzzy_tag_matched_results = [
r
for r in results
if r.get("match_score", 0) >= 40
and r.get("match_score", 0) < 60
and "matched_tags" in r
]
# If we don't find fuzzy matches, try a different query that's more likely to match
if len(fuzzy_tag_matched_results) == 0:
# Try "dat" which should fuzzy match tag value "data"
# "dat" vs "data": overlap={'d','a','t'}/union={'d','a','t','a'} = 3/4 = 75% (above threshold)
response = search_test_app.get("/search?query=dat")
assert response.status_code == 200
data = response.json()
results = data["results"]
fuzzy_tag_matched_results = [
r
for r in results
if r.get("match_score", 0) >= 40
and r.get("match_score", 0) < 60
and "matched_tags" in r
]
if len(fuzzy_tag_matched_results) > 0:
# Verify matched_tags is present for fuzzy matches
for result in fuzzy_tag_matched_results:
matched_tags = result.get("matched_tags")
assert matched_tags is not None, (
f"matched_tags should not be None for fuzzy-matched result {result['name']}"
)
assert isinstance(matched_tags, dict), (
f"matched_tags should be a dictionary, got {type(matched_tags)}"
)
assert len(matched_tags) > 0, (
"matched_tags should not be empty for fuzzy tag matches"
)
# Verify the match_score is in the fuzzy range
assert 40 <= result.get("match_score", 0) < 60, (
f"Fuzzy tag match should have score in [40, 60), got {result.get('match_score')}"
)
logger.debug(
f"Found {len(fuzzy_tag_matched_results)} results with fuzzy matched_tags: {[r['name'] + ' -> ' + str(r.get('matched_tags', 'N/A')) + ' (score: ' + str(r.get('match_score', 'N/A')) + ')' for r in fuzzy_tag_matched_results]}"
)
def test_search_sorting_functionality(self, shared_search_responses):
"""Test search results sorting using pre-computed responses"""
# Test match_score descending sort
match_score_data = shared_search_responses["sorted_by_match_score"]
results = match_score_data["results"]
if len(results) > 1:
for i in range(len(results) - 1):
current_score = results[i].get("match_score", 0)
next_score = results[i + 1].get("match_score", 0)
assert current_score >= next_score, (
"Results not sorted descending by match_score"
)
# Test name ascending sort
name_data = shared_search_responses["sorted_by_name"]
results = name_data["results"]
if len(results) > 1:
for i in range(len(results) - 1):
current_name = results[i].get("name", "")
next_name = results[i + 1].get("name", "")
assert current_name <= next_name, "Results not sorted ascending by name"
def test_search_query_functionality(self, shared_search_responses):
"""Test basic search functionality with different query types using shared responses"""
# Test empty query returns all resources
empty_data = shared_search_responses["empty_query"]
assert len(empty_data["results"]) > 0
assert empty_data["query"] == ""
results = empty_data["results"]
# Get all resource types returned
returned_types = set(result["type"] for result in results)
# Should include all expected resource types (including new 'feature' type)
expected_types = {
"entity",
"featureView",
"feature",
"featureService",
"dataSource",
"savedDataset",
}
# All expected types should be present (or at least no filtering happening)
# Note: Some types might not exist in test data, but if they do exist, they should all be returned
available_types_in_data = expected_types.intersection(returned_types)
assert len(available_types_in_data) >= 4, (
f"Expected multiple resource types in results, but only got {returned_types}. "
"All available resource types should be searched."
)
# Verify feature result structure
for result in results:
# Check required fields
assert "type" in result
assert "name" in result
assert "description" in result
assert "project" in result
# Get all feature results
feature_results = [result for result in results if result["type"] == "feature"]
# Should have individual features in search results
assert len(feature_results) > 0, (
"Expected individual features to appear in search results, but found none"
)
for feature_result in feature_results:
assert "featureView" in feature_result
assert feature_result["featureView"] in [
"user_features",
"product_features",
"transaction_features",
"user_on_demand_features",
]
# Verify we have features that likely come from different feature views
feature_names = {f["name"] for f in feature_results}
# Based on test fixture features: age, income (from user_features), price, category (from product_features),
# amount, payment_method (from transaction_features)
expected_features = {
"age",
"income",
"price",
"category",
"amount",
"payment_method",
}
found_features = expected_features.intersection(feature_names)
assert len(found_features) >= 3, (
f"Expected features from multiple feature views, but only found features: {feature_names}. "
f"Expected to find at least 3 of: {expected_features}"
)
# Get all feature view results to understand the source feature views
feature_view_results = [
result for result in results if result["type"] == "featureView"
]
feature_view_names = {fv["name"] for fv in feature_view_results}
# Based on test fixture: user_features, product_features, transaction_features
expected_feature_views = {
"user_features",
"product_features",
"transaction_features",
}
# Should have feature views from test fixture
found_feature_views = expected_feature_views.intersection(feature_view_names)
assert len(found_feature_views) >= 2, (
f"Expected features from multiple feature views, but only found feature views: {feature_view_names}. "
f"Expected to find some of: {expected_feature_views}"
)
# Test nonexistent query
nonexistent_data = shared_search_responses["nonexistent_query"]
logger.debug(f"Nonexistent data: {nonexistent_data}")
assert len(nonexistent_data["results"]) == 0
# Search for a specific feature name 'age'
age_feature_response = shared_search_responses["feature_name_query"]
results = age_feature_response["results"]