-
Notifications
You must be signed in to change notification settings - Fork 69
/
Copy pathtest_persona.py
546 lines (464 loc) · 20.1 KB
/
test_persona.py
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
import uuid
from pathlib import Path
from typing import List
import pytest
from pydantic import BaseModel, ValidationError
from codegate.db import connection
from codegate.muxing.persona import (
PersonaDoesNotExistError,
PersonaManager,
PersonaSimilarDescriptionError,
)
@pytest.fixture
def db_path():
"""Creates a temporary database file path."""
current_test_dir = Path(__file__).parent
db_filepath = current_test_dir / f"codegate_test_{uuid.uuid4()}.db"
db_fullpath = db_filepath.absolute()
connection.init_db_sync(str(db_fullpath))
yield db_fullpath
if db_fullpath.is_file():
db_fullpath.unlink()
@pytest.fixture()
def db_recorder(db_path) -> connection.DbRecorder:
"""Creates a DbRecorder instance with test database."""
return connection.DbRecorder(sqlite_path=db_path, _no_singleton=True)
@pytest.fixture()
def db_reader(db_path) -> connection.DbReader:
"""Creates a DbReader instance with test database."""
return connection.DbReader(sqlite_path=db_path, _no_singleton=True)
@pytest.fixture()
def semantic_router_mocked_db(
db_recorder: connection.DbRecorder, db_reader: connection.DbReader
) -> PersonaManager:
"""Creates a SemanticRouter instance with mocked database."""
semantic_router = PersonaManager()
semantic_router._db_reader = db_reader
semantic_router._db_recorder = db_recorder
return semantic_router
@pytest.mark.asyncio
async def test_add_persona(semantic_router_mocked_db: PersonaManager):
"""Test adding a persona to the database."""
persona_name = "test_persona"
persona_desc = "test_persona_desc"
await semantic_router_mocked_db.add_persona(persona_name, persona_desc)
retrieved_persona = await semantic_router_mocked_db.get_persona(persona_name)
assert retrieved_persona.name == persona_name
assert retrieved_persona.description == persona_desc
@pytest.mark.asyncio
async def test_add_duplicate_persona(semantic_router_mocked_db: PersonaManager):
"""Test adding a persona to the database."""
persona_name = "test_persona"
persona_desc = "test_persona_desc"
await semantic_router_mocked_db.add_persona(persona_name, persona_desc)
# Update the description to not trigger the similarity check
updated_description = "foo and bar description"
with pytest.raises(connection.AlreadyExistsError):
await semantic_router_mocked_db.add_persona(persona_name, updated_description)
@pytest.mark.asyncio
async def test_add_persona_invalid_name(semantic_router_mocked_db: PersonaManager):
"""Test adding a persona to the database."""
persona_name = "test_persona&"
persona_desc = "test_persona_desc"
with pytest.raises(ValidationError):
await semantic_router_mocked_db.add_persona(persona_name, persona_desc)
with pytest.raises(PersonaDoesNotExistError):
await semantic_router_mocked_db.delete_persona(persona_name)
@pytest.mark.asyncio
async def test_persona_not_exist_match(semantic_router_mocked_db: PersonaManager):
"""Test checking persona match when persona does not exist"""
persona_name = "test_persona"
query = "test_query"
with pytest.raises(PersonaDoesNotExistError):
await semantic_router_mocked_db.check_persona_match(persona_name, [query])
class PersonaMatchTest(BaseModel):
persona_name: str
persona_desc: str
pass_queries: List[str]
fail_queries: List[str]
simple_persona = PersonaMatchTest(
persona_name="test_persona",
persona_desc="test_desc",
pass_queries=["test_desc", "test_desc2"],
fail_queries=["foo"],
)
# Architect Persona
architect = PersonaMatchTest(
persona_name="architect",
persona_desc="""
Expert in designing and planning software systems, technical infrastructure, and solution
architecture.
Specializes in creating scalable, maintainable, and resilient system designs.
Deep knowledge of architectural patterns, principles, and best practices.
Experienced in evaluating technology stacks and making strategic technical decisions.
Skilled at creating architecture diagrams, technical specifications, and system
documentation.
Focuses on both functional and non-functional requirements like performance, security,
and reliability.
Guides development teams on implementing complex systems and following architectural
guidelines.
Designs system architectures that balance business needs with technical constraints.
Creates technical roadmaps and migration strategies for legacy system modernization.
Evaluates trade-offs between different architectural approaches (monolithic, microservices,
serverless).
Implements domain-driven design principles to align software with business domains.
Develops reference architectures and technical standards for organization-wide adoption.
Conducts architecture reviews and provides recommendations for improvement.
Collaborates with stakeholders to translate business requirements into technical solutions.
Stays current with emerging technologies and evaluates their potential application.
Designs for cloud-native environments using containerization, orchestration, and managed
services.
Implements event-driven architectures using message queues, event buses, and streaming
platforms.
Creates data architectures that address storage, processing, and analytics requirements.
Develops integration strategies for connecting disparate systems and services.
""",
pass_queries=[
"""
How should I design a system architecture that can scale with our growing user base?
""",
"""
What's the best approach for migrating our monolithic application to microservices?
""",
"""
I need to create a technical roadmap for modernizing our legacy systems. Where should
I start?
""",
"""
Can you help me evaluate different cloud providers for our new infrastructure?
""",
"""
What architectural patterns would you recommend for a distributed e-commerce platform?
""",
],
fail_queries=[
"""
How do I fix this specific bug in my JavaScript code?
""",
"""
What's the syntax for a complex SQL query joining multiple tables?
""",
"""
How do I implement authentication in my React application?
""",
"""
What's the best way to optimize the performance of this specific function?
""",
],
)
# Coder Persona
coder = PersonaMatchTest(
persona_name="coder",
persona_desc="""
Expert in full stack development, programming, and software implementation.
Specializes in writing, debugging, and optimizing code across the entire technology stack.
Proficient in multiple programming languages including JavaScript, Python, Java, C#, and
TypeScript.
Implements efficient algorithms and data structures to solve complex programming challenges.
Develops maintainable code with appropriate patterns and practices for different contexts.
Experienced in frontend development using modern frameworks and libraries.
Creates responsive, accessible user interfaces with HTML, CSS, and JavaScript frameworks.
Implements state management, component architecture,
and client-side performance optimization for frontend applications.
Skilled in backend development and server-side programming.
Builds RESTful APIs, GraphQL services, and microservices architectures.
Implements authentication, authorization, and security best practices in web applications.
Understands best ways for different backend problems, like file uploads, caching,
and database interactions.
Designs and manages databases including schema design, query optimization,
and data modeling.
Works with both SQL and NoSQL databases to implement efficient data storage solutions.
Creates data access layers and ORM implementations for application data requirements.
Handles integration between different systems and third-party services.
Implements webhooks, API clients, and service communication patterns.
Develops data transformation and processing pipelines for various application needs.
Identifies and resolves performance issues across the application stack.
Uses debugging tools, profilers, and testing frameworks to ensure code quality.
Implements comprehensive testing strategies including unit, integration,
and end-to-end tests.
""",
pass_queries=[
"""
How do I implement authentication in my web application?
""",
"""
What's the best way to structure a RESTful API for my project?
""",
"""
I need help optimizing my database queries for better performance.
""",
"""
How should I implement state management in my frontend application?
""",
"""
What's the differnce between SQL and NoSQL databases, and when should I use each?
""",
],
fail_queries=[
"""
What's the best approach for setting up a CI/CD pipeline for our team?
""",
"""
Can you help me configure auto-scaling for our Kubernetes cluster?
""",
"""
How should I structure our cloud infrastructure for better cost efficiency?
""",
"""
How do I cook a delicious lasagna for dinner?
""",
],
)
# DevOps/SRE Engineer Persona
devops_sre = PersonaMatchTest(
persona_name="devops sre engineer",
persona_desc="""
Expert in infrastructure automation, deployment pipelines, and operational reliability.
Specializes in building and maintaining scalable, resilient, and secure infrastructure.
Proficient with cloud platforms (AWS, Azure, GCP), containerization, and orchestration.
Experienced with infrastructure as code, configuration management, and automation tools.
Skilled in implementing CI/CD pipelines, monitoring systems, and observability solutions.
Focuses on reliability, performance, security, and operational efficiency.
Practices site reliability engineering principles and DevOps methodologies.
Designs and implements cloud infrastructure using services like compute, storage,
networking, and databases.
Creates infrastructure as code using tools like Terraform, CloudFormation, or Pulumi.
Configures and manages container orchestration platforms like Kubernetes and ECS.
Implements CI/CD pipelines using tools like Jenkins, GitHub Actions, GitLab CI, or CircleCI.
Sets up comprehensive monitoring, alerting, and observability solutions.
Implements logging aggregation, metrics collection, and distributed tracing.
Creates dashboards and visualizations for system performance and health.
Designs and implements disaster recovery and backup strategies.
Automates routine operational tasks and infrastructure maintenance.
Conducts capacity planning, performance tuning, and cost optimization.
Implements security best practices, compliance controls, and access management.
Performs incident response, troubleshooting, and post-mortem analysis.
Designs for high availability, fault tolerance, and graceful degradation.
Implements auto-scaling, load balancing, and traffic management solutions.
Creates runbooks, documentation, and operational procedures.
Conducts chaos engineering experiments to improve system resilience.
""",
pass_queries=[
"""
How do I set up a Kubernetes cluster with proper high availability?
""",
"""
What's the best approach for implementing a CI/CD pipeline for our microservices?
""",
"""
How can I automate our infrastructure provisioning using Terraform?
""",
"""
What monitoring metrics should I track to ensure the reliability of our system?
""",
],
fail_queries=[
"""
How do I implement a sorting algorithm in Python?
""",
"""
What's the best way to structure my React components for a single-page application?
""",
"""
Can you help me design a database schema for my e-commerce application?
""",
"""
How do I create a responsive layout using CSS Grid and Flexbox?
""",
"""
What's the most efficient algorithm for finding the shortest path in a graph?
""",
],
)
@pytest.mark.asyncio
@pytest.mark.parametrize(
"persona_match_test",
[
simple_persona,
architect,
coder,
devops_sre,
],
)
async def test_check_persona_pass_match(
semantic_router_mocked_db: PersonaManager, persona_match_test: PersonaMatchTest
):
"""Test checking persona match."""
await semantic_router_mocked_db.add_persona(
persona_match_test.persona_name, persona_match_test.persona_desc
)
# Check for the queries that should pass
for query in persona_match_test.pass_queries:
match = await semantic_router_mocked_db.check_persona_match(
persona_match_test.persona_name, [query]
)
assert match is True
@pytest.mark.asyncio
@pytest.mark.parametrize(
"persona_match_test",
[
simple_persona,
architect,
coder,
devops_sre,
],
)
async def test_check_persona_pass_match_vector(
semantic_router_mocked_db: PersonaManager, persona_match_test: PersonaMatchTest
):
"""Test checking persona match."""
await semantic_router_mocked_db.add_persona(
persona_match_test.persona_name, persona_match_test.persona_desc
)
# We disable the weighting between distances since these are no user messages that
# need to be weighted differently, they all are weighted the same.
semantic_router_mocked_db._distances_weight_factor = 1.0
# Check for match passing the entire list
match = await semantic_router_mocked_db.check_persona_match(
persona_match_test.persona_name, persona_match_test.pass_queries
)
assert match is True
@pytest.mark.asyncio
@pytest.mark.parametrize(
"persona_match_test",
[
simple_persona,
architect,
coder,
devops_sre,
],
)
async def test_check_persona_fail_match(
semantic_router_mocked_db: PersonaManager, persona_match_test: PersonaMatchTest
):
"""Test checking persona match."""
await semantic_router_mocked_db.add_persona(
persona_match_test.persona_name, persona_match_test.persona_desc
)
# Check for the queries that should fail
for query in persona_match_test.fail_queries:
match = await semantic_router_mocked_db.check_persona_match(
persona_match_test.persona_name, [query]
)
assert match is False
@pytest.mark.asyncio
@pytest.mark.parametrize(
"persona_match_test",
[
simple_persona,
architect,
coder,
devops_sre,
],
)
async def test_check_persona_fail_match_vector(
semantic_router_mocked_db: PersonaManager, persona_match_test: PersonaMatchTest
):
"""Test checking persona match."""
await semantic_router_mocked_db.add_persona(
persona_match_test.persona_name, persona_match_test.persona_desc
)
# We disable the weighting between distances since these are no user messages that
# need to be weighted differently, they all are weighted the same.
semantic_router_mocked_db._distances_weight_factor = 1.0
# Check for match passing the entire list
match = await semantic_router_mocked_db.check_persona_match(
persona_match_test.persona_name, persona_match_test.fail_queries
)
assert match is False
@pytest.mark.asyncio
@pytest.mark.parametrize(
"personas",
[
[
coder,
devops_sre,
architect,
]
],
)
async def test_persona_diff_description(
semantic_router_mocked_db: PersonaManager,
personas: List[PersonaMatchTest],
):
# First, add all existing personas
for persona in personas:
await semantic_router_mocked_db.add_persona(persona.persona_name, persona.persona_desc)
last_added_persona = personas[-1]
with pytest.raises(PersonaSimilarDescriptionError):
await semantic_router_mocked_db.add_persona(
"repeated persona", last_added_persona.persona_desc
)
@pytest.mark.asyncio
async def test_update_persona(semantic_router_mocked_db: PersonaManager):
"""Test updating a persona to the database different name and description."""
persona_name = "test_persona"
persona_desc = "test_persona_desc"
await semantic_router_mocked_db.add_persona(persona_name, persona_desc)
updated_description = "foo and bar description"
await semantic_router_mocked_db.update_persona(
persona_name, new_persona_name="new test persona", new_persona_desc=updated_description
)
@pytest.mark.asyncio
async def test_update_persona_same_desc(semantic_router_mocked_db: PersonaManager):
"""Test updating a persona to the database with same description."""
persona_name = "test_persona"
persona_desc = "test_persona_desc"
await semantic_router_mocked_db.add_persona(persona_name, persona_desc)
await semantic_router_mocked_db.update_persona(
persona_name, new_persona_name="new test persona", new_persona_desc=persona_desc
)
@pytest.mark.asyncio
async def test_update_persona_not_exists(semantic_router_mocked_db: PersonaManager):
"""Test updating a persona to the database."""
persona_name = "test_persona"
persona_desc = "test_persona_desc"
with pytest.raises(PersonaDoesNotExistError):
await semantic_router_mocked_db.update_persona(
persona_name, new_persona_name="new test persona", new_persona_desc=persona_desc
)
@pytest.mark.asyncio
async def test_update_persona_same_name(semantic_router_mocked_db: PersonaManager):
"""Test updating a persona to the database."""
persona_name = "test_persona"
persona_desc = "test_persona_desc"
await semantic_router_mocked_db.add_persona(persona_name, persona_desc)
persona_name_2 = "test_persona_2"
persona_desc_2 = "foo and bar"
await semantic_router_mocked_db.add_persona(persona_name_2, persona_desc_2)
with pytest.raises(connection.AlreadyExistsError):
await semantic_router_mocked_db.update_persona(
persona_name_2, new_persona_name=persona_name, new_persona_desc=persona_desc_2
)
@pytest.mark.asyncio
async def test_delete_persona(semantic_router_mocked_db: PersonaManager):
"""Test deleting a persona from the database."""
persona_name = "test_persona"
persona_desc = "test_persona_desc"
await semantic_router_mocked_db.add_persona(persona_name, persona_desc)
await semantic_router_mocked_db.delete_persona(persona_name)
with pytest.raises(PersonaDoesNotExistError):
await semantic_router_mocked_db.get_persona(persona_name)
@pytest.mark.asyncio
async def test_delete_persona_not_exists(semantic_router_mocked_db: PersonaManager):
persona_name = "test_persona"
with pytest.raises(PersonaDoesNotExistError):
await semantic_router_mocked_db.delete_persona(persona_name)
@pytest.mark.asyncio
async def test_get_personas(semantic_router_mocked_db: PersonaManager):
"""Test getting personas from the database."""
persona_name = "test_persona"
persona_desc = "test_persona_desc"
await semantic_router_mocked_db.add_persona(persona_name, persona_desc)
persona_name_2 = "test_persona_2"
persona_desc_2 = "foo and bar"
await semantic_router_mocked_db.add_persona(persona_name_2, persona_desc_2)
all_personas = await semantic_router_mocked_db.get_all_personas()
assert len(all_personas) == 2
assert all_personas[0].name == persona_name
assert all_personas[1].name == persona_name_2
@pytest.mark.asyncio
async def test_get_personas_empty(semantic_router_mocked_db: PersonaManager):
"""Test adding a persona to the database."""
all_personas = await semantic_router_mocked_db.get_all_personas()
assert len(all_personas) == 0