Skip to content

Commit 8f81335

Browse files
WillatShopKeepWill Chan
authored and
Will Chan
committed
add tests to properly test interfaces and fix constant naming conventions
1 parent a3be1d7 commit 8f81335

File tree

7 files changed

+74
-68
lines changed

7 files changed

+74
-68
lines changed

auth.go

Lines changed: 24 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -12,12 +12,12 @@ import (
1212
)
1313

1414
const (
15-
ACCESS_ENV_KEY = "AWS_ACCESS_KEY"
16-
SECRET_ENV_KEY = "AWS_SECRET_KEY"
15+
AccessEnvKey = "AWS_ACCESS_KEY"
16+
SecretEnvKey = "AWS_SECRET_KEY"
1717

18-
AWS_METADATA_SERVER = "169.254.169.254"
19-
AWS_IAM_CREDS_PATH = "/latest/meta-data/iam/security-credentials"
20-
AWS_IAM_CREDS_URL = "http://" + AWS_METADATA_SERVER + AWS_IAM_CREDS_PATH
18+
AWSMetadataServer = "169.254.169.254"
19+
AWSIAMCredsPath = "/latest/meta-data/iam/security-credentials"
20+
AWSIAMCredsURL = "http://" + AWSMetadataServer + "/" + AWSIAMCredsPath
2121
)
2222

2323
// Auth interface for authentication credentials and information
@@ -31,7 +31,7 @@ type Auth interface {
3131
Sign(*Service, time.Time) []byte
3232
}
3333

