File size: 26,523 Bytes
cc036ff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Artifact Routes Test Suite

Comprehensive test coverage for artifact version control routes (artifact_routes.py).

Target Coverage: 75%+ line coverage for api/artifact_routes.py

Scope:
- Artifact listing with filters (session_id, type, workspace_id)
- Artifact creation (save) with optional fields
- Artifact updates with versioning (version records created)
- Artifact version history retrieval
- Authentication required for all endpoints
- Error paths (validation 422, not found 404)

Test Fixtures:
- In-memory SQLite database with manually created tables
- Mock User object (NOT real model - avoids SQLAlchemy relationship issues)
- TestClient with auth and DB overrides
- Factory fixtures for test data

External Services: None (all tests use database)
"""

import pytest
from unittest.mock import MagicMock
from datetime import datetime
from fastapi import FastAPI
from fastapi.testclient import TestClient
from sqlalchemy import create_engine, text
from sqlalchemy.orm import sessionmaker, Session
from sqlalchemy.pool import StaticPool

# Import router
from api.artifact_routes import router
from core.database import get_db
from core.security_dependencies import get_current_user

# Import models for type hints
from core.models import Artifact, ArtifactVersion


# ============================================================================
# Fixtures
# ============================================================================

@pytest.fixture(scope="function")
def test_db():
    """
    In-memory SQLite database with manually created tables.

    We create Artifact and ArtifactVersion tables manually using raw SQL to avoid
    JSONB compatibility issues with SQLite (PackageInstallation uses JSONB which
    SQLite doesn't support).
    """
    engine = create_engine(
        "sqlite:///:memory:",
        connect_args={"check_same_thread": False},
        poolclass=StaticPool,
    )

    # Create tables manually using raw SQL
    with engine.connect() as conn:
        # Create artifacts table (all columns from core.models.Artifact)
        # Using CURRENT_TIMESTAMP as default for datetime fields
        conn.execute(text("""
            CREATE TABLE artifacts (
                id VARCHAR PRIMARY KEY,
                workspace_id VARCHAR NOT NULL,
                tenant_id VARCHAR NOT NULL,
                agent_id VARCHAR,
                session_id VARCHAR,
                canvas_id VARCHAR,
                name VARCHAR NOT NULL,
                type VARCHAR NOT NULL,
                content TEXT NOT NULL,
                metadata_json TEXT DEFAULT '{}',
                version INTEGER DEFAULT 1,
                is_locked BOOLEAN DEFAULT 0,
                locked_by_user_id VARCHAR,
                author_id VARCHAR,
                created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
                updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
            )
        """))

        # Create artifact_versions table (all columns from core.models.ArtifactVersion)
        conn.execute(text("""
            CREATE TABLE artifact_versions (
                id VARCHAR PRIMARY KEY,
                artifact_id VARCHAR NOT NULL,
                version INTEGER NOT NULL,
                content TEXT NOT NULL,
                metadata_json TEXT DEFAULT '{}',
                author_id VARCHAR,
                created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
                FOREIGN KEY(artifact_id) REFERENCES artifacts(id)
            )
        """))

        conn.commit()

    TestingSessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

    db = TestingSessionLocal()
    try:
        yield db
    finally:
        db.close()


@pytest.fixture(scope="function")
def mock_user():
    """
    Mock User object for authentication.

    Using MagicMock instead of real User model avoids SQLAlchemy relationship issues
    (Artifact.author relationship causes NoForeignKeysError with real User instances).
    """
    user = MagicMock(spec=["id", "email", "created_at"])
    user.id = "test_user_1"
    user.email = "test@example.com"
    user.created_at = datetime.now()
    return user


@pytest.fixture(scope="function")
def authenticated_client(test_db, mock_user):
    """
    TestClient with authentication and database overrides.

    This fixture overrides both get_current_user (returns mock_user) and get_db (returns test_db),
    allowing authenticated requests to the artifact routes.
    """
    app = FastAPI()
    app.include_router(router)

    # Override dependencies
    def override_get_db():
        try:
            yield test_db
        finally:
            pass

    def override_get_current_user():
        return mock_user

    app.dependency_overrides[get_db] = override_get_db
    app.dependency_overrides[get_current_user] = override_get_current_user

    client = TestClient(app)

    yield client

    # Clean up
    app.dependency_overrides.clear()


@pytest.fixture(scope="function")
def unauthenticated_client(test_db):
    """
    TestClient without authentication override.

    This fixture overrides get_db but NOT get_current_user, triggering 401 Unauthorized responses.
    """
    app = FastAPI()
    app.include_router(router)

    # Override only database dependency
    def override_get_db():
        try:
            yield test_db
        finally:
            pass

    app.dependency_overrides[get_db] = override_get_db
    # DO NOT override get_current_user - this triggers authentication error

    client = TestClient(app)

    yield client

    # Clean up
    app.dependency_overrides.clear()


@pytest.fixture(scope="function")
def sample_artifact_data():
    """
    Factory for valid ArtifactCreate request data.

    Returns a dict with all fields for creating an artifact.
    """
    return {
        "name": "test_artifact",
        "type": "code",
        "content": "print('hello world')",
        "metadata_json": {"language": "python"},
        "session_id": "test_session_1",
        "agent_id": "test_agent_1"
    }


@pytest.fixture(scope="function")
def sample_artifact(test_db, mock_user):
    """
    Artifact model fixture for database insertion.

    Creates a real Artifact instance in the database for testing.
    """
    artifact = Artifact(
        id="test_artifact_1",
        workspace_id="default",
        tenant_id="default_tenant",  # Required field
        agent_id="test_agent_1",
        session_id="test_session_1",
        name="Test Artifact",
        type="code",
        content="print('hello')",
        metadata_json={"language": "python"},
        version=1,
        is_locked=False,
        author_id=mock_user.id,
        created_at=datetime.now(),
        updated_at=datetime.now()
    )
    test_db.add(artifact)
    test_db.commit()
    test_db.refresh(artifact)
    return artifact


# ============================================================================
# Test Artifact List
# ============================================================================

class TestArtifactList:
    """Test artifact listing endpoint with various filters."""

    def test_list_artifacts_success(self, authenticated_client, test_db, mock_user):
        """Test listing all artifacts returns 200 with artifact list."""
        # Create 3 test artifacts
        for i in range(3):
            artifact = Artifact(
                id=f"artifact_{i}",
                workspace_id="default",
                tenant_id="default_tenant",  # Required field
                name=f"Artifact {i}",
                type="code",
                content=f"content_{i}",
                version=1,
                author_id=mock_user.id
            )
            test_db.add(artifact)
        test_db.commit()

        # List artifacts
        response = authenticated_client.get("/api/artifacts/")

        assert response.status_code == 200
        artifacts = response.json()
        assert len(artifacts) == 3
        # Check response fields (workspace_id and tenant_id not in ArtifactResponse)
        assert all("id" in a for a in artifacts)
        assert all("name" in a for a in artifacts)

    def test_list_artifacts_filter_by_session(self, authenticated_client, test_db, mock_user):
        """Test filtering artifacts by session_id."""
        # Create artifacts with different session_id values
        artifact1 = Artifact(
            id="artifact_1",
            workspace_id="default",
            tenant_id="default_tenant",  # Required field
            session_id="session_A",
            name="Artifact A",
            type="code",
            content="content_A",
            version=1,
            author_id=mock_user.id
        )
        artifact2 = Artifact(
            id="artifact_2",
            workspace_id="default",
            tenant_id="default_tenant",  # Required field
            session_id="session_B",
            name="Artifact B",
            type="code",
            content="content_B",
            version=1,
            author_id=mock_user.id
        )
        test_db.add_all([artifact1, artifact2])
        test_db.commit()

        # Filter by session_id
        response = authenticated_client.get("/api/artifacts/?session_id=session_A")

        assert response.status_code == 200
        artifacts = response.json()
        assert len(artifacts) == 1
        assert artifacts[0]["session_id"] == "session_A"

    def test_list_artifacts_filter_by_type(self, authenticated_client, test_db, mock_user):
        """Test filtering artifacts by type."""
        # Create artifacts with different types
        artifact1 = Artifact(
            id="artifact_1",
            workspace_id="default",
            tenant_id="default_tenant",  # Required field
            name="Code Artifact",
            type="code",
            content="python code",
            version=1,
            author_id=mock_user.id
        )
        artifact2 = Artifact(
            id="artifact_2",
            workspace_id="default",
            tenant_id="default_tenant",  # Required field
            name="Markdown Artifact",
            type="markdown",
            content="# markdown",
            version=1,
            author_id=mock_user.id
        )
        test_db.add_all([artifact1, artifact2])
        test_db.commit()

        # Filter by type
        response = authenticated_client.get("/api/artifacts/?type=code")

        assert response.status_code == 200
        artifacts = response.json()
        assert len(artifacts) == 1
        assert artifacts[0]["type"] == "code"

    def test_list_artifacts_combined_filters(self, authenticated_client, test_db, mock_user):
        """Test filtering artifacts by both session_id and type."""
        # Create artifacts with mixed attributes
        artifact1 = Artifact(
            id="artifact_1",
            workspace_id="default",
            tenant_id="default_tenant",  # Required field
            session_id="session_A",
            name="Code A",
            type="code",
            content="code_A",
            version=1,
            author_id=mock_user.id
        )
        artifact2 = Artifact(
            id="artifact_2",
            workspace_id="default",
            tenant_id="default_tenant",  # Required field
            session_id="session_A",
            name="Markdown A",
            type="markdown",
            content="md_A",
            version=1,
            author_id=mock_user.id
        )
        artifact3 = Artifact(
            id="artifact_3",
            workspace_id="default",
            tenant_id="default_tenant",  # Required field
            session_id="session_B",
            name="Code B",
            type="code",
            content="code_B",
            version=1,
            author_id=mock_user.id
        )
        test_db.add_all([artifact1, artifact2, artifact3])
        test_db.commit()

        # Filter by both session_id and type
        response = authenticated_client.get("/api/artifacts/?session_id=session_A&type=code")

        assert response.status_code == 200
        artifacts = response.json()
        assert len(artifacts) == 1
        assert artifacts[0]["session_id"] == "session_A"
        assert artifacts[0]["type"] == "code"

    def test_list_artifacts_empty(self, authenticated_client, test_db):
        """Test listing artifacts when database is empty."""
        # No artifacts in database
        response = authenticated_client.get("/api/artifacts/")

        assert response.status_code == 200
        artifacts = response.json()
        assert len(artifacts) == 0


# ============================================================================
# Test Artifact Save
# ============================================================================

class TestArtifactSave:
    """Test artifact creation (save) endpoint."""

    def test_save_artifact_success(self, authenticated_client, sample_artifact_data):
        """Test creating an artifact with valid data returns 200."""
        response = authenticated_client.post("/api/artifacts/", json=sample_artifact_data)

        assert response.status_code == 200
        artifact = response.json()
        assert "id" in artifact
        assert artifact["name"] == sample_artifact_data["name"]
        assert artifact["type"] == sample_artifact_data["type"]
        assert artifact["content"] == sample_artifact_data["content"]
        assert artifact["version"] == 1
        # Note: workspace_id and tenant_id not in ArtifactResponse

    def test_save_artifact_with_agent_id(self, authenticated_client, sample_artifact_data):
        """Test creating artifact with agent_id field."""
        response = authenticated_client.post("/api/artifacts/", json=sample_artifact_data)

        assert response.status_code == 200
        artifact = response.json()
        assert artifact["agent_id"] == sample_artifact_data["agent_id"]

    def test_save_artifact_with_metadata(self, authenticated_client, sample_artifact_data):
        """Test creating artifact with metadata_json field."""
        response = authenticated_client.post("/api/artifacts/", json=sample_artifact_data)

        assert response.status_code == 200
        artifact = response.json()
        assert artifact["metadata_json"] == sample_artifact_data["metadata_json"]

    def test_save_artifact_minimal(self, authenticated_client):
        """Test creating artifact with only required fields."""
        minimal_data = {
            "name": "minimal_artifact",
            "type": "markdown",
            "content": "# Minimal"
        }

        response = authenticated_client.post("/api/artifacts/", json=minimal_data)

        assert response.status_code == 200
        artifact = response.json()
        assert artifact["name"] == "minimal_artifact"
        assert artifact["version"] == 1
        # Note: workspace_id and tenant_id not in ArtifactResponse
        # Optional fields should be None or default
        assert artifact["session_id"] is None

    def test_save_artifact_author_assigned(self, authenticated_client, mock_user, sample_artifact_data):
        """Test that author_id is set to authenticated user ID."""
        response = authenticated_client.post("/api/artifacts/", json=sample_artifact_data)

        assert response.status_code == 200
        artifact = response.json()
        assert artifact["author_id"] == mock_user.id


# ============================================================================
# Test Artifact Update
# ============================================================================

class TestArtifactUpdate:
    """Test artifact update endpoint with versioning."""

    def test_update_artifact_name(self, authenticated_client, test_db, sample_artifact):
        """Test updating artifact name increments version."""
        update_data = {
            "id": sample_artifact.id,
            "name": "Updated Artifact Name"
        }

        response = authenticated_client.post("/api/artifacts/update", json=update_data)

        assert response.status_code == 200
        artifact = response.json()
        assert artifact["name"] == "Updated Artifact Name"
        assert artifact["version"] == 2  # Version incremented

    def test_update_artifact_content(self, authenticated_client, test_db, sample_artifact):
        """Test updating artifact content increments version."""
        update_data = {
            "id": sample_artifact.id,
            "content": "print('updated content')"
        }

        response = authenticated_client.post("/api/artifacts/update", json=update_data)

        assert response.status_code == 200
        artifact = response.json()
        assert artifact["content"] == "print('updated content')"
        assert artifact["version"] == 2

    def test_update_artifact_metadata(self, authenticated_client, test_db, sample_artifact):
        """Test updating artifact metadata increments version."""
        new_metadata = {"language": "python", "version": "3.11"}
        update_data = {
            "id": sample_artifact.id,
            "metadata_json": new_metadata
        }

        response = authenticated_client.post("/api/artifacts/update", json=update_data)

        assert response.status_code == 200
        artifact = response.json()
        assert artifact["metadata_json"] == new_metadata
        assert artifact["version"] == 2

    def test_update_creates_version_record(self, authenticated_client, test_db, sample_artifact, mock_user):
        """Test that update creates ArtifactVersion record with old content."""
        # Verify initial state
        assert sample_artifact.version == 1
        assert sample_artifact.content == "print('hello')"

        # Update content
        update_data = {
            "id": sample_artifact.id,
            "content": "print('updated')"
        }

        response = authenticated_client.post("/api/artifacts/update", json=update_data)

        assert response.status_code == 200

        # Verify artifact updated
        updated_artifact = test_db.query(Artifact).filter(Artifact.id == sample_artifact.id).first()
        assert updated_artifact.version == 2
        assert updated_artifact.content == "print('updated')"

        # Verify ArtifactVersion record created
        versions = test_db.query(ArtifactVersion).filter(
            ArtifactVersion.artifact_id == sample_artifact.id
        ).all()
        assert len(versions) == 1
        assert versions[0].version == 1  # Old version stored
        assert versions[0].content == "print('hello')"  # Old content stored

    def test_update_multiple_fields(self, authenticated_client, test_db, sample_artifact):
        """Test updating name, content, and metadata together."""
        update_data = {
            "id": sample_artifact.id,
            "name": "Multi Update",
            "content": "new content",
            "metadata_json": {"key": "value"}
        }

        response = authenticated_client.post("/api/artifacts/update", json=update_data)

        assert response.status_code == 200
        artifact = response.json()
        assert artifact["name"] == "Multi Update"
        assert artifact["content"] == "new content"
        assert artifact["metadata_json"] == {"key": "value"}
        assert artifact["version"] == 2

        # Verify single version record created
        versions = test_db.query(ArtifactVersion).filter(
            ArtifactVersion.artifact_id == sample_artifact.id
        ).all()
        assert len(versions) == 1


# ============================================================================
# Test Artifact Versions
# ============================================================================

class TestArtifactVersions:
    """Test artifact version history retrieval."""

    def test_get_artifact_versions_success(self, authenticated_client, test_db, sample_artifact):
        """Test retrieving version history returns all versions ordered desc."""
        # Update artifact twice to create 2 version records
        for i in range(2):
            update_data = {
                "id": sample_artifact.id,
                "content": f"update_{i}"
            }
            authenticated_client.post("/api/artifacts/update", json=update_data)

        # Get versions
        response = authenticated_client.get(f"/api/artifacts/{sample_artifact.id}/versions")

        assert response.status_code == 200
        versions = response.json()
        assert len(versions) == 2
        # Verify ordered by version desc (version 2, then version 1)
        assert versions[0]["version"] == 2
        assert versions[1]["version"] == 1

    def test_get_artifact_versions_empty(self, authenticated_client, sample_artifact):
        """Test retrieving versions for artifact with no updates."""
        # Artifact never updated - no version records
        response = authenticated_client.get(f"/api/artifacts/{sample_artifact.id}/versions")

        assert response.status_code == 200
        versions = response.json()
        assert len(versions) == 0

    def test_get_artifact_versions_content_preserved(self, authenticated_client, test_db, sample_artifact):
        """Test that version records preserve old content."""
        # Store original content
        original_content = sample_artifact.content

        # Update artifact
        update_data = {
            "id": sample_artifact.id,
            "content": "updated content"
        }
        authenticated_client.post("/api/artifacts/update", json=update_data)

        # Get versions
        response = authenticated_client.get(f"/api/artifacts/{sample_artifact.id}/versions")

        assert response.status_code == 200
        versions = response.json()
        assert len(versions) == 1

        # Verify version record has old content
        assert versions[0]["content"] == original_content

        # Verify current artifact has new content
        current_artifact = test_db.query(Artifact).filter(Artifact.id == sample_artifact.id).first()
        assert current_artifact.content == "updated content"


# ============================================================================
# Test Artifact Authentication
# ============================================================================

class TestArtifactAuth:
    """Test that all artifact endpoints require authentication."""

    def test_list_requires_auth(self, unauthenticated_client):
        """Test GET /api/artifacts/ requires authentication."""
        response = unauthenticated_client.get("/api/artifacts/")

        assert response.status_code == 401

    def test_save_requires_auth(self, unauthenticated_client):
        """Test POST /api/artifacts/ requires authentication."""
        artifact_data = {
            "name": "test",
            "type": "code",
            "content": "test content"
        }
        response = unauthenticated_client.post("/api/artifacts/", json=artifact_data)

        assert response.status_code == 401

    def test_update_requires_auth(self, unauthenticated_client):
        """Test POST /api/artifacts/update requires authentication."""
        update_data = {
            "id": "some_id",
            "name": "updated"
        }
        response = unauthenticated_client.post("/api/artifacts/update", json=update_data)

        assert response.status_code == 401

    def test_versions_requires_auth(self, unauthenticated_client):
        """Test GET /api/artifacts/{id}/versions requires authentication."""
        response = unauthenticated_client.get("/api/artifacts/some_id/versions")

        assert response.status_code == 401


# ============================================================================
# Test Artifact Error Paths
# ============================================================================

class TestArtifactErrorPaths:
    """Test error handling for artifact endpoints."""

    def test_save_missing_name(self, authenticated_client):
        """Test POST /api/artifacts/ without name returns 422."""
        invalid_data = {
            "type": "code",
            "content": "test"
        }
        response = authenticated_client.post("/api/artifacts/", json=invalid_data)

        assert response.status_code == 422

    def test_save_missing_type(self, authenticated_client):
        """Test POST /api/artifacts/ without type returns 422."""
        invalid_data = {
            "name": "test",
            "content": "test"
        }
        response = authenticated_client.post("/api/artifacts/", json=invalid_data)

        assert response.status_code == 422

    def test_update_artifact_not_found(self, authenticated_client):
        """Test POST /api/artifacts/update with invalid ID returns 404."""
        update_data = {
            "id": "nonexistent_artifact_id",
            "name": "updated"
        }
        response = authenticated_client.post("/api/artifacts/update", json=update_data)

        assert response.status_code == 404

    def test_update_empty_request(self, authenticated_client, test_db, sample_artifact):
        """Test POST /api/artifacts/update with no changes."""
        # Original content
        original_name = sample_artifact.name

        # Send update with only ID (no actual changes)
        update_data = {
            "id": sample_artifact.id
        }
        response = authenticated_client.post("/api/artifacts/update", json=update_data)

        # Should succeed (200) but not change anything
        assert response.status_code == 200
        artifact = test_db.query(Artifact).filter(Artifact.id == sample_artifact.id).first()
        assert artifact.name == original_name

    def test_get_versions_not_found(self, authenticated_client):
        """Test GET /api/artifacts/{invalid_id}/versions with non-existent artifact."""
        response = authenticated_client.get("/api/artifacts/nonexistent_id/versions")

        # Returns empty list for non-existent artifact (no 404)
        assert response.status_code == 200
        versions = response.json()
        assert len(versions) == 0

    def test_update_invalid_id_format(self, authenticated_client):
        """Test POST /api/artifacts/update with malformed ID."""
        # Even malformed ID format returns 404 (artifact not found)
        update_data = {
            "id": "invalid_uuid_format",
            "name": "updated"
        }
        response = authenticated_client.post("/api/artifacts/update", json=update_data)

        assert response.status_code == 404