File size: 12,073 Bytes
96af7c9 |
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 |
/**
* Property-Based Tests for API Client
* Feature: admin-ui-modernization, Property 14: Backend API integration
* Validates: Requirements 15.1, 15.2, 15.4
*/
import fc from 'fast-check';
// Mock fetch for testing
class MockFetch {
constructor() {
this.calls = [];
this.mockResponse = null;
}
reset() {
this.calls = [];
this.mockResponse = null;
}
setMockResponse(response) {
this.mockResponse = response;
}
async fetch(url, options) {
this.calls.push({ url, options });
if (this.mockResponse) {
return this.mockResponse;
}
// Default mock response
return {
ok: true,
status: 200,
headers: {
get: (key) => {
if (key === 'content-type') return 'application/json';
return null;
}
},
json: async () => ({ success: true, data: {} })
};
}
}
// Simple ApiClient implementation for testing
class ApiClient {
constructor(baseURL = 'https://test-backend.example.com') {
this.baseURL = baseURL.replace(/\/$/, '');
this.cache = new Map();
this.requestLogs = [];
this.errorLogs = [];
this.fetchImpl = null;
}
setFetchImpl(fetchImpl) {
this.fetchImpl = fetchImpl;
}
buildUrl(endpoint) {
if (!endpoint.startsWith('/')) {
return `${this.baseURL}/${endpoint}`;
}
return `${this.baseURL}${endpoint}`;
}
async request(method, endpoint, { body, cache = true, ttl = 60000 } = {}) {
const url = this.buildUrl(endpoint);
const cacheKey = `${method}:${url}`;
if (method === 'GET' && cache && this.cache.has(cacheKey)) {
const cached = this.cache.get(cacheKey);
if (Date.now() - cached.timestamp < ttl) {
return { ok: true, data: cached.data, cached: true };
}
}
const started = Date.now();
const entry = {
id: `${Date.now()}-${Math.random()}`,
method,
endpoint,
status: 'pending',
duration: 0,
time: new Date().toISOString(),
};
try {
const fetchFn = this.fetchImpl || fetch;
const response = await fetchFn(url, {
method,
headers: {
'Content-Type': 'application/json',
},
body: body ? JSON.stringify(body) : undefined,
});
const duration = Date.now() - started;
entry.duration = Math.round(duration);
entry.status = response.status;
const contentType = response.headers.get('content-type') || '';
let data = null;
if (contentType.includes('application/json')) {
data = await response.json();
} else if (contentType.includes('text')) {
data = await response.text();
}
if (!response.ok) {
const error = new Error((data && data.message) || response.statusText || 'Unknown error');
error.status = response.status;
throw error;
}
if (method === 'GET' && cache) {
this.cache.set(cacheKey, { timestamp: Date.now(), data });
}
this.requestLogs.push({ ...entry, success: true });
return { ok: true, data };
} catch (error) {
const duration = Date.now() - started;
entry.duration = Math.round(duration);
entry.status = error.status || 'error';
this.requestLogs.push({ ...entry, success: false, error: error.message });
this.errorLogs.push({
message: error.message,
endpoint,
method,
time: new Date().toISOString(),
});
return { ok: false, error: error.message };
}
}
get(endpoint, options) {
return this.request('GET', endpoint, options);
}
post(endpoint, body, options = {}) {
return this.request('POST', endpoint, { ...options, body });
}
}
// Generators for property-based testing
const httpMethodGen = fc.constantFrom('GET', 'POST');
const endpointGen = fc.oneof(
fc.constant('/api/health'),
fc.constant('/api/market'),
fc.constant('/api/coins'),
fc.webPath().map(p => `/api/${p}`)
);
const baseURLGen = fc.webUrl({ withFragments: false, withQueryParameters: false });
/**
* Property 14: Backend API integration
* For any API request made through apiClient, it should:
* 1. Use the configured baseURL
* 2. Return a standardized response format ({ ok, data } or { ok: false, error })
* 3. Log the request for debugging
*/
console.log('Running Property-Based Tests for API Client...\n');
// Property 1: All requests use the configured baseURL
console.log('Property 1: All requests use the configured baseURL');
fc.assert(
fc.asyncProperty(
baseURLGen,
httpMethodGen,
endpointGen,
async (baseURL, method, endpoint) => {
const client = new ApiClient(baseURL);
const mockFetch = new MockFetch();
client.setFetchImpl(mockFetch.fetch.bind(mockFetch));
await client.request(method, endpoint);
// Check that the URL starts with the baseURL
const expectedBase = baseURL.replace(/\/$/, '');
const actualURL = mockFetch.calls[0].url;
return actualURL.startsWith(expectedBase);
}
),
{ numRuns: 100 }
);
console.log('✓ Property 1 passed: All requests use the configured baseURL\n');
// Property 2: All successful responses have standardized format { ok: true, data }
console.log('Property 2: All successful responses have standardized format');
fc.assert(
fc.asyncProperty(
httpMethodGen,
endpointGen,
fc.jsonValue(),
async (method, endpoint, responseData) => {
const client = new ApiClient('https://test.example.com');
const mockFetch = new MockFetch();
mockFetch.setMockResponse({
ok: true,
status: 200,
headers: {
get: (key) => key === 'content-type' ? 'application/json' : null
},
json: async () => responseData
});
client.setFetchImpl(mockFetch.fetch.bind(mockFetch));
const result = await client.request(method, endpoint);
// Check standardized response format
return (
typeof result === 'object' &&
result !== null &&
'ok' in result &&
result.ok === true &&
'data' in result
);
}
),
{ numRuns: 100 }
);
console.log('✓ Property 2 passed: All successful responses have standardized format\n');
// Property 3: All error responses have standardized format { ok: false, error }
console.log('Property 3: All error responses have standardized format');
fc.assert(
fc.asyncProperty(
httpMethodGen,
endpointGen,
fc.integer({ min: 400, max: 599 }),
fc.string({ minLength: 1, maxLength: 100 }),
async (method, endpoint, statusCode, errorMessage) => {
const client = new ApiClient('https://test.example.com');
const mockFetch = new MockFetch();
mockFetch.setMockResponse({
ok: false,
status: statusCode,
statusText: errorMessage,
headers: {
get: (key) => key === 'content-type' ? 'application/json' : null
},
json: async () => ({ message: errorMessage })
});
client.setFetchImpl(mockFetch.fetch.bind(mockFetch));
const result = await client.request(method, endpoint);
// Check standardized error response format
return (
typeof result === 'object' &&
result !== null &&
'ok' in result &&
result.ok === false &&
'error' in result &&
typeof result.error === 'string'
);
}
),
{ numRuns: 100 }
);
console.log('✓ Property 3 passed: All error responses have standardized format\n');
// Property 4: All requests are logged for debugging
console.log('Property 4: All requests are logged for debugging');
fc.assert(
fc.asyncProperty(
httpMethodGen,
endpointGen,
async (method, endpoint) => {
const client = new ApiClient('https://test.example.com');
const mockFetch = new MockFetch();
client.setFetchImpl(mockFetch.fetch.bind(mockFetch));
const initialLogCount = client.requestLogs.length;
await client.request(method, endpoint);
const finalLogCount = client.requestLogs.length;
// Check that a log entry was added
if (finalLogCount !== initialLogCount + 1) {
return false;
}
// Check that the log entry has required fields
const logEntry = client.requestLogs[client.requestLogs.length - 1];
return (
typeof logEntry === 'object' &&
logEntry !== null &&
'method' in logEntry &&
'endpoint' in logEntry &&
'status' in logEntry &&
'duration' in logEntry &&
'time' in logEntry &&
'success' in logEntry
);
}
),
{ numRuns: 100 }
);
console.log('✓ Property 4 passed: All requests are logged for debugging\n');
// Property 5: Error requests are logged in errorLogs
console.log('Property 5: Error requests are logged in errorLogs');
fc.assert(
fc.asyncProperty(
httpMethodGen,
endpointGen,
fc.integer({ min: 400, max: 599 }),
async (method, endpoint, statusCode) => {
const client = new ApiClient('https://test.example.com');
const mockFetch = new MockFetch();
mockFetch.setMockResponse({
ok: false,
status: statusCode,
statusText: 'Error',
headers: {
get: () => 'application/json'
},
json: async () => ({ message: 'Test error' })
});
client.setFetchImpl(mockFetch.fetch.bind(mockFetch));
const initialErrorCount = client.errorLogs.length;
await client.request(method, endpoint);
const finalErrorCount = client.errorLogs.length;
// Check that an error log entry was added
if (finalErrorCount !== initialErrorCount + 1) {
return false;
}
// Check that the error log entry has required fields
const errorEntry = client.errorLogs[client.errorLogs.length - 1];
return (
typeof errorEntry === 'object' &&
errorEntry !== null &&
'message' in errorEntry &&
'endpoint' in errorEntry &&
'method' in errorEntry &&
'time' in errorEntry
);
}
),
{ numRuns: 100 }
);
console.log('✓ Property 5 passed: Error requests are logged in errorLogs\n');
console.log('All property-based tests passed! ✓');
|