zhangqian
2024-01-12 fea217048591823280a888b6c26f68558e51dded
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
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
/*
Copyright 2014 The Kubernetes Authors.
 
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
 
    http://www.apache.org/licenses/LICENSE-2.0
 
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
 
package rest
 
import (
    "bytes"
    "context"
    "errors"
    "flag"
    "fmt"
    "io"
    "io/ioutil"
    "net"
    "net/http"
    "net/http/httptest"
    "net/url"
    "os"
    "reflect"
    "strings"
    "sync"
    "syscall"
    "testing"
    "time"
 
    "k8s.io/klog/v2"
 
    v1 "k8s.io/api/core/v1"
    apiequality "k8s.io/apimachinery/pkg/api/equality"
    apierrors "k8s.io/apimachinery/pkg/api/errors"
    metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
    "k8s.io/apimachinery/pkg/runtime"
    "k8s.io/apimachinery/pkg/runtime/schema"
    "k8s.io/apimachinery/pkg/runtime/serializer/streaming"
    "k8s.io/apimachinery/pkg/util/clock"
    "k8s.io/apimachinery/pkg/util/diff"
    "k8s.io/apimachinery/pkg/util/httpstream"
    "k8s.io/apimachinery/pkg/util/intstr"
    "k8s.io/apimachinery/pkg/watch"
    "k8s.io/client-go/kubernetes/scheme"
    restclientwatch "k8s.io/client-go/rest/watch"
    "k8s.io/client-go/util/flowcontrol"
    utiltesting "k8s.io/client-go/util/testing"
)
 
func TestNewRequestSetsAccept(t *testing.T) {
    r := NewRequestWithClient(&url.URL{Path: "/path/"}, "", ClientContentConfig{}, nil).Verb("get")
    if r.headers.Get("Accept") != "" {
        t.Errorf("unexpected headers: %#v", r.headers)
    }
    r = NewRequestWithClient(&url.URL{Path: "/path/"}, "", ClientContentConfig{ContentType: "application/other"}, nil).Verb("get")
    if r.headers.Get("Accept") != "application/other, */*" {
        t.Errorf("unexpected headers: %#v", r.headers)
    }
}
 
func clientForFunc(fn clientFunc) *http.Client {
    return &http.Client{
        Transport: fn,
    }
}
 
type clientFunc func(req *http.Request) (*http.Response, error)
 
func (f clientFunc) RoundTrip(req *http.Request) (*http.Response, error) {
    return f(req)
}
 
func TestRequestSetsHeaders(t *testing.T) {
    server := clientForFunc(func(req *http.Request) (*http.Response, error) {
        if req.Header.Get("Accept") != "application/other, */*" {
            t.Errorf("unexpected headers: %#v", req.Header)
        }
        return &http.Response{
            StatusCode: http.StatusForbidden,
            Body:       ioutil.NopCloser(bytes.NewReader([]byte{})),
        }, nil
    })
    config := defaultContentConfig()
    config.ContentType = "application/other"
    r := NewRequestWithClient(&url.URL{Path: "/path"}, "", config, nil).Verb("get")
    r.c.Client = server
 
    // Check if all "issue" methods are setting headers.
    _ = r.Do(context.Background())
    _, _ = r.Watch(context.Background())
    _, _ = r.Stream(context.Background())
}
 
func TestRequestWithErrorWontChange(t *testing.T) {
    gvCopy := v1.SchemeGroupVersion
    original := Request{
        err: errors.New("test"),
        c: &RESTClient{
            content: ClientContentConfig{GroupVersion: gvCopy},
        },
    }
    r := original
    changed := r.Param("foo", "bar").
        AbsPath("/abs").
        Prefix("test").
        Suffix("testing").
        Namespace("new").
        Resource("foos").
        Name("bars").
        Body("foo").
        Timeout(time.Millisecond)
    if changed != &r {
        t.Errorf("returned request should point to the same object")
    }
    if !reflect.DeepEqual(changed, &original) {
        t.Errorf("expected %#v, got %#v", &original, changed)
    }
}
 
func TestRequestPreservesBaseTrailingSlash(t *testing.T) {
    r := &Request{c: &RESTClient{base: &url.URL{}}, pathPrefix: "/path/"}
    if s := r.URL().String(); s != "/path/" {
        t.Errorf("trailing slash should be preserved: %s", s)
    }
}
 
func TestRequestAbsPathPreservesTrailingSlash(t *testing.T) {
    r := (&Request{c: &RESTClient{base: &url.URL{}}}).AbsPath("/foo/")
    if s := r.URL().String(); s != "/foo/" {
        t.Errorf("trailing slash should be preserved: %s", s)
    }
 
    r = (&Request{c: &RESTClient{base: &url.URL{}}}).AbsPath("/foo/")
    if s := r.URL().String(); s != "/foo/" {
        t.Errorf("trailing slash should be preserved: %s", s)
    }
}
 
func TestRequestAbsPathJoins(t *testing.T) {
    r := (&Request{c: &RESTClient{base: &url.URL{}}}).AbsPath("foo/bar", "baz")
    if s := r.URL().String(); s != "foo/bar/baz" {
        t.Errorf("trailing slash should be preserved: %s", s)
    }
}
 
func TestRequestSetsNamespace(t *testing.T) {
    r := (&Request{
        c: &RESTClient{base: &url.URL{Path: "/"}},
    }).Namespace("foo")
    if r.namespace == "" {
        t.Errorf("namespace should be set: %#v", r)
    }
 
    if s := r.URL().String(); s != "namespaces/foo" {
        t.Errorf("namespace should be in path: %s", s)
    }
}
 
func TestRequestOrdersNamespaceInPath(t *testing.T) {
    r := (&Request{
        c:          &RESTClient{base: &url.URL{}},
        pathPrefix: "/test/",
    }).Name("bar").Resource("baz").Namespace("foo")
    if s := r.URL().String(); s != "/test/namespaces/foo/baz/bar" {
        t.Errorf("namespace should be in order in path: %s", s)
    }
}
 
func TestRequestOrdersSubResource(t *testing.T) {
    r := (&Request{
        c:          &RESTClient{base: &url.URL{}},
        pathPrefix: "/test/",
    }).Name("bar").Resource("baz").Namespace("foo").Suffix("test").SubResource("a", "b")
    if s := r.URL().String(); s != "/test/namespaces/foo/baz/bar/a/b/test" {
        t.Errorf("namespace should be in order in path: %s", s)
    }
}
 
func TestRequestSetTwiceError(t *testing.T) {
    if (&Request{}).Name("bar").Name("baz").err == nil {
        t.Errorf("setting name twice should result in error")
    }
    if (&Request{}).Namespace("bar").Namespace("baz").err == nil {
        t.Errorf("setting namespace twice should result in error")
    }
    if (&Request{}).Resource("bar").Resource("baz").err == nil {
        t.Errorf("setting resource twice should result in error")
    }
    if (&Request{}).SubResource("bar").SubResource("baz").err == nil {
        t.Errorf("setting subresource twice should result in error")
    }
}
 
func TestInvalidSegments(t *testing.T) {
    invalidSegments := []string{".", "..", "test/segment", "test%2bsegment"}
    setters := map[string]func(string, *Request){
        "namespace":   func(s string, r *Request) { r.Namespace(s) },
        "resource":    func(s string, r *Request) { r.Resource(s) },
        "name":        func(s string, r *Request) { r.Name(s) },
        "subresource": func(s string, r *Request) { r.SubResource(s) },
    }
    for _, invalidSegment := range invalidSegments {
        for setterName, setter := range setters {
            r := &Request{}
            setter(invalidSegment, r)
            if r.err == nil {
                t.Errorf("%s: %s: expected error, got none", setterName, invalidSegment)
            }
        }
    }
}
 
func TestRequestParam(t *testing.T) {
    r := (&Request{}).Param("foo", "a")
    if !reflect.DeepEqual(r.params, url.Values{"foo": []string{"a"}}) {
        t.Errorf("should have set a param: %#v", r)
    }
 
    r.Param("bar", "1")
    r.Param("bar", "2")
    if !reflect.DeepEqual(r.params, url.Values{"foo": []string{"a"}, "bar": []string{"1", "2"}}) {
        t.Errorf("should have set a param: %#v", r)
    }
}
 
func TestRequestVersionedParams(t *testing.T) {
    r := (&Request{c: &RESTClient{content: ClientContentConfig{GroupVersion: v1.SchemeGroupVersion}}}).Param("foo", "a")
    if !reflect.DeepEqual(r.params, url.Values{"foo": []string{"a"}}) {
        t.Errorf("should have set a param: %#v", r)
    }
    r.VersionedParams(&v1.PodLogOptions{Follow: true, Container: "bar"}, scheme.ParameterCodec)
 
    if !reflect.DeepEqual(r.params, url.Values{
        "foo":       []string{"a"},
        "container": []string{"bar"},
        "follow":    []string{"true"},
    }) {
        t.Errorf("should have set a param: %#v", r)
    }
}
 
func TestRequestVersionedParamsFromListOptions(t *testing.T) {
    r := &Request{c: &RESTClient{content: ClientContentConfig{GroupVersion: v1.SchemeGroupVersion}}}
    r.VersionedParams(&metav1.ListOptions{ResourceVersion: "1"}, scheme.ParameterCodec)
    if !reflect.DeepEqual(r.params, url.Values{
        "resourceVersion": []string{"1"},
    }) {
        t.Errorf("should have set a param: %#v", r)
    }
 
    var timeout int64 = 10
    r.VersionedParams(&metav1.ListOptions{ResourceVersion: "2", TimeoutSeconds: &timeout}, scheme.ParameterCodec)
    if !reflect.DeepEqual(r.params, url.Values{
        "resourceVersion": []string{"1", "2"},
        "timeoutSeconds":  []string{"10"},
    }) {
        t.Errorf("should have set a param: %#v %v", r.params, r.err)
    }
}
 
func TestRequestURI(t *testing.T) {
    r := (&Request{}).Param("foo", "a")
    r.Prefix("other")
    r.RequestURI("/test?foo=b&a=b&c=1&c=2")
    if r.pathPrefix != "/test" {
        t.Errorf("path is wrong: %#v", r)
    }
    if !reflect.DeepEqual(r.params, url.Values{"a": []string{"b"}, "foo": []string{"b"}, "c": []string{"1", "2"}}) {
        t.Errorf("should have set a param: %#v", r)
    }
}
 
type NotAnAPIObject struct{}
 
func (obj NotAnAPIObject) GroupVersionKind() *schema.GroupVersionKind       { return nil }
func (obj NotAnAPIObject) SetGroupVersionKind(gvk *schema.GroupVersionKind) {}
 
func defaultContentConfig() ClientContentConfig {
    gvCopy := v1.SchemeGroupVersion
    return ClientContentConfig{
        ContentType:  "application/json",
        GroupVersion: gvCopy,
        Negotiator:   runtime.NewClientNegotiator(scheme.Codecs.WithoutConversion(), gvCopy),
    }
}
 
