File: test_controller.py

package info (click to toggle)
hishel 0.1.3-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,548 kB
  • sloc: python: 6,387; sh: 13; makefile: 4
file content (1225 lines) | stat: -rw-r--r-- 38,488 bytes parent folder | download | duplicates (2)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
import logging
import re

import pytest
from httpcore import Request, Response

from hishel._controller import (
    Controller,
    allowed_stale,
    get_age,
    get_freshness_lifetime,
    get_heuristic_freshness,
)
from hishel._utils import BaseClock, Clock


def test_is_cachable_for_cachables():
    controller = Controller()

    request = Request(b"GET", b"https://example.com", headers=[])

    response = Response(200, headers=[(b"Expires", b"some-date")])

    assert controller.is_cachable(request=request, response=response)

    response = Response(200, headers=[(b"Cache-Control", b"max-age=10000")])

    assert controller.is_cachable(request=request, response=response)


def test_force_cache_property_for_is_cachable():
    controller = Controller(force_cache=True, cacheable_status_codes=[400])
    request = Request("GET", "https://example.com", extensions={"force_cache": False})
    uncachable_response = Response(status=400)

    assert controller.is_cachable(request=request, response=uncachable_response) is False

    request = Request("GET", "https://example.com")

    assert controller.is_cachable(request=request, response=uncachable_response) is True


def test_force_cache_property_for_construct_response_from_cache():
    class MockedClock(BaseClock):
        def now(self) -> int:
            return 1440504001  # Mon, 25 Aug 2015 12:00:01 GMT

    controller = Controller(clock=MockedClock(), force_cache=True)
    original_request = Request("GET", "https://example.com")
    request = Request("GET", "https://example.com", extensions={"force_cache": False})
    cachable_response = Response(
        200,
        headers=[
            (b"Cache-Control", b"max-age=0"),
            (b"Date", b"Mon, 25 Aug 2015 12:00:00 GMT"),  # 1 second before the clock
        ],
    )

    assert isinstance(
        controller.construct_response_from_cache(
            request=request,
            response=cachable_response,
            original_request=original_request,
        ),
        Request,
    )

    request = Request("Get", "https://example.com")

    assert isinstance(
        controller.construct_response_from_cache(
            request=request,
            response=cachable_response,
            original_request=original_request,
        ),
        Response,
    )


def test_is_cachable_for_non_cachables(caplog):
    controller = Controller()

    request = Request(b"GET", b"https://example.com", headers=[])

    response = Response(200, headers=[])

    with caplog.at_level(logging.DEBUG):
        assert not controller.is_cachable(request=request, response=response)

    assert caplog.messages == [
        "Considering the resource located at https://example.com/ as not cachable "
        "since it does not contain any of the required cache directives."
    ]


def test_is_cachable_for_heuristically_cachable(caplog):
    controller = Controller(allow_heuristics=True)

    request = Request(b"GET", b"https://example.com", headers=[])

    response = Response(200, headers=[])

    with caplog.at_level(logging.DEBUG):
        assert controller.is_cachable(request=request, response=response)

    assert caplog.messages == [
        "Considering the resource located at https://example.com/ as "
        "cachable since its status code is heuristically cacheable."
    ]


def test_is_cachable_for_invalid_method(caplog):
    controller = Controller(cacheable_methods=["GET"])

    request = Request(b"POST", b"https://example.com", headers=[])

    response = Response(200, headers=[])

    with caplog.at_level(logging.DEBUG):
        assert not controller.is_cachable(request=request, response=response)

    assert caplog.messages == [
        (
            "Considering the resource located at https://example.com/ "
            "as not cachable since the request method (POST) is not in the list of cacheable methods."
        )
    ]


def test_is_cachable_for_post():
    controller = Controller(cacheable_methods=["POST"])

    request = Request(b"POST", b"https://example.com", headers=[])
    response = Response(
        status=200,
        headers=[
            (b"Cache-Control", b"max-age=3600"),
        ],
    )
    assert controller.is_cachable(request=request, response=response)


def test_controller_with_unsupported_method():
    with pytest.raises(
        RuntimeError,
        match=re.escape(
            "Hishel does not support the HTTP method `INVALID_METHOD`.\nPlease use the methods "
            "from this list: ['GET', 'HEAD', 'POST', 'PUT', 'DELETE', 'CONNECT', 'OPTIONS', 'TRACE', 'PATCH']"
        ),
    ):
        Controller(cacheable_methods=["INVALID_METHOD"])


