-
Notifications
You must be signed in to change notification settings - Fork 9k
Expand file tree
/
Copy pathtest_json_extraction.py
More file actions
90 lines (81 loc) · 1.91 KB
/
Copy pathtest_json_extraction.py
File metadata and controls
90 lines (81 loc) · 1.91 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
import pytest
from autogen_core.utils import extract_json_from_str
def test_extract_json_from_str() -> None:
json_str = """
{
"name": "John",
"age": 30,
"city": "New York"
}
"""
json_resp = [{"name": "John", "age": 30, "city": "New York"}]
resp = extract_json_from_str(json_str)
assert resp == json_resp
invalid_json_str = """
{
"name": "John",
"age": 30,
"city": "New York"
"""
with pytest.raises(ValueError):
extract_json_from_str(invalid_json_str)
def test_extract_json_from_str_codeblock() -> None:
code_block_lang_str = """
```json
{
"name": "Alice",
"age": 28,
"city": "Seattle"
}
```
"""
code_block_no_lang_str = """
```
{
"name": "Alice",
"age": 28,
"city": "Seattle"
}
```
"""
code_block_resp = [{"name": "Alice", "age": 28, "city": "Seattle"}]
multi_json_str = """
```json
{
"name": "John",
"age": 30,
"city": "New York"
}
```
```json
{
"name": "Jane",
"age": 25,
"city": "Los Angeles"
}
```
"""
multi_json_resp = [
{"name": "John", "age": 30, "city": "New York"},
{"name": "Jane", "age": 25, "city": "Los Angeles"},
]
lang_resp = extract_json_from_str(code_block_lang_str)
assert lang_resp == code_block_resp
no_lang_resp = extract_json_from_str(code_block_no_lang_str)
assert no_lang_resp == code_block_resp
multi_resp = extract_json_from_str(multi_json_str)
assert multi_resp == multi_json_resp
crlf_code_block_str = '```json\r\n{"name": "Alice", "age": 28, "city": "Seattle"}\r\n```'
crlf_resp = extract_json_from_str(crlf_code_block_str)
assert crlf_resp == code_block_resp
invalid_lang_code_block_str = """
```notjson
{
"name": "Jane",
"age": 25,
"city": "Los Angeles"
}
```
"""
with pytest.raises(ValueError):
extract_json_from_str(invalid_lang_code_block_str)