func TestRequestBody(t *testing.T) {
    // test unknown type
    r := (&Request{}).Body([]string{"test"})
    if r.err == nil || r.body != nil {
        t.Errorf("should have set err and left body nil: %#v", r)
    }
 
    // test error set when failing to read file
    f, err := ioutil.TempFile("", "test")
    if err != nil {
        t.Fatalf("unable to create temp file")
    }
    defer f.Close()
    os.Remove(f.Name())
    r = (&Request{}).Body(f.Name())
    if r.err == nil || r.body != nil {
        t.Errorf("should have set err and left body nil: %#v", r)
    }
 
    // test unencodable api object
    r = (&Request{c: &RESTClient{content: defaultContentConfig()}}).Body(&NotAnAPIObject{})
    if r.err == nil || r.body != nil {
        t.Errorf("should have set err and left body nil: %#v", r)
    }
}
 
func TestResultIntoWithErrReturnsErr(t *testing.T) {
    res := Result{err: errors.New("test")}
    if err := res.Into(&v1.Pod{}); err != res.err {
        t.Errorf("should have returned exact error from result")
    }
}
 
func TestResultIntoWithNoBodyReturnsErr(t *testing.T) {
    res := Result{
        body:    []byte{},
        decoder: scheme.Codecs.LegacyCodec(v1.SchemeGroupVersion),
    }
    if err := res.Into(&v1.Pod{}); err == nil || !strings.Contains(err.Error(), "0-length") {
        t.Errorf("should have complained about 0 length body")
    }
}
 
func TestURLTemplate(t *testing.T) {
    uri, _ := url.Parse("http://localhost/some/base/url/path")
    uriSingleSlash, _ := url.Parse("http://localhost/")
    testCases := []struct {
        Request          *Request
        ExpectedFullURL  string
        ExpectedFinalURL string
    }{
        {
            // non dynamic client
            Request: NewRequestWithClient(uri, "", ClientContentConfig{GroupVersion: schema.GroupVersion{Group: "test"}}, nil).Verb("POST").
                Prefix("api", "v1").Resource("r1").Namespace("ns").Name("nm").Param("p0", "v0"),
            ExpectedFullURL:  "http://localhost/some/base/url/path/api/v1/namespaces/ns/r1/nm?p0=v0",
            ExpectedFinalURL: "http://localhost/some/base/url/path/api/v1/namespaces/%7Bnamespace%7D/r1/%7Bname%7D?p0=%7Bvalue%7D",
        },
        {
            // non dynamic client with wrong api group
            Request: NewRequestWithClient(uri, "", ClientContentConfig{GroupVersion: schema.GroupVersion{Group: "test"}}, nil).Verb("POST").
                Prefix("pre1", "v1").Resource("r1").Namespace("ns").Name("nm").Param("p0", "v0"),
            ExpectedFullURL:  "http://localhost/some/base/url/path/pre1/v1/namespaces/ns/r1/nm?p0=v0",
            ExpectedFinalURL: "http://localhost/%7Bprefix%7D",
        },
        {
            // dynamic client with core group + namespace + resourceResource (with name)
            // /api/$RESOURCEVERSION/namespaces/$NAMESPACE/$RESOURCE/%NAME
            Request: NewRequestWithClient(uri, "", ClientContentConfig{GroupVersion: schema.GroupVersion{Group: "test"}}, nil).Verb("DELETE").
                Prefix("/api/v1/namespaces/ns/r1/name1"),
            ExpectedFullURL:  "http://localhost/some/base/url/path/api/v1/namespaces/ns/r1/name1",
            ExpectedFinalURL: "http://localhost/some/base/url/path/api/v1/namespaces/%7Bnamespace%7D/r1/%7Bname%7D",
        },
        {
            // dynamic client with named group + namespace + resourceResource (with name)
            // /apis/$NAMEDGROUPNAME/$RESOURCEVERSION/namespaces/$NAMESPACE/$RESOURCE/%NAME
            Request: NewRequestWithClient(uri, "", ClientContentConfig{GroupVersion: schema.GroupVersion{Group: "test"}}, nil).Verb("DELETE").
                Prefix("/apis/g1/v1/namespaces/ns/r1/name1"),
            ExpectedFullURL:  "http://localhost/some/base/url/path/apis/g1/v1/namespaces/ns/r1/name1",
            ExpectedFinalURL: "http://localhost/some/base/url/path/apis/g1/v1/namespaces/%7Bnamespace%7D/r1/%7Bname%7D",
        },
        {
            // dynamic client with core group + namespace + resourceResource (with NO name)
            // /api/$RESOURCEVERSION/namespaces/$NAMESPACE/$RESOURCE
            Request: NewRequestWithClient(uri, "", ClientContentConfig{GroupVersion: schema.GroupVersion{Group: "test"}}, nil).Verb("DELETE").
                Prefix("/api/v1/namespaces/ns/r1"),
            ExpectedFullURL:  "http://localhost/some/base/url/path/api/v1/namespaces/ns/r1",
            ExpectedFinalURL: "http://localhost/some/base/url/path/api/v1/namespaces/%7Bnamespace%7D/r1",
        },
        {
            // dynamic client with named group + namespace + resourceResource (with NO name)
            // /apis/$NAMEDGROUPNAME/$RESOURCEVERSION/namespaces/$NAMESPACE/$RESOURCE
            Request: NewRequestWithClient(uri, "", ClientContentConfig{GroupVersion: schema.GroupVersion{Group: "test"}}, nil).Verb("DELETE").
                Prefix("/apis/g1/v1/namespaces/ns/r1"),
            ExpectedFullURL:  "http://localhost/some/base/url/path/apis/g1/v1/namespaces/ns/r1",
            ExpectedFinalURL: "http://localhost/some/base/url/path/apis/g1/v1/namespaces/%7Bnamespace%7D/r1",
        },
        {
            // dynamic client with core group + resourceResource (with name)
            // /api/$RESOURCEVERSION/$RESOURCE/%NAME
            Request: NewRequestWithClient(uri, "", ClientContentConfig{GroupVersion: schema.GroupVersion{Group: "test"}}, nil).Verb("DELETE").
                Prefix("/api/v1/r1/name1"),
            ExpectedFullURL:  "http://localhost/some/base/url/path/api/v1/r1/name1",
            ExpectedFinalURL: "http://localhost/some/base/url/path/api/v1/r1/%7Bname%7D",
        },
        {
            // dynamic client with named group + resourceResource (with name)
            // /apis/$NAMEDGROUPNAME/$RESOURCEVERSION/$RESOURCE/%NAME
            Request: NewRequestWithClient(uri, "", ClientContentConfig{GroupVersion: schema.GroupVersion{Group: "test"}}, nil).Verb("DELETE").
                Prefix("/apis/g1/v1/r1/name1"),
            ExpectedFullURL:  "http://localhost/some/base/url/path/apis/g1/v1/r1/name1",
            ExpectedFinalURL: "http://localhost/some/base/url/path/apis/g1/v1/r1/%7Bname%7D",
        },
        {
            // dynamic client with named group + namespace + resourceResource (with name) + subresource
            // /apis/$NAMEDGROUPNAME/$RESOURCEVERSION/namespaces/$NAMESPACE/$RESOURCE/%NAME/$SUBRESOURCE
            Request: NewRequestWithClient(uri, "", ClientContentConfig{GroupVersion: schema.GroupVersion{Group: "test"}}, nil).Verb("DELETE").
                Prefix("/apis/namespaces/namespaces/namespaces/namespaces/namespaces/namespaces/finalize"),
            ExpectedFullURL:  "http://localhost/some/base/url/path/apis/namespaces/namespaces/namespaces/namespaces/namespaces/namespaces/finalize",
            ExpectedFinalURL: "http://localhost/some/base/url/path/apis/namespaces/namespaces/namespaces/%7Bnamespace%7D/namespaces/%7Bname%7D/finalize",
        },
        {
            // dynamic client with named group + namespace + resourceResource (with name)
            // /apis/$NAMEDGROUPNAME/$RESOURCEVERSION/namespaces/$NAMESPACE/$RESOURCE/%NAME
            Request: NewRequestWithClient(uri, "", ClientContentConfig{GroupVersion: schema.GroupVersion{Group: "test"}}, nil).Verb("DELETE").
                Prefix("/apis/namespaces/namespaces/namespaces/namespaces/namespaces/namespaces"),
            ExpectedFullURL:  "http://localhost/some/base/url/path/apis/namespaces/namespaces/namespaces/namespaces/namespaces/namespaces",
            ExpectedFinalURL: "http://localhost/some/base/url/path/apis/namespaces/namespaces/namespaces/%7Bnamespace%7D/namespaces/%7Bname%7D",
        },
        {
            // dynamic client with named group + namespace + resourceResource (with NO name) + subresource
            // /apis/$NAMEDGROUPNAME/$RESOURCEVERSION/namespaces/$NAMESPACE/$RESOURCE/%SUBRESOURCE
            Request: NewRequestWithClient(uri, "", ClientContentConfig{GroupVersion: schema.GroupVersion{Group: "test"}}, nil).Verb("DELETE").
                Prefix("/apis/namespaces/namespaces/namespaces/namespaces/namespaces/finalize"),
            ExpectedFullURL:  "http://localhost/some/base/url/path/apis/namespaces/namespaces/namespaces/namespaces/namespaces/finalize",
            ExpectedFinalURL: "http://localhost/some/base/url/path/apis/namespaces/namespaces/namespaces/%7Bnamespace%7D/namespaces/finalize",
        },
        {
            // dynamic client with named group + namespace + resourceResource (with NO name) + subresource
            // /apis/$NAMEDGROUPNAME/$RESOURCEVERSION/namespaces/$NAMESPACE/$RESOURCE/%SUBRESOURCE
            Request: NewRequestWithClient(uri, "", ClientContentConfig{GroupVersion: schema.GroupVersion{Group: "test"}}, nil).Verb("DELETE").
                Prefix("/apis/namespaces/namespaces/namespaces/namespaces/namespaces/status"),
            ExpectedFullURL:  "http://localhost/some/base/url/path/apis/namespaces/namespaces/namespaces/namespaces/namespaces/status",
            ExpectedFinalURL: "http://localhost/some/base/url/path/apis/namespaces/namespaces/namespaces/%7Bnamespace%7D/namespaces/status",
        },
        {
            // dynamic client with named group + namespace + resourceResource (with no name)
            // /apis/$NAMEDGROUPNAME/$RESOURCEVERSION/namespaces/$NAMESPACE/$RESOURCE/%NAME
            Request: NewRequestWithClient(uri, "", ClientContentConfig{GroupVersion: schema.GroupVersion{Group: "test"}}, nil).Verb("DELETE").
                Prefix("/apis/namespaces/namespaces/namespaces/namespaces/namespaces"),
            ExpectedFullURL:  "http://localhost/some/base/url/path/apis/namespaces/namespaces/namespaces/namespaces/namespaces",
            ExpectedFinalURL: "http://localhost/some/base/url/path/apis/namespaces/namespaces/namespaces/%7Bnamespace%7D/namespaces",
        },
        {
            // dynamic client with named group + resourceResource (with name) + subresource
            // /apis/$NAMEDGROUPNAME/$RESOURCEVERSION/namespaces/$NAMESPACE/$RESOURCE/%NAME
            Request: NewRequestWithClient(uri, "", ClientContentConfig{GroupVersion: schema.GroupVersion{Group: "test"}}, nil).Verb("DELETE").
                Prefix("/apis/namespaces/namespaces/namespaces/namespaces/finalize"),
            ExpectedFullURL:  "http://localhost/some/base/url/path/apis/namespaces/namespaces/namespaces/namespaces/finalize",
            ExpectedFinalURL: "http://localhost/some/base/url/path/apis/namespaces/namespaces/namespaces/%7Bname%7D/finalize",
        },
        {
            // dynamic client with named group + resourceResource (with name) + subresource
            // /apis/$NAMEDGROUPNAME/$RESOURCEVERSION/namespaces/$NAMESPACE/$RESOURCE/%NAME
            Request: NewRequestWithClient(uri, "", ClientContentConfig{GroupVersion: schema.GroupVersion{Group: "test"}}, nil).Verb("DELETE").
                Prefix("/apis/namespaces/namespaces/namespaces/namespaces/status"),
            ExpectedFullURL:  "http://localhost/some/base/url/path/apis/namespaces/namespaces/namespaces/namespaces/status",
            ExpectedFinalURL: "http://localhost/some/base/url/path/apis/namespaces/namespaces/namespaces/%7Bname%7D/status",
        },
        {
            // dynamic client with named group + resourceResource (with name)
            // /apis/$NAMEDGROUPNAME/$RESOURCEVERSION/$RESOURCE/%NAME
            Request: NewRequestWithClient(uri, "", ClientContentConfig{GroupVersion: schema.GroupVersion{Group: "test"}}, nil).Verb("DELETE").
                Prefix("/apis/namespaces/namespaces/namespaces/namespaces"),
            ExpectedFullURL:  "http://localhost/some/base/url/path/apis/namespaces/namespaces/namespaces/namespaces",
            ExpectedFinalURL: "http://localhost/some/base/url/path/apis/namespaces/namespaces/namespaces/%7Bname%7D",
        },
        {
            // dynamic client with named group + resourceResource (with no name)
            // /apis/$NAMEDGROUPNAME/$RESOURCEVERSION/$RESOURCE/%NAME
            Request: NewRequestWithClient(uri, "", ClientContentConfig{GroupVersion: schema.GroupVersion{Group: "test"}}, nil).Verb("DELETE").
                Prefix("/apis/namespaces/namespaces/namespaces"),
            ExpectedFullURL:  "http://localhost/some/base/url/path/apis/namespaces/namespaces/namespaces",
            ExpectedFinalURL: "http://localhost/some/base/url/path/apis/namespaces/namespaces/namespaces",
        },
        {
            // dynamic client with wrong api group + namespace + resourceResource (with name) + subresource
            // /apis/$NAMEDGROUPNAME/$RESOURCEVERSION/namespaces/$NAMESPACE/$RESOURCE/%NAME/$SUBRESOURCE
            Request: NewRequestWithClient(uri, "", ClientContentConfig{GroupVersion: schema.GroupVersion{Group: "test"}}, nil).Verb("DELETE").
                Prefix("/pre1/namespaces/namespaces/namespaces/namespaces/namespaces/namespaces/finalize"),
            ExpectedFullURL:  "http://localhost/some/base/url/path/pre1/namespaces/namespaces/namespaces/namespaces/namespaces/namespaces/finalize",
            ExpectedFinalURL: "http://localhost/%7Bprefix%7D",
        },
        {
            // dynamic client with core group + namespace + resourceResource (with name) where baseURL is a single /
            // /api/$RESOURCEVERSION/namespaces/$NAMESPACE/$RESOURCE/%NAME
            Request: NewRequestWithClient(uriSingleSlash, "", ClientContentConfig{GroupVersion: schema.GroupVersion{Group: "test"}}, nil).Verb("DELETE").
                Prefix("/api/v1/namespaces/ns/r2/name1"),
            ExpectedFullURL:  "http://localhost/api/v1/namespaces/ns/r2/name1",
            ExpectedFinalURL: "http://localhost/api/v1/namespaces/%7Bnamespace%7D/r2/%7Bname%7D",
        },
        {
            // dynamic client with core group + namespace + resourceResource (with name) where baseURL is 'some/base/url/path'
            // /api/$RESOURCEVERSION/namespaces/$NAMESPACE/$RESOURCE/%NAME
            Request: NewRequestWithClient(uri, "", ClientContentConfig{GroupVersion: schema.GroupVersion{Group: "test"}}, nil).Verb("DELETE").
                Prefix("/api/v1/namespaces/ns/r3/name1"),
            ExpectedFullURL:  "http://localhost/some/base/url/path/api/v1/namespaces/ns/r3/name1",
            ExpectedFinalURL: "http://localhost/some/base/url/path/api/v1/namespaces/%7Bnamespace%7D/r3/%7Bname%7D",
        },
        {
            // dynamic client where baseURL is a single /
            // /
            Request: NewRequestWithClient(uriSingleSlash, "", ClientContentConfig{GroupVersion: schema.GroupVersion{Group: "test"}}, nil).Verb("DELETE").
                Prefix("/"),
            ExpectedFullURL:  "http://localhost/",
            ExpectedFinalURL: "http://localhost/",
        },
        {
            // dynamic client where baseURL is a single /
            // /version
            Request: NewRequestWithClient(uriSingleSlash, "", ClientContentConfig{GroupVersion: schema.GroupVersion{Group: "test"}}, nil).Verb("DELETE").
                Prefix("/version"),
            ExpectedFullURL:  "http://localhost/version",
            ExpectedFinalURL: "http://localhost/version",
        },
    }
    for i, testCase := range testCases {
        r := testCase.Request
        full := r.URL()
        if full.String() != testCase.ExpectedFullURL {
            t.Errorf("%d: unexpected initial URL: %s %s", i, full, testCase.ExpectedFullURL)
        }
        actualURL := r.finalURLTemplate()
        actual := actualURL.String()
        if actual != testCase.ExpectedFinalURL {
            t.Errorf("%d: unexpected URL template: %s %s", i, actual, testCase.ExpectedFinalURL)
        }
        if r.URL().String() != full.String() {
            t.Errorf("%d, creating URL template changed request: %s -> %s", i, full.String(), r.URL().String())
        }
    }
}
 