def test_is_cachable_for_unsupported_status(caplog):
    controller = Controller(cacheable_status_codes=[301])

    request = Request(b"GET", b"https://example.com", headers=[])

    response = Response(200, headers=[(b"Expires", b"some-date")])

    with caplog.at_level(logging.DEBUG):
        assert not controller.is_cachable(request=request, response=response)

    assert caplog.messages == [
        (
            "Considering the resource located at https://example.com/ "
            "as not cachable since its status code (200) is not in the list of cacheable status codes."
        )
    ]


def test_is_cachable_for_not_final(caplog):
    controller = Controller(cacheable_status_codes=[100])

    request = Request(b"GET", b"https://example.com", headers=[])

    response = Response(100, headers=[(b"Expires", b"some-date")])

    with caplog.at_level(logging.DEBUG):
        assert not controller.is_cachable(request=request, response=response)

    assert caplog.messages == [
        "Considering the resource located at https://example.com/ as "
        "not cachable since its status code is informational."
    ]


def test_is_cachable_for_no_store(caplog):
    controller = Controller(allow_heuristics=True)

    request = Request(b"GET", b"https://example.com", headers=[])

    response = Response(200, headers=[(b"Cache-Control", b"no-store")])

    with caplog.at_level(logging.DEBUG):
        assert not controller.is_cachable(request=request, response=response)

    assert caplog.messages == [
        "Considering the resource located at https://example.com/ as not cachable"
        " since the response contains the no-store directive."
    ]


def test_is_cachable_for_shared_cache():
    controller = Controller(cache_private=False, allow_heuristics=True)

    request = Request(b"GET", b"https://example.com", headers=[])

    response = Response(200, headers=[(b"Cache-Control", b"public")])

    assert controller.is_cachable(request=request, response=response)

    response = Response(200, headers=[(b"Cache-Control", b"private")])

    assert not controller.is_cachable(request=request, response=response)

    response = Response(200, headers=[(b"Cache-Control", b"private=set-cookie")])

    assert not controller.is_cachable(request=request, response=response)


def test_is_cachable_for_private_cache(caplog):
    controller = Controller()

    request = Request(b"GET", b"https://example.com", headers=[])

    response = Response(200, headers=[(b"Cache-Control", b"private")])

    with caplog.at_level(logging.DEBUG):
        assert controller.is_cachable(request=request, response=response)

    assert caplog.messages == [
        "Considering the resource located at https://example.com/ as cachable since it"
        " meets the criteria for being stored in the cache."
    ]


def test_get_freshness_lifetime():
    response = Response(status=200, headers=[(b"Cache-Control", b"max-age=3600")])

    freshness_lifetime = get_freshness_lifetime(response=response)
    assert freshness_lifetime == 3600


def test_get_freshness_omit():
    response = Response(status=200, headers=[])

    freshness_lifetime = get_freshness_lifetime(response=response)
    assert freshness_lifetime is None


def test_get_freshness_lifetime_with_expires():
    response = Response(
        status=200,
        headers=[
            (b"Expires", b"Mon, 25 Aug 2015 12:00:00 GMT"),
            (b"Date", b"Mon, 24 Aug 2015 12:00:00 GMT"),
        ],
    )

    freshness_lifetime = get_freshness_lifetime(response=response)
    assert freshness_lifetime == 86400  # one day


def test_get_freshness_lifetime_with_invalid_expires():
    response = Response(
        status=200,
        headers=[
            (b"Expires", b"0"),
            (b"Date", b"Mon, 24 Aug 2015 12:00:00 GMT"),
        ],
    )

    freshness_lifetime = get_freshness_lifetime(response=response)
    assert freshness_lifetime is None


def test_get_freshness_lifetime_with_invalid_date():
    response = Response(
        status=200,
        headers=[
            (b"Expires", b"Mon, 25 Aug 2015 12:00:00 GMT"),
            (b"Date", b"0"),
        ],
    )

    freshness_lifetime = get_freshness_lifetime(response=response)
    assert freshness_lifetime is None


def test_get_heuristic_freshness():
    ONE_WEEK = 604_800

    class MockedClock(BaseClock):
        def now(self) -> int:
            return 1093435200  # Mon, 25 Aug 2003 12:00:00 GMT

    response = Response(status=200, headers=[(b"Last-Modified", "Mon, 25 Aug 2003 12:00:00 GMT")])
    assert get_heuristic_freshness(response=response, clock=MockedClock()) == ONE_WEEK


