aboutsummaryrefslogtreecommitdiffstats
path: root/examples/test_pydantic.py
blob: ee0d493789afc49a74e74301ff7c77eafab853a6 (plain) (blame)
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
#!/usr/bin/env python3
"""
Tests for Pydantic SelectItem model and JSON conversion.
"""

import os
import sys

sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', 'src'))

from selectui import SelectItem, SelectUI


def test_selectitem_creation():
    """Test basic SelectItem creation."""
    item = SelectItem(
        title="Test Item",
        subtitle="Test Subtitle",
        info="Test Info",
        data={"key": "value"}
    )

    assert item.title == "Test Item"
    assert item.subtitle == "Test Subtitle"
    assert item.info == "Test Info"
    assert item.data == {"key": "value"}
    print("✓ SelectItem creation test passed")


def test_selectitem_minimal():
    """Test SelectItem with only required fields."""
    item = SelectItem(title="Minimal Item")

    assert item.title == "Minimal Item"
    assert item.subtitle is None
    assert item.info is None
    assert item.data == {}
    print("✓ Minimal SelectItem test passed")


def test_selectitem_validation():
    """Test SelectItem validation."""
    # Empty title should fail
    try:
        SelectItem(title="")
        assert False, "Should have raised validation error for empty title"
    except Exception:
        print("✓ Empty title validation test passed")

    # Whitespace-only title should fail
    try:
        SelectItem(title="   ")
        assert False, "Should have raised validation error for whitespace title"
    except Exception:
        print("✓ Whitespace title validation test passed")


def test_selectitem_to_dict():
    """Test SelectItem.to_dict() conversion."""
    item = SelectItem(
        title="Test",
        subtitle="Subtitle",
        info="Info",
        data={"custom": "field"}
    )

    result = item.to_dict()

    assert result["title"] == "Test"
    assert result["subtitle"] == "Subtitle"
    assert result["info"] == "Info"
    assert result["custom"] == "field"
    print("✓ to_dict() conversion test passed")


def test_selectitem_from_dict():
    """Test SelectItem.from_dict() with default keys."""
    data = {
        "title": "Item Title",
        "subtitle": "Item Subtitle",
        "info": "Item Info",
        "extra": "data"
    }

    item = SelectItem.from_dict(data)

    assert item.title == "Item Title"
    assert item.subtitle == "Item Subtitle"
    assert item.info == "Item Info"
    assert item.data["extra"] == "data"
    print("✓ from_dict() with default keys test passed")


def test_selectitem_from_dict_custom_keys():
    """Test SelectItem.from_dict() with custom key mappings."""
    data = {
        "name": "Alice",
        "role": "Engineer",
        "team": "Backend",
        "level": "Senior"
    }

    item = SelectItem.from_dict(
        data,
        title_key="name",
        subtitle_key="role",
        info_key="team"
    )

    assert item.title == "Alice"
    assert item.subtitle == "Engineer"
    assert item.info == "Backend"
    assert item.data["level"] == "Senior"
    print("✓ from_dict() with custom keys test passed")


def test_selectitem_from_dict_no_subtitle():
    """Test SelectItem.from_dict() without subtitle."""
    data = {"filename": "test.py", "size": 1024}

    item = SelectItem.from_dict(
        data,
        title_key="filename",
        subtitle_key=None,
        info_key="size"
    )

    assert item.title == "test.py"
    assert item.subtitle is None
    assert item.info == "1024"
    print("✓ from_dict() without subtitle test passed")


def test_selectui_with_pydantic_items():
    """Test SelectUI initialization with SelectItem instances."""
    items = [
        SelectItem(title="Item 1", subtitle="Subtitle 1"),
        SelectItem(title="Item 2", subtitle="Subtitle 2"),
    ]

    app = SelectUI(items=items, oneshot=True)

    assert len(app.items) == 2
    assert app.items[0]["title"] == "Item 1"
    assert app.items[1]["title"] == "Item 2"
    print("✓ SelectUI with Pydantic items test passed")


def test_selectui_with_custom_keys():
    """Test SelectUI with Pydantic items and custom key mappings."""
    items = [
        SelectItem(title="Python", subtitle="Programming language", info="1991"),
        SelectItem(title="Rust", subtitle="Systems language", info="2010"),
    ]

    app = SelectUI(
        items=items,
        oneshot=True,
        title_key="name",
        subtitle_key="desc",
        info_key="year"
    )

    # Items should have both standard keys and custom keys
    assert app.items[0]["title"] == "Python"
    assert app.items[0]["name"] == "Python"
    assert app.items[0]["subtitle"] == "Programming language"
    assert app.items[0]["desc"] == "Programming language"
    print("✓ SelectUI with custom keys test passed")


def test_mixed_dict_support():
    """Test that SelectUI still works with plain dicts."""
    items = [
        {"title": "Dict Item 1", "subtitle": "From dict"},
        {"title": "Dict Item 2", "subtitle": "Also dict"},
    ]

    app = SelectUI(items=items, oneshot=True)

    assert len(app.items) == 2
    assert app.items[0]["title"] == "Dict Item 1"
    print("✓ Plain dict support test passed")


if __name__ == "__main__":
    print("Running Pydantic SelectItem tests...\n")

    try:
        test_selectitem_creation()
        test_selectitem_minimal()
        test_selectitem_validation()
        test_selectitem_to_dict()
        test_selectitem_from_dict()
        test_selectitem_from_dict_custom_keys()
        test_selectitem_from_dict_no_subtitle()
        test_selectui_with_pydantic_items()
        test_selectui_with_custom_keys()
        test_mixed_dict_support()

        print("\n✅ All Pydantic tests passed!")
        print("\nSelectItem model is ready to use.")
        print("See examples/pydantic_example.py for usage examples.")

    except AssertionError as e:
        print(f"\n❌ Test failed: {e}")
        import traceback
        traceback.print_exc()
        sys.exit(1)
    except Exception as e:
        print(f"\n❌ Error: {e}")
        import traceback
        traceback.print_exc()
        sys.exit(1)