func TestTransformResponse(t *testing.T) {
    invalid := []byte("aaaaa")
    uri, _ := url.Parse("http://localhost")
    testCases := []struct {
        Response *http.Response
        Data     []byte
        Created  bool
        Error    bool
        ErrFn    func(err error) bool
    }{
        {Response: &http.Response{StatusCode: http.StatusOK}, Data: []byte{}},
        {Response: &http.Response{StatusCode: http.StatusCreated}, Data: []byte{}, Created: true},
        {Response: &http.Response{StatusCode: 199}, Error: true},
        {Response: &http.Response{StatusCode: http.StatusInternalServerError}, Error: true},
        {Response: &http.Response{StatusCode: http.StatusUnprocessableEntity}, Error: true},
        {Response: &http.Response{StatusCode: http.StatusConflict}, Error: true},
        {Response: &http.Response{StatusCode: http.StatusNotFound}, Error: true},
        {Response: &http.Response{StatusCode: http.StatusUnauthorized}, Error: true},
        {
            Response: &http.Response{
                StatusCode: http.StatusUnauthorized,
                Header:     http.Header{"Content-Type": []string{"application/json"}},
                Body:       ioutil.NopCloser(bytes.NewReader(invalid)),
            },
            Error: true,
            ErrFn: func(err error) bool {
                return err.Error() != "aaaaa" && apierrors.IsUnauthorized(err)
            },
        },
        {
            Response: &http.Response{
                StatusCode: http.StatusUnauthorized,
                Header:     http.Header{"Content-Type": []string{"text/any"}},
                Body:       ioutil.NopCloser(bytes.NewReader(invalid)),
            },
            Error: true,
            ErrFn: func(err error) bool {
                return strings.Contains(err.Error(), "server has asked for the client to provide") && apierrors.IsUnauthorized(err)
            },
        },
        {Response: &http.Response{StatusCode: http.StatusForbidden}, Error: true},
        {Response: &http.Response{StatusCode: http.StatusOK, Body: ioutil.NopCloser(bytes.NewReader(invalid))}, Data: invalid},
        {Response: &http.Response{StatusCode: http.StatusOK, Body: ioutil.NopCloser(bytes.NewReader(invalid))}, Data: invalid},
    }
    for i, test := range testCases {
        r := NewRequestWithClient(uri, "", defaultContentConfig(), nil)
        if test.Response.Body == nil {
            test.Response.Body = ioutil.NopCloser(bytes.NewReader([]byte{}))
        }
        result := r.transformResponse(test.Response, &http.Request{})
        response, created, err := result.body, result.statusCode == http.StatusCreated, result.err
        hasErr := err != nil
        if hasErr != test.Error {
            t.Errorf("%d: unexpected error: %t %v", i, test.Error, err)
        } else if hasErr && test.Response.StatusCode > 399 {
            status, ok := err.(apierrors.APIStatus)
            if !ok {
                t.Errorf("%d: response should have been transformable into APIStatus: %v", i, err)
                continue
            }
            if int(status.Status().Code) != test.Response.StatusCode {
                t.Errorf("%d: status code did not match response: %#v", i, status.Status())
            }
        }
        if test.ErrFn != nil && !test.ErrFn(err) {
            t.Errorf("%d: error function did not match: %v", i, err)
        }
        if !(test.Data == nil && response == nil) && !apiequality.Semantic.DeepDerivative(test.Data, response) {
            t.Errorf("%d: unexpected response: %#v %#v", i, test.Data, response)
        }
        if test.Created != created {
            t.Errorf("%d: expected created %t, got %t", i, test.Created, created)
        }
    }
}
 
type renegotiator struct {
    called      bool
    contentType string
    params      map[string]string
    decoder     runtime.Decoder
    err         error
}
 
func (r *renegotiator) Decoder(contentType string, params map[string]string) (runtime.Decoder, error) {
    r.called = true
    r.contentType = contentType
    r.params = params
    return r.decoder, r.err
}
 
func (r *renegotiator) Encoder(contentType string, params map[string]string) (runtime.Encoder, error) {
    return nil, fmt.Errorf("UNIMPLEMENTED")
}
 
func (r *renegotiator) StreamDecoder(contentType string, params map[string]string) (runtime.Decoder, runtime.Serializer, runtime.Framer, error) {
    return nil, nil, nil, fmt.Errorf("UNIMPLEMENTED")
}
 