def test_get_heuristic_freshness_without_last_modified():
    ONE_DAY = 86400

    response = Response(200)
    assert get_heuristic_freshness(response=response, clock=Clock()) == ONE_DAY


def test_get_heuristic_invalid_last_modified():
    ONE_DAY = 86400

    response = Response(status=200, headers=[(b"Last-Modified", "0")])
    assert get_heuristic_freshness(response=response, clock=Clock()) == ONE_DAY


def test_get_age():
    class MockedClock(BaseClock):
        def now(self) -> int:
            return 1440590400

    response = Response(status=200, headers=[(b"Date", b"Tue, 25 Aug 2015 12:00:00 GMT")])
    age = get_age(response=response, clock=MockedClock())
    assert age == 86400  # One day


def test_get_age_return_inf_for_invalid_date():
    response = Response(status=200, headers=[(b"Date", b"0")])
    age = get_age(response=response, clock=Clock())

    assert age == float("inf")


def test_get_age_return_inf_for_no_date():
    age = get_age(response=Response(status=200), clock=Clock())

    assert age == float("inf")


def test_allowed_stale_no_cache():
    response = Response(status=200, headers=[(b"Cache-Control", b"no-cache")])

    assert not allowed_stale(response)


def test_allowed_stale_must_revalidate():
    response = Response(status=200, headers=[(b"Cache-Control", b"must-revalidate")])

    assert not allowed_stale(response)


def test_allowed_stale_allowed():
    response = Response(status=200, headers=[(b"Cache-Control", b"max-age=3600")])

    assert allowed_stale(response)


def test_clock():
    date_07_19_2023 = 1689764505
    assert Clock().now() > date_07_19_2023


def test_permanent_redirect_cache(caplog):
    controller = Controller()

    request = Request(b"GET", b"https://example.com")

    response = Response(status=301)

    with caplog.at_level(logging.DEBUG):
        assert controller.is_cachable(request=request, response=response)

    assert caplog.messages == [
        (
            "Considering the resource located at https://example.com/ "
            "as cachable since its status code is a permanent redirect."
        )
    ]

    response = Response(status=302)

    assert not controller.is_cachable(request=request, response=response)


def test_make_conditional_request_with_etag(caplog):
    controller = Controller()

    request = Request(
        b"GET",
        b"https://example.com",
        headers=[
            (b"Content-Type", b"application/json"),
        ],
    )

    response = Response(status=200, headers=[(b"Etag", b"some-etag")])

    with caplog.at_level(logging.DEBUG):
        controller._make_request_conditional(request=request, response=response)

    assert request.headers == [
        (b"Content-Type", b"application/json"),
        (b"If-None-Match", b"some-etag"),
    ]
    assert caplog.messages == [
        (
            "Adding the 'If-None-Match' header with the value of 'some-etag' "
            "to the request for the resource located at https://example.com/."
        )
    ]


def test_make_conditional_request_with_last_modified(caplog):
    controller = Controller()

    request = Request(
        b"GET",
        b"https://example.com",
        headers=[
            (b"Content-Type", b"application/json"),
        ],
    )

    response = Response(status=200, headers=[(b"Last-Modified", b"Wed, 21 Oct 2015 07:28:00 GMT")])

    with caplog.at_level(logging.DEBUG):
        controller._make_request_conditional(request=request, response=response)

    assert request.headers == [
        (b"Content-Type", b"application/json"),
        (b"If-Modified-Since", b"Wed, 21 Oct 2015 07:28:00 GMT"),
    ]
    assert caplog.messages == [
        "Adding the 'If-Modified-Since' header with the value of 'Wed, 21 Oct 2015 07:28:00 GMT' "
        "to the request for the resource located at https://example.com/."
    ]


def test_construct_response_from_cache_redirect(caplog):
    controller = Controller()
    response = Response(status=301)
    original_request = Request("GET", "https://example.com")
    request = Request("GET", "https://example.com")

    with caplog.at_level(logging.DEBUG):
        assert response is controller.construct_response_from_cache(
            request=request, response=response, original_request=original_request
        )

    assert caplog.messages == [
        "Considering the resource located at https://example.com/ "
        "as valid for cache use since its status code is a permanent redirect."
    ]


