Example #1
0
func TestLoadBalancerNameUnbound(t *testing.T) {
	// an app stack with Tags but no "Name" tag is an unbound/legacy app
	mb := ManifestBalancer{
		Entry: ManifestEntry{
			app: &App{
				Name: "foo",
				Tags: map[string]string{
					"Rack":   "convox",
					"System": "convox",
					"Type":   "app",
				},
			},
			Name:    "web",
			primary: true,
		},
	}

	// legacy naming for backwards compatibility
	assert.Equal(t, `{ "Ref": "AWS::StackName" }`, string(mb.LoadBalancerName()))

	// known bug in primary / internal naming
	mb.Public = false
	assert.Equal(t, `{ "Ref": "AWS::StackName" }`, string(mb.LoadBalancerName()))

	mb.Entry.primary = false
	assert.Equal(t, `{ "Fn::Join": [ "-", [ { "Ref": "AWS::StackName" }, "web", "i" ] ] }`, string(mb.LoadBalancerName()))

	mb.Public = true
	assert.Equal(t, `{ "Fn::Join": [ "-", [ { "Ref": "AWS::StackName" }, "web" ] ] }`, string(mb.LoadBalancerName()))
}
Example #2
0
func TestAppStackName(t *testing.T) {
	// unbound app (no rack prefix)
	a := models.App{
		Name: "httpd",
		Tags: map[string]string{
			"Type":   "app",
			"System": "convox",
			"Rack":   "convox-test",
		},
	}

	assert.Equal(t, "httpd", a.StackName())

	// bound app (rack prefix, and Name tag)
	a = models.App{
		Name: "httpd",
		Tags: map[string]string{
			"Name":   "httpd",
			"Type":   "app",
			"System": "convox",
			"Rack":   "convox-test",
		},
	}

	assert.Equal(t, "convox-test-httpd", a.StackName())
}
Example #3
0
func TestLoadBalancerNameUniquePerEntryWithTruncation(t *testing.T) {
	mb1 := ManifestBalancer{
		Entry: ManifestEntry{
			app: &App{
				Name: "myverylogappname-production",
			},
			Name: "web",
		},
		Public: true,
	}

	mb2 := ManifestBalancer{
		Entry: ManifestEntry{
			app: &App{
				Name: "myverylogappname-production",
			},
			Name: "worker",
		},
		Public: true,
	}

	assert.EqualValues(t, `"myverylogappname-product-DIVTGA7"`, mb1.LoadBalancerName())
	assert.EqualValues(t, `"myverylogappname-product-LQYILNJ"`, mb2.LoadBalancerName())

	assert.Equal(t, 34, len(mb1.LoadBalancerName())) // ELB name is max 32 characters + quotes

	mb1.Public = false
	mb2.Public = false

	assert.EqualValues(t, `"myverylogappname-produ-DIVTGA7-i"`, mb1.LoadBalancerName())
	assert.EqualValues(t, `"myverylogappname-produ-LQYILNJ-i"`, mb2.LoadBalancerName())

	assert.Equal(t, 34, len(mb1.LoadBalancerName())) // ELB name is max 32 characters + quotes
}
Example #4
0
// Test the primary path: creating an app on a `convox` rack
// Return to testing against a `convox-test` rack afterwards
func TestAppCreate(t *testing.T) {
	r := os.Getenv("RACK")
	os.Setenv("RACK", "convox")
	defer os.Setenv("RACK", r)

	aws := test.StubAws(
		test.DescribeStackNotFound("application"),
		test.CreateAppStackCycle("convox-application"),
		test.DescribeAppStackCycle("convox-application"),
	)
	defer aws.Close()

	val := url.Values{"name": []string{"application"}}
	body := test.HTTPBody("POST", "http://convox/apps", val)

	if assert.NotEqual(t, "", body) {
		var resp map[string]string
		err := json.Unmarshal([]byte(body), &resp)

		if assert.Nil(t, err) {
			assert.Equal(t, "application", resp["name"])
			assert.Equal(t, "running", resp["status"])
		}
	}
}
Example #5
0
func TestPresignHandler(t *testing.T) {
	svc := s3.New(unit.Session)
	req, _ := svc.PutObjectRequest(&s3.PutObjectInput{
		Bucket:             aws.String("bucket"),
		Key:                aws.String("key"),
		ContentDisposition: aws.String("a+b c$d"),
		ACL:                aws.String("public-read"),
	})
	req.Time = time.Unix(0, 0)
	urlstr, err := req.Presign(5 * time.Minute)

	assert.NoError(t, err)

	expectedDate := "19700101T000000Z"
	expectedHeaders := "host;x-amz-acl"
	expectedSig := "7edcb4e3a1bf12f4989018d75acbe3a7f03df24bd6f3112602d59fc551f0e4e2"
	expectedCred := "AKID/19700101/mock-region/s3/aws4_request"

	u, _ := url.Parse(urlstr)
	urlQ := u.Query()
	assert.Equal(t, expectedSig, urlQ.Get("X-Amz-Signature"))
	assert.Equal(t, expectedCred, urlQ.Get("X-Amz-Credential"))
	assert.Equal(t, expectedHeaders, urlQ.Get("X-Amz-SignedHeaders"))
	assert.Equal(t, expectedDate, urlQ.Get("X-Amz-Date"))
	assert.Equal(t, "300", urlQ.Get("X-Amz-Expires"))

	assert.NotContains(t, urlstr, "+") // + encoded as %20
}
Example #6
0
func TestValidateCRC32DoesNotMatch(t *testing.T) {
	req := mockCRCResponse(db, 200, "{}", "1234")
	assert.Error(t, req.Error)

	assert.Equal(t, "CRC32CheckFailed", req.Error.(awserr.Error).Code())
	assert.Equal(t, 2, req.RetryCount)
}
Example #7
0
func TestNextBadVersionData(t *testing.T) {
	vs := Versions{
		Version{
			Version:   "1",
			Published: true,
		},
		Version{
			Version:   "2",
			Published: false,
			Required:  true, // Required but not Published makes no sense
		},
	}

	next, err := vs.Next("1")
	assert.Equal(t, "", next)
	assert.EqualError(t, err, `current version "1" is latest`)

	vs = Versions{
		Version{
			Version:   "1",
			Published: false,
		},
		Version{
			Version:   "2",
			Published: false, // nothing Published is not helpful
		},
	}

	latest, err := vs.Latest()
	assert.Equal(t, "", latest.Version)
	assert.EqualError(t, err, `no published versions`)
}
Example #8
0
func TestTimeValueSlice(t *testing.T) {
	for idx, in := range testCasesTimeValueSlice {
		if in == nil {
			continue
		}
		out := TimeValueSlice(in)
		assert.Len(t, out, len(in), "Unexpected len at idx %d", idx)
		for i := range out {
			if in[i] == nil {
				assert.Empty(t, out[i], "Unexpected value at idx %d", idx)
			} else {
				assert.Equal(t, *(in[i]), out[i], "Unexpected value at idx %d", idx)
			}
		}

		out2 := TimeSlice(out)
		assert.Len(t, out2, len(in), "Unexpected len at idx %d", idx)
		for i := range out2 {
			if in[i] == nil {
				assert.Empty(t, *(out2[i]), "Unexpected value at idx %d", idx)
			} else {
				assert.Equal(t, in[i], out2[i], "Unexpected value at idx %d", idx)
			}
		}
	}
}
Example #9
0
func TestDownloadError(t *testing.T) {
	s, names, _ := dlLoggingSvc([]byte{1, 2, 3})

	num := 0
	s.Handlers.Send.PushBack(func(r *request.Request) {
		num++
		if num > 1 {
			r.HTTPResponse.StatusCode = 400
			r.HTTPResponse.Body = ioutil.NopCloser(bytes.NewReader([]byte{}))
		}
	})

	d := s3manager.NewDownloaderWithClient(s, func(d *s3manager.Downloader) {
		d.Concurrency = 1
		d.PartSize = 1
	})
	w := &aws.WriteAtBuffer{}
	n, err := d.Download(w, &s3.GetObjectInput{
		Bucket: aws.String("bucket"),
		Key:    aws.String("key"),
	})

	assert.NotNil(t, err)
	assert.Equal(t, int64(1), n)
	assert.Equal(t, []string{"GetObject", "GetObject"}, *names)
	assert.Equal(t, []byte{1}, w.Bytes())
}
Example #10
0
func TestWithFieldsShouldAllowAssignments(t *testing.T) {
	var buffer bytes.Buffer
	var fields Fields

	logger := New()
	logger.Out = &buffer
	logger.Formatter = new(JSONFormatter)

	localLog := logger.WithFields(Fields{
		"key1": "value1",
	})

	localLog.WithField("key2", "value2").Info("test")
	err := json.Unmarshal(buffer.Bytes(), &fields)
	assert.Nil(t, err)

	assert.Equal(t, "value2", fields["key2"])
	assert.Equal(t, "value1", fields["key1"])

	buffer = bytes.Buffer{}
	fields = Fields{}
	localLog.Info("test")
	err = json.Unmarshal(buffer.Bytes(), &fields)
	assert.Nil(t, err)

	_, ok := fields["key2"]
	assert.Equal(t, false, ok)
	assert.Equal(t, "value1", fields["key1"])
}
Example #11
0
func TestOutputService9ProtocolTestSupportsHeaderMapsCase1(t *testing.T) {
	sess := session.New()
	svc := NewOutputService9ProtocolTest(sess, &aws.Config{Endpoint: aws.String("https://test")})

	buf := bytes.NewReader([]byte("{}"))
	req, out := svc.OutputService9TestCaseOperation1Request(nil)
	req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}}

	// set headers
	req.HTTPResponse.Header.Set("Content-Length", "10")
	req.HTTPResponse.Header.Set("X-Bam", "boo")
	req.HTTPResponse.Header.Set("X-Foo", "bar")

	// unmarshal response
	restjson.UnmarshalMeta(req)
	restjson.Unmarshal(req)
	assert.NoError(t, req.Error)

	// assert response
	assert.NotNil(t, out) // ensure out variable is used
	assert.Equal(t, "10", *out.AllHeaders["Content-Length"])
	assert.Equal(t, "boo", *out.AllHeaders["X-Bam"])
	assert.Equal(t, "bar", *out.AllHeaders["X-Foo"])
	assert.Equal(t, "boo", *out.PrefixedHeaders["Bam"])
	assert.Equal(t, "bar", *out.PrefixedHeaders["Foo"])

}
Example #12
0
func TestInputService2ProtocolTestTimestampValuesCase1(t *testing.T) {
	sess := session.New()
	svc := NewInputService2ProtocolTest(sess, &aws.Config{Endpoint: aws.String("https://test")})

	input := &InputService2TestShapeInputService2TestCaseOperation1Input{
		TimeArg: aws.Time(time.Unix(1422172800, 0)),
	}
	req, _ := svc.InputService2TestCaseOperation1Request(input)
	r := req.HTTPRequest

	// build request
	jsonrpc.Build(req)
	assert.NoError(t, req.Error)

	// assert body
	assert.NotNil(t, r.Body)
	body, _ := ioutil.ReadAll(r.Body)
	awstesting.AssertJSON(t, `{"TimeArg":1422172800}`, util.Trim(string(body)))

	// assert URL
	awstesting.AssertURL(t, "https://test/", r.URL.String())

	// assert headers
	assert.Equal(t, "application/x-amz-json-1.1", r.Header.Get("Content-Type"))
	assert.Equal(t, "com.amazonaws.foo.OperationName", r.Header.Get("X-Amz-Target"))

}
Example #13
0
func TestInputService4ProtocolTestNestedBlobsCase1(t *testing.T) {
	sess := session.New()
	svc := NewInputService4ProtocolTest(sess, &aws.Config{Endpoint: aws.String("https://test")})

	input := &InputService4TestShapeInputService4TestCaseOperation1Input{
		ListParam: [][]byte{
			[]byte("foo"),
			[]byte("bar"),
		},
	}
	req, _ := svc.InputService4TestCaseOperation1Request(input)
	r := req.HTTPRequest

	// build request
	jsonrpc.Build(req)
	assert.NoError(t, req.Error)

	// assert body
	assert.NotNil(t, r.Body)
	body, _ := ioutil.ReadAll(r.Body)
	awstesting.AssertJSON(t, `{"ListParam":["Zm9v","YmFy"]}`, util.Trim(string(body)))

	// assert URL
	awstesting.AssertURL(t, "https://test/", r.URL.String())

	// assert headers
	assert.Equal(t, "application/x-amz-json-1.1", r.Header.Get("Content-Type"))
	assert.Equal(t, "com.amazonaws.foo.OperationName", r.Header.Get("X-Amz-Target"))

}
Example #14
0
func TestInputService5ProtocolTestRecursiveShapesCase3(t *testing.T) {
	sess := session.New()
	svc := NewInputService5ProtocolTest(sess, &aws.Config{Endpoint: aws.String("https://test")})

	input := &InputService5TestShapeInputShape{
		RecursiveStruct: &InputService5TestShapeRecursiveStructType{
			RecursiveStruct: &InputService5TestShapeRecursiveStructType{
				RecursiveStruct: &InputService5TestShapeRecursiveStructType{
					RecursiveStruct: &InputService5TestShapeRecursiveStructType{
						NoRecurse: aws.String("foo"),
					},
				},
			},
		},
	}
	req, _ := svc.InputService5TestCaseOperation3Request(input)
	r := req.HTTPRequest

	// build request
	jsonrpc.Build(req)
	assert.NoError(t, req.Error)

	// assert body
	assert.NotNil(t, r.Body)
	body, _ := ioutil.ReadAll(r.Body)
	awstesting.AssertJSON(t, `{"RecursiveStruct":{"RecursiveStruct":{"RecursiveStruct":{"RecursiveStruct":{"NoRecurse":"foo"}}}}}`, util.Trim(string(body)))

	// assert URL
	awstesting.AssertURL(t, "https://test/", r.URL.String())

	// assert headers
	assert.Equal(t, "application/x-amz-json-1.1", r.Header.Get("Content-Type"))
	assert.Equal(t, "com.amazonaws.foo.OperationName", r.Header.Get("X-Amz-Target"))

}
Example #15
0
func TestInfo(t *testing.T) {
	LogAndAssertJSON(t, func(log *Logger) {
		log.Info("test")
	}, func(fields Fields) {
		assert.Equal(t, fields["msg"], "test")
		assert.Equal(t, fields["level"], "info")
	})
}
Example #16
0
func TestUserSuppliedMsgFieldHasPrefix(t *testing.T) {
	LogAndAssertJSON(t, func(log *Logger) {
		log.WithField("msg", "hello").Info("test")
	}, func(fields Fields) {
		assert.Equal(t, fields["msg"], "test")
		assert.Equal(t, fields["fields.msg"], "hello")
	})
}
Example #17
0
func TestWarn(t *testing.T) {
	LogAndAssertJSON(t, func(log *Logger) {
		log.Warn("test")
	}, func(fields Fields) {
		assert.Equal(t, fields["msg"], "test")
		assert.Equal(t, fields["level"], "warning")
	})
}
Example #18
0
func TestUserSuppliedLevelFieldHasPrefix(t *testing.T) {
	LogAndAssertJSON(t, func(log *Logger) {
		log.WithField("level", 1).Info("test")
	}, func(fields Fields) {
		assert.Equal(t, fields["level"], "info")
		assert.Equal(t, fields["fields.level"], 1.0) // JSON has floats only
	})
}
Example #19
0
func TestNewDefaultSession(t *testing.T) {
	s := session.New(&aws.Config{Region: aws.String("region")})

	assert.Equal(t, "region", *s.Config.Region)
	assert.Equal(t, http.DefaultClient, s.Config.HTTPClient)
	assert.NotNil(t, s.Config.Logger)
	assert.Equal(t, aws.LogOff, *s.Config.LogLevel)
}
Example #20
0
func (er ExecRun) Test(t *testing.T) {
	stdout, stderr, code, err := er.exec()

	assert.Nil(t, err, "should be nil")
	assert.Equal(t, er.Exit, code, "exit code should be equal")
	assert.Equal(t, er.Stdout, stdout, "stdout should be equal")
	assert.Contains(t, stderr, er.Stderr,
		fmt.Sprintf("stderr should contain %q", stderr))
}
Example #21
0
func TestEventsSince(t *testing.T) {
	services, _ := getClusterServices()

	events := services.EventsSince(time.Unix(0, 0))
	assert.Equal(t, 4, len(events))

	events = services.EventsSince(time.Unix(1450120333, 0)) // just before last event "createdAt": 1450120334.038
	assert.Equal(t, 1, len(events))
}
Example #22
0
func TestMissingRequiredParameters(t *testing.T) {
	input := &StructShape{}
	req := testSvc.NewRequest(&request.Operation{}, input, nil)
	corehandlers.ValidateParametersHandler.Fn(req)

	require.Error(t, req.Error)
	assert.Equal(t, "InvalidParameter", req.Error.(awserr.Error).Code())
	assert.Equal(t, "3 validation errors:\n- missing required parameter: RequiredList\n- missing required parameter: RequiredMap\n- missing required parameter: RequiredBool", req.Error.(awserr.Error).Message())
}
Example #23
0
func TestGlobalEndpoints(t *testing.T) {
	region := "mock-region-1"
	svcs := []string{"cloudfront", "iam", "importexport", "route53", "sts", "waf"}

	for _, name := range svcs {
		ep, sr := endpoints.EndpointForRegion(name, region, false)
		assert.Equal(t, fmt.Sprintf("https://%s.amazonaws.com", name), ep)
		assert.Equal(t, "us-east-1", sr)
	}
}
Example #24
0
func TestSignSeekedBody(t *testing.T) {
	signer := buildSigner("dynamodb", "us-east-1", time.Now(), 0, "   hello")
	signer.Body.Read(make([]byte, 3)) // consume first 3 bytes so body is now "hello"
	signer.sign()
	hash := signer.Request.Header.Get("X-Amz-Content-Sha256")
	assert.Equal(t, "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824", hash)

	start, _ := signer.Body.Seek(0, 1)
	assert.Equal(t, int64(3), start)
}
Example #25
0
func TestCopyDifferentStructs(t *testing.T) {
	type SrcFoo struct {
		A                int
		B                []*string
		C                map[string]*int
		SrcUnique        string
		SameNameDiffType int
		unexportedPtr    *int
		ExportedPtr      *int
	}
	type DstFoo struct {
		A                int
		B                []*string
		C                map[string]*int
		DstUnique        int
		SameNameDiffType string
		unexportedPtr    *int
		ExportedPtr      *int
	}

	// Create the initial value
	str1 := "hello"
	str2 := "bye bye"
	int1 := 1
	int2 := 2
	f1 := &SrcFoo{
		A: 1,
		B: []*string{&str1, &str2},
		C: map[string]*int{
			"A": &int1,
			"B": &int2,
		},
		SrcUnique:        "unique",
		SameNameDiffType: 1,
		unexportedPtr:    &int1,
		ExportedPtr:      &int2,
	}

	// Do the copy
	var f2 DstFoo
	awsutil.Copy(&f2, f1)

	// Values are equal
	assert.Equal(t, f2.A, f1.A)
	assert.Equal(t, f2.B, f1.B)
	assert.Equal(t, f2.C, f1.C)
	assert.Equal(t, "unique", f1.SrcUnique)
	assert.Equal(t, 1, f1.SameNameDiffType)
	assert.Equal(t, 0, f2.DstUnique)
	assert.Equal(t, "", f2.SameNameDiffType)
	assert.Equal(t, int1, *f1.unexportedPtr)
	assert.Nil(t, f2.unexportedPtr)
	assert.Equal(t, int2, *f1.ExportedPtr)
	assert.Equal(t, int2, *f2.ExportedPtr)
}
func TestSharedCredentialsProvider(t *testing.T) {
	os.Clearenv()

	p := SharedCredentialsProvider{Filename: "example.ini", Profile: ""}
	creds, err := p.Retrieve()
	assert.Nil(t, err, "Expect no error")

	assert.Equal(t, "accessKey", creds.AccessKeyID, "Expect access key ID to match")
	assert.Equal(t, "secret", creds.SecretAccessKey, "Expect secret access key to match")
	assert.Equal(t, "token", creds.SessionToken, "Expect session token to match")
}
Example #27
0
func TestGetProcessesWithDeployments(t *testing.T) {
	os.Setenv("RACK", "convox-test")
	os.Setenv("CLUSTER", "convox-test-cluster")

	aws := test.StubAws(
		test.DescribeAppStackCycle("convox-test-myapp-staging"),
		test.DescribeAppStackCycle("convox-test-myapp-staging"),
		test.DescribeAppStackResourcesCycle("convox-test-myapp-staging"),

		test.ListContainerInstancesCycle("convox-test-cluster"),
		test.DescribeContainerInstancesCycle("convox-test-cluster"),
		test.DescribeInstancesCycle(),

		test.ListTasksCycle("convox-test-cluster", "convox-test-myapp-staging-worker-SCELGCIYSKF"),
		test.DescribeTasksCycle("convox-test-cluster"),
		test.ListTasksOneoffEmptyCycle("convox-test-cluster"),
		test.DescribeTaskDefinitionCycle("convox-test-cluster"),

		test.DescribeAppStackResourcesCycle("convox-test-myapp-staging"),
		test.DescribeServicesWithDeploymentsCycle("convox-test-cluster"),
		test.DescribeTaskDefinition3Cycle("convox-test-cluster"),
		test.DescribeTaskDefinition1Cycle("convox-test-cluster"),
	)
	defer aws.Close()

	docker := test.StubDocker(
		// query for every ECS task to get docker id, command, created
		test.ListECSContainersCycle(),

		// query every instance for one-off containers
		test.ListOneoffContainersEmptyCycle(),
		test.ListOneoffContainersEmptyCycle(),
		test.ListOneoffContainersEmptyCycle(),

		// query for every container to get CPU and Memory stats
		test.StatsCycle(),
	)
	defer docker.Close()

	v := url.Values{}
	v.Add("stats", "true")
	body := test.HTTPBody("GET", "http://convox/apps/myapp-staging/processes", v)

	var resp client.Processes
	err := json.Unmarshal([]byte(body), &resp)

	if assert.Nil(t, err) {
		assert.Equal(t, 2, len(resp))
		assert.Equal(t, "8dfafdbc3a40", resp[0].Id)
		assert.Equal(t, 0.0974, resp[0].Memory)
		assert.Equal(t, "pending", resp[1].Id)
		assert.EqualValues(t, 0, resp[1].Memory)
	}
}
Example #28
0
func TestSignRequest(t *testing.T) {
	signer := buildSigner("dynamodb", "us-east-1", time.Unix(0, 0), 0, "{}")
	signer.sign()

	expectedDate := "19700101T000000Z"
	expectedSig := "AWS4-HMAC-SHA256 Credential=AKID/19700101/us-east-1/dynamodb/aws4_request, SignedHeaders=host;x-amz-date;x-amz-meta-other-header;x-amz-security-token;x-amz-target, Signature=69ada33fec48180dab153576e4dd80c4e04124f80dda3eccfed8a67c2b91ed5e"

	q := signer.Request.Header
	assert.Equal(t, expectedSig, q.Get("Authorization"))
	assert.Equal(t, expectedDate, q.Get("X-Amz-Date"))
}
Example #29
0
func TestNamedHandlers(t *testing.T) {
	l := request.HandlerList{}
	named := request.NamedHandler{Name: "Name", Fn: func(r *request.Request) {}}
	named2 := request.NamedHandler{Name: "NotName", Fn: func(r *request.Request) {}}
	l.PushBackNamed(named)
	l.PushBackNamed(named)
	l.PushBackNamed(named2)
	l.PushBack(func(r *request.Request) {})
	assert.Equal(t, 4, l.Len())
	l.Remove(named)
	assert.Equal(t, 2, l.Len())
}
Example #30
0
func TestHandlerList(t *testing.T) {
	s := ""
	r := &request.Request{}
	l := request.HandlerList{}
	l.PushBack(func(r *request.Request) {
		s += "a"
		r.Data = s
	})
	l.Run(r)
	assert.Equal(t, "a", s)
	assert.Equal(t, "a", r.Data)
}