func TestTransformResponseNegotiate(t *testing.T) {
    invalid := []byte("aaaaa")
    uri, _ := url.Parse("http://localhost")
    testCases := []struct {
        Response *http.Response
        Data     []byte
        Created  bool
        Error    bool
        ErrFn    func(err error) bool
 
        ContentType       string
        Called            bool
        ExpectContentType string
        Decoder           runtime.Decoder
        NegotiateErr      error
    }{
        {
            ContentType: "application/json",
            Response: &http.Response{
                StatusCode: http.StatusUnauthorized,
                Header:     http.Header{"Content-Type": []string{"application/json"}},
                Body:       ioutil.NopCloser(bytes.NewReader(invalid)),
            },
            Called:            true,
            ExpectContentType: "application/json",
            Error:             true,
            ErrFn: func(err error) bool {
                return err.Error() != "aaaaa" && apierrors.IsUnauthorized(err)
            },
        },
        {
            ContentType: "application/json",
            Response: &http.Response{
                StatusCode: http.StatusUnauthorized,
                Header:     http.Header{"Content-Type": []string{"application/protobuf"}},
                Body:       ioutil.NopCloser(bytes.NewReader(invalid)),
            },
            Decoder: scheme.Codecs.LegacyCodec(v1.SchemeGroupVersion),
 
            Called:            true,
            ExpectContentType: "application/protobuf",
 
            Error: true,
            ErrFn: func(err error) bool {
                return err.Error() != "aaaaa" && apierrors.IsUnauthorized(err)
            },
        },
        {
            ContentType: "application/json",
            Response: &http.Response{
                StatusCode: http.StatusInternalServerError,
                Header:     http.Header{"Content-Type": []string{"application/,others"}},
            },
            Decoder: scheme.Codecs.LegacyCodec(v1.SchemeGroupVersion),
 
            Error: true,
            ErrFn: func(err error) bool {
                return err.Error() == "Internal error occurred: mime: expected token after slash" && err.(apierrors.APIStatus).Status().Code == 500
            },
        },
        {
            // negotiate when no content type specified
            Response: &http.Response{
                StatusCode: http.StatusOK,
                Header:     http.Header{"Content-Type": []string{"text/any"}},
                Body:       ioutil.NopCloser(bytes.NewReader(invalid)),
            },
            Decoder:           scheme.Codecs.LegacyCodec(v1.SchemeGroupVersion),
            Called:            true,
            ExpectContentType: "text/any",
        },
        {
            // negotiate when no response content type specified
            ContentType: "text/any",
            Response: &http.Response{
                StatusCode: http.StatusOK,
                Body:       ioutil.NopCloser(bytes.NewReader(invalid)),
            },
            Decoder:           scheme.Codecs.LegacyCodec(v1.SchemeGroupVersion),
            Called:            true,
            ExpectContentType: "text/any",
        },
        {
            // unrecognized content type is not handled
            ContentType: "application/json",
            Response: &http.Response{
                StatusCode: http.StatusNotFound,
                Header:     http.Header{"Content-Type": []string{"application/unrecognized"}},
                Body:       ioutil.NopCloser(bytes.NewReader(invalid)),
            },
            Decoder: scheme.Codecs.LegacyCodec(v1.SchemeGroupVersion),
 
            NegotiateErr:      fmt.Errorf("aaaa"),
            Called:            true,
            ExpectContentType: "application/unrecognized",
 
            Error: true,
            ErrFn: func(err error) bool {
                return err.Error() != "aaaaa" && apierrors.IsNotFound(err)
            },
        },
    }
    for i, test := range testCases {
        contentConfig := defaultContentConfig()
        contentConfig.ContentType = test.ContentType
        negotiator := &renegotiator{
            decoder: test.Decoder,
            err:     test.NegotiateErr,
        }
        contentConfig.Negotiator = negotiator
        r := NewRequestWithClient(uri, "", contentConfig, nil)
        if test.Response.Body == nil {
            test.Response.Body = ioutil.NopCloser(bytes.NewReader([]byte{}))
        }
        result := r.transformResponse(test.Response, &http.Request{})
        _, err := result.body, result.err
        hasErr := err != nil
        if hasErr != test.Error {
            t.Errorf("%d: unexpected error: %t %v", i, test.Error, err)
            continue
        } else if hasErr && test.Response.StatusCode > 399 {
            status, ok := err.(apierrors.APIStatus)
            if !ok {
                t.Errorf("%d: response should have been transformable into APIStatus: %v", i, err)
                continue
            }
            if int(status.Status().Code) != test.Response.StatusCode {
                t.Errorf("%d: status code did not match response: %#v", i, status.Status())
            }
        }
        if test.ErrFn != nil && !test.ErrFn(err) {
            t.Errorf("%d: error function did not match: %v", i, err)
        }
        if negotiator.called != test.Called {
            t.Errorf("%d: negotiator called %t != %t", i, negotiator.called, test.Called)
        }
        if !test.Called {
            continue
        }
        if negotiator.contentType != test.ExpectContentType {
            t.Errorf("%d: unexpected content type: %s", i, negotiator.contentType)
        }
    }
}
 
func TestTransformUnstructuredError(t *testing.T) {
    testCases := []struct {
        Req *http.Request
        Res *http.Response
 
        Resource string
        Name     string
 
        ErrFn       func(error) bool
        Transformed error
    }{
        {
            Resource: "foo",
            Name:     "bar",
            Req: &http.Request{
                Method: "POST",
            },
            Res: &http.Response{
                StatusCode: http.StatusConflict,
                Body:       ioutil.NopCloser(bytes.NewReader(nil)),
            },
            ErrFn: apierrors.IsAlreadyExists,
        },
        {
            Resource: "foo",
            Name:     "bar",
            Req: &http.Request{
                Method: "PUT",
            },
            Res: &http.Response{
                StatusCode: http.StatusConflict,
                Body:       ioutil.NopCloser(bytes.NewReader(nil)),
            },
            ErrFn: apierrors.IsConflict,
        },
        {
            Resource: "foo",
            Name:     "bar",
            Req:      &http.Request{},
            Res: &http.Response{
                StatusCode: http.StatusNotFound,
                Body:       ioutil.NopCloser(bytes.NewReader(nil)),
            },
            ErrFn: apierrors.IsNotFound,
        },
        {
            Req: &http.Request{},
            Res: &http.Response{
                StatusCode: http.StatusBadRequest,
                Body:       ioutil.NopCloser(bytes.NewReader(nil)),
            },
            ErrFn: apierrors.IsBadRequest,
        },
        {
            // status in response overrides transformed result
            Req:   &http.Request{},
            Res:   &http.Response{StatusCode: http.StatusBadRequest, Body: ioutil.NopCloser(bytes.NewReader([]byte(`{"kind":"Status","apiVersion":"v1","status":"Failure","code":404}`)))},
            ErrFn: apierrors.IsBadRequest,
            Transformed: &apierrors.StatusError{
                ErrStatus: metav1.Status{Status: metav1.StatusFailure, Code: http.StatusNotFound},
            },
        },
        {
            // successful status is ignored
            Req:   &http.Request{},
            Res:   &http.Response{StatusCode: http.StatusBadRequest, Body: ioutil.NopCloser(bytes.NewReader([]byte(`{"kind":"Status","apiVersion":"v1","status":"Success","code":404}`)))},
            ErrFn: apierrors.IsBadRequest,
        },
        {
            // empty object does not change result
            Req:   &http.Request{},
            Res:   &http.Response{StatusCode: http.StatusBadRequest, Body: ioutil.NopCloser(bytes.NewReader([]byte(`{}`)))},
            ErrFn: apierrors.IsBadRequest,
        },
        {
            // we default apiVersion for backwards compatibility with old clients
            // TODO: potentially remove in 1.7
            Req:   &http.Request{},
            Res:   &http.Response{StatusCode: http.StatusBadRequest, Body: ioutil.NopCloser(bytes.NewReader([]byte(`{"kind":"Status","status":"Failure","code":404}`)))},
            ErrFn: apierrors.IsBadRequest,
            Transformed: &apierrors.StatusError{
                ErrStatus: metav1.Status{Status: metav1.StatusFailure, Code: http.StatusNotFound},
            },
        },
        {
            // we do not default kind
            Req:   &http.Request{},
            Res:   &http.Response{StatusCode: http.StatusBadRequest, Body: ioutil.NopCloser(bytes.NewReader([]byte(`{"status":"Failure","code":404}`)))},
            ErrFn: apierrors.IsBadRequest,
        },
    }
 
    for _, testCase := range testCases {
        t.Run("", func(t *testing.T) {
            r := &Request{
                c: &RESTClient{
                    content: defaultContentConfig(),
                },
                resourceName: testCase.Name,
                resource:     testCase.Resource,
            }
            result := r.transformResponse(testCase.Res, testCase.Req)
            err := result.err
            if !testCase.ErrFn(err) {
                t.Fatalf("unexpected error: %v", err)
            }
            if !apierrors.IsUnexpectedServerError(err) {
                t.Errorf("unexpected error type: %v", err)
            }
            if len(testCase.Name) != 0 && !strings.Contains(err.Error(), testCase.Name) {
                t.Errorf("unexpected error string: %s", err)
            }
            if len(testCase.Resource) != 0 && !strings.Contains(err.Error(), testCase.Resource) {
                t.Errorf("unexpected error string: %s", err)
            }
 
            // verify Error() properly transforms the error
            transformed := result.Error()
            expect := testCase.Transformed
            if expect == nil {
                expect = err
            }
            if !reflect.DeepEqual(expect, transformed) {
                t.Errorf("unexpected Error(): %s", diff.ObjectReflectDiff(expect, transformed))
            }
 
            // verify result.Get properly transforms the error
            if _, err := result.Get(); !reflect.DeepEqual(expect, err) {
                t.Errorf("unexpected error on Get(): %s", diff.ObjectReflectDiff(expect, err))
            }
 
            // verify result.Into properly handles the error
            if err := result.Into(&v1.Pod{}); !reflect.DeepEqual(expect, err) {
                t.Errorf("unexpected error on Into(): %s", diff.ObjectReflectDiff(expect, err))
            }
 
            // verify result.Raw leaves the error in the untransformed state
            if _, err := result.Raw(); !reflect.DeepEqual(result.err, err) {
                t.Errorf("unexpected error on Raw(): %s", diff.ObjectReflectDiff(expect, err))
            }
        })
    }
}
 
type errorReader struct {
    err error
}
 
func (r errorReader) Read(data []byte) (int, error) { return 0, r.err }
func (r errorReader) Close() error                  { return nil }
 
