-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCaseEditor.tsx
More file actions
290 lines (274 loc) · 16.6 KB
/
Copy pathCaseEditor.tsx
File metadata and controls
290 lines (274 loc) · 16.6 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
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
import type { JSX } from 'react';
import { useMemo, useState } from 'react';
import { useTestingStore } from '../../stores/testingStore';
import { Button, Input, Select, Checkbox, TextArea, Badge, Field } from '../../components/ui/primitives';
import { Icon } from '../../components/ui/Icons';
import type { Assertion, AssertionSource, AssertionOperator, TestCase, TestCaseRequest } from './types';
const METHODS = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'];
const SOURCES: AssertionSource[] = ['status', 'statusText', 'header', 'body', 'jsonPath', 'duration', 'size'];
const OPERATORS: AssertionOperator[] = [
'eq', 'ne', 'gt', 'gte', 'lt', 'lte', 'contains', 'notContains', 'matches', 'notMatches',
'in', 'notIn', 'exists', 'notExists', 'truthy', 'falsy', 'empty', 'notEmpty',
'isType', 'isArray', 'isObject', 'isNull', 'lengthEq', 'lengthGt', 'lengthLt',
'countEq', 'countGt', 'countLt', 'schemaValid', 'custom',
];
function KVRow({ k, value, enabled, onPatch, onRemove }: { k: string; value: string; enabled: boolean; onPatch: (patch: { key?: string; value?: string; enabled?: boolean }) => void; onRemove: () => void }): JSX.Element {
return (
<div className="row">
<Checkbox checked={enabled} onChange={(e) => onPatch({ enabled: e.target.checked })} label="" />
<Input placeholder="Key" value={k} onChange={(e) => onPatch({ key: e.target.value })} />
<Input placeholder="Value" value={value} onChange={(e) => onPatch({ value: e.target.value })} />
<Button variant="ghost" className="btn-icon" aria-label="Remove" onClick={onRemove}><Icon name="trash" size={13} /></Button>
</div>
);
}
function HeaderAndQuery({ request, patchRequest }: { request: TestCaseRequest; patchRequest: (patch: Partial<TestCaseRequest>) => void }): JSX.Element {
return (
<div className="stack">
<div className="card-title">Headers</div>
{request.headers.map((h) => (
<KVRow
key={h.id}
k={h.key}
value={h.value}
enabled={h.enabled}
onPatch={(patch) => patchRequest({ headers: request.headers.map((x) => (x.id === h.id ? { ...x, ...patch } : x)) })}
onRemove={() => patchRequest({ headers: request.headers.filter((x) => x.id !== h.id) })}
/>
))}
<Button variant="ghost" size="sm" onClick={() => patchRequest({ headers: [...request.headers, { id: crypto.randomUUID(), key: '', value: '', enabled: true }] })}>
<Icon name="plus" size={13} /> Add header
</Button>
<div className="card-title" style={{ marginTop: 8 }}>Query params</div>
{request.query.map((q) => (
<KVRow
key={q.id}
k={q.key}
value={q.value}
enabled={q.enabled}
onPatch={(patch) => patchRequest({ query: request.query.map((x) => (x.id === q.id ? { ...x, ...patch } : x)) })}
onRemove={() => patchRequest({ query: request.query.filter((x) => x.id !== q.id) })}
/>
))}
<Button variant="ghost" size="sm" onClick={() => patchRequest({ query: [...request.query, { id: crypto.randomUUID(), key: '', value: '', enabled: true }] })}>
<Icon name="plus" size={13} /> Add query param
</Button>
</div>
);
}
function BodyEditor({ request, patchRequest }: { request: TestCaseRequest; patchRequest: (patch: Partial<TestCaseRequest>) => void }): JSX.Element {
return (
<div className="stack">
<Field label="Body type">
<Select value={request.bodyType} onChange={(e) => patchRequest({ bodyType: e.target.value as TestCaseRequest['bodyType'] })}>
<option value="none">none</option>
<option value="json">application/json</option>
<option value="xml">application/xml</option>
<option value="form">application/x-www-form-urlencoded</option>
<option value="text">text/plain</option>
</Select>
</Field>
{request.bodyType !== 'none' && (
<TextArea rows={10} className="mono" value={request.body} onChange={(e) => patchRequest({ body: e.target.value })} placeholder="{}" />
)}
</div>
);
}
function AuthEditor({ request, patchRequest }: { request: TestCaseRequest; patchRequest: (patch: Partial<TestCaseRequest>) => void }): JSX.Element {
const auth = request.auth;
return (
<div className="stack">
<Field label="Auth type">
<Select value={request.authType} onChange={(e) => patchRequest({ authType: e.target.value as TestCaseRequest['authType'] })}>
<option value="none">No auth</option>
<option value="bearer">Bearer token</option>
<option value="basic">Basic auth</option>
<option value="apiKey">API key</option>
</Select>
</Field>
{request.authType === 'bearer' && (
<Field label="Token"><Input value={auth.token ?? ''} onChange={(e) => patchRequest({ auth: { ...auth, token: e.target.value } })} /></Field>
)}
{request.authType === 'basic' && (
<div className="grid-2">
<Field label="Username"><Input value={auth.username ?? ''} onChange={(e) => patchRequest({ auth: { ...auth, username: e.target.value } })} /></Field>
<Field label="Password"><Input type="password" value={auth.password ?? ''} onChange={(e) => patchRequest({ auth: { ...auth, password: e.target.value } })} /></Field>
</div>
)}
{request.authType === 'apiKey' && (
<div className="grid-2">
<Field label="Header name"><Input value={auth.headerName ?? ''} onChange={(e) => patchRequest({ auth: { ...auth, headerName: e.target.value } })} /></Field>
<Field label="Value"><Input value={auth.headerValue ?? ''} onChange={(e) => patchRequest({ auth: { ...auth, headerValue: e.target.value } })} /></Field>
</div>
)}
</div>
);
}
function assertionLabel(a: Assertion): string {
const left = a.source === 'header' ? `header.${a.headerName}` : a.source === 'jsonPath' ? a.path : a.source;
if (a.operator === 'schemaValid') return `${left} matches schema`;
if (a.operator === 'custom') return `custom: ${a.customExpression}`;
const exp = typeof a.expected === 'string' ? a.expected : JSON.stringify(a.expected);
return `${left} ${a.operator} ${exp}`;
}
function AssertionEditor({ testCase, updateCase }: { testCase: TestCase; updateCase: (id: string, patch: Partial<TestCase>) => void }): JSX.Element {
const [adding, setAdding] = useState(false);
const assertions = testCase.assertions;
const setAssertion = (id: string, patch: Partial<Assertion>): void => {
updateCase(testCase.id, { assertions: assertions.map((a) => (a.id === id ? { ...a, ...patch } : a)) });
};
const removeAssertion = (id: string): void => {
updateCase(testCase.id, { assertions: assertions.filter((a) => a.id !== id) });
};
const addDefault = (): void => {
const a: Assertion = { id: crypto.randomUUID(), enabled: true, source: 'status', operator: 'gte', expected: 200 };
updateCase(testCase.id, { assertions: [...assertions, a] });
setAdding(false);
};
return (
<div className="stack">
<div className="row">
<Button variant="ghost" size="sm" onClick={addDefault}><Icon name="plus" size={13} /> Add assertion</Button>
<span className="muted small">{assertions.length} assertion(s)</span>
</div>
{assertions.map((a) => (
<div key={a.id} className="card" style={{ padding: 10 }}>
<div className="row" style={{ justifyContent: 'space-between', marginBottom: 6 }}>
<div className="row">
<Checkbox checked={a.enabled} onChange={(e) => setAssertion(a.id, { enabled: e.target.checked })} label="" />
<Badge tone={a.enabled ? 'blue' : 'gray'}>{assertionLabel(a)}</Badge>
</div>
<Button variant="ghost" className="btn-icon" onClick={() => removeAssertion(a.id)} aria-label="Remove assertion"><Icon name="trash" size={13} /></Button>
</div>
<div className="row">
<Select value={a.source} onChange={(e) => setAssertion(a.id, { source: e.target.value as AssertionSource })} style={{ width: 110 }}>
{SOURCES.map((s) => <option key={s} value={s}>{s}</option>)}
</Select>
{a.source === 'header' && <Input placeholder="Header name" value={a.headerName ?? ''} onChange={(e) => setAssertion(a.id, { headerName: e.target.value })} style={{ width: 140 }} />}
{a.source === 'jsonPath' && <Input placeholder="$.path" value={a.path ?? ''} onChange={(e) => setAssertion(a.id, { path: e.target.value })} style={{ width: 160 }} />}
<Select value={a.operator} onChange={(e) => setAssertion(a.id, { operator: e.target.value as AssertionOperator })} style={{ width: 120 }}>
{OPERATORS.map((o) => <option key={o} value={o}>{o}</option>)}
</Select>
{a.operator !== 'custom' && a.operator !== 'schemaValid' && !['exists', 'notExists', 'truthy', 'falsy', 'empty', 'notEmpty', 'isArray', 'isObject', 'isNull'].includes(a.operator) && (
<Input placeholder="Expected" value={typeof a.expected === 'string' ? a.expected : a.expected === undefined ? '' : JSON.stringify(a.expected)} onChange={(e) => setAssertion(a.id, { expected: e.target.value })} style={{ width: 160 }} />
)}
</div>
{a.operator === 'schemaValid' && (
<TextArea rows={5} className="mono" placeholder='{"type":"object"}' value={a.schema ?? ''} onChange={(e) => setAssertion(a.id, { schema: e.target.value })} style={{ marginTop: 6 }} />
)}
{a.operator === 'custom' && (
<TextArea rows={3} className="mono" placeholder="status === 200 && jsonPath('$.id').length > 0" value={a.customExpression ?? ''} onChange={(e) => setAssertion(a.id, { customExpression: e.target.value })} style={{ marginTop: 6 }} />
)}
<Input placeholder="Message (optional)" value={a.message ?? ''} onChange={(e) => setAssertion(a.id, { message: e.target.value })} style={{ marginTop: 6 }} />
</div>
))}
{adding && null}
</div>
);
}
function ExtractionEditor({ testCase, updateCase }: { testCase: TestCase; updateCase: (id: string, patch: Partial<TestCase>) => void }): JSX.Element {
const extractions = testCase.extractions;
const setExtraction = (id: string, patch: Partial<TestCase['extractions'][number]>): void => {
updateCase(testCase.id, { extractions: extractions.map((x) => (x.id === id ? { ...x, ...patch } : x)) });
};
return (
<div className="stack">
<Button variant="ghost" size="sm" onClick={() => updateCase(testCase.id, { extractions: [...extractions, { id: crypto.randomUUID(), variableName: '', source: 'jsonPath', jsonPath: '' }] })}>
<Icon name="plus" size={13} /> Add extraction
</Button>
{extractions.map((x) => (
<div key={x.id} className="card" style={{ padding: 10 }}>
<div className="row">
<Input placeholder="Variable name" value={x.variableName} onChange={(e) => setExtraction(x.id, { variableName: e.target.value })} style={{ width: 160 }} />
<Select value={x.source} onChange={(e) => setExtraction(x.id, { source: e.target.value as typeof x.source })} style={{ width: 110 }}>
<option value="jsonPath">jsonPath</option>
<option value="header">header</option>
<option value="status">status</option>
<option value="body">body</option>
</Select>
{x.source === 'jsonPath' && <Input placeholder="$.id" value={x.jsonPath ?? ''} onChange={(e) => setExtraction(x.id, { jsonPath: e.target.value })} style={{ width: 160 }} />}
{x.source === 'header' && <Input placeholder="Header name" value={x.headerName ?? ''} onChange={(e) => setExtraction(x.id, { headerName: e.target.value })} style={{ width: 160 }} />}
<Button variant="ghost" className="btn-icon" onClick={() => updateCase(testCase.id, { extractions: extractions.filter((y) => y.id !== x.id) })} aria-label="Remove extraction"><Icon name="trash" size={13} /></Button>
</div>
</div>
))}
</div>
);
}
function ScriptEditor({ testCase, updateCase }: { testCase: TestCase; updateCase: (id: string, patch: Partial<TestCase>) => void }): JSX.Element {
return (
<div className="stack">
<Field label="Pre-request script" hint="Available: vars, setVar(name, value), getVar(name), random, log(...), jsonPath(expr).">
<TextArea rows={6} className="mono" value={testCase.preScript ?? ''} onChange={(e) => updateCase(testCase.id, { preScript: e.target.value })} placeholder="setVar('token', 'abc')" />
</Field>
<Field label="Post-request script" hint="Runs after the request; extracted variables are chained to later cases.">
<TextArea rows={6} className="mono" value={testCase.postScript ?? ''} onChange={(e) => updateCase(testCase.id, { postScript: e.target.value })} placeholder="log('status', status)" />
</Field>
</div>
);
}
export function CaseEditor({ testCase }: { testCase: TestCase }): JSX.Element {
const updateCase = useTestingStore((s) => s.updateCase);
const runCase = useTestingStore((s) => s.runCase);
const running = useTestingStore((s) => s.running);
const [tab, setTab] = useState<'request' | 'headers' | 'query' | 'body' | 'auth' | 'assertions' | 'extract' | 'scripts'>('request');
const patchRequest = (patch: Partial<TestCaseRequest>): void => updateCase(testCase.id, { request: { ...testCase.request, ...patch } });
const overview = useMemo(() => {
const parts: string[] = [];
if (testCase.assertions.length > 0) parts.push(`${testCase.assertions.length} assertions`);
if (testCase.extractions.length > 0) parts.push(`${testCase.extractions.length} extractions`);
return parts.join(' · ');
}, [testCase.assertions.length, testCase.extractions.length]);
return (
<div className="stack" style={{ flex: 1, minHeight: 0 }}>
<div className="card">
<div className="row">
<Checkbox checked={testCase.enabled} onChange={(e) => updateCase(testCase.id, { enabled: e.target.checked })} label="Enabled" />
<Input value={testCase.name} onChange={(e) => updateCase(testCase.id, { name: e.target.value })} style={{ fontWeight: 600 }} />
<Button variant="primary" disabled={running} onClick={() => void runCase(testCase.id)}>
<Icon name="play" size={14} /> Run
</Button>
</div>
<div className="muted small" style={{ marginTop: 6 }}>{overview || 'No assertions yet.'}</div>
</div>
<div className="card">
<div className="row" style={{ marginBottom: 10 }}>
{(['request', 'headers', 'query', 'body', 'auth', 'assertions', 'extract', 'scripts'] as const).map((t) => (
<Button key={t} variant={tab === t ? 'primary' : 'ghost'} size="sm" onClick={() => setTab(t)}>{t}</Button>
))}
</div>
{tab === 'request' && (
<div className="row">
<Select value={testCase.request.method} onChange={(e) => patchRequest({ method: e.target.value as TestCaseRequest['method'] })} style={{ width: 110 }}>
{METHODS.map((m) => <option key={m}>{m}</option>)}
</Select>
<Input value={testCase.request.url} onChange={(e) => patchRequest({ url: e.target.value })} placeholder="https://api.example.com/pets" className="mono" />
</div>
)}
{tab === 'headers' && <HeaderAndQuery request={testCase.request} patchRequest={patchRequest} />}
{tab === 'query' && (
<div className="stack">
{testCase.request.query.map((q) => (
<KVRow
key={q.id}
k={q.key}
value={q.value}
enabled={q.enabled}
onPatch={(patch) => patchRequest({ query: testCase.request.query.map((x) => (x.id === q.id ? { ...x, ...patch } : x)) })}
onRemove={() => patchRequest({ query: testCase.request.query.filter((x) => x.id !== q.id) })}
/>
))}
<Button variant="ghost" size="sm" onClick={() => patchRequest({ query: [...testCase.request.query, { id: crypto.randomUUID(), key: '', value: '', enabled: true }] })}>
<Icon name="plus" size={13} /> Add query param
</Button>
</div>
)}
{tab === 'body' && <BodyEditor request={testCase.request} patchRequest={patchRequest} />}
{tab === 'auth' && <AuthEditor request={testCase.request} patchRequest={patchRequest} />}
{tab === 'assertions' && <AssertionEditor testCase={testCase} updateCase={updateCase} />}
{tab === 'extract' && <ExtractionEditor testCase={testCase} updateCase={updateCase} />}
{tab === 'scripts' && <ScriptEditor testCase={testCase} updateCase={updateCase} />}
</div>
</div>
);
}