def test_construct_response_from_cache_fresh():
    class MockedClock(BaseClock):
        def now(self) -> int:
            return 1440504000

    controller = Controller(clock=MockedClock())
    response = Response(
        status=200,
        headers=[
            (b"Cache-Control", b"max-age=3600"),
            (b"Date", b"Mon, 25 Aug 2015 12:00:00 GMT"),
        ],
    )
    original_request = Request("GET", "https://example.com")
    request = Request("GET", "https://example.com")
    assert response is controller.construct_response_from_cache(
        request=request, response=response, original_request=original_request
    )


def test_construct_response_from_cache_stale():
    class MockedClock(BaseClock):
        def now(self) -> int:
            return 1440504002

    controller = Controller(clock=MockedClock())
    response = Response(
        status=200,
        headers=[
            (b"Cache-Control", b"max-age=1"),
            (b"Date", b"Mon, 25 Aug 2015 12:00:00 GMT"),
        ],
    )
    original_request = Request("GET", "https://example.com")
    request = Request("GET", "https://example.com")
    conditional_request = controller.construct_response_from_cache(
        request=request, response=response, original_request=original_request
    )
    assert isinstance(conditional_request, Request)


def test_construct_response_from_cache_with_always_revalidate(caplog):
    controller = Controller(always_revalidate=True)
    response = Response(
        status=200,
        headers=[
            (b"Cache-Control", b"max-age=1"),
            (b"Date", b"Mon, 25 Aug 2015 12:00:00 GMT"),
        ],
    )
    original_request = Request("GET", "https://example.com")
    request = Request("GET", "https://example.com")

    with caplog.at_level(logging.DEBUG):
        conditional_request = controller.construct_response_from_cache(
            request=request, response=response, original_request=original_request
        )
        assert isinstance(conditional_request, Request)

    assert caplog.messages == [
        "Considering the resource located at https://example.com/ "
        "as needing revalidation since the cache is set to always revalidate."
    ]


def test_construct_response_from_cache_with_must_revalidate(caplog):
    controller = Controller()
    response = Response(
        status=200,
        headers=[
            (b"Cache-Control", b"max-age=1, must-revalidate"),
            (b"Date", b"Mon, 25 Aug 2015 12:00:00 GMT"),
        ],
    )
    original_request = Request("GET", "https://example.com")
    request = Request("GET", "https://example.com")

    with caplog.at_level(logging.DEBUG):
        conditional_request = controller.construct_response_from_cache(
            request=request, response=response, original_request=original_request
        )
        assert isinstance(conditional_request, Request)

    assert caplog.messages == [
        "Considering the resource located at https://example.com/ "
        "as needing revalidation since the response contains the must-revalidate directive."
    ]


def test_construct_response_from_cache_with_request_no_cache(caplog):
    controller = Controller(allow_stale=True)
    response = Response(
        status=200,
        headers=[
            (b"Cache-Control", b"max-age=1"),
            (b"Date", b"Mon, 25 Aug 2015 12:00:00 GMT"),
        ],
    )
    original_request = Request("GET", "https://example.com")
    request = Request("GET", "https://example.com", headers=[(b"Cache-Control", b"no-cache")])

    with caplog.at_level(logging.DEBUG):
        conditional_request = controller.construct_response_from_cache(
            request=request, response=response, original_request=original_request
        )
        assert isinstance(conditional_request, Request)

    assert caplog.messages == [
        "Considering the resource located at https://example.com/ "
        "as needing revalidation since the request contains the no-cache directive."
    ]


def test_construct_response_from_cache_with_no_cache(caplog):
    controller = Controller(allow_stale=True)
    response = Response(
        status=200,
        headers=[
            (b"Cache-Control", b"max-age=1, no-cache"),
            (b"Date", b"Mon, 25 Aug 2015 12:00:00 GMT"),
        ],
    )
    original_request = Request("GET", "https://example.com")
    request = Request("GET", "https://example.com")

    with caplog.at_level(logging.DEBUG):
        conditional_request = controller.construct_response_from_cache(
            request=request, response=response, original_request=original_request
        )
        assert isinstance(conditional_request, Request)

    assert caplog.messages == [
        "Considering the resource located at https://example.com/ "
        "as needing revalidation since the response contains the no-cache directive."
    ]