func TestRequestWatch(t *testing.T) {
    testCases := []struct {
        Request *Request
        Expect  []watch.Event
        Err     bool
        ErrFn   func(error) bool
        Empty   bool
    }{
        {
            Request: &Request{err: errors.New("bail")},
            Err:     true,
        },
        {
            Request: &Request{c: &RESTClient{base: &url.URL{}}, pathPrefix: "%"},
            Err:     true,
        },
        {
            Request: &Request{
                c: &RESTClient{
                    Client: clientForFunc(func(req *http.Request) (*http.Response, error) {
                        return nil, errors.New("err")
                    }),
                    base: &url.URL{},
                },
            },
            Err: true,
        },
        {
            Request: &Request{
                c: &RESTClient{
                    content: defaultContentConfig(),
                    Client: clientForFunc(func(req *http.Request) (*http.Response, error) {
                        return &http.Response{
                            StatusCode: http.StatusForbidden,
                            Body:       ioutil.NopCloser(bytes.NewReader([]byte{})),
                        }, nil
                    }),
                    base: &url.URL{},
                },
            },
            Expect: []watch.Event{
                {
                    Type: watch.Error,
                    Object: &metav1.Status{
                        Status:  "Failure",
                        Code:    500,
                        Reason:  "InternalError",
                        Message: `an error on the server ("unable to decode an event from the watch stream: test error") has prevented the request from succeeding`,
                        Details: &metav1.StatusDetails{
                            Causes: []metav1.StatusCause{
                                {
                                    Type:    "UnexpectedServerResponse",
                                    Message: "unable to decode an event from the watch stream: test error",
                                },
                                {
                                    Type:    "ClientWatchDecoding",
                                    Message: "unable to decode an event from the watch stream: test error",
                                },
                            },
                        },
                    },
                },
            },
            Err: true,
            ErrFn: func(err error) bool {
                return apierrors.IsForbidden(err)
            },
        },
        {
            Request: &Request{
                c: &RESTClient{
                    content: defaultContentConfig(),
                    Client: clientForFunc(func(req *http.Request) (*http.Response, error) {
                        return &http.Response{
                            StatusCode: http.StatusForbidden,
                            Body:       ioutil.NopCloser(bytes.NewReader([]byte{})),
                        }, nil
                    }),
                    base: &url.URL{},
                },
            },
            Err: true,
            ErrFn: func(err error) bool {
                return apierrors.IsForbidden(err)
            },
        },
        {
            Request: &Request{
                c: &RESTClient{
                    content: defaultContentConfig(),
                    Client: clientForFunc(func(req *http.Request) (*http.Response, error) {
                        return &http.Response{
                            StatusCode: http.StatusUnauthorized,
                            Body:       ioutil.NopCloser(bytes.NewReader([]byte{})),
                        }, nil
                    }),
                    base: &url.URL{},
                },
            },
            Err: true,
            ErrFn: func(err error) bool {
                return apierrors.IsUnauthorized(err)
            },
        },
        {
            Request: &Request{
                c: &RESTClient{
                    content: defaultContentConfig(),
                    Client: clientForFunc(func(req *http.Request) (*http.Response, error) {
                        return &http.Response{
                            StatusCode: http.StatusUnauthorized,
                            Body: ioutil.NopCloser(bytes.NewReader([]byte(runtime.EncodeOrDie(scheme.Codecs.LegacyCodec(v1.SchemeGroupVersion), &metav1.Status{
                                Status: metav1.StatusFailure,
                                Reason: metav1.StatusReasonUnauthorized,
                            })))),
                        }, nil
                    }),
                    base: &url.URL{},
                },
            },
            Err: true,
            ErrFn: func(err error) bool {
                return apierrors.IsUnauthorized(err)
            },
        },
        {
            Request: &Request{
                c: &RESTClient{
                    Client: clientForFunc(func(req *http.Request) (*http.Response, error) {
                        return nil, io.EOF
                    }),
                    base: &url.URL{},
                },
            },
            Empty: true,
        },
        {
            Request: &Request{
                c: &RESTClient{
                    Client: clientForFunc(func(req *http.Request) (*http.Response, error) {
                        return nil, errors.New("http: can't write HTTP request on broken connection")
                    }),
                    base: &url.URL{},
                },
            },
            Empty: true,
        },
        {
            Request: &Request{
                c: &RESTClient{
                    Client: clientForFunc(func(req *http.Request) (*http.Response, error) {
                        return nil, errors.New("foo: connection reset by peer")
                    }),
                    base: &url.URL{},
                },
            },
            Empty: true,
        },
    }
    for _, testCase := range testCases {
        t.Run("", func(t *testing.T) {
            testCase.Request.backoff = &NoBackoff{}
            watch, err := testCase.Request.Watch(context.Background())
            hasErr := err != nil
            if hasErr != testCase.Err {
                t.Fatalf("expected %t, got %t: %v", testCase.Err, hasErr, err)
            }
            if testCase.ErrFn != nil && !testCase.ErrFn(err) {
                t.Errorf("error not valid: %v", err)
            }
            if hasErr && watch != nil {
                t.Fatalf("watch should be nil when error is returned")
            }
            if hasErr {
                return
            }
            defer watch.Stop()
            if testCase.Empty {
                evt, ok := <-watch.ResultChan()
                if ok {
                    t.Errorf("expected the watch to be empty: %#v", evt)
                }
            }
            if testCase.Expect != nil {
                for i, evt := range testCase.Expect {
                    out, ok := <-watch.ResultChan()
                    if !ok {
                        t.Fatalf("Watch closed early, %d/%d read", i, len(testCase.Expect))
                    }
                    if !reflect.DeepEqual(evt, out) {
                        t.Fatalf("Event %d does not match: %s", i, diff.ObjectReflectDiff(evt, out))
                    }
                }
            }
        })
    }
}
 
func TestRequestStream(t *testing.T) {
    testCases := []struct {
        Request *Request
        Err     bool
        ErrFn   func(error) bool
    }{
        {
            Request: &Request{err: errors.New("bail")},
            Err:     true,
        },
        {
            Request: &Request{c: &RESTClient{base: &url.URL{}}, pathPrefix: "%"},
            Err:     true,
        },
        {
            Request: &Request{
                c: &RESTClient{
                    Client: clientForFunc(func(req *http.Request) (*http.Response, error) {
                        return nil, errors.New("err")
                    }),
                    base: &url.URL{},
                },
            },
            Err: true,
        },
        {
            Request: &Request{
                c: &RESTClient{
                    Client: clientForFunc(func(req *http.Request) (*http.Response, error) {
                        return &http.Response{
                            StatusCode: http.StatusUnauthorized,
                            Body: ioutil.NopCloser(bytes.NewReader([]byte(runtime.EncodeOrDie(scheme.Codecs.LegacyCodec(v1.SchemeGroupVersion), &metav1.Status{
                                Status: metav1.StatusFailure,
                                Reason: metav1.StatusReasonUnauthorized,
                            })))),
                        }, nil
                    }),
                    content: defaultContentConfig(),
                    base:    &url.URL{},
                },
            },
            Err: true,
        },
        {
            Request: &Request{
                c: &RESTClient{
                    Client: clientForFunc(func(req *http.Request) (*http.Response, error) {
                        return &http.Response{
                            StatusCode: http.StatusBadRequest,
                            Body:       ioutil.NopCloser(bytes.NewReader([]byte(`{"kind":"Status","apiVersion":"v1","metadata":{},"status":"Failure","message":"a container name must be specified for pod kube-dns-v20-mz5cv, choose one of: [kubedns dnsmasq healthz]","reason":"BadRequest","code":400}`))),
                        }, nil
                    }),
                    content: defaultContentConfig(),
                    base:    &url.URL{},
                },
            },
            Err: true,
            ErrFn: func(err error) bool {
                if err.Error() == "a container name must be specified for pod kube-dns-v20-mz5cv, choose one of: [kubedns dnsmasq healthz]" {
                    return true
                }
                return false
            },
        },
    }
    for i, testCase := range testCases {
        testCase.Request.backoff = &NoBackoff{}
        body, err := testCase.Request.Stream(context.Background())
        hasErr := err != nil
        if hasErr != testCase.Err {
            t.Errorf("%d: expected %t, got %t: %v", i, testCase.Err, hasErr, err)
        }
        if hasErr && body != nil {
            t.Errorf("%d: body should be nil when error is returned", i)
        }
 
        if hasErr {
            if testCase.ErrFn != nil && !testCase.ErrFn(err) {
                t.Errorf("unexpected error: %v", err)
            }
        }
    }
}
 
type fakeUpgradeConnection struct{}
 
func (c *fakeUpgradeConnection) CreateStream(headers http.Header) (httpstream.Stream, error) {
    return nil, nil
}
func (c *fakeUpgradeConnection) Close() error {
    return nil
}
func (c *fakeUpgradeConnection) CloseChan() <-chan bool {
    return make(chan bool)
}
func (c *fakeUpgradeConnection) SetIdleTimeout(timeout time.Duration) {
}
 
type fakeUpgradeRoundTripper struct {
    req  *http.Request
    conn httpstream.Connection
}
 
func (f *fakeUpgradeRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
    f.req = req
    b := []byte{}
    body := ioutil.NopCloser(bytes.NewReader(b))
    resp := &http.Response{
        StatusCode: http.StatusSwitchingProtocols,
        Body:       body,
    }
    return resp, nil
}
 
func (f *fakeUpgradeRoundTripper) NewConnection(resp *http.Response) (httpstream.Connection, error) {
    return f.conn, nil
}
 
func TestRequestDo(t *testing.T) {
    testCases := []struct {
        Request *Request
        Err     bool
    }{
        {
            Request: &Request{c: &RESTClient{}, err: errors.New("bail")},
            Err:     true,
        },
        {
            Request: &Request{c: &RESTClient{base: &url.URL{}}, pathPrefix: "%"},
            Err:     true,
        },
        {
            Request: &Request{
                c: &RESTClient{
                    Client: clientForFunc(func(req *http.Request) (*http.Response, error) {
                        return nil, errors.New("err")
                    }),
                    base: &url.URL{},
                },
            },
            Err: true,
        },
    }
    for i, testCase := range testCases {
        testCase.Request.backoff = &NoBackoff{}
        body, err := testCase.Request.Do(context.Background()).Raw()
        hasErr := err != nil
        if hasErr != testCase.Err {
            t.Errorf("%d: expected %t, got %t: %v", i, testCase.Err, hasErr, err)
        }
        if hasErr && body != nil {
            t.Errorf("%d: body should be nil when error is returned", i)
        }
    }
}
 
func TestDoRequestNewWay(t *testing.T) {
    reqBody := "request body"
    expectedObj := &v1.Service{Spec: v1.ServiceSpec{Ports: []v1.ServicePort{{
        Protocol:   "TCP",
        Port:       12345,
        TargetPort: intstr.FromInt(12345),
    }}}}
    expectedBody, _ := runtime.Encode(scheme.Codecs.LegacyCodec(v1.SchemeGroupVersion), expectedObj)
    fakeHandler := utiltesting.FakeHandler{
        StatusCode:   200,
        ResponseBody: string(expectedBody),
        T:            t,
    }
    testServer := httptest.NewServer(&fakeHandler)
    defer testServer.Close()
    c := testRESTClient(t, testServer)
    obj, err := c.Verb("POST").
        Prefix("foo", "bar").
        Suffix("baz").
        Timeout(time.Second).
        Body([]byte(reqBody)).
        Do(context.Background()).Get()
    if err != nil {
        t.Errorf("Unexpected error: %v %#v", err, err)
        return
    }
    if obj == nil {
        t.Error("nil obj")
    } else if !apiequality.Semantic.DeepDerivative(expectedObj, obj) {
        t.Errorf("Expected: %#v, got %#v", expectedObj, obj)
    }
    requestURL := defaultResourcePathWithPrefix("foo/bar", "", "", "baz")
    requestURL += "?timeout=1s"
    fakeHandler.ValidateRequest(t, requestURL, "POST", &reqBody)
}
 
