func (s *V4SignerSuite) TestCases(c *gocheck.C) { signer := aws.NewV4Signer(s.auth, "host", s.region) for _, testCase := range s.cases { req, err := http.NewRequest(testCase.request.method, "http://"+testCase.request.host+testCase.request.url, strings.NewReader(testCase.request.body)) c.Assert(err, gocheck.IsNil, gocheck.Commentf("Testcase: %s", testCase.label)) for _, v := range testCase.request.headers { h := strings.SplitN(v, ":", 2) req.Header.Add(h[0], h[1]) } req.Header.Set("host", req.Host) t := signer.RequestTime(req) canonicalRequest := signer.CanonicalRequest(req) c.Check(canonicalRequest, gocheck.Equals, testCase.canonicalRequest, gocheck.Commentf("Testcase: %s", testCase.label)) stringToSign := signer.StringToSign(t, canonicalRequest) c.Check(stringToSign, gocheck.Equals, testCase.stringToSign, gocheck.Commentf("Testcase: %s", testCase.label)) signature := signer.Signature(t, stringToSign) c.Check(signature, gocheck.Equals, testCase.signature, gocheck.Commentf("Testcase: %s", testCase.label)) authorization := signer.Authorization(req.Header, t, signature) c.Check(authorization, gocheck.Equals, testCase.authorization, gocheck.Commentf("Testcase: %s", testCase.label)) signer.Sign(req) c.Check(req.Header.Get("Authorization"), gocheck.Equals, testCase.authorization, gocheck.Commentf("Testcase: %s", testCase.label)) } }
func (s *ClientTests) TestConfigureHealthCheck(c *gocheck.C) { createLBReq := elb.CreateLoadBalancer{ Name: "testlb", AvailabilityZones: []string{"us-east-1a"}, Listeners: []elb.Listener{ { InstancePort: 80, InstanceProtocol: "http", LoadBalancerPort: 80, Protocol: "http", }, }, } _, err := s.elb.CreateLoadBalancer(&createLBReq) c.Assert(err, gocheck.IsNil) defer func() { _, err := s.elb.DeleteLoadBalancer(createLBReq.Name) c.Check(err, gocheck.IsNil) }() hc := elb.HealthCheck{ HealthyThreshold: 10, Interval: 30, Target: "HTTP:80/", Timeout: 5, UnhealthyThreshold: 2, } resp, err := s.elb.ConfigureHealthCheck(createLBReq.Name, &hc) c.Assert(err, gocheck.IsNil) c.Assert(resp.HealthCheck.HealthyThreshold, gocheck.Equals, 10) c.Assert(resp.HealthCheck.Interval, gocheck.Equals, 30) c.Assert(resp.HealthCheck.Target, gocheck.Equals, "HTTP:80/") c.Assert(resp.HealthCheck.Timeout, gocheck.Equals, 5) c.Assert(resp.HealthCheck.UnhealthyThreshold, gocheck.Equals, 2) }
func (s *ClientTests) TestConfigureHealthCheckBadRequest(c *gocheck.C) { createLBReq := elb.CreateLoadBalancer{ Name: "testlb", AvailabilityZones: []string{"us-east-1a"}, Listeners: []elb.Listener{ { InstancePort: 80, InstanceProtocol: "http", LoadBalancerPort: 80, Protocol: "http", }, }, } _, err := s.elb.CreateLoadBalancer(&createLBReq) c.Assert(err, gocheck.IsNil) defer func() { _, err := s.elb.DeleteLoadBalancer(createLBReq.Name) c.Check(err, gocheck.IsNil) }() hc := elb.HealthCheck{ HealthyThreshold: 10, Interval: 30, Target: "HTTP:80", Timeout: 5, UnhealthyThreshold: 2, } resp, err := s.elb.ConfigureHealthCheck(createLBReq.Name, &hc) c.Assert(resp, gocheck.IsNil) c.Assert(err, gocheck.NotNil) expected := "HealthCheck HTTP Target must specify a port followed by a path that begins with a slash. e.g. HTTP:80/ping/this/path (ValidationError)" c.Assert(err.Error(), gocheck.Equals, expected) }
// Communicate with all endpoints to see if they are alive. func (s *ClientTests) TestRegions(c *gocheck.C) { errs := make(chan error, len(aws.Regions)) for _, region := range aws.Regions { go func(r aws.Region) { s := s3.New(s.s3.Auth, r) b := s.Bucket("goamz-" + s.Auth.AccessKey) _, err := b.Get("non-existent") errs <- err }(region) } for _ = range aws.Regions { err := <-errs if err != nil { s3_err, ok := err.(*s3.Error) if ok { c.Check(s3_err.Code, gocheck.Matches, "NoSuchBucket") } else if _, ok = err.(*net.DNSError); ok { // Okay as well. } else { c.Errorf("Non-S3 error: %s", err) } } else { c.Errorf("Test should have errored but it seems to have succeeded") } } }
// Communicate with all EC2 endpoints to see if they are alive. func (s *ClientTests) TestRegions(c *gocheck.C) { name := sessionName("goamz-region-test") perms := []ec2.IPPerm{{ Protocol: "tcp", FromPort: 80, ToPort: 80, SourceIPs: []string{"127.0.0.1/32"}, }} errs := make(chan error, len(allRegions)) for _, region := range allRegions { go func(r aws.Region) { e := ec2.NewWithClient(s.ec2.Auth, r, testutil.DefaultClient) _, err := e.AuthorizeSecurityGroup(ec2.SecurityGroup{Name: name}, perms) errs <- err }(region) } for _ = range allRegions { err := <-errs if err != nil { ec2_err, ok := err.(*ec2.Error) if ok { c.Check(ec2_err.Code, gocheck.Matches, "InvalidGroup.NotFound") } else { c.Errorf("Non-EC2 error: %s", err) } } else { c.Errorf("Test should have errored but it seems to have succeeded") } } }
func (s *ClientTests) TestBasicFunctionality(c *gocheck.C) { b := testBucket(s.s3) err := b.PutBucket(s3.PublicRead) c.Assert(err, gocheck.IsNil) err = b.Put("name", []byte("yo!"), "text/plain", s3.PublicRead, s3.Options{}) c.Assert(err, gocheck.IsNil) defer b.Del("name") data, err := b.Get("name") c.Assert(err, gocheck.IsNil) c.Assert(string(data), gocheck.Equals, "yo!") data, err = get(b.URL("name")) c.Assert(err, gocheck.IsNil) c.Assert(string(data), gocheck.Equals, "yo!") buf := bytes.NewBufferString("hey!") err = b.PutReader("name2", buf, int64(buf.Len()), "text/plain", s3.Private, s3.Options{}) c.Assert(err, gocheck.IsNil) defer b.Del("name2") rc, err := b.GetReader("name2") c.Assert(err, gocheck.IsNil) data, err = ioutil.ReadAll(rc) c.Check(err, gocheck.IsNil) c.Check(string(data), gocheck.Equals, "hey!") rc.Close() data, err = get(b.SignedURL("name2", time.Now().Add(time.Hour))) c.Assert(err, gocheck.IsNil) c.Assert(string(data), gocheck.Equals, "hey!") if !s.authIsBroken { data, err = get(b.SignedURL("name2", time.Now().Add(-time.Hour))) c.Assert(err, gocheck.IsNil) c.Assert(string(data), gocheck.Matches, "(?s).*AccessDenied.*") } err = b.DelBucket() c.Assert(err, gocheck.NotNil) s3err, ok := err.(*s3.Error) c.Assert(ok, gocheck.Equals, true) c.Assert(s3err.Code, gocheck.Equals, "BucketNotEmpty") c.Assert(s3err.BucketName, gocheck.Equals, b.Name) c.Assert(s3err.Message, gocheck.Equals, "The bucket you tried to delete is not empty") err = b.Del("name") c.Assert(err, gocheck.IsNil) err = b.Del("name2") c.Assert(err, gocheck.IsNil) err = b.DelBucket() c.Assert(err, gocheck.IsNil) }
func (s *MarshallerSuite) TestMarshalEmptySets(c *gocheck.C) { testObj := testObjectWithEmptySets() attrs, err := dynamodb.MarshalAttributes(testObj) if err != nil { c.Errorf("Error from dynamodb.MarshalAttributes: %#v", err) } expected := testAttrsWithNilSets() c.Check(attrs, gocheck.DeepEquals, expected) }
func terminateInstances(c *gocheck.C, e *ec2.EC2, insts []*ec2.Instance) { var ids []string for _, inst := range insts { if inst != nil { ids = append(ids, inst.InstanceId) } } _, err := e.TerminateInstances(ids) c.Check(err, gocheck.IsNil, gocheck.Commentf("%d INSTANCES LEFT RUNNING!!!", len(ids))) }
func (s *QueryBuilderSuite) TestEmptyQuery(c *gocheck.C) { q := dynamodb.NewEmptyQuery() queryString := q.String() expectedString := "{}" c.Check(queryString, gocheck.Equals, expectedString) if expectedString != queryString { c.Fatalf("Unexpected Query String : %s\n", queryString) } }
func (s *QueryBuilderSuite) TestGetItemQuery(c *gocheck.C) { primary := dynamodb.NewStringAttribute("domain", "") key := dynamodb.PrimaryKey{primary, nil} table := s.server.NewTable("sites", key) q := dynamodb.NewQuery(table) q.AddKey(table, &dynamodb.Key{HashKey: "test"}) { queryJson, err := simplejson.NewJson([]byte(q.String())) if err != nil { c.Fatal(err) } expectedJson, err := simplejson.NewJson([]byte(` { "Key": { "domain": { "S": "test" } }, "TableName": "sites" } `)) if err != nil { c.Fatal(err) } c.Check(queryJson, gocheck.DeepEquals, expectedJson) } // Use ConsistentRead { q.ConsistentRead(true) queryJson, err := simplejson.NewJson([]byte(q.String())) if err != nil { c.Fatal(err) } expectedJson, err := simplejson.NewJson([]byte(` { "ConsistentRead": "true", "Key": { "domain": { "S": "test" } }, "TableName": "sites" } `)) if err != nil { c.Fatal(err) } c.Check(queryJson, gocheck.DeepEquals, expectedJson) } }
func (s *ItemSuite) TestUpdateItemWithSet(c *gocheck.C) { attrs := []dynamodb.Attribute{ *dynamodb.NewStringSetAttribute("list", []string{"A", "B"}), } var rk string if s.WithRange { rk = "1" } if ok, err := s.table.PutItem("NewHashKeyVal", rk, attrs); !ok { c.Error(err) } // UpdateItem with Add attrs = []dynamodb.Attribute{ *dynamodb.NewStringSetAttribute("list", []string{"C"}), } pk := &dynamodb.Key{HashKey: "NewHashKeyVal", RangeKey: rk} if ok, err := s.table.AddAttributes(pk, attrs); !ok { c.Error(err) } // Get to verify Add operation if item, err := s.table.GetItem(pk); err != nil { c.Error(err) } else { if val, ok := item["list"]; ok { c.Check(val, gocheck.DeepEquals, dynamodb.NewStringSetAttribute("list", []string{"A", "B", "C"})) } else { c.Error("Expect count to be found") } } // UpdateItem with Delete attrs = []dynamodb.Attribute{ *dynamodb.NewStringSetAttribute("list", []string{"A"}), } if ok, err := s.table.DeleteAttributes(pk, attrs); !ok { c.Error(err) } // Get to verify Delete operation if item, err := s.table.GetItem(pk); err != nil { c.Error(err) } else { if val, ok := item["list"]; ok { c.Check(val, gocheck.DeepEquals, dynamodb.NewStringSetAttribute("list", []string{"B", "C"})) } else { c.Error("Expect list to be remained") } } }
func (s *ClientTests) TestDescribeLoadBalancers(c *gocheck.C) { createLBReq := elb.CreateLoadBalancer{ Name: "testlb", AvailabilityZones: []string{"us-east-1a"}, Listeners: []elb.Listener{ { InstancePort: 80, InstanceProtocol: "http", LoadBalancerPort: 80, Protocol: "http", }, }, } _, err := s.elb.CreateLoadBalancer(&createLBReq) c.Assert(err, gocheck.IsNil) defer func() { _, err := s.elb.DeleteLoadBalancer(createLBReq.Name) c.Check(err, gocheck.IsNil) }() resp, err := s.elb.DescribeLoadBalancers() c.Assert(err, gocheck.IsNil) c.Assert(len(resp.LoadBalancerDescriptions) > 0, gocheck.Equals, true) c.Assert(resp.LoadBalancerDescriptions[0].AvailabilityZones, gocheck.DeepEquals, []string{"us-east-1a"}) c.Assert(resp.LoadBalancerDescriptions[0].LoadBalancerName, gocheck.Equals, "testlb") c.Assert(resp.LoadBalancerDescriptions[0].Scheme, gocheck.Equals, "internet-facing") hc := elb.HealthCheck{ HealthyThreshold: 10, Interval: 30, Target: "TCP:80", Timeout: 5, UnhealthyThreshold: 2, } c.Assert(resp.LoadBalancerDescriptions[0].HealthCheck, gocheck.DeepEquals, hc) ld := []elb.ListenerDescription{ { Listener: elb.Listener{ Protocol: "HTTP", LoadBalancerPort: 80, InstanceProtocol: "HTTP", InstancePort: 80, }, }, } c.Assert(resp.LoadBalancerDescriptions[0].ListenerDescriptions, gocheck.DeepEquals, ld) ssg := elb.SourceSecurityGroup{ GroupName: "amazon-elb-sg", OwnerAlias: "amazon-elb", } c.Assert(resp.LoadBalancerDescriptions[0].SourceSecurityGroup, gocheck.DeepEquals, ssg) }
func (s *ClientTests) TestBucketList(c *gocheck.C) { b := testBucket(s.s3) err := b.PutBucket(s3.Private) c.Assert(err, gocheck.IsNil) objData := make(map[string][]byte) for i, path := range objectNames { data := []byte(strings.Repeat("a", i)) err := b.Put(path, data, "text/plain", s3.Private, s3.Options{}) c.Assert(err, gocheck.IsNil) defer b.Del(path) objData[path] = data } for i, t := range listTests { c.Logf("test %d", i) resp, err := b.List(t.Prefix, t.Delimiter, t.Marker, t.MaxKeys) c.Assert(err, gocheck.IsNil) c.Check(resp.Name, gocheck.Equals, b.Name) c.Check(resp.Delimiter, gocheck.Equals, t.Delimiter) c.Check(resp.IsTruncated, gocheck.Equals, t.IsTruncated) c.Check(resp.CommonPrefixes, gocheck.DeepEquals, t.CommonPrefixes) checkContents(c, resp.Contents, objData, t.Contents) } }
// Cost: 0.02 USD func (s *ClientTests) TestCreateRegisterAndDeregisterInstanceWithLoadBalancer(c *gocheck.C) { createLBReq, instId := s.createInstanceAndLB(c) defer func() { _, err := s.elb.DeleteLoadBalancer(createLBReq.Name) c.Check(err, gocheck.IsNil) _, err = s.ec2.TerminateInstances([]string{instId}) c.Check(err, gocheck.IsNil) }() resp, err := s.elb.RegisterInstancesWithLoadBalancer([]string{instId}, createLBReq.Name) c.Assert(err, gocheck.IsNil) c.Assert(resp.InstanceIds, gocheck.DeepEquals, []string{instId}) resp2, err := s.elb.DeregisterInstancesFromLoadBalancer([]string{instId}, createLBReq.Name) c.Assert(err, gocheck.IsNil) c.Assert(resp2, gocheck.Not(gocheck.Equals), "") }
func (s *MarshallerSuite) TestUnmarshalEmptySets(c *gocheck.C) { testObj := &TestStruct{} attrMap := map[string]*dynamodb.Attribute{} attrs := testAttrsWithNilSets() for i, _ := range attrs { attrMap[attrs[i].Name] = &attrs[i] } err := dynamodb.UnmarshalAttributes(&attrMap, testObj) if err != nil { c.Fatalf("Error from dynamodb.UnmarshalAttributes: %#v (Built: %#v)", err, testObj) } expected := testObjectWithNilSets() c.Check(testObj, gocheck.DeepEquals, expected) }
func (s *QueryBuilderSuite) TestAddKeyConditions(c *gocheck.C) { primary := dynamodb.NewStringAttribute("domain", "") key := dynamodb.PrimaryKey{primary, nil} table := s.server.NewTable("sites", key) q := dynamodb.NewQuery(table) acs := []dynamodb.AttributeComparison{ *dynamodb.NewStringAttributeComparison("domain", "EQ", "example.com"), *dynamodb.NewStringAttributeComparison("path", "EQ", "/"), } q.AddKeyConditions(acs) queryJson, err := simplejson.NewJson([]byte(q.String())) if err != nil { c.Fatal(err) } expectedJson, err := simplejson.NewJson([]byte(` { "KeyConditions": { "domain": { "AttributeValueList": [ { "S": "example.com" } ], "ComparisonOperator": "EQ" }, "path": { "AttributeValueList": [ { "S": "/" } ], "ComparisonOperator": "EQ" } }, "TableName": "sites" } `)) if err != nil { c.Fatal(err) } c.Check(queryJson, gocheck.DeepEquals, expectedJson) }
func (s *QueryBuilderSuite) TestAddExpectedQuery(c *gocheck.C) { primary := dynamodb.NewStringAttribute("domain", "") key := dynamodb.PrimaryKey{primary, nil} table := s.server.NewTable("sites", key) q := dynamodb.NewQuery(table) q.AddKey(table, &dynamodb.Key{HashKey: "test"}) expected := []dynamodb.Attribute{ *dynamodb.NewStringAttribute("domain", "expectedTest").SetExists(true), *dynamodb.NewStringAttribute("testKey", "").SetExists(false), } q.AddExpected(expected) queryJson, err := simplejson.NewJson([]byte(q.String())) if err != nil { c.Fatal(err) } expectedJson, err := simplejson.NewJson([]byte(` { "Expected": { "domain": { "Exists": "true", "Value": { "S": "expectedTest" } }, "testKey": { "Exists": "false" } }, "Key": { "domain": { "S": "test" } }, "TableName": "sites" } `)) if err != nil { c.Fatal(err) } c.Check(queryJson, gocheck.DeepEquals, expectedJson) }
func (s *TableSuite) TestCreateListTable(c *gocheck.C) { status, err := s.server.CreateTable(s.TableDescriptionT) if err != nil { c.Fatal(err) } if status != "ACTIVE" && status != "CREATING" { c.Error("Expect status to be ACTIVE or CREATING") } s.WaitUntilStatus(c, "ACTIVE") tables, err := s.server.ListTables() if err != nil { c.Fatal(err) } c.Check(len(tables), gocheck.Not(gocheck.Equals), 0) c.Check(findTableByName(tables, s.TableDescriptionT.TableName), gocheck.Equals, true) }
func (s *ClientTests) TestDescribeInstanceHealth(c *gocheck.C) { createLBReq, instId := s.createInstanceAndLB(c) defer func() { _, err := s.elb.DeleteLoadBalancer(createLBReq.Name) c.Check(err, gocheck.IsNil) _, err = s.ec2.TerminateInstances([]string{instId}) c.Check(err, gocheck.IsNil) }() _, err := s.elb.RegisterInstancesWithLoadBalancer([]string{instId}, createLBReq.Name) c.Assert(err, gocheck.IsNil) resp, err := s.elb.DescribeInstanceHealth(createLBReq.Name, instId) c.Assert(err, gocheck.IsNil) c.Assert(len(resp.InstanceStates) > 0, gocheck.Equals, true) c.Assert(resp.InstanceStates[0].Description, gocheck.Equals, "Instance is in pending state.") c.Assert(resp.InstanceStates[0].InstanceId, gocheck.Equals, instId) c.Assert(resp.InstanceStates[0].State, gocheck.Equals, "OutOfService") c.Assert(resp.InstanceStates[0].ReasonCode, gocheck.Equals, "Instance") }
func (s *QueryBuilderSuite) TestUpdateQuery(c *gocheck.C) { primary := dynamodb.NewStringAttribute("domain", "") rangek := dynamodb.NewNumericAttribute("time", "") key := dynamodb.PrimaryKey{primary, rangek} table := s.server.NewTable("sites", key) countAttribute := dynamodb.NewNumericAttribute("count", "4") attributes := []dynamodb.Attribute{*countAttribute} q := dynamodb.NewQuery(table) q.AddKey(table, &dynamodb.Key{HashKey: "test", RangeKey: "1234"}) q.AddUpdates(attributes, "ADD") queryJson, err := simplejson.NewJson([]byte(q.String())) if err != nil { c.Fatal(err) } expectedJson, err := simplejson.NewJson([]byte(` { "AttributeUpdates": { "count": { "Action": "ADD", "Value": { "N": "4" } } }, "Key": { "domain": { "S": "test" }, "time": { "N": "1234" } }, "TableName": "sites" } `)) if err != nil { c.Fatal(err) } c.Check(queryJson, gocheck.DeepEquals, expectedJson) }
func (s *QueryBuilderSuite) TestAddUpdates(c *gocheck.C) { primary := dynamodb.NewStringAttribute("domain", "") key := dynamodb.PrimaryKey{primary, nil} table := s.server.NewTable("sites", key) q := dynamodb.NewQuery(table) q.AddKey(table, &dynamodb.Key{HashKey: "test"}) attr := dynamodb.NewStringSetAttribute("StringSet", []string{"str", "str2"}) q.AddUpdates([]dynamodb.Attribute{*attr}, "ADD") queryJson, err := simplejson.NewJson([]byte(q.String())) if err != nil { c.Fatal(err) } expectedJson, err := simplejson.NewJson([]byte(` { "AttributeUpdates": { "StringSet": { "Action": "ADD", "Value": { "SS": ["str", "str2"] } } }, "Key": { "domain": { "S": "test" } }, "TableName": "sites" } `)) if err != nil { c.Fatal(err) } c.Check(queryJson, gocheck.DeepEquals, expectedJson) }
func checkContents(c *gocheck.C, contents []s3.Key, data map[string][]byte, expected []s3.Key) { c.Assert(contents, gocheck.HasLen, len(expected)) for i, k := range contents { c.Check(k.Key, gocheck.Equals, expected[i].Key) // TODO mtime c.Check(k.Size, gocheck.Equals, int64(len(data[k.Key]))) c.Check(k.ETag, gocheck.Equals, etag(data[k.Key])) } }
func (s *ClientTests) TestDescribeInstanceHealthBadRequest(c *gocheck.C) { createLBReq := elb.CreateLoadBalancer{ Name: "testlb", AvailabilityZones: []string{"us-east-1a"}, Listeners: []elb.Listener{ { InstancePort: 80, InstanceProtocol: "http", LoadBalancerPort: 80, Protocol: "http", }, }, } _, err := s.elb.CreateLoadBalancer(&createLBReq) c.Assert(err, gocheck.IsNil) defer func() { _, err := s.elb.DeleteLoadBalancer(createLBReq.Name) c.Check(err, gocheck.IsNil) }() resp, err := s.elb.DescribeInstanceHealth(createLBReq.Name, "i-foo") c.Assert(resp, gocheck.IsNil) c.Assert(err, gocheck.NotNil) c.Assert(err, gocheck.ErrorMatches, ".*i-foo.*(InvalidInstance).*") }
func (s *ItemSuite) TestPutGetDeleteItem(c *gocheck.C) { attrs := []dynamodb.Attribute{ *dynamodb.NewStringAttribute("Attr1", "Attr1Val"), } var rk string if s.WithRange { rk = "1" } // Put if ok, err := s.table.PutItem("NewHashKeyVal", rk, attrs); !ok { c.Fatal(err) } // Get to verify Put operation pk := &dynamodb.Key{HashKey: "NewHashKeyVal", RangeKey: rk} item, err := s.table.GetItem(pk) if err != nil { c.Fatal(err) } if val, ok := item["TestHashKey"]; ok { c.Check(val, gocheck.DeepEquals, dynamodb.NewStringAttribute("TestHashKey", "NewHashKeyVal")) } else { c.Error("Expect TestHashKey to be found") } if s.WithRange { if val, ok := item["TestRangeKey"]; ok { c.Check(val, gocheck.DeepEquals, dynamodb.NewNumericAttribute("TestRangeKey", "1")) } else { c.Error("Expect TestRangeKey to be found") } } // Delete if ok, _ := s.table.DeleteItem(pk); !ok { c.Fatal(err) } // Get to verify Delete operation _, err = s.table.GetItem(pk) c.Check(err.Error(), gocheck.Matches, "Item not found") }
func (s *ItemSuite) TestConditionalPutUpdateDeleteItem(c *gocheck.C) { if s.WithRange { // No rangekey test required return } attrs := []dynamodb.Attribute{ *dynamodb.NewStringAttribute("Attr1", "Attr1Val"), } pk := &dynamodb.Key{HashKey: "NewHashKeyVal"} // Put if ok, err := s.table.PutItem("NewHashKeyVal", "", attrs); !ok { c.Fatal(err) } { // Put with condition failed expected := []dynamodb.Attribute{ *dynamodb.NewStringAttribute("Attr1", "expectedAttr1Val").SetExists(true), *dynamodb.NewStringAttribute("AttrNotExists", "").SetExists(false), } if ok, err := s.table.ConditionalPutItem("NewHashKeyVal", "", attrs, expected); ok { c.Errorf("Expect condition does not meet.") } else { c.Check(err.Error(), gocheck.Matches, "ConditionalCheckFailedException.*") } // Add attributes with condition failed if ok, err := s.table.ConditionalAddAttributes(pk, attrs, expected); ok { c.Errorf("Expect condition does not meet.") } else { c.Check(err.Error(), gocheck.Matches, "ConditionalCheckFailedException.*") } // Update attributes with condition failed if ok, err := s.table.ConditionalUpdateAttributes(pk, attrs, expected); ok { c.Errorf("Expect condition does not meet.") } else { c.Check(err.Error(), gocheck.Matches, "ConditionalCheckFailedException.*") } // Delete attributes with condition failed if ok, err := s.table.ConditionalDeleteAttributes(pk, attrs, expected); ok { c.Errorf("Expect condition does not meet.") } else { c.Check(err.Error(), gocheck.Matches, "ConditionalCheckFailedException.*") } } { expected := []dynamodb.Attribute{ *dynamodb.NewStringAttribute("Attr1", "Attr1Val").SetExists(true), } // Add attributes with condition met addNewAttrs := []dynamodb.Attribute{ *dynamodb.NewNumericAttribute("AddNewAttr1", "10"), *dynamodb.NewNumericAttribute("AddNewAttr2", "20"), } if ok, err := s.table.ConditionalAddAttributes(pk, addNewAttrs, nil); !ok { c.Errorf("Expect condition met. %s", err) } // Update attributes with condition met updateAttrs := []dynamodb.Attribute{ *dynamodb.NewNumericAttribute("AddNewAttr1", "100"), } if ok, err := s.table.ConditionalUpdateAttributes(pk, updateAttrs, expected); !ok { c.Errorf("Expect condition met. %s", err) } // Delete attributes with condition met deleteAttrs := []dynamodb.Attribute{ *dynamodb.NewNumericAttribute("AddNewAttr2", ""), } if ok, err := s.table.ConditionalDeleteAttributes(pk, deleteAttrs, expected); !ok { c.Errorf("Expect condition met. %s", err) } // Get to verify operations that condition are met item, err := s.table.GetItem(pk) if err != nil { c.Fatal(err) } if val, ok := item["AddNewAttr1"]; ok { c.Check(val, gocheck.DeepEquals, dynamodb.NewNumericAttribute("AddNewAttr1", "100")) } else { c.Error("Expect AddNewAttr1 attribute to be added and updated") } if _, ok := item["AddNewAttr2"]; ok { c.Error("Expect AddNewAttr2 attribute to be deleted") } } { // Put with condition met expected := []dynamodb.Attribute{ *dynamodb.NewStringAttribute("Attr1", "Attr1Val").SetExists(true), } newattrs := []dynamodb.Attribute{ *dynamodb.NewStringAttribute("Attr1", "Attr2Val"), } if ok, err := s.table.ConditionalPutItem("NewHashKeyVal", "", newattrs, expected); !ok { c.Errorf("Expect condition met. %s", err) } // Get to verify Put operation that condition are met item, err := s.table.GetItem(pk) if err != nil { c.Fatal(err) } if val, ok := item["Attr1"]; ok { c.Check(val, gocheck.DeepEquals, dynamodb.NewStringAttribute("Attr1", "Attr2Val")) } else { c.Error("Expect Attr1 attribute to be updated") } } { // Delete with condition failed expected := []dynamodb.Attribute{ *dynamodb.NewStringAttribute("Attr1", "expectedAttr1Val").SetExists(true), } if ok, err := s.table.ConditionalDeleteItem(pk, expected); ok { c.Errorf("Expect condition does not meet.") } else { c.Check(err.Error(), gocheck.Matches, "ConditionalCheckFailedException.*") } } { // Delete with condition met expected := []dynamodb.Attribute{ *dynamodb.NewStringAttribute("Attr1", "Attr2Val").SetExists(true), } if ok, _ := s.table.ConditionalDeleteItem(pk, expected); !ok { c.Errorf("Expect condition met.") } // Get to verify Delete operation _, err := s.table.GetItem(pk) c.Check(err.Error(), gocheck.Matches, "Item not found") } }
func (s *ServerTests) TestIPPerms(c *gocheck.C) { g0 := s.makeTestGroup(c, "goamz-test0", "ec2test group 0") defer s.ec2.DeleteSecurityGroup(g0) g1 := s.makeTestGroup(c, "goamz-test1", "ec2test group 1") defer s.ec2.DeleteSecurityGroup(g1) resp, err := s.ec2.SecurityGroups([]ec2.SecurityGroup{g0, g1}, nil) c.Assert(err, gocheck.IsNil) c.Assert(resp.Groups, gocheck.HasLen, 2) c.Assert(resp.Groups[0].IPPerms, gocheck.HasLen, 0) c.Assert(resp.Groups[1].IPPerms, gocheck.HasLen, 0) ownerId := resp.Groups[0].OwnerId // test some invalid parameters // TODO more _, err = s.ec2.AuthorizeSecurityGroup(g0, []ec2.IPPerm{{ Protocol: "tcp", FromPort: 0, ToPort: 1024, SourceIPs: []string{"z127.0.0.1/24"}, }}) c.Assert(err, gocheck.NotNil) c.Check(err.(*ec2.Error).Code, gocheck.Equals, "InvalidPermission.Malformed") // Check that AuthorizeSecurityGroup adds the correct authorizations. _, err = s.ec2.AuthorizeSecurityGroup(g0, []ec2.IPPerm{{ Protocol: "tcp", FromPort: 2000, ToPort: 2001, SourceIPs: []string{"127.0.0.0/24"}, SourceGroups: []ec2.UserSecurityGroup{{ Name: g1.Name, }, { Id: g0.Id, }}, }, { Protocol: "tcp", FromPort: 2000, ToPort: 2001, SourceIPs: []string{"200.1.1.34/32"}, }}) c.Assert(err, gocheck.IsNil) resp, err = s.ec2.SecurityGroups([]ec2.SecurityGroup{g0}, nil) c.Assert(err, gocheck.IsNil) c.Assert(resp.Groups, gocheck.HasLen, 1) c.Assert(resp.Groups[0].IPPerms, gocheck.HasLen, 1) perm := resp.Groups[0].IPPerms[0] srcg := perm.SourceGroups c.Assert(srcg, gocheck.HasLen, 2) // Normalize so we don't care about returned order. if srcg[0].Name == g1.Name { srcg[0], srcg[1] = srcg[1], srcg[0] } c.Check(srcg[0].Name, gocheck.Equals, g0.Name) c.Check(srcg[0].Id, gocheck.Equals, g0.Id) c.Check(srcg[0].OwnerId, gocheck.Equals, ownerId) c.Check(srcg[1].Name, gocheck.Equals, g1.Name) c.Check(srcg[1].Id, gocheck.Equals, g1.Id) c.Check(srcg[1].OwnerId, gocheck.Equals, ownerId) sort.Strings(perm.SourceIPs) c.Check(perm.SourceIPs, gocheck.DeepEquals, []string{"127.0.0.0/24", "200.1.1.34/32"}) // Check that we can't delete g1 (because g0 is using it) _, err = s.ec2.DeleteSecurityGroup(g1) c.Assert(err, gocheck.NotNil) c.Check(err.(*ec2.Error).Code, gocheck.Equals, "InvalidGroup.InUse") _, err = s.ec2.RevokeSecurityGroup(g0, []ec2.IPPerm{{ Protocol: "tcp", FromPort: 2000, ToPort: 2001, SourceGroups: []ec2.UserSecurityGroup{{Id: g1.Id}}, }, { Protocol: "tcp", FromPort: 2000, ToPort: 2001, SourceIPs: []string{"200.1.1.34/32"}, }}) c.Assert(err, gocheck.IsNil) resp, err = s.ec2.SecurityGroups([]ec2.SecurityGroup{g0}, nil) c.Assert(err, gocheck.IsNil) c.Assert(resp.Groups, gocheck.HasLen, 1) c.Assert(resp.Groups[0].IPPerms, gocheck.HasLen, 1) perm = resp.Groups[0].IPPerms[0] srcg = perm.SourceGroups c.Assert(srcg, gocheck.HasLen, 1) c.Check(srcg[0].Name, gocheck.Equals, g0.Name) c.Check(srcg[0].Id, gocheck.Equals, g0.Id) c.Check(srcg[0].OwnerId, gocheck.Equals, ownerId) c.Check(perm.SourceIPs, gocheck.DeepEquals, []string{"127.0.0.0/24"}) // We should be able to delete g1 now because we've removed its only use. _, err = s.ec2.DeleteSecurityGroup(g1) c.Assert(err, gocheck.IsNil) _, err = s.ec2.DeleteSecurityGroup(g0) c.Assert(err, gocheck.IsNil) f := ec2.NewFilter() f.Add("group-id", g0.Id, g1.Id) resp, err = s.ec2.SecurityGroups(nil, f) c.Assert(err, gocheck.IsNil) c.Assert(resp.Groups, gocheck.HasLen, 0) }
func (s *ServerTests) TestInstanceFiltering(c *gocheck.C) { groupResp, err := s.ec2.CreateSecurityGroup(ec2.SecurityGroup{Name: sessionName("testgroup1"), Description: "testgroup one description"}) c.Assert(err, gocheck.IsNil) group1 := groupResp.SecurityGroup defer s.ec2.DeleteSecurityGroup(group1) groupResp, err = s.ec2.CreateSecurityGroup(ec2.SecurityGroup{Name: sessionName("testgroup2"), Description: "testgroup two description"}) c.Assert(err, gocheck.IsNil) group2 := groupResp.SecurityGroup defer s.ec2.DeleteSecurityGroup(group2) insts := make([]*ec2.Instance, 3) inst, err := s.ec2.RunInstances(&ec2.RunInstancesOptions{ MinCount: 2, ImageId: imageId, InstanceType: "t1.micro", SecurityGroups: []ec2.SecurityGroup{group1}, }) c.Assert(err, gocheck.IsNil) insts[0] = &inst.Instances[0] insts[1] = &inst.Instances[1] defer terminateInstances(c, s.ec2, insts) imageId2 := "ami-e358958a" // Natty server, i386, EBS store inst, err = s.ec2.RunInstances(&ec2.RunInstancesOptions{ ImageId: imageId2, InstanceType: "t1.micro", SecurityGroups: []ec2.SecurityGroup{group2}, }) c.Assert(err, gocheck.IsNil) insts[2] = &inst.Instances[0] ids := func(indices ...int) (instIds []string) { for _, index := range indices { instIds = append(instIds, insts[index].InstanceId) } return } tests := []struct { about string instanceIds []string // instanceIds argument to Instances method. filters []filterSpec // filters argument to Instances method. resultIds []string // set of instance ids of expected results. allowExtra bool // resultIds may be incomplete. err string // expected error. }{ { about: "check that Instances returns all instances", resultIds: ids(0, 1, 2), allowExtra: true, }, { about: "check that specifying two instance ids returns them", instanceIds: ids(0, 2), resultIds: ids(0, 2), }, { about: "check that specifying a non-existent instance id gives an error", instanceIds: append(ids(0), "i-deadbeef"), err: `.*\(InvalidInstanceID\.NotFound\)`, }, { about: "check that a filter allowed both instances returns both of them", filters: []filterSpec{ {"instance-id", ids(0, 2)}, }, resultIds: ids(0, 2), }, { about: "check that a filter allowing only one instance returns it", filters: []filterSpec{ {"instance-id", ids(1)}, }, resultIds: ids(1), }, { about: "check that a filter allowing no instances returns none", filters: []filterSpec{ {"instance-id", []string{"i-deadbeef12345"}}, }, }, { about: "check that filtering on group id works", filters: []filterSpec{ {"group-id", []string{group1.Id}}, }, resultIds: ids(0, 1), }, { about: "check that filtering on group name works", filters: []filterSpec{ {"group-name", []string{group1.Name}}, }, resultIds: ids(0, 1), }, { about: "check that filtering on image id works", filters: []filterSpec{ {"image-id", []string{imageId}}, }, resultIds: ids(0, 1), allowExtra: true, }, { about: "combination filters 1", filters: []filterSpec{ {"image-id", []string{imageId, imageId2}}, {"group-name", []string{group1.Name}}, }, resultIds: ids(0, 1), }, { about: "combination filters 2", filters: []filterSpec{ {"image-id", []string{imageId2}}, {"group-name", []string{group1.Name}}, }, }, } for i, t := range tests { c.Logf("%d. %s", i, t.about) var f *ec2.Filter if t.filters != nil { f = ec2.NewFilter() for _, spec := range t.filters { f.Add(spec.name, spec.values...) } } resp, err := s.ec2.DescribeInstances(t.instanceIds, f) if t.err != "" { c.Check(err, gocheck.ErrorMatches, t.err) continue } c.Assert(err, gocheck.IsNil) insts := make(map[string]*ec2.Instance) for _, r := range resp.Reservations { for j := range r.Instances { inst := &r.Instances[j] c.Check(insts[inst.InstanceId], gocheck.IsNil, gocheck.Commentf("duplicate instance id: %q", inst.InstanceId)) insts[inst.InstanceId] = inst } } if !t.allowExtra { c.Check(insts, gocheck.HasLen, len(t.resultIds), gocheck.Commentf("expected %d instances got %#v", len(t.resultIds), insts)) } for j, id := range t.resultIds { c.Check(insts[id], gocheck.NotNil, gocheck.Commentf("instance id %d (%q) not found; got %#v", j, id, insts)) } } }
func (s *ServerTests) TestGroupFiltering(c *gocheck.C) { g := make([]ec2.SecurityGroup, 4) for i := range g { resp, err := s.ec2.CreateSecurityGroup(ec2.SecurityGroup{Name: sessionName(fmt.Sprintf("testgroup%d", i)), Description: fmt.Sprintf("testdescription%d", i)}) c.Assert(err, gocheck.IsNil) g[i] = resp.SecurityGroup c.Logf("group %d: %v", i, g[i]) defer s.ec2.DeleteSecurityGroup(g[i]) } perms := [][]ec2.IPPerm{ {{ Protocol: "tcp", FromPort: 100, ToPort: 200, SourceIPs: []string{"1.2.3.4/32"}, }}, {{ Protocol: "tcp", FromPort: 200, ToPort: 300, SourceGroups: []ec2.UserSecurityGroup{{Id: g[1].Id}}, }}, {{ Protocol: "udp", FromPort: 200, ToPort: 400, SourceGroups: []ec2.UserSecurityGroup{{Id: g[1].Id}}, }}, } for i, ps := range perms { _, err := s.ec2.AuthorizeSecurityGroup(g[i], ps) c.Assert(err, gocheck.IsNil) } groups := func(indices ...int) (gs []ec2.SecurityGroup) { for _, index := range indices { gs = append(gs, g[index]) } return } type groupTest struct { about string groups []ec2.SecurityGroup // groupIds argument to SecurityGroups method. filters []filterSpec // filters argument to SecurityGroups method. results []ec2.SecurityGroup // set of expected result groups. allowExtra bool // specified results may be incomplete. err string // expected error. } filterCheck := func(name, val string, gs []ec2.SecurityGroup) groupTest { return groupTest{ about: "filter check " + name, filters: []filterSpec{{name, []string{val}}}, results: gs, allowExtra: true, } } tests := []groupTest{ { about: "check that SecurityGroups returns all groups", results: groups(0, 1, 2, 3), allowExtra: true, }, { about: "check that specifying two group ids returns them", groups: idsOnly(groups(0, 2)), results: groups(0, 2), }, { about: "check that specifying names only works", groups: namesOnly(groups(0, 2)), results: groups(0, 2), }, { about: "check that specifying a non-existent group id gives an error", groups: append(groups(0), ec2.SecurityGroup{Id: "sg-eeeeeeeee"}), err: `.*\(InvalidGroup\.NotFound\)`, }, { about: "check that a filter allowed two groups returns both of them", filters: []filterSpec{ {"group-id", []string{g[0].Id, g[2].Id}}, }, results: groups(0, 2), }, { about: "check that the previous filter works when specifying a list of ids", groups: groups(1, 2), filters: []filterSpec{ {"group-id", []string{g[0].Id, g[2].Id}}, }, results: groups(2), }, { about: "check that a filter allowing no groups returns none", filters: []filterSpec{ {"group-id", []string{"sg-eeeeeeeee"}}, }, }, filterCheck("description", "testdescription1", groups(1)), filterCheck("group-name", g[2].Name, groups(2)), filterCheck("ip-permission.cidr", "1.2.3.4/32", groups(0)), filterCheck("ip-permission.group-name", g[1].Name, groups(1, 2)), filterCheck("ip-permission.protocol", "udp", groups(2)), filterCheck("ip-permission.from-port", "200", groups(1, 2)), filterCheck("ip-permission.to-port", "200", groups(0)), // TODO owner-id } for i, t := range tests { c.Logf("%d. %s", i, t.about) var f *ec2.Filter if t.filters != nil { f = ec2.NewFilter() for _, spec := range t.filters { f.Add(spec.name, spec.values...) } } resp, err := s.ec2.SecurityGroups(t.groups, f) if t.err != "" { c.Check(err, gocheck.ErrorMatches, t.err) continue } c.Assert(err, gocheck.IsNil) groups := make(map[string]*ec2.SecurityGroup) for j := range resp.Groups { group := &resp.Groups[j].SecurityGroup c.Check(groups[group.Id], gocheck.IsNil, gocheck.Commentf("duplicate group id: %q", group.Id)) groups[group.Id] = group } // If extra groups may be returned, eliminate all groups that // we did not create in this session apart from the default group. if t.allowExtra { namePat := regexp.MustCompile(sessionName("testgroup[0-9]")) for id, g := range groups { if !namePat.MatchString(g.Name) { delete(groups, id) } } } c.Check(groups, gocheck.HasLen, len(t.results)) for j, g := range t.results { rg := groups[g.Id] c.Assert(rg, gocheck.NotNil, gocheck.Commentf("group %d (%v) not found; got %#v", j, g, groups)) c.Check(rg.Name, gocheck.Equals, g.Name, gocheck.Commentf("group %d (%v)", j, g)) } } }
func (s *QueryBuilderSuite) TestAddWriteRequestItems(c *gocheck.C) { primary := dynamodb.NewStringAttribute("WidgetFoo", "") secondary := dynamodb.NewNumericAttribute("Created", "") key := dynamodb.PrimaryKey{primary, secondary} table := s.server.NewTable("FooData", key) primary2 := dynamodb.NewStringAttribute("TestHashKey", "") secondary2 := dynamodb.NewNumericAttribute("TestRangeKey", "") key2 := dynamodb.PrimaryKey{primary2, secondary2} table2 := s.server.NewTable("TestTable", key2) q := dynamodb.NewEmptyQuery() attribute1 := dynamodb.NewNumericAttribute("testing", "4") attribute2 := dynamodb.NewNumericAttribute("testingbatch", "2111") attribute3 := dynamodb.NewStringAttribute("testingstrbatch", "mystr") item1 := []dynamodb.Attribute{*attribute1, *attribute2, *attribute3} attribute4 := dynamodb.NewNumericAttribute("testing", "444") attribute5 := dynamodb.NewNumericAttribute("testingbatch", "93748249272") attribute6 := dynamodb.NewStringAttribute("testingstrbatch", "myotherstr") item2 := []dynamodb.Attribute{*attribute4, *attribute5, *attribute6} attributeDel1 := dynamodb.NewStringAttribute("TestHashKeyDel", "DelKey") attributeDel2 := dynamodb.NewNumericAttribute("TestRangeKeyDel", "7777777") itemDel := []dynamodb.Attribute{*attributeDel1, *attributeDel2} attributeTest1 := dynamodb.NewStringAttribute("TestHashKey", "MyKey") attributeTest2 := dynamodb.NewNumericAttribute("TestRangeKey", "0193820384293") itemTest := []dynamodb.Attribute{*attributeTest1, *attributeTest2} tableItems := map[*dynamodb.Table]map[string][][]dynamodb.Attribute{} actionItems := make(map[string][][]dynamodb.Attribute) actionItems["Put"] = [][]dynamodb.Attribute{item1, item2} actionItems["Delete"] = [][]dynamodb.Attribute{itemDel} tableItems[table] = actionItems actionItems2 := make(map[string][][]dynamodb.Attribute) actionItems2["Put"] = [][]dynamodb.Attribute{itemTest} tableItems[table2] = actionItems2 q.AddWriteRequestItems(tableItems) queryJson, err := simplejson.NewJson([]byte(q.String())) if err != nil { c.Fatal(err) } expectedJson, err := simplejson.NewJson([]byte(` { "RequestItems": { "TestTable": [ { "PutRequest": { "Item": { "TestRangeKey": { "N": "0193820384293" }, "TestHashKey": { "S": "MyKey" } } } } ], "FooData": [ { "PutRequest": { "Item": { "testingstrbatch": { "S": "mystr" }, "testingbatch": { "N": "2111" }, "testing": { "N": "4" } } } }, { "PutRequest": { "Item": { "testingstrbatch": { "S": "myotherstr" }, "testingbatch": { "N": "93748249272" }, "testing": { "N": "444" } } } }, { "DeleteRequest": { "Key": { "TestRangeKeyDel": { "N": "7777777" }, "TestHashKeyDel": { "S": "DelKey" } } } } ] } } `)) if err != nil { c.Fatal(err) } c.Check(queryJson, gocheck.DeepEquals, expectedJson) }
func (s *S) TestDescribeSecurityGroupsDumpWithGroup(c *gocheck.C) { testServer.Response(200, nil, DescribeSecurityGroupsDump) resp, err := s.ec2.SecurityGroups(nil, nil) req := testServer.WaitRequest() c.Assert(req.Form["Action"], gocheck.DeepEquals, []string{"DescribeSecurityGroups"}) c.Assert(err, gocheck.IsNil) c.Check(resp.Groups, gocheck.HasLen, 1) c.Check(resp.Groups[0].IPPerms, gocheck.HasLen, 2) ipp0 := resp.Groups[0].IPPerms[0] c.Assert(ipp0.SourceIPs, gocheck.IsNil) c.Check(ipp0.Protocol, gocheck.Equals, "icmp") c.Assert(ipp0.SourceGroups, gocheck.HasLen, 1) c.Check(ipp0.SourceGroups[0].OwnerId, gocheck.Equals, "12345") c.Check(ipp0.SourceGroups[0].Name, gocheck.Equals, "default") c.Check(ipp0.SourceGroups[0].Id, gocheck.Equals, "sg-67ad940e") ipp1 := resp.Groups[0].IPPerms[1] c.Check(ipp1.Protocol, gocheck.Equals, "tcp") c.Assert(ipp0.SourceIPs, gocheck.IsNil) c.Assert(ipp0.SourceGroups, gocheck.HasLen, 1) c.Check(ipp1.SourceGroups[0].Id, gocheck.Equals, "sg-76abc467") c.Check(ipp1.SourceGroups[0].OwnerId, gocheck.Equals, "12345") c.Check(ipp1.SourceGroups[0].Name, gocheck.Equals, "other") }