def test_construct_response_heuristically(caplog):
    class MockedClock(BaseClock):
        def now(self) -> int:
            return 1440590400  # Mon, 26 Aug 2015 12:00:00 GMT

    controller = Controller(allow_heuristics=True, clock=MockedClock())

    # Age less than 7 days
    response = Response(
        status=200,
        headers=[
            (b"Date", b"Mon, 25 Aug 2015 12:00:00 GMT"),
            (b"Last-Modified", b"Mon, 25 Aug 2003 12:00:00 GMT"),
        ],
    )
    original_request = Request("GET", "https://example.com")
    request = Request("GET", "https://example.com")

    with caplog.at_level(logging.DEBUG):
        res = controller.construct_response_from_cache(
            request=request, response=response, original_request=original_request
        )
    assert caplog.messages == [
        "Could not determine the freshness lifetime of the resource located at "
        "https://example.com/, trying to use heuristics to calculate it.",
        "Successfully calculated the freshness lifetime of the resource "
        "located at https://example.com/ using heuristics.",
        "Considering the resource located at https://example.com/ as valid for cache use since it is fresh.",
    ]
    assert isinstance(res, Response)

    # Age more than 7 days
    response = Response(
        status=200,
        headers=[
            (b"Date", b"Mon, 18 Aug 2015 12:00:00 GMT"),
            (b"Last-Modified", b"Mon, 25 Aug 2003 12:00:00 GMT"),
        ],
    )

    caplog.clear()
    with caplog.at_level(logging.DEBUG):
        res = controller.construct_response_from_cache(
            request=request, response=response, original_request=original_request
        )
    assert caplog.messages == [
        "Could not determine the freshness lifetime of the resource located at "
        "https://example.com/, trying to use heuristics to calculate it.",
        "Successfully calculated the freshness lifetime of the resource"
        " located at https://example.com/ using heuristics.",
        "Considering the resource located at https://example.com/ as needing revalidation since it is not fresh.",
        "Adding the 'If-Modified-Since' header with the value of 'Mon, 25 Aug 2003 12:00:00 GMT'"
        " to the request for the resource located at https://example.com/.",
    ]

    assert not isinstance(res, Response)


def test_handle_validation_response_changed():
    controller = Controller()

    old_response = Response(status=200, headers=[(b"old-response", b"true")], content=b"old")

    new_response = Response(status=200, headers=[(b"new-response", b"true")], content=b"new")

    response = controller.handle_validation_response(old_response=old_response, new_response=new_response)
    response.read()

    assert response.headers == [(b"new-response", b"true")]
    assert response.content == b"new"


def test_handle_validation_response_not_changed():
    controller = Controller()

    old_response = Response(status=200, headers=[(b"old-response", b"true")], content=b"old")

    new_response = Response(
        status=304,
        headers=[(b"new-response", b"false"), (b"old-response", b"true")],
        content=b"new",
    )

    response = controller.handle_validation_response(old_response=old_response, new_response=new_response)
    response.read()

    assert response.headers == [(b"old-response", b"true"), (b"new-response", b"false")]
    assert response.content == b"old"


def test_vary_validation():
    original_request = Request(
        method="GET",
        url="https://example.com",
        headers=[
            (b"Content-Type", b"application/json"),
            (b"Content-Language", b"en-US"),
        ],
    )
    request = Request(
        method="GET",
        url="https://example.com",
        headers=[
            (b"Content-Type", b"application/json"),
            (b"Content-Language", b"en-US"),
        ],
    )

    response = Response(
        status=200,
        headers=[
            (b"Content-Type", b"application/json"),
            (b"Content-Language", b"en-US"),
            (b"Vary", b"Content-Type, Content-Language"),
        ],
    )

    controller = Controller()

    assert controller._validate_vary(request=request, response=response, original_request=original_request)

    original_request.headers.pop(0)

    assert not controller._validate_vary(request=request, response=response, original_request=original_request)


