1 package imds
2
3 import (
4 "context"
5 "net/http/httptest"
6 "strings"
7 "testing"
8 "time"
9 )
10
11 const instanceIdentityDocument = `{
12 "devpayProductCodes" : ["abc","123"],
13 "marketplaceProductCodes" : [ "1a2bc3" ],
14 "availabilityZone" : "us-east-1d",
15 "privateIp" : "10.158.112.84",
16 "version" : "2010-08-31",
17 "region" : "us-east-1",
18 "instanceId" : "i-1234567890abcdef0",
19 "billingProducts" : ["123"],
20 "instanceType" : "t1.micro",
21 "accountId" : "123456789012",
22 "pendingTime" : "2015-11-19T16:32:11Z",
23 "imageId" : "ami-5fb8c835",
24 "kernelId" : "aki-919dcaf8",
25 "ramdiskId" : "abc123",
26 "architecture" : "x86_64"
27 }`
28
29 func TestGetInstanceIdentityDocument(t *testing.T) {
30
31 cases := map[string]struct {
32 Body []byte
33 ExpectResult InstanceIdentityDocument
34 ExpectTrace []string
35 ExpectErr string
36 }{
37 "success": {
38 Body: []byte(instanceIdentityDocument),
39 ExpectResult: InstanceIdentityDocument{
40 DevpayProductCodes: []string{"abc", "123"},
41 MarketplaceProductCodes: []string{"1a2bc3"},
42 AvailabilityZone: "us-east-1d",
43 PrivateIP: "10.158.112.84",
44 Version: "2010-08-31",
45 Region: "us-east-1",
46 InstanceID: "i-1234567890abcdef0",
47 BillingProducts: []string{"123"},
48 InstanceType: "t1.micro",
49 AccountID: "123456789012",
50 PendingTime: time.Date(2015, 11, 19, 16, 32, 11, 0, time.UTC),
51 ImageID: "ami-5fb8c835",
52 KernelID: "aki-919dcaf8",
53 RamdiskID: "abc123",
54 Architecture: "x86_64",
55 },
56 ExpectTrace: []string{
57 getTokenPath,
58 getInstanceIdentityDocumentPath,
59 },
60 },
61 }
62
63 ctx := context.Background()
64
65 for name, c := range cases {
66 t.Run(name, func(t *testing.T) {
67 trace := newRequestTrace()
68 server := httptest.NewServer(trace.WrapHandler(
69 newTestServeMux(t,
70 newSecureAPIHandler(t,
71 []string{"tokenA"},
72 5*time.Minute,
73 &successAPIResponseHandler{t: t,
74 path: getInstanceIdentityDocumentPath,
75 method: "GET",
76 body: append([]byte{}, c.Body...),
77 },
78 ))))
79 defer server.Close()
80
81
82 client := New(Options{
83 Endpoint: server.URL,
84 })
85
86 resp, err := client.GetInstanceIdentityDocument(ctx, nil)
87 if len(c.ExpectErr) != 0 {
88 if err == nil {
89 t.Fatalf("expect error, got none")
90 }
91 if e, a := c.ExpectErr, err.Error(); !strings.Contains(a, e) {
92 t.Fatalf("expect error to contain %v, got %v", e, a)
93 }
94 return
95 }
96 if err != nil {
97 t.Fatalf("expect no error, got %v", err)
98 }
99
100 if resp == nil {
101 t.Fatalf("expect resp, got none")
102 }
103
104 if diff := cmpDiff(c.ExpectResult, resp.InstanceIdentityDocument); len(diff) != 0 {
105 t.Errorf("expect result to match\n%s", diff)
106 }
107
108 if diff := cmpDiff(c.ExpectTrace, trace.requests); len(diff) != 0 {
109 t.Errorf("expect trace to match\n%s", diff)
110 }
111 })
112 }
113 }
114
View as plain text