1 package autorest
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 import (
18 "context"
19 "fmt"
20 "io/ioutil"
21 "net/http"
22 "net/url"
23 "reflect"
24 "strconv"
25 "strings"
26 "testing"
27
28 "github.com/Azure/go-autorest/autorest/mocks"
29 )
30
31
32
33 func ExamplePrepareDecorator() {
34 path := "a/b/c/"
35 pd := func() PrepareDecorator {
36 return func(p Preparer) Preparer {
37 return PreparerFunc(func(r *http.Request) (*http.Request, error) {
38 r, err := p.Prepare(r)
39 if err == nil {
40 if r.URL == nil {
41 return r, fmt.Errorf("ERROR: URL is not set")
42 }
43 r.URL.Path += path
44 }
45 return r, err
46 })
47 }
48 }
49
50 r, _ := Prepare(&http.Request{},
51 WithBaseURL("https://microsoft.com/"),
52 pd())
53
54 fmt.Printf("Path is %s\n", r.URL)
55
56 }
57
58
59 func ExamplePrepareDecorator_pre() {
60 pd := func() PrepareDecorator {
61 return func(p Preparer) Preparer {
62 return PreparerFunc(func(r *http.Request) (*http.Request, error) {
63 r.Header.Add(http.CanonicalHeaderKey("ContentType"), "application/json")
64 return p.Prepare(r)
65 })
66 }
67 }
68
69 r, _ := Prepare(&http.Request{Header: http.Header{}},
70 pd())
71
72 fmt.Printf("ContentType is %s\n", r.Header.Get("ContentType"))
73
74 }
75
76
77 func ExampleCreatePreparer() {
78 p := CreatePreparer(
79 WithBaseURL("https://microsoft.com/"),
80 WithPath("a"),
81 WithPath("b"),
82 WithPath("c"))
83 r, err := p.Prepare(&http.Request{})
84 if err != nil {
85 fmt.Printf("ERROR: %v\n", err)
86 } else {
87 fmt.Println(r.URL)
88 }
89
90 }
91
92
93 func ExampleCreatePreparer_multiple() {
94 params := map[string]interface{}{
95 "param1": "a",
96 "param2": "c",
97 }
98
99 p1 := CreatePreparer(WithBaseURL("https://microsoft.com/"))
100 p2 := CreatePreparer(WithPathParameters("/{param1}/b/{param2}/", params))
101
102 r, err := p1.Prepare(&http.Request{})
103 if err != nil {
104 fmt.Printf("ERROR: %v\n", err)
105 }
106
107 r, err = p2.Prepare(r)
108 if err != nil {
109 fmt.Printf("ERROR: %v\n", err)
110 } else {
111 fmt.Println(r.URL)
112 }
113
114 }
115
116
117 func ExampleCreatePreparer_chain() {
118 params := map[string]interface{}{
119 "param1": "a",
120 "param2": "c",
121 }
122
123 p := CreatePreparer(WithBaseURL("https://microsoft.com/"))
124 p = DecoratePreparer(p, WithPathParameters("/{param1}/b/{param2}/", params))
125
126 r, err := p.Prepare(&http.Request{})
127 if err != nil {
128 fmt.Printf("ERROR: %v\n", err)
129 } else {
130 fmt.Println(r.URL)
131 }
132
133 }
134
135
136 func ExamplePrepare() {
137 r, err := Prepare(&http.Request{},
138 AsGet(),
139 WithBaseURL("https://microsoft.com/"),
140 WithPath("a/b/c/"))
141 if err != nil {
142 fmt.Printf("ERROR: %v\n", err)
143 } else {
144 fmt.Printf("%s %s", r.Method, r.URL)
145 }
146
147 }
148
149
150 func ExampleWithBaseURL() {
151 r, err := Prepare(&http.Request{},
152 WithBaseURL("https://microsoft.com/a/b/c/"))
153 if err != nil {
154 fmt.Printf("ERROR: %v\n", err)
155 } else {
156 fmt.Println(r.URL)
157 }
158
159 }
160
161 func TestWithBaseURL_second(t *testing.T) {
162 _, err := Prepare(&http.Request{}, WithBaseURL(":"))
163 if err == nil {
164 t.Fatal("unexpected nil error")
165 }
166 }
167
168
169 func TestWithBytes(t *testing.T) {
170 input := []byte{41, 82, 109}
171
172 r, err := Prepare(&http.Request{},
173 WithBytes(&input))
174 if err != nil {
175 t.Fatalf("ERROR: %v\n", err)
176 }
177
178 b, err := ioutil.ReadAll(r.Body)
179 if err != nil {
180 t.Fatalf("ERROR: %v\n", err)
181 }
182
183 if len(b) != len(input) {
184 t.Fatalf("Expected the Body to contain %d bytes but got %d", len(input), len(b))
185 }
186
187 if !reflect.DeepEqual(b, input) {
188 t.Fatalf("Body doesn't contain the same bytes: %s (Expected %s)", b, input)
189 }
190 }
191
192 func ExampleWithCustomBaseURL() {
193 r, err := Prepare(&http.Request{},
194 WithCustomBaseURL("https://{account}.{service}.core.windows.net/",
195 map[string]interface{}{
196 "account": "myaccount",
197 "service": "blob",
198 }))
199 if err != nil {
200 fmt.Printf("ERROR: %v\n", err)
201 } else {
202 fmt.Println(r.URL)
203 }
204
205 }
206
207 func TestWithCustomBaseURL_second(t *testing.T) {
208 _, err := Prepare(&http.Request{},
209 WithCustomBaseURL(":", map[string]interface{}{}))
210 if err == nil {
211 t.Fatal("unexpected nil error")
212 }
213 }
214
215
216 func ExampleWithHeader() {
217 r, err := Prepare(&http.Request{},
218 WithBaseURL("https://microsoft.com/a/b/c/"),
219 WithHeader("x-foo", "bar"))
220 if err != nil {
221 fmt.Printf("ERROR: %v\n", err)
222 } else {
223 fmt.Printf("Header %s=%s\n", "x-foo", r.Header.Get("x-foo"))
224 }
225
226 }
227
228
229 func ExampleWithFormData() {
230 v := url.Values{}
231 v.Add("name", "Rob Pike")
232 v.Add("age", "42")
233
234 r, err := Prepare(&http.Request{},
235 WithFormData(v))
236 if err != nil {
237 fmt.Printf("ERROR: %v\n", err)
238 }
239
240 b, err := ioutil.ReadAll(r.Body)
241 if err != nil {
242 fmt.Printf("ERROR: %v\n", err)
243 } else {
244 fmt.Printf("Request Body contains %s\n", string(b))
245 }
246
247 }
248
249
250 func ExampleWithJSON() {
251 t := mocks.T{Name: "Rob Pike", Age: 42}
252
253 r, err := Prepare(&http.Request{},
254 WithJSON(&t))
255 if err != nil {
256 fmt.Printf("ERROR: %v\n", err)
257 }
258
259 b, err := ioutil.ReadAll(r.Body)
260 if err != nil {
261 fmt.Printf("ERROR: %v\n", err)
262 } else {
263 fmt.Printf("Request Body contains %s\n", string(b))
264 }
265
266 }
267
268
269 func ExampleWithXML() {
270 t := mocks.T{Name: "Rob Pike", Age: 42}
271
272 r, err := Prepare(&http.Request{},
273 WithXML(&t))
274 if err != nil {
275 fmt.Printf("ERROR: %v\n", err)
276 }
277
278 b, err := ioutil.ReadAll(r.Body)
279 if err != nil {
280 fmt.Printf("ERROR: %v\n", err)
281 } else {
282 fmt.Printf("Request Body contains %s\n", string(b))
283 }
284
285
286 }
287
288
289 func ExampleWithEscapedPathParameters() {
290 params := map[string]interface{}{
291 "param1": "a b c",
292 "param2": "d e f",
293 }
294 r, err := Prepare(&http.Request{},
295 WithBaseURL("https://microsoft.com/"),
296 WithEscapedPathParameters("/{param1}/b/{param2}/", params))
297 if err != nil {
298 fmt.Printf("ERROR: %v\n", err)
299 } else {
300 fmt.Println(r.URL)
301 }
302
303 }
304
305
306 func ExampleWithPathParameters() {
307 params := map[string]interface{}{
308 "param1": "a",
309 "param2": "c",
310 }
311 r, err := Prepare(&http.Request{},
312 WithBaseURL("https://microsoft.com/"),
313 WithPathParameters("/{param1}/b/{param2}/", params))
314 if err != nil {
315 fmt.Printf("ERROR: %v\n", err)
316 } else {
317 fmt.Println(r.URL)
318 }
319
320 }
321
322
323 func ExampleWithQueryParameters() {
324 params := map[string]interface{}{
325 "q1": []string{"value1"},
326 "q2": []string{"value2"},
327 }
328 r, err := Prepare(&http.Request{},
329 WithBaseURL("https://microsoft.com/"),
330 WithPath("/a/b/c/"),
331 WithQueryParameters(params))
332 if err != nil {
333 fmt.Printf("ERROR: %v\n", err)
334 } else {
335 fmt.Println(r.URL)
336 }
337
338 }
339
340 func TestWithCustomBaseURL(t *testing.T) {
341 r, err := Prepare(&http.Request{}, WithCustomBaseURL("https://{account}.{service}.core.windows.net/",
342 map[string]interface{}{
343 "account": "myaccount",
344 "service": "blob",
345 }))
346 if err != nil {
347 t.Fatalf("autorest: WithCustomBaseURL should not fail")
348 }
349 if r.URL.String() != "https://myaccount.blob.core.windows.net/" {
350 t.Fatalf("autorest: WithCustomBaseURL expected https://myaccount.blob.core.windows.net/, got %s", r.URL)
351 }
352 }
353
354 func TestWithCustomBaseURLwithInvalidURL(t *testing.T) {
355 _, err := Prepare(&http.Request{}, WithCustomBaseURL("hello/{account}.{service}.core.windows.net/",
356 map[string]interface{}{
357 "account": "myaccount",
358 "service": "blob",
359 }))
360 if err == nil {
361 t.Fatalf("autorest: WithCustomBaseURL should fail fo URL parse error")
362 }
363 }
364
365 func TestWithPathWithInvalidPath(t *testing.T) {
366 p := "path%2*end"
367 if _, err := Prepare(&http.Request{}, WithBaseURL("https://microsoft.com/"), WithPath(p)); err == nil {
368 t.Fatalf("autorest: WithPath should fail for invalid URL escape error for path '%v' ", p)
369 }
370
371 }
372
373 func TestWithPathParametersWithInvalidPath(t *testing.T) {
374 p := "path%2*end"
375 m := map[string]interface{}{
376 "path1": p,
377 }
378 if _, err := Prepare(&http.Request{}, WithBaseURL("https://microsoft.com/"), WithPathParameters("/{path1}/", m)); err == nil {
379 t.Fatalf("autorest: WithPath should fail for invalid URL escape for path '%v' ", p)
380 }
381
382 }
383
384 func TestCreatePreparerDoesNotModify(t *testing.T) {
385 r1 := &http.Request{}
386 p := CreatePreparer()
387 r2, err := p.Prepare(r1)
388 if err != nil {
389 t.Fatalf("autorest: CreatePreparer failed (%v)", err)
390 }
391 if !reflect.DeepEqual(r1, r2) {
392 t.Fatalf("autorest: CreatePreparer without decorators modified the request")
393 }
394 }
395
396 func TestCreatePreparerRunsDecoratorsInOrder(t *testing.T) {
397 p := CreatePreparer(WithBaseURL("https://microsoft.com/"), WithPath("1"), WithPath("2"), WithPath("3"))
398 r, err := p.Prepare(&http.Request{})
399 if err != nil {
400 t.Fatalf("autorest: CreatePreparer failed (%v)", err)
401 }
402 if r.URL.String() != "https:/1/2/3" && r.URL.Host != "microsoft.com" {
403 t.Fatalf("autorest: CreatePreparer failed to run decorators in order")
404 }
405 }
406
407 func TestWithBaseURLEncodeQueryParams(t *testing.T) {
408 p := CreatePreparer(WithBaseURL("https://contoso.com/path?$qp1=something/else&$qp2=do/this&$skipToken=US1:0637720028736481134:ad5b2d5b;AS1:-1:FFFFFFFF"))
409 r, err := p.Prepare(&http.Request{})
410 if err != nil {
411 t.Fatalf("autorest: CreatePreparer failed (%v)", err)
412 }
413 want := "https://contoso.com/path?%24qp1=something%2Felse&%24qp2=do%2Fthis&%24skipToken=US1%3A0637720028736481134%3Aad5b2d5b%3BAS1%3A-1%3AFFFFFFFF"
414 if u := r.URL.String(); u != want {
415 t.Fatalf("unexpected URL, got %s, want %s", u, want)
416 }
417 }
418
419 func TestAsContentType(t *testing.T) {
420 r, err := Prepare(mocks.NewRequest(), AsContentType("application/text"))
421 if err != nil {
422 fmt.Printf("ERROR: %v", err)
423 }
424 if r.Header.Get(headerContentType) != "application/text" {
425 t.Fatalf("autorest: AsContentType failed to add header (%s=%s)", headerContentType, r.Header.Get(headerContentType))
426 }
427 }
428
429 func TestAsFormURLEncoded(t *testing.T) {
430 r, err := Prepare(mocks.NewRequest(), AsFormURLEncoded())
431 if err != nil {
432 fmt.Printf("ERROR: %v", err)
433 }
434 if r.Header.Get(headerContentType) != mimeTypeFormPost {
435 t.Fatalf("autorest: AsFormURLEncoded failed to add header (%s=%s)", headerContentType, r.Header.Get(headerContentType))
436 }
437 }
438
439 func TestAsJSON(t *testing.T) {
440 r, err := Prepare(mocks.NewRequest(), AsJSON())
441 if err != nil {
442 fmt.Printf("ERROR: %v", err)
443 }
444 if r.Header.Get(headerContentType) != mimeTypeJSON {
445 t.Fatalf("autorest: AsJSON failed to add header (%s=%s)", headerContentType, r.Header.Get(headerContentType))
446 }
447 }
448
449 func TestWithNothing(t *testing.T) {
450 r1 := mocks.NewRequest()
451 r2, err := Prepare(r1, WithNothing())
452 if err != nil {
453 t.Fatalf("autorest: WithNothing returned an unexpected error (%v)", err)
454 }
455
456 if !reflect.DeepEqual(r1, r2) {
457 t.Fatal("azure: WithNothing modified the passed HTTP Request")
458 }
459 }
460
461 func TestWithBearerAuthorization(t *testing.T) {
462 r, err := Prepare(mocks.NewRequest(), WithBearerAuthorization("SOME-TOKEN"))
463 if err != nil {
464 fmt.Printf("ERROR: %v", err)
465 }
466 if r.Header.Get(headerAuthorization) != "Bearer SOME-TOKEN" {
467 t.Fatalf("autorest: WithBearerAuthorization failed to add header (%s=%s)", headerAuthorization, r.Header.Get(headerAuthorization))
468 }
469 }
470
471 func TestWithUserAgent(t *testing.T) {
472 ua := "User Agent Go"
473 r, err := Prepare(mocks.NewRequest(), WithUserAgent(ua))
474 if err != nil {
475 fmt.Printf("ERROR: %v", err)
476 }
477 if r.UserAgent() != ua || r.Header.Get(headerUserAgent) != ua {
478 t.Fatalf("autorest: WithUserAgent failed to add header (%s=%s)", headerUserAgent, r.Header.Get(headerUserAgent))
479 }
480 }
481
482 func TestWithMethod(t *testing.T) {
483 r, _ := Prepare(mocks.NewRequest(), WithMethod("HEAD"))
484 if r.Method != "HEAD" {
485 t.Fatal("autorest: WithMethod failed to set HTTP method header")
486 }
487 }
488
489 func TestAsDelete(t *testing.T) {
490 r, _ := Prepare(mocks.NewRequest(), AsDelete())
491 if r.Method != "DELETE" {
492 t.Fatal("autorest: AsDelete failed to set HTTP method header to DELETE")
493 }
494 }
495
496 func TestAsGet(t *testing.T) {
497 r, _ := Prepare(mocks.NewRequest(), AsGet())
498 if r.Method != "GET" {
499 t.Fatal("autorest: AsGet failed to set HTTP method header to GET")
500 }
501 }
502
503 func TestAsHead(t *testing.T) {
504 r, _ := Prepare(mocks.NewRequest(), AsHead())
505 if r.Method != "HEAD" {
506 t.Fatal("autorest: AsHead failed to set HTTP method header to HEAD")
507 }
508 }
509
510 func TestAsMerge(t *testing.T) {
511 r, _ := Prepare(mocks.NewRequest(), AsMerge())
512 if r.Method != "MERGE" {
513 t.Fatal("autorest: AsMerge failed to set HTTP method header to MERGE")
514 }
515 }
516
517 func TestAsOptions(t *testing.T) {
518 r, _ := Prepare(mocks.NewRequest(), AsOptions())
519 if r.Method != "OPTIONS" {
520 t.Fatal("autorest: AsOptions failed to set HTTP method header to OPTIONS")
521 }
522 }
523
524 func TestAsPatch(t *testing.T) {
525 r, _ := Prepare(mocks.NewRequest(), AsPatch())
526 if r.Method != "PATCH" {
527 t.Fatal("autorest: AsPatch failed to set HTTP method header to PATCH")
528 }
529 }
530
531 func TestAsPost(t *testing.T) {
532 r, _ := Prepare(mocks.NewRequest(), AsPost())
533 if r.Method != "POST" {
534 t.Fatal("autorest: AsPost failed to set HTTP method header to POST")
535 }
536 }
537
538 func TestAsPut(t *testing.T) {
539 r, _ := Prepare(mocks.NewRequest(), AsPut())
540 if r.Method != "PUT" {
541 t.Fatal("autorest: AsPut failed to set HTTP method header to PUT")
542 }
543 }
544
545 func TestPrepareWithNullRequest(t *testing.T) {
546 _, err := Prepare(nil)
547 if err == nil {
548 t.Fatal("autorest: Prepare failed to return an error when given a null http.Request")
549 }
550 }
551
552 func TestWithFormData(t *testing.T) {
553 v := url.Values{}
554 v.Add("name", "Rob Pike")
555 v.Add("age", "42")
556
557 r, err := Prepare(&http.Request{},
558 WithFormData(v))
559 if err != nil {
560 t.Fatalf("autorest: WithFormData failed with error (%v)", err)
561 }
562
563 b, err := ioutil.ReadAll(r.Body)
564 if err != nil {
565 t.Fatalf("autorest: WithFormData failed with error (%v)", err)
566 }
567
568 expected := "name=Rob+Pike&age=42"
569 if !(string(b) == "name=Rob+Pike&age=42" || string(b) == "age=42&name=Rob+Pike") {
570 t.Fatalf("autorest:WithFormData failed to return correct string got (%v), expected (%v)", string(b), expected)
571 }
572
573 if r.ContentLength != int64(len(b)) {
574 t.Fatalf("autorest:WithFormData set Content-Length to %v, expected %v", r.ContentLength, len(b))
575 }
576
577 if expected, got := r.Header.Get(http.CanonicalHeaderKey(headerContentType)), mimeTypeFormPost; expected != got {
578 t.Fatalf("autorest:WithFormData Content Type not set or set to wrong value. Expected %v and got %v", expected, got)
579 }
580 }
581
582 func TestWithMultiPartFormDataSetsContentLength(t *testing.T) {
583 v := map[string]interface{}{
584 "file": ioutil.NopCloser(strings.NewReader("Hello Gopher")),
585 "age": "42",
586 }
587
588 r, err := Prepare(&http.Request{},
589 WithMultiPartFormData(v))
590 if err != nil {
591 t.Fatalf("autorest: WithMultiPartFormData failed with error (%v)", err)
592 }
593
594 b, err := ioutil.ReadAll(r.Body)
595 if err != nil {
596 t.Fatalf("autorest: WithMultiPartFormData failed with error (%v)", err)
597 }
598
599 if r.ContentLength != int64(len(b)) {
600 t.Fatalf("autorest:WithMultiPartFormData set Content-Length to %v, expected %v", r.ContentLength, len(b))
601 }
602 }
603
604 func TestWithMultiPartFormDataWithNoFile(t *testing.T) {
605 v := map[string]interface{}{
606 "file": "no file",
607 "age": "42",
608 }
609
610 r, err := Prepare(&http.Request{},
611 WithMultiPartFormData(v))
612 if err != nil {
613 t.Fatalf("autorest: WithMultiPartFormData failed with error (%v)", err)
614 }
615
616 b, err := ioutil.ReadAll(r.Body)
617 if err != nil {
618 t.Fatalf("autorest: WithMultiPartFormData failed with error (%v)", err)
619 }
620
621 if r.ContentLength != int64(len(b)) {
622 t.Fatalf("autorest:WithMultiPartFormData set Content-Length to %v, expected %v", r.ContentLength, len(b))
623 }
624 }
625
626 func TestWithFile(t *testing.T) {
627 r, err := Prepare(&http.Request{},
628 WithFile(ioutil.NopCloser(strings.NewReader("Hello Gopher"))))
629 if err != nil {
630 t.Fatalf("autorest: WithFile failed with error (%v)", err)
631 }
632
633 b, err := ioutil.ReadAll(r.Body)
634 if err != nil {
635 t.Fatalf("autorest: WithFile failed with error (%v)", err)
636 }
637 if r.ContentLength != int64(len(b)) {
638 t.Fatalf("autorest:WithFile set Content-Length to %v, expected %v", r.ContentLength, len(b))
639 }
640 }
641
642 func TestWithBool_SetsTheBody(t *testing.T) {
643 r, err := Prepare(&http.Request{},
644 WithBool(false))
645 if err != nil {
646 t.Fatalf("autorest: WithBool failed with error (%v)", err)
647 }
648
649 s, err := ioutil.ReadAll(r.Body)
650 if err != nil {
651 t.Fatalf("autorest: WithBool failed with error (%v)", err)
652 }
653
654 if r.ContentLength != int64(len(fmt.Sprintf("%v", false))) {
655 t.Fatalf("autorest: WithBool set Content-Length to %v, expected %v", r.ContentLength, int64(len(fmt.Sprintf("%v", false))))
656 }
657
658 v, err := strconv.ParseBool(string(s))
659 if err != nil || v {
660 t.Fatalf("autorest: WithBool incorrectly encoded the boolean as %v", s)
661 }
662 }
663
664 func TestWithFloat32_SetsTheBody(t *testing.T) {
665 r, err := Prepare(&http.Request{},
666 WithFloat32(42.0))
667 if err != nil {
668 t.Fatalf("autorest: WithFloat32 failed with error (%v)", err)
669 }
670
671 s, err := ioutil.ReadAll(r.Body)
672 if err != nil {
673 t.Fatalf("autorest: WithFloat32 failed with error (%v)", err)
674 }
675
676 if r.ContentLength != int64(len(fmt.Sprintf("%v", 42.0))) {
677 t.Fatalf("autorest: WithFloat32 set Content-Length to %v, expected %v", r.ContentLength, int64(len(fmt.Sprintf("%v", 42.0))))
678 }
679
680 v, err := strconv.ParseFloat(string(s), 32)
681 if err != nil || float32(v) != float32(42.0) {
682 t.Fatalf("autorest: WithFloat32 incorrectly encoded the boolean as %v", s)
683 }
684 }
685
686 func TestWithFloat64_SetsTheBody(t *testing.T) {
687 r, err := Prepare(&http.Request{},
688 WithFloat64(42.0))
689 if err != nil {
690 t.Fatalf("autorest: WithFloat64 failed with error (%v)", err)
691 }
692
693 s, err := ioutil.ReadAll(r.Body)
694 if err != nil {
695 t.Fatalf("autorest: WithFloat64 failed with error (%v)", err)
696 }
697
698 if r.ContentLength != int64(len(fmt.Sprintf("%v", 42.0))) {
699 t.Fatalf("autorest: WithFloat64 set Content-Length to %v, expected %v", r.ContentLength, int64(len(fmt.Sprintf("%v", 42.0))))
700 }
701
702 v, err := strconv.ParseFloat(string(s), 64)
703 if err != nil || v != float64(42.0) {
704 t.Fatalf("autorest: WithFloat64 incorrectly encoded the boolean as %v", s)
705 }
706 }
707
708 func TestWithInt32_SetsTheBody(t *testing.T) {
709 r, err := Prepare(&http.Request{},
710 WithInt32(42))
711 if err != nil {
712 t.Fatalf("autorest: WithInt32 failed with error (%v)", err)
713 }
714
715 s, err := ioutil.ReadAll(r.Body)
716 if err != nil {
717 t.Fatalf("autorest: WithInt32 failed with error (%v)", err)
718 }
719
720 if r.ContentLength != int64(len(fmt.Sprintf("%v", 42))) {
721 t.Fatalf("autorest: WithInt32 set Content-Length to %v, expected %v", r.ContentLength, int64(len(fmt.Sprintf("%v", 42))))
722 }
723
724 v, err := strconv.ParseInt(string(s), 10, 32)
725 if err != nil || int32(v) != int32(42) {
726 t.Fatalf("autorest: WithInt32 incorrectly encoded the boolean as %v", s)
727 }
728 }
729
730 func TestWithInt64_SetsTheBody(t *testing.T) {
731 r, err := Prepare(&http.Request{},
732 WithInt64(42))
733 if err != nil {
734 t.Fatalf("autorest: WithInt64 failed with error (%v)", err)
735 }
736
737 s, err := ioutil.ReadAll(r.Body)
738 if err != nil {
739 t.Fatalf("autorest: WithInt64 failed with error (%v)", err)
740 }
741
742 if r.ContentLength != int64(len(fmt.Sprintf("%v", 42))) {
743 t.Fatalf("autorest: WithInt64 set Content-Length to %v, expected %v", r.ContentLength, int64(len(fmt.Sprintf("%v", 42))))
744 }
745
746 v, err := strconv.ParseInt(string(s), 10, 64)
747 if err != nil || v != int64(42) {
748 t.Fatalf("autorest: WithInt64 incorrectly encoded the boolean as %v", s)
749 }
750 }
751
752 func TestWithString_SetsTheBody(t *testing.T) {
753 r, err := Prepare(&http.Request{},
754 WithString("value"))
755 if err != nil {
756 t.Fatalf("autorest: WithString failed with error (%v)", err)
757 }
758
759 s, err := ioutil.ReadAll(r.Body)
760 if err != nil {
761 t.Fatalf("autorest: WithString failed with error (%v)", err)
762 }
763
764 if r.ContentLength != int64(len("value")) {
765 t.Fatalf("autorest: WithString set Content-Length to %v, expected %v", r.ContentLength, int64(len("value")))
766 }
767
768 if string(s) != "value" {
769 t.Fatalf("autorest: WithString incorrectly encoded the string as %v", s)
770 }
771 }
772
773 func TestWithJSONSetsContentLength(t *testing.T) {
774 r, err := Prepare(&http.Request{},
775 WithJSON(&mocks.T{Name: "Rob Pike", Age: 42}))
776 if err != nil {
777 t.Fatalf("autorest: WithJSON failed with error (%v)", err)
778 }
779
780 b, err := ioutil.ReadAll(r.Body)
781 if err != nil {
782 t.Fatalf("autorest: WithJSON failed with error (%v)", err)
783 }
784
785 if r.ContentLength != int64(len(b)) {
786 t.Fatalf("autorest:WithJSON set Content-Length to %v, expected %v", r.ContentLength, len(b))
787 }
788 }
789
790 func TestWithHeaderAllocatesHeaders(t *testing.T) {
791 r, err := Prepare(mocks.NewRequest(), WithHeader("x-foo", "bar"))
792 if err != nil {
793 t.Fatalf("autorest: WithHeader failed (%v)", err)
794 }
795 if r.Header.Get("x-foo") != "bar" {
796 t.Fatalf("autorest: WithHeader failed to add header (%s=%s)", "x-foo", r.Header.Get("x-foo"))
797 }
798 }
799
800 func TestWithPathCatchesNilURL(t *testing.T) {
801 _, err := Prepare(&http.Request{}, WithPath("a"))
802 if err == nil {
803 t.Fatalf("autorest: WithPath failed to catch a nil URL")
804 }
805 }
806
807 func TestWithEscapedPathParametersCatchesNilURL(t *testing.T) {
808 _, err := Prepare(&http.Request{}, WithEscapedPathParameters("", map[string]interface{}{"foo": "bar"}))
809 if err == nil {
810 t.Fatalf("autorest: WithEscapedPathParameters failed to catch a nil URL")
811 }
812 }
813
814 func TestWithPathParametersCatchesNilURL(t *testing.T) {
815 _, err := Prepare(&http.Request{}, WithPathParameters("", map[string]interface{}{"foo": "bar"}))
816 if err == nil {
817 t.Fatalf("autorest: WithPathParameters failed to catch a nil URL")
818 }
819 }
820
821 func TestWithQueryParametersCatchesNilURL(t *testing.T) {
822 _, err := Prepare(&http.Request{}, WithQueryParameters(map[string]interface{}{"foo": "bar"}))
823 if err == nil {
824 t.Fatalf("autorest: WithQueryParameters failed to catch a nil URL")
825 }
826 }
827
828 func TestModifyingExistingRequest(t *testing.T) {
829 r, err := Prepare(mocks.NewRequestForURL("https://bing.com"), WithPath("search"), WithQueryParameters(map[string]interface{}{"q": "golang"}))
830 if err != nil {
831 t.Fatalf("autorest: Preparing an existing request returned an error (%v)", err)
832 }
833 if r.URL.Host != "bing.com" {
834 t.Fatalf("autorest: Preparing an existing request failed when setting the host (%s)", r.URL)
835 }
836
837 if r.URL.Path != "/search" {
838 t.Fatalf("autorest: Preparing an existing request failed when setting the path (%s)", r.URL.Path)
839 }
840
841 if r.URL.RawQuery != "q=golang" {
842 t.Fatalf("autorest: Preparing an existing request failed when setting the query parameters (%s)", r.URL.RawQuery)
843 }
844 }
845
846 func TestModifyingRequestWithExistingQueryParameters(t *testing.T) {
847 r, err := Prepare(
848 mocks.NewRequestForURL("https://bing.com"),
849 WithPath("search"),
850 WithQueryParameters(map[string]interface{}{"q": "golang the best"}),
851 WithQueryParameters(map[string]interface{}{"pq": "golang+encoded"}),
852 WithQueryParameters(map[string]interface{}{"zq": []string{"one", "two"}}),
853 )
854 if err != nil {
855 t.Fatalf("autorest: Preparing an existing request returned an error (%v)", err)
856 }
857
858 if r.URL.Host != "bing.com" {
859 t.Fatalf("autorest: Preparing an existing request failed when setting the host (%s)", r.URL)
860 }
861
862 if r.URL.Path != "/search" {
863 t.Fatalf("autorest: Preparing an existing request failed when setting the path (%s)", r.URL.Path)
864 }
865
866 if r.URL.RawQuery != "pq=golang+encoded&q=golang+the+best&zq=one&zq=two" {
867 t.Fatalf("autorest: Preparing an existing request failed when setting the query parameters (%s)", r.URL.RawQuery)
868 }
869 }
870
871 func TestGetPrepareDecorators(t *testing.T) {
872 pd := GetPrepareDecorators(context.Background())
873 if l := len(pd); l != 0 {
874 t.Fatalf("expected zero length but got %d", l)
875 }
876 pd = GetPrepareDecorators(context.Background(), WithNothing(), AsFormURLEncoded())
877 if l := len(pd); l != 2 {
878 t.Fatalf("expected length of two but got %d", l)
879 }
880 }
881
882 func TestWithPrepareDecorators(t *testing.T) {
883 ctx := WithPrepareDecorators(context.Background(), []PrepareDecorator{WithUserAgent("somestring")})
884 pd := GetPrepareDecorators(ctx)
885 if l := len(pd); l != 1 {
886 t.Fatalf("expected length of one but got %d", l)
887 }
888 pd = GetPrepareDecorators(ctx, WithNothing(), WithNothing())
889 if l := len(pd); l != 1 {
890 t.Fatalf("expected length of one but got %d", l)
891 }
892 }
893
View as plain text