def test_construct_response_from_cache_with_vary_mismatch(caplog):
    original_request = Request(
        method="GET",
        url="https://example.com",
        headers=[
            (b"Content-Type", b"application/json"),
            (b"Content-Language", b"en-US"),
        ],
    )

    request = Request(
        method="GET",
        url="https://example.com",
        headers=[
            (b"Content-Type", b"application/xml"),
            (b"Content-Language", b"en-US"),
        ],
    )

    response = Response(
        status=200,
        headers=[
            (b"Content-Type", b"application/json"),
            (b"Content-Language", b"en-US"),
            (b"Vary", b"Content-Type, Content-Language"),
        ],
    )

    controller = Controller()

    with caplog.at_level(logging.DEBUG):
        cached_response = controller.construct_response_from_cache(
            original_request=original_request, request=request, response=response
        )

    assert cached_response is None
    assert caplog.messages == [
        "Considering the resource located at https://example.com/ "
        "as invalid for cache use since the vary headers do not match."
    ]


def test_vary_validation_value_mismatch():
    original_request = Request(
        method="GET",
        url="https://example.com",
        headers=[
            (b"Content-Type", b"application/json"),
            (b"Content-Language", b"en-US"),
        ],
    )

    request = Request(
        method="GET",
        url="https://example.com",
        headers=[
            (b"Content-Type", b"application/html"),
            (b"Content-Language", b"en-US"),
        ],
    )

    response = Response(
        status=200,
        headers=[
            (b"Content-Type", b"application/json"),
            (b"Content-Language", b"en-US"),
            (b"Vary", b"Content-Type, Content-Language"),
        ],
    )

    controller = Controller()

    assert not controller._validate_vary(request=request, response=response, original_request=original_request)


def test_vary_validation_value_wildcard():
    original_request = Request(
        method="GET",
        url="https://example.com",
        headers=[
            (b"Content-Type", b"application/json"),
            (b"Content-Language", b"en-US"),
        ],
    )

    request = Request(
        method="GET",
        url="https://example.com",
        headers=[
            (b"Content-Type", b"application/json"),
            (b"Content-Language", b"en-US"),
        ],
    )

    response = Response(
        status=200,
        headers=[
            (b"Content-Type", b"application/json"),
            (b"Content-Language", b"en-US"),
            (b"Vary", b"Content-Type, Content-Language, *"),
        ],
    )

    controller = Controller()

    assert not controller._validate_vary(request=request, response=response, original_request=original_request)


def test_max_age_request_directive(caplog):
    class MockedClock(BaseClock):
        def now(self) -> int:
            return 1440507600  # Mon, 25 Aug 2015 13:00:00 GMT

    original_request = Request(
        method="GET",
        url="https://example.com",
        headers=[
            (b"Content-Type", b"application/json"),
            (b"Content-Language", b"en-US"),
        ],
    )

    request = Request(
        method="GET",
        url="https://example.com",
        headers=[
            (b"Content-Type", b"application/json"),
            (b"Content-Language", b"en-US"),
            (b"Cache-Control", "max-age=3599"),
        ],
    )

    response = Response(
        status=200,
        headers=[
            (b"Content-Type", b"application/json"),
            (b"Content-Language", b"en-US"),
            (b"Cache-Control", "max-age=3600"),
            (b"Date", b"Mon, 25 Aug 2015 12:00:00 GMT"),
        ],
    )

    controller = Controller(clock=MockedClock())

    with caplog.at_level(logging.DEBUG):
        cached_response = controller.construct_response_from_cache(
            original_request=original_request, request=request, response=response
        )
    assert cached_response is None
    assert caplog.messages == [
        (
            "Considering the resource located at https://example.com/ "
            "as invalid for cache use since the age of the response exceeds the max-age directive."
        )
    ]


def test_max_age_request_directive_with_max_stale(caplog):
    class MockedClock(BaseClock):
        def now(self) -> int:
            return 1440507600  # Mon, 25 Aug 2015 13:00:00 GMT

    original_request = Request(
        method="GET",
        url="https://example.com",
        headers=[
            (b"Content-Type", b"application/json"),
            (b"Content-Language", b"en-US"),
        ],
    )

    request = Request(
        method="GET",
        url="https://example.com",
        headers=[
            (b"Content-Type", b"application/json"),
            (b"Content-Language", b"en-US"),
            (b"Cache-Control", "max-age=3600, max-stale=10000"),
        ],
    )

    response = Response(
        status=200,
        headers=[
            (b"Content-Type", b"application/json"),
            (b"Content-Language", b"en-US"),
            (b"Cache-Control", "max-age=600"),
            (b"Date", b"Mon, 25 Aug 2015 12:00:00 GMT"),
        ],
    )

    controller = Controller(clock=MockedClock())

    with caplog.at_level(logging.DEBUG):
        cached_response = controller.construct_response_from_cache(
            original_request=original_request, request=request, response=response
        )

    assert isinstance(cached_response, Response)
    assert caplog.messages == [
        "Considering the resource located at https://example.com/ as valid for "
        "cache use since the freshness lifetime has been exceeded less than max-stale."
    ]