// This test assumes that the client implementation backs off exponentially, for an individual request.
func TestBackoffLifecycle(t *testing.T) {
    count := 0
    testServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
        count++
        t.Logf("Attempt %d", count)
        if count == 5 || count == 9 {
            w.WriteHeader(http.StatusOK)
            return
        }
        w.WriteHeader(http.StatusGatewayTimeout)
        return
    }))
    defer testServer.Close()
    c := testRESTClient(t, testServer)
 
    // Test backoff recovery and increase.  This correlates to the constants
    // which are used in the server implementation returning StatusOK above.
    seconds := []int{0, 1, 2, 4, 8, 0, 1, 2, 4, 0}
    request := c.Verb("POST").Prefix("backofftest").Suffix("abc")
    clock := clock.FakeClock{}
    request.backoff = &URLBackoff{
        // Use a fake backoff here to avoid flakes and speed the test up.
        Backoff: flowcontrol.NewFakeBackOff(
            time.Duration(1)*time.Second,
            time.Duration(200)*time.Second,
            &clock,
        )}
 
    for _, sec := range seconds {
        thisBackoff := request.backoff.CalculateBackoff(request.URL())
        t.Logf("Current backoff %v", thisBackoff)
        if thisBackoff != time.Duration(sec)*time.Second {
            t.Errorf("Backoff is %v instead of %v", thisBackoff, sec)
        }
        now := clock.Now()
        request.DoRaw(context.Background())
        elapsed := clock.Since(now)
        if clock.Since(now) != thisBackoff {
            t.Errorf("CalculatedBackoff not honored by clock: Expected time of %v, but got %v ", thisBackoff, elapsed)
        }
    }
}
 
type testBackoffManager struct {
    sleeps []time.Duration
}
 
func (b *testBackoffManager) UpdateBackoff(actualUrl *url.URL, err error, responseCode int) {
}
 
func (b *testBackoffManager) CalculateBackoff(actualUrl *url.URL) time.Duration {
    return time.Duration(0)
}
 
func (b *testBackoffManager) Sleep(d time.Duration) {
    b.sleeps = append(b.sleeps, d)
}
 
func TestCheckRetryClosesBody(t *testing.T) {
    count := 0
    ch := make(chan struct{})
    testServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
        count++
        t.Logf("attempt %d", count)
        if count >= 5 {
            w.WriteHeader(http.StatusOK)
            close(ch)
            return
        }
        w.Header().Set("Retry-After", "1")
        http.Error(w, "Too many requests, please try again later.", http.StatusTooManyRequests)
    }))
    defer testServer.Close()
 
    backoff := &testBackoffManager{}
    expectedSleeps := []time.Duration{0, time.Second, 0, time.Second, 0, time.Second, 0, time.Second, 0}
 
    c := testRESTClient(t, testServer)
    c.createBackoffMgr = func() BackoffManager { return backoff }
    _, err := c.Verb("POST").
        Prefix("foo", "bar").
        Suffix("baz").
        Timeout(time.Second).
        Body([]byte(strings.Repeat("abcd", 1000))).
        DoRaw(context.Background())
    if err != nil {
        t.Fatalf("Unexpected error: %v %#v", err, err)
    }
    <-ch
    if count != 5 {
        t.Errorf("unexpected retries: %d", count)
    }
    if !reflect.DeepEqual(backoff.sleeps, expectedSleeps) {
        t.Errorf("unexpected sleeps, expected: %v, got: %v", expectedSleeps, backoff.sleeps)
    }
}
 
func TestConnectionResetByPeerIsRetried(t *testing.T) {
    count := 0
    backoff := &testBackoffManager{}
    req := &Request{
        verb: "GET",
        c: &RESTClient{
            Client: clientForFunc(func(req *http.Request) (*http.Response, error) {
                count++
                if count >= 3 {
                    return &http.Response{
                        StatusCode: http.StatusOK,
                        Body:       ioutil.NopCloser(bytes.NewReader([]byte{})),
                    }, nil
                }
                return nil, &net.OpError{Err: syscall.ECONNRESET}
            }),
        },
        backoff:    backoff,
        maxRetries: 10,
    }
    // We expect two retries of "connection reset by peer" and the success.
    _, err := req.Do(context.Background()).Raw()
    if err != nil {
        t.Errorf("Unexpected error: %v", err)
    }
    // We have a sleep before each retry (including the initial one) and for
    // every "retry-after" call - thus 5 together.
    if len(backoff.sleeps) != 5 {
        t.Errorf("Expected 5 retries, got: %d", len(backoff.sleeps))
    }
}
 
func TestCheckRetryHandles429And5xx(t *testing.T) {
    count := 0
    ch := make(chan struct{})
    testServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
        data, err := ioutil.ReadAll(req.Body)
        if err != nil {
            t.Fatalf("unable to read request body: %v", err)
        }
        if !bytes.Equal(data, []byte(strings.Repeat("abcd", 1000))) {
            t.Fatalf("retry did not send a complete body: %s", data)
        }
        t.Logf("attempt %d", count)
        if count >= 4 {
            w.WriteHeader(http.StatusOK)
            close(ch)
            return
        }
        w.Header().Set("Retry-After", "0")
        w.WriteHeader([]int{http.StatusTooManyRequests, 500, 501, 504}[count])
        count++
    }))
    defer testServer.Close()
 
    c := testRESTClient(t, testServer)
    _, err := c.Verb("POST").
        Prefix("foo", "bar").
        Suffix("baz").
        Timeout(time.Second).
        Body([]byte(strings.Repeat("abcd", 1000))).
        DoRaw(context.Background())
    if err != nil {
        t.Fatalf("Unexpected error: %v %#v", err, err)
    }
    <-ch
    if count != 4 {
        t.Errorf("unexpected retries: %d", count)
    }
}
 
func BenchmarkCheckRetryClosesBody(b *testing.B) {
    count := 0
    testServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
        count++
        if count%3 == 0 {
            w.WriteHeader(http.StatusOK)
            return
        }
        w.Header().Set("Retry-After", "0")
        w.WriteHeader(http.StatusTooManyRequests)
    }))
    defer testServer.Close()
 
    c := testRESTClient(b, testServer)
 
    requests := make([]*Request, 0, b.N)
    for i := 0; i < b.N; i++ {
        requests = append(requests, c.Verb("POST").
            Prefix("foo", "bar").
            Suffix("baz").
            Timeout(time.Second).
            Body([]byte(strings.Repeat("abcd", 1000))))
    }
 
    b.ResetTimer()
    for i := 0; i < b.N; i++ {
        if _, err := requests[i].DoRaw(context.Background()); err != nil {
            b.Fatalf("Unexpected error (%d/%d): %v", i, b.N, err)
        }
    }
}
 
func TestDoRequestNewWayReader(t *testing.T) {
    reqObj := &v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "foo"}}
    reqBodyExpected, _ := runtime.Encode(scheme.Codecs.LegacyCodec(v1.SchemeGroupVersion), reqObj)
    expectedObj := &v1.Service{Spec: v1.ServiceSpec{Ports: []v1.ServicePort{{
        Protocol:   "TCP",
        Port:       12345,
        TargetPort: intstr.FromInt(12345),
    }}}}
    expectedBody, _ := runtime.Encode(scheme.Codecs.LegacyCodec(v1.SchemeGroupVersion), expectedObj)
    fakeHandler := utiltesting.FakeHandler{
        StatusCode:   200,
        ResponseBody: string(expectedBody),
        T:            t,
    }
    testServer := httptest.NewServer(&fakeHandler)
    defer testServer.Close()
    c := testRESTClient(t, testServer)
    obj, err := c.Verb("POST").
        Resource("bar").
        Name("baz").
        Prefix("foo").
        Timeout(time.Second).
        Body(bytes.NewBuffer(reqBodyExpected)).
        Do(context.Background()).Get()
    if err != nil {
        t.Errorf("Unexpected error: %v %#v", err, err)
        return
    }
    if obj == nil {
        t.Error("nil obj")
    } else if !apiequality.Semantic.DeepDerivative(expectedObj, obj) {
        t.Errorf("Expected: %#v, got %#v", expectedObj, obj)
    }
    tmpStr := string(reqBodyExpected)
    requestURL := defaultResourcePathWithPrefix("foo", "bar", "", "baz")
    requestURL += "?timeout=1s"
    fakeHandler.ValidateRequest(t, requestURL, "POST", &tmpStr)
}
 
func TestDoRequestNewWayObj(t *testing.T) {
    reqObj := &v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "foo"}}
    reqBodyExpected, _ := runtime.Encode(scheme.Codecs.LegacyCodec(v1.SchemeGroupVersion), reqObj)
    expectedObj := &v1.Service{Spec: v1.ServiceSpec{Ports: []v1.ServicePort{{
        Protocol:   "TCP",
        Port:       12345,
        TargetPort: intstr.FromInt(12345),
    }}}}
    expectedBody, _ := runtime.Encode(scheme.Codecs.LegacyCodec(v1.SchemeGroupVersion), expectedObj)
    fakeHandler := utiltesting.FakeHandler{
        StatusCode:   200,
        ResponseBody: string(expectedBody),
        T:            t,
    }
    testServer := httptest.NewServer(&fakeHandler)
    defer testServer.Close()
    c := testRESTClient(t, testServer)
    obj, err := c.Verb("POST").
        Suffix("baz").
        Name("bar").
        Resource("foo").
        Timeout(time.Second).
        Body(reqObj).
        Do(context.Background()).Get()
    if err != nil {
        t.Errorf("Unexpected error: %v %#v", err, err)
        return
    }
    if obj == nil {
        t.Error("nil obj")
    } else if !apiequality.Semantic.DeepDerivative(expectedObj, obj) {
        t.Errorf("Expected: %#v, got %#v", expectedObj, obj)
    }
    tmpStr := string(reqBodyExpected)
    requestURL := defaultResourcePathWithPrefix("", "foo", "", "bar/baz")
    requestURL += "?timeout=1s"
    fakeHandler.ValidateRequest(t, requestURL, "POST", &tmpStr)
}
 
