stringify-comparison-test.html 15.7 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 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 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Stringify 对比测试</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f5f5f5;
        }
        .container {
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            margin-bottom: 20px;
        }
        h1 {
            color: #333;
            text-align: center;
        }
        .test-case {
            border: 1px solid #ddd;
            border-radius: 4px;
            padding: 15px;
            margin: 10px 0;
            background-color: #fafafa;
        }
        .test-title {
            font-weight: bold;
            color: #2c3e50;
            margin-bottom: 10px;
        }
        .result {
            margin: 5px 0;
            padding: 8px;
            border-radius: 4px;
            font-family: monospace;
            word-break: break-all;
        }
        .custom-result {
            background-color: #e8f5e8;
            border-left: 4px solid #4caf50;
        }
        .qs-result {
            background-color: #e3f2fd;
            border-left: 4px solid #2196f3;
        }
        .diff {
            background-color: #ffebee;
            border-left: 4px solid #f44336;
            color: #d32f2f;
        }
        .same {
            background-color: #f1f8e9;
            border-left: 4px solid #8bc34a;
            color: #558b2f;
        }
        .input-data {
            background-color: #fff3e0;
            border-left: 4px solid #ff9800;
            margin-bottom: 10px;
            padding: 8px;
            font-family: monospace;
        }
        button {
            background-color: #2196f3;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 4px;
            cursor: pointer;
            margin: 5px;
        }
        button:hover {
            background-color: #1976d2;
        }
        .summary {
            background-color: #fff;
            border: 2px solid #4caf50;
            border-radius: 8px;
            padding: 15px;
            margin-top: 20px;
        }
        .warning {
            background-color: #fff3cd;
            border: 2px solid #ffc107;
            color: #856404;
        }
        .error {
            background-color: #f8d7da;
            border: 2px solid #dc3545;
            color: #721c24;
        }
    </style>
    <script src="https://cdn.jsdelivr.net/npm/qs@6.11.0/dist/qs.min.js"></script>