def test_max_stale_request_directive(caplog):
    class MockedClock(BaseClock):
        def now(self) -> int:
            return 1440507600  # Mon, 25 Aug 2015 13:00:00 GMT

    original_request = Request(
        method="GET",
        url="https://example.com",
        headers=[
            (b"Content-Type", b"application/json"),
            (b"Content-Language", b"en-US"),
        ],
    )

    request = Request(
        method="GET",
        url="https://example.com",
        headers=[
            (b"Content-Type", b"application/json"),
            (b"Content-Language", b"en-US"),
            (b"Cache-Control", b"max-stale=2999"),
        ],
    )

    response = Response(
        status=200,
        headers=[
            (b"Content-Type", b"application/json"),
            (b"Content-Language", b"en-US"),
            (b"Cache-Control", "max-age=600"),
            (b"Date", b"Mon, 25 Aug 2015 12:00:00 GMT"),
        ],
    )

    controller = Controller(clock=MockedClock())

    with caplog.at_level(logging.DEBUG):
        cached_response = controller.construct_response_from_cache(
            original_request=original_request, request=request, response=response
        )
    assert cached_response is None
    assert caplog.messages == [
        "Considering the resource located at https://example.com/ as invalid for"
        " cache use since the freshness lifetime has been exceeded more than max-stale."
    ]


def test_min_fresh_request_directive(caplog):
    class MockedClock(BaseClock):
        def now(self) -> int:
            return 1440507600  # Mon, 25 Aug 2015 13:00:00 GMT

    original_request = Request(
        method="GET",
        url="https://example.com",
        headers=[
            (b"Content-Type", b"application/json"),
            (b"Content-Language", b"en-US"),
        ],
    )

    request = Request(
        method="GET",
        url="https://example.com",
        headers=[
            (b"Content-Type", b"application/json"),
            (b"Content-Language", b"en-US"),
            (b"Cache-Control", b"min_fresh=10000"),
        ],
    )

    response = Response(
        status=200,
        headers=[
            (b"Content-Type", b"application/json"),
            (b"Content-Language", b"en-US"),
            (b"Cache-Control", "max-age=4000"),
            (b"Date", b"Mon, 25 Aug 2015 12:00:00 GMT"),
        ],
    )

    controller = Controller(clock=MockedClock())

    with caplog.at_level(logging.DEBUG):
        cached_response = controller.construct_response_from_cache(
            original_request=original_request, request=request, response=response
        )
    assert cached_response is None
    assert caplog.messages == [
        "Considering the resource located at https://example.com/ as invalid for cache"
        " use since the time left for freshness is less than the min-fresh directive."
    ]


def test_no_cache_request_directive():
    original_request = Request(
        method="GET",
        url="https://example.com",
        headers=[
            (b"Content-Type", b"application/json"),
            (b"Content-Language", b"en-US"),
        ],
    )

    request = Request(
        method="GET",
        url="https://example.com",
        headers=[
            (b"Content-Type", b"application/json"),
            (b"Content-Language", b"en-US"),
            (b"Cache-Control", b"no-cache"),
        ],
    )

    response = Response(
        status=200,
        headers=[
            (b"Content-Type", b"application/json"),
            (b"Content-Language", b"en-US"),
            (b"Cache-Control", "max-age=4000"),
            (b"Date", b"Mon, 25 Aug 2015 12:00:00 GMT"),
        ],
    )

    controller = Controller()

    cached_response = controller.construct_response_from_cache(
        original_request=original_request, request=request, response=response
    )
    assert isinstance(cached_response, Request)


def test_no_store_request_directive():
    request = Request(
        method="GET",
        url="https://example.com",
        headers=[
            (b"Content-Type", b"application/json"),
            (b"Content-Language", b"en-US"),
            (b"Cache-Control", b"no-store"),
        ],
    )

    response = Response(
        status=200,
        headers=[
            (b"Content-Type", b"application/json"),
            (b"Content-Language", b"en-US"),
            (b"Cache-Control", "max-age=4000"),
            (b"Date", b"Mon, 25 Aug 2015 12:00:00 GMT"),
        ],
    )

    controller = Controller()

    assert not controller.is_cachable(request=request, response=response)


