-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_app.py
More file actions
1394 lines (1015 loc) · 38.5 KB
/
Copy pathtest_app.py
File metadata and controls
1394 lines (1015 loc) · 38.5 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
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
日期 API 單元測試
測試日期計算和驗證功能。
"""
import pytest
from datetime import datetime
from date_calculator import DateCalculator, DateValidator
from app import app, DateAPIService
class TestDateCalculator:
"""
測試 DateCalculator 類別
"""
def setup_method(self):
"""
設置測試環境。
在每個測試方法執行前調用。
Args:
無
Returns:
None
Examples:
自動在每個測試方法前執行
Raises:
不拋出異常
"""
self.calculator = DateCalculator()
def test_calculate_dates_basic(self):
"""
測試基本日期計算功能。
驗證當輸入有效的月份偏移量和日期時,能正確計算目標日期。
Args:
無
Returns:
None
Examples:
pytest test_app.py::TestDateCalculator::test_calculate_dates_basic
Raises:
AssertionError: 當測試失敗時
"""
result = self.calculator.calculate_dates(0, 15, 20)
current_date = datetime.now()
expected_year = current_date.year
expected_month = current_date.month
assert result["target_year"] == expected_year
assert result["target_month"] == expected_month
assert result["departure_date"] == f"{expected_year}-{expected_month:02d}-15"
assert result["return_date"] == f"{expected_year}-{expected_month:02d}-20"
def test_calculate_dates_with_offset(self):
"""
測試帶月份偏移量的日期計算。
驗證當輸入月份偏移量時,能正確計算未來月份的日期。
Args:
無
Returns:
None
Examples:
pytest test_app.py::TestDateCalculator::test_calculate_dates_with_offset
Raises:
AssertionError: 當測試失敗時
"""
result = self.calculator.calculate_dates(2, 5, 10)
current_date = datetime.now()
target_month = current_date.month + 2
target_year = current_date.year
if target_month > 12:
target_month -= 12
target_year += 1
assert result["target_year"] == target_year
assert result["target_month"] == target_month
assert result["departure_date"] == f"{target_year}-{target_month:02d}-05"
assert result["return_date"] == f"{target_year}-{target_month:02d}-10"
def test_calculate_dates_cross_year(self):
"""
測試跨年的日期計算。
驗證當月份偏移量導致跨年時,能正確處理年份變化。
Args:
無
Returns:
None
Examples:
pytest test_app.py::TestDateCalculator::test_calculate_dates_cross_year
Raises:
AssertionError: 當測試失敗時
"""
result = self.calculator.calculate_dates(15, 5, 10)
current_date = datetime.now()
target_month = current_date.month + 15
target_year = current_date.year
while target_month > 12:
target_month -= 12
target_year += 1
assert result["target_year"] == target_year
assert result["target_month"] == target_month
def test_calculate_dates_exceeds_month_days(self):
"""
測試日期超過月份天數的情況。
驗證當輸入的日期天數超過目標月份的最大天數時,能自動調整為該月份的最後一天。
Args:
無
Returns:
None
Examples:
pytest test_app.py::TestDateCalculator::test_calculate_dates_exceeds_month_days
Raises:
AssertionError: 當測試失敗時
"""
# 2月最多29天(閏年)或28天
result = self.calculator.calculate_dates(1, 31, 31)
# 驗證日期不會超過該月份的最大天數
dep_date_parts = result["departure_date"].split("-")
return_date_parts = result["return_date"].split("-")
assert int(dep_date_parts[2]) <= 31
assert int(return_date_parts[2]) <= 31
def test_calculate_dates_negative_offset(self):
"""
測試負數月份偏移量的錯誤處理。
驗證當輸入負數月份偏移量時,拋出 ValueError。
Args:
無
Returns:
None
Examples:
pytest test_app.py::TestDateCalculator::test_calculate_dates_negative_offset
Raises:
AssertionError: 當測試失敗時
"""
with pytest.raises(ValueError) as exc_info:
self.calculator.calculate_dates(-1, 5, 10)
assert "月份偏移量必須為非負整數" in str(exc_info.value)
def test_calculate_dates_invalid_dep_day(self):
"""
測試無效出發日期的錯誤處理。
驗證當出發日期超出範圍時,拋出 ValueError。
Args:
無
Returns:
None
Examples:
pytest test_app.py::TestDateCalculator::test_calculate_dates_invalid_dep_day
Raises:
AssertionError: 當測試失敗時
"""
with pytest.raises(ValueError) as exc_info:
self.calculator.calculate_dates(2, 0, 10)
assert "出發日期天數必須在 1-31 之間" in str(exc_info.value)
def test_calculate_dates_invalid_return_day(self):
"""
測試無效回程日期的錯誤處理。
驗證當回程日期超出範圍時,拋出 ValueError。
Args:
無
Returns:
None
Examples:
pytest test_app.py::TestDateCalculator::test_calculate_dates_invalid_return_day
Raises:
AssertionError: 當測試失敗時
"""
with pytest.raises(ValueError) as exc_info:
self.calculator.calculate_dates(2, 5, 32)
assert "回程日期天數必須在 1-31 之間" in str(exc_info.value)
class TestDateValidator:
"""
測試 DateValidator 類別
"""
def setup_method(self):
"""
設置測試環境。
在每個測試方法執行前調用。
Args:
無
Returns:
None
Examples:
自動在每個測試方法前執行
Raises:
不拋出異常
"""
self.validator = DateValidator()
def test_validate_input_valid(self):
"""
測試有效輸入的驗證。
驗證當所有參數都有效時,返回 True。
Args:
無
Returns:
None
Examples:
pytest test_app.py::TestDateValidator::test_validate_input_valid
Raises:
AssertionError: 當測試失敗時
"""
data = {
"month_offset": 2,
"dep_day": 5,
"return_day": 10
}
is_valid, error = self.validator.validate_input(data)
assert is_valid is True
assert error == ""
def test_validate_input_missing_fields(self):
"""
測試缺少必要欄位的驗證。
驗證當缺少必要參數時,返回 False 和錯誤訊息。
Args:
無
Returns:
None
Examples:
pytest test_app.py::TestDateValidator::test_validate_input_missing_fields
Raises:
AssertionError: 當測試失敗時
"""
data = {
"month_offset": 2,
"dep_day": 5
}
is_valid, error = self.validator.validate_input(data)
assert is_valid is False
assert "缺少必要參數" in error
def test_validate_input_invalid_type(self):
"""
測試無效數據類型的驗證。
驗證當參數類型錯誤時,返回 False 和錯誤訊息。
Args:
無
Returns:
None
Examples:
pytest test_app.py::TestDateValidator::test_validate_input_invalid_type
Raises:
AssertionError: 當測試失敗時
"""
data = {
"month_offset": "invalid",
"dep_day": 5,
"return_day": 10
}
is_valid, error = self.validator.validate_input(data)
assert is_valid is False
assert "參數必須為整數類型" in error
def test_validate_input_negative_offset(self):
"""
測試負數月份偏移量的驗證。
驗證當月份偏移量為負數時,返回 False 和錯誤訊息。
Args:
無
Returns:
None
Examples:
pytest test_app.py::TestDateValidator::test_validate_input_negative_offset
Raises:
AssertionError: 當測試失敗時
"""
data = {
"month_offset": -1,
"dep_day": 5,
"return_day": 10
}
is_valid, error = self.validator.validate_input(data)
assert is_valid is False
assert "month_offset 必須為非負整數" in error
def test_validate_input_invalid_day_range(self):
"""
測試日期範圍超出的驗證。
驗證當日期天數超出 1-31 範圍時,返回 False 和錯誤訊息。
Args:
無
Returns:
None
Examples:
pytest test_app.py::TestDateValidator::test_validate_input_invalid_day_range
Raises:
AssertionError: 當測試失敗時
"""
data = {
"month_offset": 2,
"dep_day": 0,
"return_day": 10
}
is_valid, error = self.validator.validate_input(data)
assert is_valid is False
assert "dep_day 必須在 1-31 之間" in error
class TestFlaskAPI:
"""
測試 Flask API 端點
"""
@pytest.fixture
def client(self):
"""
創建 Flask 測試客戶端。
用於測試 API 端點。
Args:
無
Returns:
FlaskClient: Flask 測試客戶端
Examples:
在測試方法中作為參數使用
Raises:
不拋出異常
"""
app.config['TESTING'] = True
with app.test_client() as client:
yield client
def test_calculate_dates_endpoint_success(self, client):
"""
測試成功的日期計算 API 請求。
驗證 POST /calculate_dates 端點在有效輸入下返回正確結果。
Args:
client: Flask 測試客戶端
Returns:
None
Examples:
pytest test_app.py::TestFlaskAPI::test_calculate_dates_endpoint_success
Raises:
AssertionError: 當測試失敗時
"""
response = client.post(
'/calculate_dates',
json={
"month_offset": 2,
"dep_day": 5,
"return_day": 10
}
)
assert response.status_code == 200
data = response.get_json()
assert data["success"] is True
assert "data" in data
assert "departure_date" in data["data"]
assert "return_date" in data["data"]
assert "target_year" in data["data"]
assert "target_month" in data["data"]
def test_calculate_dates_endpoint_missing_params(self, client):
"""
測試缺少參數的 API 請求。
驗證當缺少必要參數時,API 返回 400 錯誤。
Args:
client: Flask 測試客戶端
Returns:
None
Examples:
pytest test_app.py::TestFlaskAPI::test_calculate_dates_endpoint_missing_params
Raises:
AssertionError: 當測試失敗時
"""
response = client.post(
'/calculate_dates',
json={
"month_offset": 2,
"dep_day": 5
}
)
assert response.status_code == 400
data = response.get_json()
assert "error" in data
def test_calculate_dates_endpoint_invalid_json(self, client):
"""
測試無效 JSON 格式的 API 請求。
驗證當請求體不是 JSON 格式時,API 返回錯誤(415 或 400)。
Args:
client: Flask 測試客戶端
Returns:
None
Examples:
pytest test_app.py::TestFlaskAPI::test_calculate_dates_endpoint_invalid_json
Raises:
AssertionError: 當測試失敗時
"""
response = client.post(
'/calculate_dates',
data="invalid json"
)
# Flask 對於非 JSON 內容類型返回 415 Unsupported Media Type
assert response.status_code in [400, 415]
def test_calculate_dates_endpoint_negative_offset(self, client):
"""
測試負數月份偏移量的 API 請求。
驗證當月份偏移量為負數時,API 返回 400 錯誤。
Args:
client: Flask 測試客戶端
Returns:
None
Examples:
pytest test_app.py::TestFlaskAPI::test_calculate_dates_endpoint_negative_offset
Raises:
AssertionError: 當測試失敗時
"""
response = client.post(
'/calculate_dates',
json={
"month_offset": -1,
"dep_day": 5,
"return_day": 10
}
)
assert response.status_code == 400
data = response.get_json()
assert "error" in data
def test_health_endpoint(self, client):
"""
測試健康檢查端點。
驗證 GET /health 端點返回正確的健康狀態。
Args:
client: Flask 測試客戶端
Returns:
None
Examples:
pytest test_app.py::TestFlaskAPI::test_health_endpoint
Raises:
AssertionError: 當測試失敗時
"""
response = client.get('/health')
assert response.status_code == 200
data = response.get_json()
assert data["status"] == "healthy"
class TestDateAPIService:
"""
測試 DateAPIService 類別
"""
def setup_method(self):
"""
設置測試環境。
在每個測試方法執行前調用。
Args:
無
Returns:
None
Examples:
自動在每個測試方法前執行
Raises:
不拋出異常
"""
self.service = DateAPIService(DateCalculator(), DateValidator())
def test_process_request_success(self):
"""
測試成功處理請求。
驗證服務能正確處理有效的請求數據。
Args:
無
Returns:
None
Examples:
pytest test_app.py::TestDateAPIService::test_process_request_success
Raises:
AssertionError: 當測試失敗時
"""
data = {
"month_offset": 2,
"dep_day": 5,
"return_day": 10
}
response, status_code = self.service.process_request(data)
assert status_code == 200
assert response["success"] is True
assert "data" in response
def test_process_request_validation_error(self):
"""
測試驗證錯誤的處理。
驗證服務能正確處理驗證失敗的情況。
Args:
無
Returns:
None
Examples:
pytest test_app.py::TestDateAPIService::test_process_request_validation_error
Raises:
AssertionError: 當測試失敗時
"""
data = {
"month_offset": -1,
"dep_day": 5,
"return_day": 10
}
response, status_code = self.service.process_request(data)
assert status_code == 400
assert "error" in response
class TestHolidayDateCalculator:
"""
測試 HolidayDateCalculator 類別
"""
def setup_method(self):
"""
設置測試環境。
在每個測試方法執行前調用。
Args:
無
Returns:
None
Examples:
自動在每個測試方法前執行
Raises:
不拋出異常
"""
from holiday_calculator import HolidayDateCalculator
self.calculator = HolidayDateCalculator()
def test_calculate_dates_basic(self):
"""
測試基本節日日期計算功能。
驗證當輸入有效的月份偏移量時,能返回正確的結構。
Args:
無
Returns:
None
Examples:
pytest test_app.py::TestHolidayDateCalculator::test_calculate_dates_basic
Raises:
AssertionError: 當測試失敗時
"""
result = self.calculator.calculate_dates(2)
assert "target_year" in result
assert "target_month" in result
assert "holidays" in result
assert isinstance(result["holidays"], list)
def test_calculate_dates_negative_offset(self):
"""
測試負數月份偏移量的錯誤處理。
驗證當輸入負數月份偏移量時,拋出 ValueError。
Args:
無
Returns:
None
Examples:
pytest test_app.py::TestHolidayDateCalculator::test_calculate_dates_negative_offset
Raises:
AssertionError: 當測試失敗時
"""
with pytest.raises(ValueError) as exc_info:
self.calculator.calculate_dates(-1)
assert "月份偏移量必須為非負整數" in str(exc_info.value)
class TestHolidayFilter:
"""
測試 HolidayFilter 類別
"""
def setup_method(self):
"""
設置測試環境。
在每個測試方法執行前調用。
Args:
無
Returns:
None
Examples:
自動在每個測試方法前執行
Raises:
不拋出異常
"""
from holiday_calculator import HolidayFilter
self.filter = HolidayFilter()
def test_should_skip_spring_festival(self):
"""
測試春節過濾。
驗證春節應該被過濾掉。
Args:
無
Returns:
None
Examples:
pytest test_app.py::TestHolidayFilter::test_should_skip_spring_festival
Raises:
AssertionError: 當測試失敗時
"""
holiday = {'description': '春節', 'date': '20250129'}
assert self.filter.should_skip_holiday(holiday, 2) is True
def test_should_skip_lunar_new_year_eve(self):
"""
測試農曆除夕過濾。
驗證農曆除夕應該被過濾掉。
Args:
無
Returns:
None
Examples:
pytest test_app.py::TestHolidayFilter::test_should_skip_lunar_new_year_eve
Raises:
AssertionError: 當測試失敗時
"""
holiday = {'description': '農曆除夕', 'date': '20250128'}
assert self.filter.should_skip_holiday(holiday, 2) is True
def test_should_skip_fixed_range_month2(self):
"""
測試2個月後固定區間過濾。
驗證2個月後的5-10號應該被過濾掉。
Args:
無
Returns:
None
Examples:
pytest test_app.py::TestHolidayFilter::test_should_skip_fixed_range_month2
Raises:
AssertionError: 當測試失敗時
"""
holiday = {'description': '端午節', 'date': '20251207'}
assert self.filter.should_skip_holiday(holiday, 2) is True
def test_should_not_skip_normal_holiday(self):
"""
測試正常節日不應被過濾。
驗證正常的節日不應該被過濾掉。
Args:
無
Returns:
None
Examples:
pytest test_app.py::TestHolidayFilter::test_should_not_skip_normal_holiday
Raises:
AssertionError: 當測試失敗時
"""
holiday = {'description': '元旦', 'date': '20260101'}
assert self.filter.should_skip_holiday(holiday, 3) is False
class TestHolidayDateRangeCalculator:
"""
測試 HolidayDateRangeCalculator 類別
"""
def setup_method(self):
"""
設置測試環境。
在每個測試方法執行前調用。
Args:
無
Returns:
None
Examples:
自動在每個測試方法前執行
Raises:
不拋出異常
"""
from holiday_calculator import HolidayDateRangeCalculator
self.calculator = HolidayDateRangeCalculator()
def test_calculate_date_range_general_monday(self):
"""
測試一般週一假日的日期範圍計算。
驗證週一假日的出發和回程日期計算正確(前4天到當天)。
Args:
無
Returns:
None
Examples:
pytest test_app.py::TestHolidayDateRangeCalculator::test_calculate_date_range_general_monday
Raises:
AssertionError: 當測試失敗時
"""
from datetime import datetime
holiday = {'date': '20260105', 'week': '一', 'description': '測試假日'}
dep, ret = self.calculator.calculate_date_range(holiday)
# 週一假日:前4天到當天 (-4, 0)
assert dep == datetime(2026, 1, 1)
assert ret == datetime(2026, 1, 5)
def test_calculate_date_range_general_tuesday(self):
"""
測試一般週二假日的日期範圍計算。
驗證週二假日的出發和回程日期計算正確(前4天到當天)。
Args:
無
Returns:
None
Examples:
pytest test_app.py::TestHolidayDateRangeCalculator::test_calculate_date_range_general_tuesday
Raises:
AssertionError: 當測試失敗時
"""
from datetime import datetime
holiday = {'date': '20260106', 'week': '二', 'description': '測試假日'}
dep, ret = self.calculator.calculate_date_range(holiday)
# 週二假日:前4天到當天 (-4, 0)
assert dep == datetime(2026, 1, 2)
assert ret == datetime(2026, 1, 6)
def test_calculate_date_range_general_wednesday(self):
"""
測試一般週三假日的日期範圍計算。
驗證週三假日的出發和回程日期計算正確(當天到後3天)。
Args:
無
Returns:
None
Examples:
pytest test_app.py::TestHolidayDateRangeCalculator::test_calculate_date_range_general_wednesday
Raises:
AssertionError: 當測試失敗時
"""
from datetime import datetime
holiday = {'date': '20260107', 'week': '三', 'description': '測試假日'}
dep, ret = self.calculator.calculate_date_range(holiday)
# 週三假日:當天到後3天 (0, 3)
assert dep == datetime(2026, 1, 7)
assert ret == datetime(2026, 1, 10)
def test_calculate_date_range_general_thursday(self):
"""
測試一般週四假日的日期範圍計算。
驗證週四假日的出發和回程日期計算正確(前1天到後3天)。
Args:
無
Returns:
None
Examples:
pytest test_app.py::TestHolidayDateRangeCalculator::test_calculate_date_range_general_thursday
Raises:
AssertionError: 當測試失敗時
"""
from datetime import datetime
holiday = {'date': '20260108', 'week': '四', 'description': '測試假日'}
dep, ret = self.calculator.calculate_date_range(holiday)
# 週四假日:前1天到後3天 (-1, 3)
assert dep == datetime(2026, 1, 7)
assert ret == datetime(2026, 1, 11)
def test_calculate_date_range_general_friday(self):
"""
測試一般週五假日的日期範圍計算。
驗證週五假日的出發和回程日期計算正確(前2天到後2天)。
Args:
無
Returns:
None
Examples:
pytest test_app.py::TestHolidayDateRangeCalculator::test_calculate_date_range_general_friday
Raises:
AssertionError: 當測試失敗時
"""
from datetime import datetime
holiday = {'date': '20260109', 'week': '五', 'description': '測試假日'}
dep, ret = self.calculator.calculate_date_range(holiday)
# 週五假日:前2天到後2天 (-2, 2)
assert dep == datetime(2026, 1, 7)
assert ret == datetime(2026, 1, 11)
def test_calculate_date_range_general_saturday(self):
"""
測試一般週六假日的日期範圍計算。