github.com/waldiirawan/apm-agent-go/v2@v2.2.2/internal/apmcloudutil/aws_test.go (about) 1 // Licensed to Elasticsearch B.V. under one or more contributor 2 // license agreements. See the NOTICE file distributed with 3 // this work for additional information regarding copyright 4 // ownership. Elasticsearch B.V. licenses this file to you under 5 // the Apache License, Version 2.0 (the "License"); you may 6 // not use this file except in compliance with the License. 7 // You may obtain a copy of the License at 8 // 9 // http://www.apache.org/licenses/LICENSE-2.0 10 // 11 // Unless required by applicable law or agreed to in writing, 12 // software distributed under the License is distributed on an 13 // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 14 // KIND, either express or implied. See the License for the 15 // specific language governing permissions and limitations 16 // under the License. 17 18 package apmcloudutil 19 20 import ( 21 "context" 22 "net/http" 23 "net/http/httptest" 24 "testing" 25 26 "github.com/stretchr/testify/assert" 27 28 "github.com/waldiirawan/apm-agent-go/v2/model" 29 ) 30 31 func TestAWSCloudMetadata(t *testing.T) { 32 srv, client := newAWSMetadataServer() 33 defer srv.Close() 34 35 for _, provider := range []Provider{Auto, AWS} { 36 var out model.Cloud 37 var logger testLogger 38 assert.True(t, provider.getCloudMetadata(context.Background(), client, &logger, &out)) 39 assert.Zero(t, logger) 40 assert.Equal(t, model.Cloud{ 41 Provider: "aws", 42 Region: "us-east-2", 43 AvailabilityZone: "us-east-2a", 44 Instance: &model.CloudInstance{ 45 ID: "i-0ae894a7c1c4f2a75", 46 }, 47 Machine: &model.CloudMachine{ 48 Type: "t2.medium", 49 }, 50 Account: &model.CloudAccount{ 51 ID: "946960629917", 52 }, 53 }, out) 54 } 55 } 56 57 func newAWSMetadataServer() (*httptest.Server, *http.Client) { 58 srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 59 switch r.URL.Path { 60 case "/latest/api/token": 61 w.Write([]byte("topsecret")) 62 return 63 case "/latest/dynamic/instance-identity/document": 64 token := r.Header.Get("X-Aws-Ec2-Metadata-Token") 65 if token != "topsecret" { 66 w.WriteHeader(http.StatusBadRequest) 67 w.Write([]byte("invalid token")) 68 return 69 } 70 break 71 default: 72 w.WriteHeader(http.StatusNotFound) 73 return 74 } 75 76 w.Write([]byte(`{ 77 "accountId": "946960629917", 78 "architecture": "x86_64", 79 "availabilityZone": "us-east-2a", 80 "billingProducts": null, 81 "devpayProductCodes": null, 82 "marketplaceProductCodes": null, 83 "imageId": "ami-07c1207a9d40bc3bd", 84 "instanceId": "i-0ae894a7c1c4f2a75", 85 "instanceType": "t2.medium", 86 "kernelId": null, 87 "pendingTime": "2020-06-12T17:46:09Z", 88 "privateIp": "172.31.0.212", 89 "ramdiskId": null, 90 "region": "us-east-2", 91 "version": "2017-09-30" 92 }`)) 93 })) 94 95 client := &http.Client{Transport: newTargetedRoundTripper("169.254.169.254", srv.Listener.Addr().String())} 96 return srv, client 97 }