def test_no_store_response_directive():
    request = Request(
        method="GET",
        url="https://example.com",
        headers=[
            (b"Content-Type", b"application/json"),
            (b"Content-Language", b"en-US"),
        ],
    )

    response = Response(
        status=200,
        headers=[
            (b"Content-Type", b"application/json"),
            (b"Content-Language", b"en-US"),
            (b"Cache-Control", b"no-store, max-age=4000"),
            (b"Date", b"Mon, 25 Aug 2015 12:00:00 GMT"),
        ],
    )

    controller = Controller()

    assert not controller.is_cachable(request=request, response=response)


def test_must_understand_response_directive(caplog):
    request = Request(
        method="GET",
        url="https://example.com",
        headers=[
            (b"Content-Type", b"application/json"),
            (b"Content-Language", b"en-US"),
        ],
    )

    response = Response(
        status=200,
        headers=[
            (b"Content-Type", b"application/json"),
            (b"Content-Language", b"en-US"),
            (b"Cache-Control", b"no-store, must-understand, max-age=4000"),
            (b"Date", b"Mon, 25 Aug 2015 12:00:00 GMT"),
        ],
    )

    controller = Controller()

    with caplog.at_level(logging.DEBUG):
        assert controller.is_cachable(request=request, response=response)

    assert caplog.messages == [
        "Skipping the no-store directive for the resource located at https://example.com/"
        " since the response contains the must-understand directive.",
        "Considering the resource located at https://example.com/ as cachable "
        "since it meets the criteria for being stored in the cache.",
    ]


def test_freshness_lifetime_invalid_information(caplog):
    controller = Controller()
    response = Response(
        status=400,
    )
    original_request = Request("GET", "https://example.com")
    request = Request("GET", "https://example.com")

    with caplog.at_level(logging.DEBUG):
        conditional_request = controller.construct_response_from_cache(
            request=request, response=response, original_request=original_request
        )
    assert isinstance(conditional_request, Request)
    assert caplog.messages == [
        "Could not determine the freshness lifetime of the resource located at https://example.com/, "
        "trying to use heuristics to calculate it.",
        (
            "Could not calculate the freshness lifetime of the resource located at https://example.com/. "
            "Making a conditional request to revalidate the response."
        ),
    ]


def test_force_cache_extension_for_is_cachable(caplog):
    controller = Controller(cacheable_status_codes=[400])
    request = Request("GET", "https://example.com")
    uncachable_response = Response(status=400)

    assert controller.is_cachable(request=request, response=uncachable_response) is False

    request = Request("GET", "https://example.com", extensions={"force_cache": True})

    with caplog.at_level(logging.DEBUG):
        assert controller.is_cachable(request=request, response=uncachable_response) is True

    assert caplog.messages == [
        "Considering the resource located at https://example.com/ as"
        " cachable since the request is forced to use the cache."
    ]


def test_force_cache_extension_for_construct_response_from_cache(caplog):
    class MockedClock(BaseClock):
        def now(self) -> int:
            return 1440504001  # Mon, 25 Aug 2015 12:00:01 GMT

    controller = Controller(clock=MockedClock())
    original_request = Request("GET", "https://example.com")
    request = Request("GET", "https://example.com")
    cachable_response = Response(
        200,
        headers=[
            (b"Cache-Control", b"max-age=0"),
            (b"Date", b"Mon, 25 Aug 2015 12:00:00 GMT"),  # 1 second before the clock
        ],
    )

    with caplog.at_level(logging.DEBUG):
        assert isinstance(
            controller.construct_response_from_cache(
                request=request,
                response=cachable_response,
                original_request=original_request,
            ),
            Request,
        )
    assert caplog.messages == [
        "Considering the resource located at https://example.com/ as needing revalidation since it is not fresh."
    ]

    request = Request("Get", "https://example.com", extensions={"force_cache": True})

    caplog.clear()
    with caplog.at_level(logging.DEBUG):
        assert isinstance(
            controller.construct_response_from_cache(
                request=request,
                response=cachable_response,
                original_request=original_request,
            ),
            Response,
        )

    assert caplog.messages == [
        "Considering the resource located at https://example.com/ "
        "as valid for cache use since the request is forced to use the cache."
    ]