-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathhttpclient_unittest.cc
More file actions
810 lines (652 loc) · 24.8 KB
/
httpclient_unittest.cc
File metadata and controls
810 lines (652 loc) · 24.8 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
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
#include "httpclient.hpp"
#include <QCoreApplication>
#include <QFile>
#include <QJsonArray>
#include <QJsonObject>
#include <QMutex>
#include <QTemporaryDir>
#include <QTest>
#include <QThread>
#include <QTimer>
class HttpClientTest : public QObject
{
Q_OBJECT
private slots:
void initTestCase();
void cleanupTestCase();
void init();
void cleanup();
// 基础功能测试
void testGetRequest();
void testPostRequest();
void testPutRequest();
void testDeleteRequest();
void testPostRequestWithVariousData();
// 文件传输测试
void testDownload();
void testDownloadProgress();
void testUploadPutFile();
void testUploadPutData();
void testUploadPostFile();
void testUploadPostData();
// 错误和边界情况测试
void testTimeout();
void testNetworkErrorScenarios();
void testCancelMechanism();
void testBoundaryConditions();
void testDownloadEdgeCases();
// 功能特性测试
void testSyncRequest();
void testCustomHeaders();
void testMultipleRequests();
void testConcurrentRequests();
void testHttpClientStateManagement();
private:
// 测试辅助方法
bool isTestServerAvailable();
QNetworkReply *createBasicGetRequest();
void verifySuccessfulResponse(const QJsonObject &response);
void createFile(const QString &filename, const QByteArray &data);
void removeFile(const QString &filename);
QJsonObject waitForReply(QNetworkReply *reply);
void cleanupReply(QNetworkReply *reply);
HttpClient *m_httpClient;
QString m_baseUrl;
QTemporaryDir m_tempDir;
bool m_serverAvailable;
};
void HttpClientTest::initTestCase()
{
m_httpClient = new HttpClient(this);
m_baseUrl = "http://127.0.0.1:8000/api";
QVERIFY(m_tempDir.isValid());
qDebug() << "HttpClient Unit Tests Starting";
qDebug() << "Base URL:" << m_baseUrl;
qDebug() << "Temp Dir:" << m_tempDir.path();
m_serverAvailable = isTestServerAvailable();
if (!m_serverAvailable) {
qWarning() << "Test server not available at" << m_baseUrl;
qWarning() << "Some tests will be skipped";
}
}
void HttpClientTest::cleanupTestCase()
{
delete m_httpClient;
qDebug() << "HttpClient Unit Tests Finished";
}
void HttpClientTest::init()
{
if (!m_serverAvailable) {
QSKIP("Test server not available");
}
}
void HttpClientTest::cleanup()
{
// 每个测试后的小延迟,确保资源清理
QTest::qWait(100);
}
bool HttpClientTest::isTestServerAvailable()
{
QNetworkAccessManager nam;
QNetworkRequest request(QUrl("http://127.0.0.1:8000/api/health"));
QNetworkReply *reply = nam.get(request);
QEventLoop loop;
QTimer timeoutTimer;
timeoutTimer.setSingleShot(true);
connect(reply, &QNetworkReply::finished, &loop, &QEventLoop::quit);
connect(&timeoutTimer, &QTimer::timeout, &loop, &QEventLoop::quit);
timeoutTimer.start(3000);
loop.exec();
bool available = (reply->error() == QNetworkReply::NoError);
if (available) {
QByteArray response = reply->readAll();
qDebug() << "Server health check response:" << response;
}
reply->deleteLater();
return available;
}
QNetworkReply *HttpClientTest::createBasicGetRequest()
{
return m_httpClient->sendRequest(HttpClient::Method::GET, m_baseUrl + "/test", {}, {}, -1, true);
}
void HttpClientTest::verifySuccessfulResponse(const QJsonObject &response)
{
QVERIFY(!response.isEmpty());
QVERIFY(!response.contains("error"));
// 根据API响应结构验证基本字段
if (response.contains("method")) {
QString method = response["method"].toString();
QVERIFY(!method.isEmpty());
}
if (response.contains("message")) {
QString message = response["message"].toString();
QVERIFY(!message.isEmpty());
}
}
void HttpClientTest::createFile(const QString &filename, const QByteArray &data)
{
QString filepath = m_tempDir.filePath(filename);
QDir().mkpath(QFileInfo(filepath).absoluteDir().path());
QFile file(filepath);
QVERIFY(file.open(QIODevice::WriteOnly));
file.write(data);
file.close();
}
void HttpClientTest::removeFile(const QString &filename)
{
QString filepath = m_tempDir.filePath(filename);
QFile file(filepath);
if (file.exists()) {
file.remove();
}
}
QJsonObject HttpClientTest::waitForReply(QNetworkReply *reply)
{
QEventLoop loop;
QJsonObject result;
bool finished = false;
// 连接ready信号
connect(m_httpClient,
&HttpClient::ready,
&loop,
[&](QNetworkReply *readyReply, const QJsonObject &json) {
if (readyReply == reply) {
result = json;
finished = true;
loop.quit();
}
});
// 设置超时
QTimer::singleShot(10000, &loop, [&]() {
if (!finished) {
qWarning() << "Request timeout in waitForReply for URL:" << reply->url().toString();
loop.quit();
}
});
loop.exec();
return result;
}
void HttpClientTest::cleanupReply(QNetworkReply *reply)
{
if (reply) {
reply->deleteLater();
}
}
// 基础功能测试
void HttpClientTest::testGetRequest()
{
auto *reply = createBasicGetRequest();
QVERIFY(reply != nullptr);
QJsonObject response = waitForReply(reply);
verifySuccessfulResponse(response);
QCOMPARE(response["method"].toString(), QString("GET"));
QVERIFY(reply->isFinished());
QCOMPARE(reply->error(), QNetworkReply::NoError);
cleanupReply(reply);
}
void HttpClientTest::testPostRequest()
{
QJsonObject requestBody;
requestBody["test_key"] = "test_value";
requestBody["number"] = 42;
auto *reply = m_httpClient->sendRequest(HttpClient::Method::POST,
m_baseUrl + "/echo",
{},
requestBody,
-1,
true);
QJsonObject response = waitForReply(reply);
verifySuccessfulResponse(response);
// 验证回显数据
QVERIFY(response.contains("echo_data"));
cleanupReply(reply);
}
void HttpClientTest::testPutRequest()
{
auto *reply = m_httpClient->upload_put(m_baseUrl + "/echo",
QByteArray("test put data"),
-1,
true);
QJsonObject response = waitForReply(reply);
verifySuccessfulResponse(response);
cleanupReply(reply);
}
void HttpClientTest::testDeleteRequest()
{
auto *reply = m_httpClient->sendRequest(HttpClient::Method::DELETE,
m_baseUrl + "/test",
{},
{},
-1,
true);
QJsonObject response = waitForReply(reply);
verifySuccessfulResponse(response);
QCOMPARE(response["method"].toString(), QString("DELETE"));
cleanupReply(reply);
}
void HttpClientTest::testPostRequestWithVariousData()
{
struct TestCase
{
QJsonObject requestBody;
QString description;
};
QVector<TestCase> testCases = {{QJsonObject{{"string", "value"}}, "Simple string"},
{QJsonObject{{"number", 42}, {"float", 3.14}}, "Numbers"},
{QJsonObject{{"bool_true", true}, {"bool_false", false}},
"Booleans"},
{QJsonObject{{"array", QJsonArray{1, 2, 3}}}, "Array"},
{QJsonObject{{"nested", QJsonObject{{"key", "value"}}}},
"Nested object"},
{QJsonObject{}, "Empty object"}};
for (const auto &testCase : testCases) {
qDebug() << "Testing POST with:" << testCase.description;
auto *reply = m_httpClient->sendRequest(HttpClient::Method::POST,
m_baseUrl + "/echo",
{},
testCase.requestBody,
-1,
true);
QJsonObject response = waitForReply(reply);
QVERIFY(!response.isEmpty());
QVERIFY(response.contains("echo_data"));
cleanupReply(reply);
}
}
// 文件传输测试
void HttpClientTest::testDownload()
{
QString downloadPath = m_tempDir.filePath("test_download.txt");
auto *reply = m_httpClient->downLoad(QUrl("http://127.0.0.1:8000/download"),
downloadPath,
-1,
true);
QJsonObject response = waitForReply(reply);
// 验证下载完成
QVERIFY(QFile::exists(downloadPath));
QFile file(downloadPath);
QVERIFY(file.open(QIODevice::ReadOnly));
QByteArray content = file.readAll();
file.close();
QVERIFY(content.contains("test file content"));
cleanupReply(reply);
}
void HttpClientTest::testDownloadProgress()
{
QString downloadPath = m_tempDir.filePath("progress_test.txt");
QVector<qint64> progressValues;
QMutex progressMutex;
bool progressCalled = false;
HttpClient::ProgressCallback progressCallback = [&](qint64 bytesReceived, qint64 bytesTotal) {
QMutexLocker locker(&progressMutex);
progressCalled = true;
progressValues.append(bytesReceived);
qDebug() << "Download progress:" << bytesReceived << "/" << bytesTotal;
QVERIFY(bytesReceived >= 0);
QVERIFY(bytesTotal >= 0);
if (bytesTotal > 0) {
QVERIFY(bytesReceived <= bytesTotal);
}
};
auto *reply = m_httpClient->downLoad(QUrl("http://127.0.0.1:8000/download"),
downloadPath,
-1,
true,
progressCallback);
QJsonObject response = waitForReply(reply);
// 验证进度回调被调用
QVERIFY(progressCalled);
QVERIFY(progressValues.size() > 0);
// 验证文件下载完成
QVERIFY(QFile::exists(downloadPath));
cleanupReply(reply);
}
void HttpClientTest::testUploadPutFile()
{
QString filename = "test_upload_put.txt";
QByteArray fileData = "This is test content for PUT file upload";
createFile(filename, fileData);
auto *reply = m_httpClient->upload_put(m_baseUrl + "/echo",
m_tempDir.filePath(filename),
-1,
true);
QJsonObject response = waitForReply(reply);
verifySuccessfulResponse(response);
cleanupReply(reply);
removeFile(filename);
}
void HttpClientTest::testUploadPutData()
{
QByteArray data = "This is test data for PUT upload";
auto *reply = m_httpClient->upload_put(m_baseUrl + "/echo", data, -1, true);
QJsonObject response = waitForReply(reply);
verifySuccessfulResponse(response);
cleanupReply(reply);
}
void HttpClientTest::testUploadPostFile()
{
QString filename = "test_upload_post.txt";
QByteArray fileData = "This is test content for POST file upload";
createFile(filename, fileData);
auto *reply = m_httpClient->upload_post(m_baseUrl + "/echo",
m_tempDir.filePath(filename),
-1,
true);
QJsonObject response = waitForReply(reply);
verifySuccessfulResponse(response);
cleanupReply(reply);
removeFile(filename);
}
void HttpClientTest::testUploadPostData()
{
QByteArray data = "This is test data for POST upload";
auto *reply = m_httpClient->upload_post(m_baseUrl + "/echo", "test_file.txt", data, -1, true);
QJsonObject response = waitForReply(reply);
verifySuccessfulResponse(response);
cleanupReply(reply);
}
// 错误和边界情况测试
void HttpClientTest::testTimeout()
{
bool timeoutReceived = false;
bool callbackCalled = false;
connect(m_httpClient, &HttpClient::timeOut, this, [&timeoutReceived]() {
timeoutReceived = true;
qDebug() << "Timeout signal received";
});
HttpClient::JsonCallback callback = [&callbackCalled](const QJsonObject &json) {
callbackCalled = true;
qDebug() << "Timeout callback called with error:" << json["error"].toInt();
};
// 使用1秒超时,请求会超时的端点
auto *reply = m_httpClient->sendRequest(HttpClient::Method::GET,
QUrl("http://127.0.0.1:8000/api/timeout"),
{},
{},
1, // 1秒超时
true,
callback);
QJsonObject response = waitForReply(reply);
QVERIFY(timeoutReceived);
QVERIFY(callbackCalled);
QVERIFY(response.contains("error"));
cleanupReply(reply);
}
void HttpClientTest::testNetworkErrorScenarios()
{
struct ErrorCase
{
QUrl url;
QString description;
bool expectError;
};
QVector<ErrorCase> errorCases
= {{QUrl("http://invalid-domain-that-definitely-does-not-exist-12345.xyz"),
"Invalid domain",
true},
{QUrl("http://192.168.255.255:9999"), "Unreachable IP", true},
{m_baseUrl + "/test", "Valid URL", false}};
for (const auto &errorCase : errorCases) {
qDebug() << "Testing error case:" << errorCase.description;
bool errorOccurred = false;
bool finished = false;
HttpClient::JsonCallback callback = [&](const QJsonObject &json) {
finished = true;
if (json.contains("error")) {
errorOccurred = true;
qDebug() << "Error occurred:" << json["error"].toInt();
}
};
auto *reply = m_httpClient->sendRequest(HttpClient::Method::GET,
errorCase.url,
{},
{},
3, // 3秒超时
true,
callback);
QTRY_VERIFY_WITH_TIMEOUT(finished, 5000);
QCOMPARE(errorOccurred, errorCase.expectError);
if (reply) {
cleanupReply(reply);
}
}
}
void HttpClientTest::testCancelMechanism()
{
// 测试立即取消
{
bool callbackCalled = false;
HttpClient::JsonCallback callback = [&](const QJsonObject &) { callbackCalled = true; };
auto *reply = m_httpClient->sendRequest(HttpClient::Method::GET,
m_baseUrl + "/test",
{},
{},
-1,
true,
callback);
// 立即取消
m_httpClient->cancel(reply);
QTest::qWait(100);
QVERIFY(!callbackCalled);
}
// 测试进行中取消
{
QEventLoop loop;
bool callbackCalled = false;
HttpClient::JsonCallback callback = [&](const QJsonObject &) {
callbackCalled = true;
loop.quit();
};
auto *reply = m_httpClient->sendRequest(HttpClient::Method::GET,
m_baseUrl + "/test",
{},
{},
-1,
true,
callback);
QTimer::singleShot(50, [this, reply]() { m_httpClient->cancel(reply); });
QTimer::singleShot(1000, &loop, &QEventLoop::quit);
loop.exec();
// 主要验证不会崩溃,回调是否被调用取决于取消时机
QVERIFY(true);
}
}
void HttpClientTest::testBoundaryConditions()
{
// 测试空URL
auto *reply1 = m_httpClient->sendRequest(HttpClient::Method::GET, QUrl(), {}, {}, -1, true);
QJsonObject response1 = waitForReply(reply1);
QVERIFY(response1.contains("error"));
cleanupReply(reply1);
// 测试自定义headers
HttpClient::HttpHeaders headers;
headers["X-Custom-Header"] = "CustomValue";
headers["Authorization"] = "Bearer test-token";
auto *reply2 = m_httpClient->sendRequest(HttpClient::Method::GET,
m_baseUrl + "/headers",
headers,
{},
-1,
true);
QJsonObject response2 = waitForReply(reply2);
QVERIFY(!response2.isEmpty());
QVERIFY(response2.contains("headers"));
cleanupReply(reply2);
// 测试特殊字符
HttpClient::HttpHeaders specialHeaders{{"X-Special", "Header with spaces and \t tabs"},
{"X-Unicode", "测试 🚀 emoji"}};
auto *reply3 = m_httpClient->sendRequest(HttpClient::Method::GET,
m_baseUrl + "/headers",
specialHeaders,
{},
-1,
true);
QJsonObject response3 = waitForReply(reply3);
QVERIFY(!response3.isEmpty());
cleanupReply(reply3);
}
void HttpClientTest::testDownloadEdgeCases()
{
// 测试下载到已存在的文件
QString existingPath = m_tempDir.filePath("existing_file.txt");
QFile existingFile(existingPath);
QVERIFY(existingFile.open(QIODevice::WriteOnly));
existingFile.write("Existing content");
existingFile.close();
auto *reply1 = m_httpClient->downLoad(QUrl("http://127.0.0.1:8000/download"),
existingPath,
-1,
true);
QJsonObject response1 = waitForReply(reply1);
QVERIFY(QFile::exists(existingPath));
cleanupReply(reply1);
// 测试无效的下载路径
QString invalidPath = "/invalid/path/test.txt";
auto *reply2 = m_httpClient->downLoad(QUrl("http://127.0.0.1:8000/download"),
invalidPath,
-1,
true);
// 对于无效路径,reply可能为nullptr或包含错误
if (reply2) {
QJsonObject response2 = waitForReply(reply2);
// 响应可能包含错误信息
QVERIFY(true); // 主要验证不会崩溃
cleanupReply(reply2);
}
}
// 功能特性测试
void HttpClientTest::testSyncRequest()
{
auto *reply = createBasicGetRequest();
QJsonObject response = m_httpClient->sync(reply);
verifySuccessfulResponse(response);
QCOMPARE(response["method"].toString(), QString("GET"));
cleanupReply(reply);
}
void HttpClientTest::testCustomHeaders()
{
HttpClient::HttpHeaders headers;
headers["X-Custom-Header"] = "CustomValue";
headers["Authorization"] = "Bearer test-token";
headers["X-Test-Number"] = "12345";
auto *reply = m_httpClient->sendRequest(HttpClient::Method::GET,
m_baseUrl + "/headers",
headers,
{},
-1,
true);
QJsonObject response = waitForReply(reply);
QVERIFY(!response.isEmpty());
QVERIFY(response.contains("headers"));
auto responseHeaders = response["headers"].toObject();
QVERIFY(responseHeaders.contains("X-Custom-Header"));
QCOMPARE(responseHeaders["X-Custom-Header"].toString(), QString("CustomValue"));
cleanupReply(reply);
}
void HttpClientTest::testMultipleRequests()
{
const int totalRequests = 3;
QVector<QJsonObject> responses;
QVector<QNetworkReply *> replies;
QEventLoop loop;
std::atomic<int> completedRequests{0};
auto sharedCallback = LifecycleCallback<const QJsonObject &>([&](const QJsonObject &json) {
responses.append(json);
completedRequests++;
if (completedRequests == totalRequests) {
loop.quit();
}
});
for (int i = 0; i < totalRequests; ++i) {
auto *reply = m_httpClient->sendRequest(HttpClient::Method::GET,
m_baseUrl + "/test",
{{"X-Request-ID", QString::number(i)}},
{},
30,
true,
sharedCallback);
QVERIFY(reply != nullptr);
replies.append(reply);
}
QTimer timeoutTimer;
timeoutTimer.setSingleShot(true);
connect(&timeoutTimer, &QTimer::timeout, &loop, &QEventLoop::quit);
timeoutTimer.start(30000);
loop.exec();
QCOMPARE(completedRequests, totalRequests);
QCOMPARE(responses.size(), totalRequests);
for (const auto &response : responses) {
verifySuccessfulResponse(response);
}
for (auto *reply : replies) {
cleanupReply(reply);
}
}
void HttpClientTest::testConcurrentRequests()
{
const int concurrentCount = 5;
QVector<QNetworkReply *> replies;
QVector<QJsonObject> responses;
QEventLoop loop;
std::atomic<int> completedCount{0};
for (int i = 0; i < concurrentCount; ++i) {
auto *reply = m_httpClient->sendRequest(HttpClient::Method::GET,
m_baseUrl + "/test",
{},
{},
-1,
true,
[&](const QJsonObject &json) {
responses.append(json);
completedCount++;
if (completedCount == concurrentCount) {
loop.quit();
}
});
replies.append(reply);
}
QTimer::singleShot(10000, &loop, &QEventLoop::quit);
loop.exec();
QCOMPARE(completedCount, concurrentCount);
QCOMPARE(responses.size(), concurrentCount);
for (const auto &response : responses) {
verifySuccessfulResponse(response);
}
for (auto *reply : replies) {
cleanupReply(reply);
}
}
void HttpClientTest::testHttpClientStateManagement()
{
const int requestCount = 3;
QVector<QNetworkReply *> replies;
QVector<QJsonObject> responses;
QMutex mutex;
for (int i = 0; i < requestCount; ++i) {
auto *reply = m_httpClient->sendRequest(HttpClient::Method::GET,
m_baseUrl + "/test",
{{"X-Request-ID", QString::number(i)}},
{},
-1,
true,
[&](const QJsonObject &json) {
QMutexLocker locker(&mutex);
responses.append(json);
});
replies.append(reply);
}
QTRY_VERIFY_WITH_TIMEOUT(responses.size() == requestCount, 10000);
for (const auto &response : responses) {
verifySuccessfulResponse(response);
}
for (auto *reply : replies) {
cleanupReply(reply);
}
// 验证HttpClient状态正常,可以继续使用
auto *newReply = createBasicGetRequest();
QJsonObject newResponse = waitForReply(newReply);
verifySuccessfulResponse(newResponse);
cleanupReply(newReply);
}
QTEST_MAIN(HttpClientTest)
#include "httpclient_unittest.moc"