</head>
<body>
    <div class="container">
        <h1>🔍 Stringify 函数对比测试</h1>
        <p>对比我们自定义的 stringify 函数与 qs.stringify 的差异</p>
        
        <button onclick="runAllTests()">🚀 运行所有测试</button>
        <button onclick="clearResults()">🧹 清空结果</button>
        
        <div id="results"></div>
        
        <div id="summary" class="summary" style="display: none;">
            <h3>📊 测试总结</h3>
            <div id="summaryContent"></div>
        </div>
    </div>

    <script>
        // 我们的自定义 stringify 函数
        function customStringify(obj, options = {}) {
            const {
                arrayFormat = 'indices',
                allowDots = false,
                encodeValuesOnly = false,
                encode = true,
                delimiter = '&'
            } = options;

            const pairs = [];

            function addPair(key, value, keyPrefix) {
                const finalKey = keyPrefix ? `${keyPrefix}${allowDots ? '.' : '['}${key}${allowDots ? '' : ']'}` : key;
                
                if (value === null) {
                    pairs.push(encode ? `${encodeURIComponent(finalKey)}=null` : `${finalKey}=null`);
                } else if (value === undefined) {
                    pairs.push(encode ? `${encodeURIComponent(finalKey)}=undefined` : `${finalKey}=undefined`);
                } else if (typeof value === 'boolean') {
                    pairs.push(encode ? `${encodeURIComponent(finalKey)}=${value}` : `${finalKey}=${value}`);
                } else if (typeof value === 'number') {
                    pairs.push(encode ? `${encodeURIComponent(finalKey)}=${value}` : `${finalKey}=${value}`);
                } else if (Array.isArray(value)) {
                    value.forEach((item, index) => {
                        let arrayKey;
                        switch (arrayFormat) {
                            case 'indices':
                                arrayKey = `${finalKey}[${index}]`;
                                break;
                            case 'brackets':
                                arrayKey = `${finalKey}[]`;
                                break;
                            case 'repeat':
                                arrayKey = finalKey;
                                break;
                            case 'comma':
                                return;
                            default:
                                arrayKey = `${finalKey}[${index}]`;
                        }
                        
                        if (typeof item === 'object' && item !== null) {
                            serializeObject(item, arrayKey);
                        } else {
                            const encodedKey = encode && !encodeValuesOnly ? encodeURIComponent(arrayKey) : arrayKey;
                            const encodedValue = encode ? encodeURIComponent(String(item)) : String(item);
                            pairs.push(`${encodedKey}=${encodedValue}`);
                        }
                    });
                    
                    if (arrayFormat === 'comma' && value.length > 0) {
                        const encodedKey = encode && !encodeValuesOnly ? encodeURIComponent(finalKey) : finalKey;
                        const encodedValues = value.map(item => encode ? encodeURIComponent(String(item)) : String(item));
                        pairs.push(`${encodedKey}=${encodedValues.join(',')}`);
                    }
                } else if (typeof value === 'object' && value !== null) {
                    serializeObject(value, finalKey);
                } else {
                    const encodedKey = encode && !encodeValuesOnly ? encodeURIComponent(finalKey) : finalKey;
                    const encodedValue = encode ? encodeURIComponent(String(value)) : String(value);
                    pairs.push(`${encodedKey}=${encodedValue}`);
                }
            }

            function serializeObject(obj, prefix) {
                Object.keys(obj).forEach(key => {
                    const value = obj[key];
                    addPair(key, value, prefix);
                });
            }

            serializeObject(obj);
            return pairs.join(delimiter);
        }

        // 测试用例
        const testCases = [
            {
                name: "基础对象",
                data: { name: "张三", age: 25, city: "北京" },
                options: { arrayFormat: 'indices', allowDots: true, encodeValuesOnly: true }
            },
            {
                name: "包含数组 - indices 格式",
                data: { users: ["alice", "bob", "charlie"], status: "active" },
                options: { arrayFormat: 'indices', allowDots: true, encodeValuesOnly: true }
            },
            {
                name: "包含数组 - brackets 格式",
                data: { users: ["alice", "bob", "charlie"], status: "active" },
                options: { arrayFormat: 'brackets', allowDots: true, encodeValuesOnly: true }
            },
            {
                name: "包含数组 - repeat 格式",
                data: { users: ["alice", "bob", "charlie"], status: "active" },
                options: { arrayFormat: 'repeat', allowDots: true, encodeValuesOnly: true }
            },
            {
                name: "包含数组 - comma 格式",
                data: { users: ["alice", "bob", "charlie"], status: "active" },
                options: { arrayFormat: 'comma', allowDots: true, encodeValuesOnly: true }
            },
            {
                name: "嵌套对象 - allowDots: true",
                data: { user: { profile: { name: "张三", age: 25 } }, status: "active" },
                options: { arrayFormat: 'indices', allowDots: true, encodeValuesOnly: true }
            },
            {
                name: "嵌套对象 - allowDots: false",
                data: { user: { profile: { name: "张三", age: 25 } }, status: "active" },
                options: { arrayFormat: 'indices', allowDots: false, encodeValuesOnly: true }
            },
            {
                name: "特殊值处理",
                data: { nullValue: null, undefinedValue: undefined, boolValue: true, numValue: 42 },
                options: { arrayFormat: 'indices', allowDots: true, encodeValuesOnly: true }
            },
            {
                name: "包含特殊字符",
                data: { message: "Hello World!", email: "test@example.com", url: "https://example.com?param=value" },
                options: { arrayFormat: 'indices', allowDots: true, encodeValuesOnly: true }
            },
            {
                name: "复杂嵌套结构",
                data: { 
                    user: { 
                        name: "张三", 
                        tags: ["developer", "javascript"],
                        settings: { theme: "dark", notifications: true }
                    },
                    timestamp: Date.now()
                },
                options: { arrayFormat: 'indices', allowDots: true, encodeValuesOnly: true }
            },
            {
                name: "签名验证场景模拟",
                data: { 
                    appId: "test-app",
                    timestamp: "1640995200000",
                    nonce: "abc123",
                    data: { userId: 123, action: "login" }
                },
                options: { arrayFormat: 'indices', allowDots: true, encodeValuesOnly: true }
            }
        ];

        let testResults = [];

        function runTest(testCase, index) {
            const { name, data, options } = testCase;
            
            let customResult, qsResult, customError, qsError;
            
            // 测试我们的自定义函数
            try {
                customResult = customStringify(data, options);
            } catch (error) {
                customError = error.message;
            }
            
            // 测试 qs.stringify
            try {
                qsResult = Qs.stringify(data, options);
            } catch (error) {
                qsError = error.message;
            }
            
            const isEqual = customResult === qsResult;
            const result = {
                name,
                data,
                options,
                customResult,
                qsResult,
                customError,
                qsError,
                isEqual
            };
            
            testResults.push(result);
            displayTestResult(result, index);
            
            return result;
        }

        function displayTestResult(result, index) {
            const resultsDiv = document.getElementById('results');
            const testDiv = document.createElement('div');
            testDiv.className = 'test-case';
            
            const statusClass = result.isEqual ? 'same' : 'diff';
            const statusText = result.isEqual ? '✅ 相同' : '❌ 不同';
            
            testDiv.innerHTML = `
                <div class="test-title">${index + 1}. ${result.name} - ${statusText}</div>
                <div class="input-data">
                    <strong>输入数据:</strong> ${JSON.stringify(result.data)}<br>
                    <strong>选项:</strong> ${JSON.stringify(result.options)}
                </div>
                <div class="result custom-result">
                    <strong>我们的 stringify:</strong> ${result.customError || result.customResult || 'undefined'}
                </div>
                <div class="result qs-result">
                    <strong>qs.stringify:</strong> ${result.qsError || result.qsResult || 'undefined'}
                </div>
                <div class="result ${statusClass}">
                    <strong>对比结果:</strong> ${statusText}
                    ${!result.isEqual ? '<br><strong>⚠️ 发现差异!这可能导致签名验证失败</strong>' : ''}
                </div>
            `;
            
            resultsDiv.appendChild(testDiv);
        }

        function runAllTests() {
            clearResults();
            testResults = [];
            
            testCases.forEach((testCase, index) => {
                runTest(testCase, index);
            });
            
            showSummary();
        }

        function clearResults() {
            document.getElementById('results').innerHTML = '';
            document.getElementById('summary').style.display = 'none';
            testResults = [];
        }

        function showSummary() {
            const summaryDiv = document.getElementById('summary');
            const summaryContent = document.getElementById('summaryContent');
            
            const totalTests = testResults.length;
            const passedTests = testResults.filter(r => r.isEqual).length;
            const failedTests = totalTests - passedTests;
            
            let summaryClass = 'summary';
            let summaryIcon = '✅';
            let riskLevel = '低风险';
            
            if (failedTests > 0) {
                summaryClass += ' warning';
                summaryIcon = '⚠️';
                riskLevel = '中等风险';
                
                if (failedTests > totalTests * 0.5) {
                    summaryClass = 'summary error';
                    summaryIcon = '❌';
                    riskLevel = '高风险';
                }
            }
            
            summaryDiv.className = summaryClass;
            
            const failedTestsList = testResults
                .filter(r => !r.isEqual)
                .map(r => `<li><strong>${r.name}</strong>: 可能影响签名验证</li>`)
                .join('');
            
            summaryContent.innerHTML = `
                <h4>${summaryIcon} 测试完成</h4>
                <p><strong>总测试数:</strong> ${totalTests}</p>
                <p><strong>通过:</strong> ${passedTests}</p>
                <p><strong>失败:</strong> ${failedTests}</p>
                <p><strong>兼容性风险等级:</strong> ${riskLevel}</p>
                
                ${failedTests > 0 ? `
                    <h4>🚨 发现的差异:</h4>
                    <ul>${failedTestsList}</ul>
                    <h4>💡 建议:</h4>
                    <ul>
                        <li>如果之前使用 qs.stringify,建议保持使用以确保向后兼容</li>
                        <li>如果必须使用自定义 stringify,需要更新现有签名验证逻辑</li>
                        <li>考虑添加兼容性层来处理两种格式</li>
                    </ul>
                ` : `
                    <h4>🎉 完全兼容!</h4>
                    <p>我们的 stringify 函数与 qs.stringify 完全兼容,可以安全替换。</p>
                `}
            `;
            
            summaryDiv.style.display = 'block';
        }

        // 页面加载完成后自动运行测试
        window.onload = function() {
            console.log('页面加载完成,准备运行 stringify 对比测试...');
        };
    </script>
</body>
</html>