34-
type auth struct {
34+
type AuthCredentials struct {
3535
// accessKey, secretKey are the standard AWS auth credentials
3636
accessKey, secretKey, token string
3737

@@ -41,22 +41,22 @@ type auth struct {
4141
expiry time.Time
4242
}
4343

44-
func NewAuth(accessKey, secretKey string) Auth {
45-
return &auth{
44+
func NewAuth(accessKey, secretKey string) *AuthCredentials {
45+
return &AuthCredentials{
4646
accessKey: accessKey,
4747
secretKey: secretKey,
4848
}
4949
}
5050

5151
// NewAuthFromEnv retrieves auth credentials from environment vars
52-
func NewAuthFromEnv() (Auth, error) {
53-
accessKey := os.Getenv(ACCESS_ENV_KEY)
54-
secretKey := os.Getenv(SECRET_ENV_KEY)
52+
func NewAuthFromEnv() (*AuthCredentials, error) {
53+
accessKey := os.Getenv(AccessEnvKey)
54+
secretKey := os.Getenv(SecretEnvKey)
5555
if accessKey == "" {
56-
return nil, fmt.Errorf("Unable to retrieve access key from %s env variable", ACCESS_ENV_KEY)
56+
return nil, fmt.Errorf("Unable to retrieve access key from %s env variable", AccessEnvKey)
5757
}
5858
if secretKey == "" {
59-
return nil, fmt.Errorf("Unable to retrieve secret key from %s env variable", SECRET_ENV_KEY)
59+
return nil, fmt.Errorf("Unable to retrieve secret key from %s env variable", SecretEnvKey)
6060
}
6161

6262
return NewAuth(accessKey, secretKey), nil
@@ -68,41 +68,41 @@ func NewAuthFromEnv() (Auth, error) {
6868
//
6969
// TODO: specify custom network (connect, read) timeouts, else this will block
7070
// for the default timeout durations.
71-
func NewAuthFromMetadata() (Auth, error) {
72-
auth := &auth{}
71+
func NewAuthFromMetadata() (*AuthCredentials, error) {
72+
auth := &AuthCredentials{}
7373
if err := auth.Renew(); err != nil {
7474
return nil, err
7575
}
7676
return auth, nil
7777
}
7878

7979
// HasExpiration returns true if the expiration time is non-zero and false otherwise
80-
func (a *auth) HasExpiration() bool {
80+
func (a *AuthCredentials) HasExpiration() bool {
8181
return !a.expiry.IsZero()
8282
}
8383

8484
// GetExpiration retrieves the current expiration time
85-
func (a *auth) GetExpiration() time.Time {
85+
func (a *AuthCredentials) GetExpiration() time.Time {
8686
return a.expiry
8787
}
8888

8989
// GetToken returns the token
90-
func (a *auth) GetToken() string {
90+
func (a *AuthCredentials) GetToken() string {
9191
return a.token
9292
}
9393

9494
// GetSecretKey returns the secret key
95-
func (a *auth) GetSecretKey() string {
95+
func (a *AuthCredentials) GetSecretKey() string {
9696
return a.secretKey
9797
}
9898

9999
// GetAccessKey returns the access key
100-
func (a *auth) GetAccessKey() string {
100+
func (a *AuthCredentials) GetAccessKey() string {
101101
return a.accessKey
102102
}
103103

104104
// Renew retrieves a new token and mutates it on an instance of the Auth struct
105-
func (a *auth) Renew() error {
105+
func (a *AuthCredentials) Renew() error {
106106
role, err := retrieveIAMRole()
107107
if err != nil {
108108
return err
@@ -127,7 +127,7 @@ func (a *auth) Renew() error {
127127
// Sign API request by
128128
// http://docs.amazonwebservices.com/general/latest/gr/signature-version-4.html
129129

130-
func (a *auth) Sign(s *Service, t time.Time) []byte {
130+
func (a *AuthCredentials) Sign(s *Service, t time.Time) []byte {
131131
h := ghmac([]byte("AWS4"+a.GetSecretKey()), []byte(t.Format(iSO8601BasicFormatShort)))
132132
h = ghmac(h, []byte(s.Region))
133133
h = ghmac(h, []byte(s.Name))
@@ -138,7 +138,7 @@ func (a *auth) Sign(s *Service, t time.Time) []byte {
138138
func retrieveAWSCredentials(role string) (map[string]string, error) {
139139
var bodybytes []byte
140140
// Retrieve the json for this role
141-
resp, err := http.Get(AWS_IAM_CREDS_URL + "/" + role)
141+
resp, err := http.Get(fmt.Sprintf("%s/%s", AWSIAMCredsURL, role))
142142
if err != nil || resp.StatusCode != http.StatusOK {
143143
return nil, err
144144
}
@@ -161,7 +161,7 @@ func retrieveAWSCredentials(role string) (map[string]string, error) {
161161
func retrieveIAMRole() (string, error) {
162162
var bodybytes []byte
163163

164-
resp, err := http.Get(AWS_IAM_CREDS_URL)
164+
resp, err := http.Get(AWSIAMCredsURL)
165165
if err != nil || resp.StatusCode != http.StatusOK {
166166
return "", err
167167
}

auth_test.go

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,13 @@ import (
55
"testing"
66
)
77

8+
func TestAuthInterfaceIsImplemented(t *testing.T) {
9+
var auth Auth = &AuthCredentials{}
10+
if auth == nil {
11+
t.Error("Invalid nil auth credentials value")
12+
}
13+
}
14+
815
func TestGetSecretKey(t *testing.T) {
916
auth := NewAuth("BAD_ACCESS_KEY", "BAD_SECRET_KEY")
1017

@@ -22,8 +29,8 @@ func TestGetAccessKey(t *testing.T) {
2229
}
2330

2431
func TestNewAuthFromEnv(t *testing.T) {
25-
os.Setenv(ACCESS_ENV_KEY, "asdf")
26-
os.Setenv(SECRET_ENV_KEY, "asdf")
32+
os.Setenv(AccessEnvKey, "asdf")
33+
os.Setenv(SecretEnvKey, "asdf")
2734

2835
auth, _ := NewAuthFromEnv()
2936

@@ -35,6 +42,6 @@ func TestNewAuthFromEnv(t *testing.T) {
3542
t.Error("Expected SecretKey to be inferred as \"asdf\"")
3643
}
3744

38-
os.Setenv(ACCESS_ENV_KEY, "") // Use Unsetenv with go1.4
39-
os.Setenv(SECRET_ENV_KEY, "") // Use Unsetenv with go1.4
45+
os.Setenv(AccessEnvKey, "") // Use Unsetenv with go1.4
46+
os.Setenv(SecretEnvKey, "") // Use Unsetenv with go1.4
4047
}

client.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ import (
55
"time"
66
)
77

8-
const AWS_SECURITY_TOKEN_HEADER = "X-Amz-Security-Token"
8+
const AWSSecurityTokenHeader = "X-Amz-Security-Token"
99

1010
// Client is like http.Client, but signs all requests using Auth.
1111
type Client struct {
@@ -42,7 +42,7 @@ func (c *Client) Do(req *http.Request) (*http.Response, error) {
4242
}
4343

4444
if c.auth.GetToken() != "" {
45-
req.Header.Add(AWS_SECURITY_TOKEN_HEADER, c.auth.GetToken())
45+
req.Header.Add(AWSSecurityTokenHeader, c.auth.GetToken())
4646
}
4747

4848
return c.client.Do(req)

examples/example.go

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,8 @@ import (
55
"os"
66
"time"
77

8-
kinesis "github.com/sendgridlabs/go-kinesis"
8+
// kinesis "github.com/sendgridlabs/go-kinesis"
9+
kinesis "github.com/wchan2/go-kinesis"
910
)
1011

1112
func getRecords(ksis kinesis.KinesisClient, streamName, ShardId string) {

kinesis-cli/kinesis-cli.go

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,8 @@ import (
2222
"strconv"
2323
"strings"
2424

25-
"github.com/sendgridlabs/go-kinesis"
25+
// "github.com/sendgridlabs/go-kinesis"
26+
"github.com/wchan2/go-kinesis"
2627
)
2728

2829
const HELP = `Usage: ./kinesis-cli <command> [<arg>, ...]
@@ -117,14 +118,14 @@ func main() {
117118
if len(os.Args) < 2 {
118119
die(true, "Error: no command specified.")
119120
}
120-
if os.Getenv(kinesis.ACCESS_ENV_KEY) == "" ||
121-
os.Getenv(kinesis.SECRET_ENV_KEY) == "" {
121+
if os.Getenv(kinesis.AccessEnvKey) == "" ||
122+
os.Getenv(kinesis.SecretEnvKey) == "" {
122123
fmt.Printf("WARNING: %s and/or %s environment variables not set. Will "+
123124
"attempt to fetch credentials from metadata server.\n",
124-
kinesis.ACCESS_ENV_KEY, kinesis.SECRET_ENV_KEY)
125+
kinesis.AccessEnvKey, kinesis.SecretEnvKey)
125126
}
126-
if os.Getenv(kinesis.REGION_ENV_NAME) == "" {
127-
fmt.Printf("WARNING: %s not set.\n", kinesis.REGION_ENV_NAME)
127+
if os.Getenv(kinesis.RegionEnvName) == "" {
128+
fmt.Printf("WARNING: %s not set.\n", kinesis.RegionEnvName)
128129
}
129130
switch os.Args[1] {
130131
case "create":

kinesis.go

Lines changed: 22 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -12,8 +12,8 @@ import (
1212
)
1313

1414
const (
15-
ACTION_KEY = "Action"
16-
REGION_ENV_NAME = "AWS_REGION_NAME"
15+
ActionKey = "Action"
16+
RegionEnvName = "AWS_REGION_NAME"
1717

1818
// Regions
1919
USEast1 = "us-east-1"
@@ -29,11 +29,11 @@ const (
2929

3030
// NewRegionFromEnv creates a region from the an expected environment variable
3131
func NewRegionFromEnv() string {
32-
return os.Getenv(REGION_ENV_NAME)
32+
return os.Getenv(RegionEnvName)
3333
}
3434

3535
// Structure for kinesis client
36-
type kinesis struct {
36+
type Kinesis struct {
3737
client *Client
3838
endpoint string
3939
region string
@@ -56,31 +56,31 @@ type KinesisClient interface {
5656

5757
// New returns an initialized AWS Kinesis client using the canonical live “production” endpoint
5858
// for AWS Kinesis, i.e. https://kinesis.{region}.amazonaws.com
59-
func New(auth Auth, region string) KinesisClient {
59+
func New(auth Auth, region string) *Kinesis {
6060
endpoint := fmt.Sprintf(kinesisURL, region)
6161
return NewWithEndpoint(auth, region, endpoint)
6262
}
6363

6464
// NewWithClient returns an initialized AWS Kinesis client using the canonical live “production” endpoint
6565
// for AWS Kinesis, i.e. https://kinesis.{region}.amazonaws.com but with the ability to create a custom client
6666
// with specific configurations like a timeout
67-
func NewWithClient(auth Auth, region string, client *Client) KinesisClient {
67+
func NewWithClient(region string, client *Client) *Kinesis {
6868
endpoint := fmt.Sprintf(kinesisURL, region)
69-
return &kinesis{client: client, version: "20131202", region: region, endpoint: endpoint}
69+
return &Kinesis{client: client, version: "20131202", region: region, endpoint: endpoint}
7070
}
7171

7272
// NewWithEndpoint returns an initialized AWS Kinesis client using the specified endpoint.
7373
// This is generally useful for testing, so a local Kinesis server can be used.
74-
func NewWithEndpoint(auth Auth, region string, endpoint string) KinesisClient {
74+
func NewWithEndpoint(auth Auth, region string, endpoint string) *Kinesis {
7575
// TODO: remove trailing slash on endpoint if there is one? does it matter?
7676
// TODO: validate endpoint somehow?
77-
return &kinesis{client: NewClient(auth), version: "20131202", region: region, endpoint: endpoint}
77+
return &Kinesis{client: NewClient(auth), version: "20131202", region: region, endpoint: endpoint}
7878
}
7979

8080
// Create params object for request
8181
func makeParams(action string) map[string]string {
8282
params := make(map[string]string)
83-
params[ACTION_KEY] = action
83+
params[ActionKey] = action
8484
return params
8585
}
8686

@@ -152,7 +152,7 @@ func buildError(r *http.Response) error {
152152
}
153153

154154
// Query by AWS API
155-
func (kinesis *kinesis) query(params map[string]string, data interface{}, resp interface{}) error {
155+
func (kinesis *Kinesis) query(params map[string]string, data interface{}, resp interface{}) error {
156156
jsonData, err := json.Marshal(data)
157157
if err != nil {
158158
return err
@@ -171,7 +171,7 @@ func (kinesis *kinesis) query(params map[string]string, data interface{}, resp i
171171

172172
// headers
173173
request.Header.Set("Content-Type", "application/x-amz-json-1.1")
174-
request.Header.Set("X-Amz-Target", fmt.Sprintf("Kinesis_%s.%s", kinesis.version, params[ACTION_KEY]))
174+
request.Header.Set("X-Amz-Target", fmt.Sprintf("Kinesis_%s.%s", kinesis.version, params[ActionKey]))
175175
request.Header.Set("User-Agent", "Golang Kinesis")
176176

177177
// response
@@ -195,7 +195,7 @@ func (kinesis *kinesis) query(params map[string]string, data interface{}, resp i
195195
// CreateStream adds a new Amazon Kinesis stream to your AWS account
196196
// StreamName is a name of stream, ShardCount is number of shards
197197
// more info http://docs.aws.amazon.com/kinesis/latest/APIReference/API_CreateStream.html
198-
func (kinesis *kinesis) CreateStream(StreamName string, ShardCount int) error {
198+
func (kinesis *Kinesis) CreateStream(StreamName string, ShardCount int) error {
199199
params := makeParams("CreateStream")
200200
requestParams := struct {
201201
StreamName string
@@ -214,7 +214,7 @@ func (kinesis *kinesis) CreateStream(StreamName string, ShardCount int) error {
214214
// DeleteStream deletes a stream and all of its shards and data from your AWS account
215215
// StreamName is a name of stream
216216
// more info http://docs.aws.amazon.com/kinesis/latest/APIReference/API_DeleteStream.html
217-
func (kinesis *kinesis) DeleteStream(StreamName string) error {
217+
func (kinesis *Kinesis) DeleteStream(StreamName string) error {
218218
params := makeParams("DeleteStream")
219219
requestParams := struct {
220220
StreamName string
@@ -230,7 +230,7 @@ func (kinesis *kinesis) DeleteStream(StreamName string) error {
230230

231231
// MergeShards merges two adjacent shards in a stream and combines them into a single shard to reduce the stream's capacity to ingest and transport data
232232
// more info http://docs.aws.amazon.com/kinesis/latest/APIReference/API_MergeShards.html
233-
func (kinesis *kinesis) MergeShards(args *RequestArgs) error {
233+
func (kinesis *Kinesis) MergeShards(args *RequestArgs) error {
234234
params := makeParams("MergeShards")
235235
err := kinesis.query(params, args.params, nil)
236236
if err != nil {
@@ -241,7 +241,7 @@ func (kinesis *kinesis) MergeShards(args *RequestArgs) error {
241241

242242
// SplitShard splits a shard into two new shards in the stream, to increase the stream's capacity to ingest and transport data
243243
// more info http://docs.aws.amazon.com/kinesis/latest/APIReference/API_SplitShard.html
244-
func (kinesis *kinesis) SplitShard(args *RequestArgs) error {
244+
func (kinesis *Kinesis) SplitShard(args *RequestArgs) error {
245245
params := makeParams("SplitShard")
246246
err := kinesis.query(params, args.params, nil)
247247
if err != nil {
@@ -258,7 +258,7 @@ type ListStreamsResp struct {
258258

259259
// ListStreams returns an array of the names of all the streams that are associated with the AWS account making the ListStreams request
260260
// more info http://docs.aws.amazon.com/kinesis/latest/APIReference/API_ListStreams.html
261-
func (kinesis *kinesis) ListStreams(args *RequestArgs) (resp *ListStreamsResp, err error) {
261+
func (kinesis *Kinesis) ListStreams(args *RequestArgs) (resp *ListStreamsResp, err error) {
262262
params := makeParams("ListStreams")
263263
resp = &ListStreamsResp{}
264264
err = kinesis.query(params, args.params, resp)
@@ -300,7 +300,7 @@ type DescribeStreamResp struct {
300300
// the shard spans, and the IDs of any earlier shards that played in a role in a MergeShards or
301301
// SplitShard operation that created the shard
302302
// more info http://docs.aws.amazon.com/kinesis/latest/APIReference/API_DescribeStream.html
303-
func (kinesis *kinesis) DescribeStream(args *RequestArgs) (resp *DescribeStreamResp, err error) {
303+
func (kinesis *Kinesis) DescribeStream(args *RequestArgs) (resp *DescribeStreamResp, err error) {
304304
params := makeParams("DescribeStream")
305305
resp = &DescribeStreamResp{}
306306
err = kinesis.query(params, args.params, resp)
@@ -317,7 +317,7 @@ type GetShardIteratorResp struct {
317317

318318
// GetShardIterator returns a shard iterator
319319
// more info http://docs.aws.amazon.com/kinesis/latest/APIReference/API_GetShardIterator.html
320-
func (kinesis *kinesis) GetShardIterator(args *RequestArgs) (resp *GetShardIteratorResp, err error) {
320+
func (kinesis *Kinesis) GetShardIterator(args *RequestArgs) (resp *GetShardIteratorResp, err error) {
321321
params := makeParams("GetShardIterator")
322322
resp = &GetShardIteratorResp{}
323323
err = kinesis.query(params, args.params, resp)
@@ -346,7 +346,7 @@ type GetRecordsResp struct {
346346

347347
// GetRecords returns one or more data records from a shard
348348
// more info http://docs.aws.amazon.com/kinesis/latest/APIReference/API_GetRecords.html
349-
func (kinesis *kinesis) GetRecords(args *RequestArgs) (resp *GetRecordsResp, err error) {
349+
func (kinesis *Kinesis) GetRecords(args *RequestArgs) (resp *GetRecordsResp, err error) {
350350
params := makeParams("GetRecords")
351351
resp = &GetRecordsResp{}
352352
err = kinesis.query(params, args.params, resp)
@@ -365,7 +365,7 @@ type PutRecordResp struct {
365365
// PutRecord puts a data record into an Amazon Kinesis stream from a producer.
366366
// args must contain a single record added with AddRecord.
367367
// More info: http://docs.aws.amazon.com/kinesis/latest/APIReference/API_PutRecord.html
368-
func (kinesis *kinesis) PutRecord(args *RequestArgs) (resp *PutRecordResp, err error) {
368+
func (kinesis *Kinesis) PutRecord(args *RequestArgs) (resp *PutRecordResp, err error) {
369369
params := makeParams("PutRecord")
370370

371371
if _, ok := args.params["Data"]; !ok && len(args.Records) == 0 {
@@ -391,7 +391,7 @@ func (kinesis *kinesis) PutRecord(args *RequestArgs) (resp *PutRecordResp, err e
391391

392392
// PutRecords puts multiple data records into an Amazon Kinesis stream from a producer
393393
// more info http://docs.aws.amazon.com/kinesis/latest/APIReference/API_PutRecords.html
394-
func (kinesis *kinesis) PutRecords(args *RequestArgs) (resp *PutRecordsResp, err error) {
394+
func (kinesis *Kinesis) PutRecords(args *RequestArgs) (resp *PutRecordsResp, err error) {
395395
params := makeParams("PutRecords")
396396
resp = &PutRecordsResp{}
397397
args.Add("Records", args.Records)

0 commit comments

Comments
 (0)