func TestDoRequestNewWayFile(t *testing.T) {
    reqObj := &v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "foo"}}
    reqBodyExpected, err := runtime.Encode(scheme.Codecs.LegacyCodec(v1.SchemeGroupVersion), reqObj)
    if err != nil {
        t.Errorf("unexpected error: %v", err)
    }
 
    file, err := ioutil.TempFile("", "foo")
    if err != nil {
        t.Errorf("unexpected error: %v", err)
    }
    defer file.Close()
    defer os.Remove(file.Name())
 
    _, err = file.Write(reqBodyExpected)
    if err != nil {
        t.Errorf("unexpected error: %v", err)
    }
 
    expectedObj := &v1.Service{Spec: v1.ServiceSpec{Ports: []v1.ServicePort{{
        Protocol:   "TCP",
        Port:       12345,
        TargetPort: intstr.FromInt(12345),
    }}}}
    expectedBody, _ := runtime.Encode(scheme.Codecs.LegacyCodec(v1.SchemeGroupVersion), expectedObj)
    fakeHandler := utiltesting.FakeHandler{
        StatusCode:   200,
        ResponseBody: string(expectedBody),
        T:            t,
    }
    testServer := httptest.NewServer(&fakeHandler)
    defer testServer.Close()
    c := testRESTClient(t, testServer)
    wasCreated := true
    obj, err := c.Verb("POST").
        Prefix("foo/bar", "baz").
        Timeout(time.Second).
        Body(file.Name()).
        Do(context.Background()).WasCreated(&wasCreated).Get()
    if err != nil {
        t.Errorf("Unexpected error: %v %#v", err, err)
        return
    }
    if obj == nil {
        t.Error("nil obj")
    } else if !apiequality.Semantic.DeepDerivative(expectedObj, obj) {
        t.Errorf("Expected: %#v, got %#v", expectedObj, obj)
    }
    if wasCreated {
        t.Errorf("expected object was created")
    }
    tmpStr := string(reqBodyExpected)
    requestURL := defaultResourcePathWithPrefix("foo/bar/baz", "", "", "")
    requestURL += "?timeout=1s"
    fakeHandler.ValidateRequest(t, requestURL, "POST", &tmpStr)
}
 
func TestWasCreated(t *testing.T) {
    reqObj := &v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "foo"}}
    reqBodyExpected, err := runtime.Encode(scheme.Codecs.LegacyCodec(v1.SchemeGroupVersion), reqObj)
    if err != nil {
        t.Errorf("unexpected error: %v", err)
    }
 
    expectedObj := &v1.Service{Spec: v1.ServiceSpec{Ports: []v1.ServicePort{{
        Protocol:   "TCP",
        Port:       12345,
        TargetPort: intstr.FromInt(12345),
    }}}}
    expectedBody, _ := runtime.Encode(scheme.Codecs.LegacyCodec(v1.SchemeGroupVersion), expectedObj)
    fakeHandler := utiltesting.FakeHandler{
        StatusCode:   201,
        ResponseBody: string(expectedBody),
        T:            t,
    }
    testServer := httptest.NewServer(&fakeHandler)
    defer testServer.Close()
    c := testRESTClient(t, testServer)
    wasCreated := false
    obj, err := c.Verb("PUT").
        Prefix("foo/bar", "baz").
        Timeout(time.Second).
        Body(reqBodyExpected).
        Do(context.Background()).WasCreated(&wasCreated).Get()
    if err != nil {
        t.Errorf("Unexpected error: %v %#v", err, err)
        return
    }
    if obj == nil {
        t.Error("nil obj")
    } else if !apiequality.Semantic.DeepDerivative(expectedObj, obj) {
        t.Errorf("Expected: %#v, got %#v", expectedObj, obj)
    }
    if !wasCreated {
        t.Errorf("Expected object was created")
    }
 
    tmpStr := string(reqBodyExpected)
    requestURL := defaultResourcePathWithPrefix("foo/bar/baz", "", "", "")
    requestURL += "?timeout=1s"
    fakeHandler.ValidateRequest(t, requestURL, "PUT", &tmpStr)
}
 
func TestVerbs(t *testing.T) {
    c := testRESTClient(t, nil)
    if r := c.Post(); r.verb != "POST" {
        t.Errorf("Post verb is wrong")
    }
    if r := c.Put(); r.verb != "PUT" {
        t.Errorf("Put verb is wrong")
    }
    if r := c.Get(); r.verb != "GET" {
        t.Errorf("Get verb is wrong")
    }
    if r := c.Delete(); r.verb != "DELETE" {
        t.Errorf("Delete verb is wrong")
    }
}
 
func TestAbsPath(t *testing.T) {
    for i, tc := range []struct {
        configPrefix   string
        resourcePrefix string
        absPath        string
        wantsAbsPath   string
    }{
        {"/", "", "", "/"},
        {"", "", "/", "/"},
        {"", "", "/api", "/api"},
        {"", "", "/api/", "/api/"},
        {"", "", "/apis", "/apis"},
        {"", "/foo", "/bar/foo", "/bar/foo"},
        {"", "/api/foo/123", "/bar/foo", "/bar/foo"},
        {"/p1", "", "", "/p1"},
        {"/p1", "", "/", "/p1/"},
        {"/p1", "", "/api", "/p1/api"},
        {"/p1", "", "/apis", "/p1/apis"},
        {"/p1", "/r1", "/apis", "/p1/apis"},
        {"/p1", "/api/r1", "/apis", "/p1/apis"},
        {"/p1/api/p2", "", "", "/p1/api/p2"},
        {"/p1/api/p2", "", "/", "/p1/api/p2/"},
        {"/p1/api/p2", "", "/api", "/p1/api/p2/api"},
        {"/p1/api/p2", "", "/api/", "/p1/api/p2/api/"},
        {"/p1/api/p2", "/r1", "/api/", "/p1/api/p2/api/"},
        {"/p1/api/p2", "/api/r1", "/api/", "/p1/api/p2/api/"},
    } {
        u, _ := url.Parse("http://localhost:123" + tc.configPrefix)
        r := NewRequestWithClient(u, "", ClientContentConfig{GroupVersion: schema.GroupVersion{Group: "test"}}, nil).Verb("POST").Prefix(tc.resourcePrefix).AbsPath(tc.absPath)
        if r.pathPrefix != tc.wantsAbsPath {
            t.Errorf("test case %d failed, unexpected path: %q, expected %q", i, r.pathPrefix, tc.wantsAbsPath)
        }
    }
}
 
func TestUnacceptableParamNames(t *testing.T) {
    table := []struct {
        name          string
        testVal       string
        expectSuccess bool
    }{
        // timeout is no longer "protected"
        {"timeout", "42", true},
    }
 
    for _, item := range table {
        c := testRESTClient(t, nil)
        r := c.Get().setParam(item.name, item.testVal)
        if e, a := item.expectSuccess, r.err == nil; e != a {
            t.Errorf("expected %v, got %v (%v)", e, a, r.err)
        }
    }
}
 
func TestBody(t *testing.T) {
    const data = "test payload"
 
    obj := &v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "foo"}}
    bodyExpected, _ := runtime.Encode(scheme.Codecs.LegacyCodec(v1.SchemeGroupVersion), obj)
 
    f, err := ioutil.TempFile("", "test_body")
    if err != nil {
        t.Fatalf("TempFile error: %v", err)
    }
    if _, err := f.WriteString(data); err != nil {
        t.Fatalf("TempFile.WriteString error: %v", err)
    }
    f.Close()
    defer os.Remove(f.Name())
 
    var nilObject *metav1.DeleteOptions
    typedObject := interface{}(nilObject)
    c := testRESTClient(t, nil)
    tests := []struct {
        input    interface{}
        expected string
        headers  map[string]string
    }{
        {[]byte(data), data, nil},
        {f.Name(), data, nil},
        {strings.NewReader(data), data, nil},
        {obj, string(bodyExpected), map[string]string{"Content-Type": "application/json"}},
        {typedObject, "", nil},
    }
    for i, tt := range tests {
        r := c.Post().Body(tt.input)
        if r.err != nil {
            t.Errorf("%d: r.Body(%#v) error: %v", i, tt, r.err)
            continue
        }
        if tt.headers != nil {
            for k, v := range tt.headers {
                if r.headers.Get(k) != v {
                    t.Errorf("%d: r.headers[%q] = %q; want %q", i, k, v, v)
                }
            }
        }
 
        if r.body == nil {
            if len(tt.expected) != 0 {
                t.Errorf("%d: r.body = %q; want %q", i, r.body, tt.expected)
            }
            continue
        }
        buf := make([]byte, len(tt.expected))
        if _, err := r.body.Read(buf); err != nil {
            t.Errorf("%d: r.body.Read error: %v", i, err)
            continue
        }
        body := string(buf)
        if body != tt.expected {
            t.Errorf("%d: r.body = %q; want %q", i, body, tt.expected)
        }
    }
}
 
func TestWatch(t *testing.T) {
    var table = []struct {
        t   watch.EventType
        obj runtime.Object
    }{
        {watch.Added, &v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "first"}}},
        {watch.Modified, &v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "second"}}},
        {watch.Deleted, &v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "last"}}},
    }
 
    testServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        flusher, ok := w.(http.Flusher)
        if !ok {
            panic("need flusher!")
        }
 
        w.Header().Set("Transfer-Encoding", "chunked")
        w.WriteHeader(http.StatusOK)
        flusher.Flush()
 
        encoder := restclientwatch.NewEncoder(streaming.NewEncoder(w, scheme.Codecs.LegacyCodec(v1.SchemeGroupVersion)), scheme.Codecs.LegacyCodec(v1.SchemeGroupVersion))
        for _, item := range table {
            if err := encoder.Encode(&watch.Event{Type: item.t, Object: item.obj}); err != nil {
                panic(err)
            }
            flusher.Flush()
        }
    }))
    defer testServer.Close()
 
    s := testRESTClient(t, testServer)
    watching, err := s.Get().Prefix("path/to/watch/thing").Watch(context.Background())
    if err != nil {
        t.Fatalf("Unexpected error: %v", err)
    }
 
    for _, item := range table {
        got, ok := <-watching.ResultChan()
        if !ok {
            t.Fatalf("Unexpected early close")
        }
        if e, a := item.t, got.Type; e != a {
            t.Errorf("Expected %v, got %v", e, a)
        }
        if e, a := item.obj, got.Object; !apiequality.Semantic.DeepDerivative(e, a) {
            t.Errorf("Expected %v, got %v", e, a)
        }
    }
 
    _, ok := <-watching.ResultChan()
    if ok {
        t.Fatal("Unexpected non-close")
    }
}
 
func TestWatchNonDefaultContentType(t *testing.T) {
    var table = []struct {
        t   watch.EventType
        obj runtime.Object
    }{
        {watch.Added, &v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "first"}}},
        {watch.Modified, &v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "second"}}},
        {watch.Deleted, &v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "last"}}},
    }
 
    testServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        flusher, ok := w.(http.Flusher)
        if !ok {
            panic("need flusher!")
        }
 
        w.Header().Set("Transfer-Encoding", "chunked")
        // manually set the content type here so we get the renegotiation behavior
        w.Header().Set("Content-Type", "application/json")
        w.WriteHeader(http.StatusOK)
        flusher.Flush()
 
        encoder := restclientwatch.NewEncoder(streaming.NewEncoder(w, scheme.Codecs.LegacyCodec(v1.SchemeGroupVersion)), scheme.Codecs.LegacyCodec(v1.SchemeGroupVersion))
        for _, item := range table {
            if err := encoder.Encode(&watch.Event{Type: item.t, Object: item.obj}); err != nil {
                panic(err)
            }
            flusher.Flush()
        }
    }))
    defer testServer.Close()
 
    // set the default content type to protobuf so that we test falling back to JSON serialization
    contentConfig := defaultContentConfig()
    contentConfig.ContentType = "application/vnd.kubernetes.protobuf"
    s := testRESTClientWithConfig(t, testServer, contentConfig)
    watching, err := s.Get().Prefix("path/to/watch/thing").Watch(context.Background())
    if err != nil {
        t.Fatalf("Unexpected error")
    }
 
    for _, item := range table {
        got, ok := <-watching.ResultChan()
        if !ok {
            t.Fatalf("Unexpected early close")
        }
        if e, a := item.t, got.Type; e != a {
            t.Errorf("Expected %v, got %v", e, a)
        }
        if e, a := item.obj, got.Object; !apiequality.Semantic.DeepDerivative(e, a) {
            t.Errorf("Expected %v, got %v", e, a)
        }
    }
 
    _, ok := <-watching.ResultChan()
    if ok {
        t.Fatal("Unexpected non-close")
    }
}
 
