-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_function.py
More file actions
231 lines (182 loc) · 7.39 KB
/
test_function.py
File metadata and controls
231 lines (182 loc) · 7.39 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
#!/usr/bin/env python3
"""
Simple test script for the convert_story_to_drama_script function.
This script shows different ways to test the function.
"""
import sys
import os
# Add the src directory to the Python path
sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'src'))
def test_without_api_key():
"""Test the function structure without making API calls."""
print("🧪 Testing Function Structure (No API Key Required)")
print("=" * 60)
try:
from storyteller.example import convert_story_to_drama_script
# Test function exists and has correct signature
import inspect
sig = inspect.signature(convert_story_to_drama_script)
print(f"✅ Function exists: convert_story_to_drama_script")
print(f"✅ Parameters: {list(sig.parameters.keys())}")
print(f"✅ Return type annotation: {sig.return_annotation}")
# Test with empty string (should return empty list)
print("\n📝 Testing with empty string...")
result = convert_story_to_drama_script("")
print(f"Result: {result}")
print(f"Type: {type(result)}")
return True
except Exception as e:
print(f"❌ Error: {e}")
return False
def test_with_mock_api():
"""Test with a mock API response to verify JSON parsing."""
print("\n🎭 Testing JSON Parsing Logic")
print("=" * 60)
try:
from storyteller.example import convert_story_to_drama_script
import json
# Test JSON parsing with mock response
mock_response = '''[
{"character": "NARRATOR", "line": "Once upon a time..."},
{"character": "ALICE", "line": "(excited) Hello world!"},
{"character": "BOB", "line": "Nice to meet you."}
]'''
# Test the JSON parsing logic
response_text = mock_response.strip()
if response_text.startswith("```json"):
response_text = response_text[7:]
if response_text.endswith("```"):
response_text = response_text[:-3]
drama_script = json.loads(response_text)
print("✅ JSON parsing works correctly")
print(f"✅ Parsed {len(drama_script)} script lines")
for i, entry in enumerate(drama_script, 1):
character = entry["character"]
line = entry["line"]
print(f" {i}. {character}: {line}")
return True
except Exception as e:
print(f"❌ JSON parsing error: {e}")
return False
def test_with_api_key():
"""Test the actual function with API key (if available)."""
print("\n🚀 Testing with Google API Key")
print("=" * 60)
# Check if API key is available
api_key = os.getenv("GOOGLE_API_KEY")
if not api_key:
print("⚠️ GOOGLE_API_KEY not found in environment")
print(" To test with real API calls:")
print(" 1. Get API key from: https://makersuite.google.com/app/apikey")
print(" 2. Set environment variable: export GOOGLE_API_KEY='your-key'")
print(" 3. Run this script again")
return False
try:
from storyteller.example import convert_story_to_drama_script
# Test story
test_story = """
Emma was a young librarian who loved books more than anything. One evening,
while closing up the library, she heard pages rustling from the fiction section.
"That's strange," she thought. "I'm sure I'm the only one here." She walked
toward the sound and found an old book glowing softly on the shelf.
"""
print(f"📖 Testing with story:\n{test_story.strip()}\n")
# Call the function
drama_script = convert_story_to_drama_script(test_story)
if drama_script:
print("✅ API call successful!")
print(f"✅ Generated {len(drama_script)} script lines\n")
print("📝 Generated Drama Script:")
print("-" * 50)
for i, entry in enumerate(drama_script, 1):
character = entry["character"]
line = entry["line"]
print(f"{i:2d}. {character:12s}: {line}")
print("-" * 50)
# Show character analysis
characters = set(entry["character"] for entry in drama_script)
print(f"\n🎭 Characters: {', '.join(sorted(characters))}")
return True
else:
print("❌ API call failed - no script generated")
return False
except Exception as e:
print(f"❌ API call error: {e}")
return False
def interactive_test():
"""Allow user to test with their own story."""
print("\n🎯 Interactive Test")
print("=" * 60)
api_key = os.getenv("GOOGLE_API_KEY")
if not api_key:
print("❌ GOOGLE_API_KEY not found. Cannot run interactive test.")
return False
try:
from storyteller.example import convert_story_to_drama_script
print("Enter your story text (press Ctrl+D when done):")
lines = []
while True:
try:
line = input()
lines.append(line)
except EOFError:
break
user_story = '\n'.join(lines).strip()
if not user_story:
print("No story provided.")
return False
print(f"\n📖 Your Story:\n{user_story}\n")
drama_script = convert_story_to_drama_script(user_story)
if drama_script:
print("✅ Conversion successful!")
print(f"Generated {len(drama_script)} script lines\n")
print("📝 Your Drama Script:")
print("-" * 50)
for i, entry in enumerate(drama_script, 1):
character = entry["character"]
line = entry["line"]
print(f"{i:2d}. {character:12s}: {line}")
print("-" * 50)
return True
else:
print("❌ Conversion failed")
return False
except KeyboardInterrupt:
print("\n\nTest cancelled.")
return False
except Exception as e:
print(f"❌ Error: {e}")
return False
def main():
"""Main test function."""
print("🎭 StoryTeller - Function Testing Suite")
print("=" * 60)
# Test 1: Function structure
success1 = test_without_api_key()
# Test 2: JSON parsing
success2 = test_with_mock_api()
# Test 3: API call (if key available)
success3 = test_with_api_key()
# Summary
print("\n📊 Test Summary")
print("=" * 60)
print(f"Function Structure: {'✅ PASS' if success1 else '❌ FAIL'}")
print(f"JSON Parsing: {'✅ PASS' if success2 else '❌ FAIL'}")
print(f"API Integration: {'✅ PASS' if success3 else '⚠️ SKIP (No API Key)'}")
if success1 and success2:
print("\n🎉 Basic functionality tests passed!")
if success3:
print("🚀 Full integration test passed!")
# Ask if user wants interactive test
try:
response = input("\nWould you like to test with your own story? (y/n): ").lower().strip()
if response in ['y', 'yes']:
interactive_test()
except KeyboardInterrupt:
print("\nGoodbye!")
else:
print("💡 To test API integration, set your GOOGLE_API_KEY environment variable")
else:
print("\n❌ Some tests failed. Please check the error messages above.")
if __name__ == "__main__":
main()