func TestWatchUnknownContentType(t *testing.T) {
    var table = []struct {
        t   watch.EventType
        obj runtime.Object
    }{
        {watch.Added, &v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "first"}}},
        {watch.Modified, &v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "second"}}},
        {watch.Deleted, &v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "last"}}},
    }
 
    testServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        flusher, ok := w.(http.Flusher)
        if !ok {
            panic("need flusher!")
        }
 
        w.Header().Set("Transfer-Encoding", "chunked")
        // manually set the content type here so we get the renegotiation behavior
        w.Header().Set("Content-Type", "foobar")
        w.WriteHeader(http.StatusOK)
        flusher.Flush()
 
        encoder := restclientwatch.NewEncoder(streaming.NewEncoder(w, scheme.Codecs.LegacyCodec(v1.SchemeGroupVersion)), scheme.Codecs.LegacyCodec(v1.SchemeGroupVersion))
        for _, item := range table {
            if err := encoder.Encode(&watch.Event{Type: item.t, Object: item.obj}); err != nil {
                panic(err)
            }
            flusher.Flush()
        }
    }))
    defer testServer.Close()
 
    s := testRESTClient(t, testServer)
    _, err := s.Get().Prefix("path/to/watch/thing").Watch(context.Background())
    if err == nil {
        t.Fatalf("Expected to fail due to lack of known stream serialization for content type")
    }
}
 
func TestStream(t *testing.T) {
    expectedBody := "expected body"
 
    testServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        flusher, ok := w.(http.Flusher)
        if !ok {
            panic("need flusher!")
        }
        w.Header().Set("Transfer-Encoding", "chunked")
        w.WriteHeader(http.StatusOK)
        w.Write([]byte(expectedBody))
        flusher.Flush()
    }))
    defer testServer.Close()
 
    s := testRESTClient(t, testServer)
    readCloser, err := s.Get().Prefix("path/to/stream/thing").Stream(context.Background())
    if err != nil {
        t.Fatalf("unexpected error: %v", err)
    }
    defer readCloser.Close()
    buf := new(bytes.Buffer)
    buf.ReadFrom(readCloser)
    resultBody := buf.String()
 
    if expectedBody != resultBody {
        t.Errorf("Expected %s, got %s", expectedBody, resultBody)
    }
}
 
func testRESTClientWithConfig(t testing.TB, srv *httptest.Server, contentConfig ClientContentConfig) *RESTClient {
    base, _ := url.Parse("http://localhost")
    if srv != nil {
        var err error
        base, err = url.Parse(srv.URL)
        if err != nil {
            t.Fatalf("failed to parse test URL: %v", err)
        }
    }
    versionedAPIPath := defaultResourcePathWithPrefix("", "", "", "")
    client, err := NewRESTClient(base, versionedAPIPath, contentConfig, nil, nil)
    if err != nil {
        t.Fatalf("failed to create a client: %v", err)
    }
    return client
 
}
 
func testRESTClient(t testing.TB, srv *httptest.Server) *RESTClient {
    contentConfig := defaultContentConfig()
    return testRESTClientWithConfig(t, srv, contentConfig)
}
 
func TestDoContext(t *testing.T) {
    receivedCh := make(chan struct{})
    block := make(chan struct{})
    testServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
        close(receivedCh)
        <-block
        w.WriteHeader(http.StatusOK)
    }))
    defer testServer.Close()
    defer close(block)
 
    ctx, cancel := context.WithCancel(context.Background())
    defer cancel()
 
    go func() {
        <-receivedCh
        cancel()
    }()
 
    c := testRESTClient(t, testServer)
    _, err := c.Verb("GET").
        Prefix("foo").
        DoRaw(ctx)
    if err == nil {
        t.Fatal("Expected context cancellation error")
    }
}
 
func buildString(length int) string {
    s := make([]byte, length)
    for i := range s {
        s[i] = 'a'
    }
    return string(s)
}
 
func init() {
    klog.InitFlags(nil)
}
 
func TestTruncateBody(t *testing.T) {
    tests := []struct {
        body  string
        want  string
        level string
    }{
        // Anything below 8 is completely truncated
        {
            body:  "Completely truncated below 8",
            want:  " [truncated 28 chars]",
            level: "0",
        },
        // Small strings are not truncated by high levels
        {
            body:  "Small body never gets truncated",
            want:  "Small body never gets truncated",
            level: "10",
        },
        {
            body:  "Small body never gets truncated",
            want:  "Small body never gets truncated",
            level: "8",
        },
        // Strings are truncated to 1024 if level is less than 9.
        {
            body:  buildString(2000),
            level: "8",
            want:  fmt.Sprintf("%s [truncated 976 chars]", buildString(1024)),
        },
        // Strings are truncated to 10240 if level is 9.
        {
            body:  buildString(20000),
            level: "9",
            want:  fmt.Sprintf("%s [truncated 9760 chars]", buildString(10240)),
        },
        // Strings are not truncated if level is 10 or higher
        {
            body:  buildString(20000),
            level: "10",
            want:  buildString(20000),
        },
        // Strings are not truncated if level is 10 or higher
        {
            body:  buildString(20000),
            level: "11",
            want:  buildString(20000),
        },
    }
 
    l := flag.Lookup("v").Value.(flag.Getter).Get().(klog.Level)
    for _, test := range tests {
        flag.Set("v", test.level)
        got := truncateBody(test.body)
        if got != test.want {
            t.Errorf("truncateBody(%v) = %v, want %v", test.body, got, test.want)
        }
    }
    flag.Set("v", l.String())
}
 
func defaultResourcePathWithPrefix(prefix, resource, namespace, name string) string {
    var path string
    path = "/api/" + v1.SchemeGroupVersion.Version
 
    if prefix != "" {
        path = path + "/" + prefix
    }
    if namespace != "" {
        path = path + "/namespaces/" + namespace
    }
    // Resource names are lower case.
    resource = strings.ToLower(resource)
    if resource != "" {
        path = path + "/" + resource
    }
    if name != "" {
        path = path + "/" + name
    }
    return path
}
 
func TestRequestPreflightCheck(t *testing.T) {
    for _, tt := range []struct {
        name         string
        verbs        []string
        namespace    string
        resourceName string
        namespaceSet bool
        expectsErr   bool
    }{
        {
            name:         "no namespace set",
            verbs:        []string{"GET", "PUT", "DELETE", "POST"},
            namespaceSet: false,
            expectsErr:   false,
        },
        {
            name:         "empty resource name and namespace",
            verbs:        []string{"GET", "PUT", "DELETE"},
            namespaceSet: true,
            expectsErr:   false,
        },
        {
            name:         "resource name with empty namespace",
            verbs:        []string{"GET", "PUT", "DELETE"},
            namespaceSet: true,
            resourceName: "ResourceName",
            expectsErr:   true,
        },
        {
            name:         "post empty resource name and namespace",
            verbs:        []string{"POST"},
            namespaceSet: true,
            expectsErr:   true,
        },
        {
            name:         "working requests",
            verbs:        []string{"GET", "PUT", "DELETE", "POST"},
            namespaceSet: true,
            resourceName: "ResourceName",
            namespace:    "Namespace",
            expectsErr:   false,
        },
    } {
        t.Run(tt.name, func(t *testing.T) {
            for _, verb := range tt.verbs {
                r := &Request{
                    verb:         verb,
                    namespace:    tt.namespace,
                    resourceName: tt.resourceName,
                    namespaceSet: tt.namespaceSet,
                }
 
                err := r.requestPreflightCheck()
                hasErr := err != nil
                if hasErr == tt.expectsErr {
                    return
                }
                t.Errorf("%s: expects error: %v, has error: %v", verb, tt.expectsErr, hasErr)
            }
        })
    }
}
 
func TestThrottledLogger(t *testing.T) {
    now := time.Now()
    oldClock := globalThrottledLogger.clock
    defer func() {
        globalThrottledLogger.clock = oldClock
    }()
    clock := clock.NewFakeClock(now)
    globalThrottledLogger.clock = clock
 
    logMessages := 0
    for i := 0; i < 1000; i++ {
        var wg sync.WaitGroup
        wg.Add(10)
        for j := 0; j < 10; j++ {
            go func() {
                if _, ok := globalThrottledLogger.attemptToLog(); ok {
                    logMessages++
                }
                wg.Done()
            }()
        }
        wg.Wait()
        now = now.Add(1 * time.Second)
        clock.SetTime(now)
    }
 
    if a, e := logMessages, 100; a != e {
        t.Fatalf("expected %v log messages, but got %v", e, a)
    }
}
 
func TestRequestMaxRetries(t *testing.T) {
    successAtNthCalls := 1
    actualCalls := 0
    retryOneTimeHandler := func(w http.ResponseWriter, req *http.Request) {
        defer func() { actualCalls++ }()
        if actualCalls >= successAtNthCalls {
            w.WriteHeader(http.StatusOK)
            return
        }
        w.Header().Set("Retry-After", "1")
        w.WriteHeader(http.StatusTooManyRequests)
        actualCalls++
    }
    testServer := httptest.NewServer(http.HandlerFunc(retryOneTimeHandler))
    defer testServer.Close()
 
    u, err := url.Parse(testServer.URL)
    if err != nil {
        t.Error(err)
    }
 
    testCases := []struct {
        name        string
        maxRetries  int
        expectError bool
    }{
        {
            name:        "no retrying should fail",
            maxRetries:  0,
            expectError: true,
        },
        {
            name:        "1 max-retry should exactly work",
            maxRetries:  1,
            expectError: false,
        },
        {
            name:        "5 max-retry should work",
            maxRetries:  5,
            expectError: false,
        },
    }
 
    for _, testCase := range testCases {
        t.Run(testCase.name, func(t *testing.T) {
            defer func() { actualCalls = 0 }()
            _, err := NewRequestWithClient(u, "", defaultContentConfig(), testServer.Client()).
                Verb("get").
                MaxRetries(testCase.maxRetries).
                AbsPath("/foo").
                DoRaw(context.TODO())
            hasError := err != nil
            if testCase.expectError != hasError {
                t.Error(" failed checking error")
            }
        })
    }
}