func TestLoggingStatements(t *testing.T) { output := new(bytes.Buffer) l := New() l.Logger.Formatter.(*logrus.TextFormatter).DisableColors = true l.Logger.Out = output // level defaults to warn l.Debug("debug") l.Info("info") l.Warn("warn") assert.NotContains(t, output.String(), "level=info") assert.NotContains(t, output.String(), "level=debug") assert.Contains(t, output.String(), "level=warn") // when on debug level, all statements are logged output.Reset() assert.Empty(t, output.String()) l.Logger.Level = logrus.DebugLevel l.Debug("1") l.Info("1") l.Warn("1") l.Error("1") assert.Contains(t, output.String(), "level=debug") assert.Contains(t, output.String(), "level=info") assert.Contains(t, output.String(), "level=warn") assert.Contains(t, output.String(), "level=error") assert.Panics(t, func() { l.Panic("boom") }, "Calling Panic() should panic") assert.Contains(t, output.String(), "level=panic") }
func test(l *Logger, t *testing.T) { b := new(bytes.Buffer) l.SetOutput(b) l.DisableColor() l.SetLevel(WARN) l.Print("print") l.Printf("print%s", "f") l.Debug("debug") l.Debugf("debug%s", "f") l.Info("info") l.Infof("info%s", "f") l.Warn("warn") l.Warnf("warn%s", "f") l.Error("error") l.Errorf("error%s", "f") assert.Contains(t, b.String(), "print\n") assert.Contains(t, b.String(), "\nprintf\n") assert.NotContains(t, b.String(), "debug") assert.NotContains(t, b.String(), "debugf") assert.NotContains(t, b.String(), "info") assert.NotContains(t, b.String(), "infof") assert.Contains(t, b.String(), "level=WARN, prefix="+l.prefix) assert.Contains(t, b.String(), "level=WARN, prefix="+l.prefix) assert.Contains(t, b.String(), "level=ERROR, prefix="+l.prefix) assert.Contains(t, b.String(), "level=ERROR, prefix="+l.prefix) }
func TestDefaultLogging(t *testing.T) { outputBuf := new(bytes.Buffer) logBuf := new(bytes.Buffer) LogHandle = logBuf OutHandle = outputBuf SetLogThreshold(LevelWarn) SetStdoutThreshold(LevelError) FATAL.Println("fatal err") CRITICAL.Println("critical err") ERROR.Println("an error") WARN.Println("a warning") INFO.Println("information") DEBUG.Println("debugging info") assert.Contains(t, logBuf.String(), "fatal err") assert.Contains(t, logBuf.String(), "critical err") assert.Contains(t, logBuf.String(), "an error") assert.Contains(t, logBuf.String(), "a warning") assert.NotContains(t, logBuf.String(), "information") assert.NotContains(t, logBuf.String(), "debugging info") assert.Contains(t, outputBuf.String(), "fatal err") assert.Contains(t, outputBuf.String(), "critical err") assert.Contains(t, outputBuf.String(), "an error") assert.NotContains(t, outputBuf.String(), "a warning") assert.NotContains(t, outputBuf.String(), "information") assert.NotContains(t, outputBuf.String(), "debugging info") }
func TestListClustersWithSecrets(t *testing.T) { ts := newTestServer(t) defer ts.Stop() r, err := ts.Client.ListClusters(context.Background(), &api.ListClustersRequest{}) assert.NoError(t, err) assert.Empty(t, r.Clusters) policy := api.AcceptancePolicy{Policies: []*api.AcceptancePolicy_RoleAdmissionPolicy{{Secret: &api.AcceptancePolicy_RoleAdmissionPolicy_Secret{Alg: "bcrypt", Data: []byte("secret")}}}} createCluster(t, ts, "id1", "name1", policy, ts.Server.rootCA) r, err = ts.Client.ListClusters(context.Background(), &api.ListClustersRequest{}) assert.NoError(t, err) assert.Equal(t, 1, len(r.Clusters)) createCluster(t, ts, "id2", "name2", policy, ts.Server.rootCA) createCluster(t, ts, "id3", "name3", policy, ts.Server.rootCA) r, err = ts.Client.ListClusters(context.Background(), &api.ListClustersRequest{}) assert.NoError(t, err) assert.Equal(t, 3, len(r.Clusters)) for _, cluster := range r.Clusters { assert.NotContains(t, cluster.String(), policy.Policies[0].Secret) assert.NotContains(t, cluster.String(), "PRIVATE") assert.NotNil(t, cluster.Spec.AcceptancePolicy.Policies[0].Secret.Data) } }
func test(l *Logger, t *testing.T) { b := new(bytes.Buffer) l.SetOutput(b) l.DisableColor() l.SetLevel(WARN) l.Print("print") l.Printf("print%s", "f") l.Debug("debug") l.Debugf("debug%s", "f") l.Info("info") l.Infof("info%s", "f") l.Warn("warn") l.Warnf("warn%s", "f") l.Error("error") l.Errorf("error%s", "f") assert.Contains(t, b.String(), "print\n") assert.Contains(t, b.String(), "\nprintf\n") assert.NotContains(t, b.String(), "debug") assert.NotContains(t, b.String(), "debugf") assert.NotContains(t, b.String(), "info") assert.NotContains(t, b.String(), "infof") assert.Contains(t, b.String(), `"level":"WARN","prefix":"`+l.prefix+`"`) assert.Contains(t, b.String(), `"message":"warn"`) assert.Contains(t, b.String(), `"level":"ERROR","prefix":"`+l.prefix+`"`) assert.Contains(t, b.String(), `"message":"errorf"`) }
func TestPublicVariables(t *testing.T) { v1 := BuildVariable{"key", "value", false} v2 := BuildVariable{"public", "value", true} v3 := BuildVariable{"private", "value", false} all := BuildVariables{v1, v2, v3} public := all.Public() assert.Contains(t, public, v2) assert.NotContains(t, public, v1) assert.NotContains(t, public, v3) }
func TestStdLogger(t *testing.T) { var buf bytes.Buffer sl := log.NewStdLogger( log.SetStdLevel(log.StdLevelTrace), log.SetStdTrace(&buf, "TEST-TRACE ", std.LstdFlags), log.SetStdDebug(&buf, "TEST-DEBUG ", std.LstdFlags), log.SetStdInfo(&buf, "TEST-INFO ", std.LstdFlags), log.SetStdWarn(&buf, "TEST-WARN ", std.LstdFlags), log.SetStdError(&buf, "TEST-ERROR ", std.LstdFlags), log.SetStdFatal(&buf, "TEST-FATAL ", std.LstdFlags), ) sl.SetLevel(log.StdLevelInfo) assert.False(t, sl.IsTrace()) assert.False(t, sl.IsDebug()) assert.True(t, sl.IsInfo()) assert.True(t, sl.IsWarn()) sl.Trace("my trace1") sl.Trace("my trace2", "int", 29) sl.Debug("my Debug", "float", 3.14152) sl.Debug("my Debug2", 2.14152) sl.Info("InfoTEST") sl.Warn("WarnTEST") haveErr := sl.Error("ErrorTEST", "err1a", 1, "err2", 32.4232) assert.Contains(t, "ErrorTEST53", sl.Error("ErrorTEST53").Error()) logs := buf.String() assert.EqualError(t, haveErr, "ErrorTEST") assert.Contains(t, logs, "InfoTEST") assert.Contains(t, logs, "WarnTEST") assert.Contains(t, logs, "ErrorTEST") assert.NotContains(t, logs, "trace1") assert.NotContains(t, logs, "Debug2") buf.Reset() sl.SetLevel(log.StdLevelTrace) assert.True(t, sl.IsTrace()) assert.True(t, sl.IsDebug()) assert.True(t, sl.IsInfo()) assert.True(t, sl.IsWarn()) sl.Trace("my trace1") sl.Trace("my trace2", "int", 29) sl.Debug("my Debug", "float", 3.14152) sl.Debug("my Debug2", 2.14152) sl.Info("InfoTEST") logs = buf.String() assert.Contains(t, logs, "InfoTEST") assert.Contains(t, logs, "trace1") assert.Contains(t, logs, "Debug2") }
func TestAutoTag(t *testing.T) { c := newConfig() c.Hostname = "cb01.test.localdomain" tags := c.GetTags() assert.Len(t, tags, 2) assert.NotContains(t, tags, "cb01") assert.NotContains(t, tags, "cb") assert.Contains(t, tags, "test") assert.Contains(t, tags, "localdomain") assert.NotContains(t, tags, "") }
func TestLogLevelError(t *testing.T) { stdout, stderr := captureOutputs(func() { logger := NewLogger(LEVEL_ERROR) logger.Debug("DEBUG", "some debug log") logger.Info("INFO", "some info log") logger.Error("ERROR", "some error log") }) assert.NotContains(t, string(stdout), "DEBUG") assert.NotContains(t, string(stdout), "INFO") assert.Contains(t, string(stderr), "ERROR") }
// TestDiff tests the diff.go source file func TestDiff(t *testing.T) { cmp := CompareStringLists([]string{"a", "b", "b", "a"}, []string{"a", "c"}) assert.Len(t, cmp, 1) assert.NotContains(t, cmp, "a") assert.Contains(t, cmp, "b") cmp = CompareStringListsInBoth([]string{"a", "a", "b", "c"}, []string{"a", "c", "c"}) assert.Len(t, cmp, 2) assert.NotContains(t, cmp, "b") assert.Contains(t, cmp, "a") assert.Contains(t, cmp, "c") }
func TestNewRootCAWithPassphrase(t *testing.T) { tempBaseDir, err := ioutil.TempDir("", "swarm-ca-test-") assert.NoError(t, err) defer os.RemoveAll(tempBaseDir) defer os.Setenv(ca.PassphraseENVVar, "") defer os.Setenv(ca.PassphraseENVVarPrev, "") paths := ca.NewConfigPaths(tempBaseDir) rootCA, err := ca.CreateAndWriteRootCA("rootCN", paths.RootCA) assert.NoError(t, err) // Ensure that we're encrypting the Key bytes out of NewRoot if there // is a passphrase set as an env Var os.Setenv(ca.PassphraseENVVar, "password1") newRootCA, err := ca.NewRootCA(rootCA.Cert, rootCA.Key, ca.DefaultNodeCertExpiration) assert.NoError(t, err) assert.NotEqual(t, rootCA.Key, newRootCA.Key) assert.Equal(t, rootCA.Cert, newRootCA.Cert) assert.NotContains(t, string(rootCA.Key), string(newRootCA.Key)) assert.Contains(t, string(newRootCA.Key), "Proc-Type: 4,ENCRYPTED") // Ensure that we're decrypting the Key bytes out of NewRoot if there // is a passphrase set as an env Var anotherNewRootCA, err := ca.NewRootCA(newRootCA.Cert, newRootCA.Key, ca.DefaultNodeCertExpiration) assert.NoError(t, err) assert.Equal(t, newRootCA, anotherNewRootCA) assert.NotContains(t, string(rootCA.Key), string(anotherNewRootCA.Key)) assert.Contains(t, string(anotherNewRootCA.Key), "Proc-Type: 4,ENCRYPTED") // Ensure that we cant decrypt the Key bytes out of NewRoot if there // is a wrong passphrase set as an env Var os.Setenv(ca.PassphraseENVVar, "password2") anotherNewRootCA, err = ca.NewRootCA(newRootCA.Cert, newRootCA.Key, ca.DefaultNodeCertExpiration) assert.Error(t, err) // Ensure that we cant decrypt the Key bytes out of NewRoot if there // is a wrong passphrase set as an env Var os.Setenv(ca.PassphraseENVVarPrev, "password2") anotherNewRootCA, err = ca.NewRootCA(newRootCA.Cert, newRootCA.Key, ca.DefaultNodeCertExpiration) assert.Error(t, err) // Ensure that we can decrypt the Key bytes out of NewRoot if there // is a wrong passphrase set as an env Var, but a valid as Prev os.Setenv(ca.PassphraseENVVarPrev, "password1") anotherNewRootCA, err = ca.NewRootCA(newRootCA.Cert, newRootCA.Key, ca.DefaultNodeCertExpiration) assert.NoError(t, err) assert.Equal(t, newRootCA, anotherNewRootCA) assert.NotContains(t, string(rootCA.Key), string(anotherNewRootCA.Key)) assert.Contains(t, string(anotherNewRootCA.Key), "Proc-Type: 4,ENCRYPTED") }
func TestPrepareAttributes(t *testing.T) { prepared := prepareAttributes(Attributes{ "v": "asd", "id": "test", "attr": "value", "name": "value", "forbidden": "value", }, []string{"name", "forbidden"}) assert.Contains(t, prepared, " v=\"asd\"", "") assert.Contains(t, prepared, " id=\"test\"", "") assert.Contains(t, prepared, " attr=\"value\"", "") assert.NotContains(t, prepared, " name=\"value\"", "") assert.NotContains(t, prepared, " forbidden=\"value\"", "") }
func TestSitemap_AddEntry(t *testing.T) { sitemap := NewSitemap() sitemap.AddEntry("http://foo.bar/1", "http://foo.bar", false) sitemap.AddEntry("http://foo.bar/2", "http://foo.bar", false) sitemap.AddEntry("http://foo.bar/3", "http://foo.bar/1", true) assert.Contains(t, sitemap.entries, "http://foo.bar") assert.Contains(t, sitemap.entries, "http://foo.bar/1") assert.NotContains(t, sitemap.entries, "http://foo.bar/2") assert.NotContains(t, sitemap.entries, "http://foo.bar/3") assert.Contains(t, sitemap.entries["http://foo.bar"], "http://foo.bar/1") assert.Contains(t, sitemap.entries["http://foo.bar"], "http://foo.bar/2") assert.Contains(t, sitemap.entries["http://foo.bar/1"], "http://foo.bar/3") }
// Ensure that version validation middleware passes through request // on a valid version, and returns a 400 on an invalid version. func TestVersionMiddleware(t *testing.T) { assert := assert.New(t) api := NewAPI(&Configuration{}) handler := new(MockResourceHandler) handler.On("Authenticate").Return(nil) handler.On("ValidVersions").Return([]string{"1"}) handler.On("Rules").Return(&rules{}) handler.On("ResourceName").Return("widgets") handler.On("ReadResourceList").Return([]Resource{"foo"}, "", nil) api.RegisterResourceHandler(handler) // Valid version req, _ := http.NewRequest("GET", "http://example.com/api/v1/widgets", nil) w := httptest.NewRecorder() api.ServeHTTP(w, req) assert.Equal(w.Code, 200) assert.Contains(w.Body.String(), "foo") // Invalid version req, _ = http.NewRequest("GET", "http://example.com/api/v2/widgets", nil) w = httptest.NewRecorder() api.ServeHTTP(w, req) assert.Equal(w.Code, http.StatusBadRequest) assert.NotContains(w.Body.String(), "foo") }
func TestIncomingReplication(t *testing.T) { if testing.Short() { t.Skip() } rep := createMockupReplication() close(rep.(*mockupReplication).syncChan) //Make sure no deadlock occur ns := auth.NamespaceFrom("ns1") r := newInMemoryRegistry(nil, rep) assert.NotContains(t, r.(*inMemoryRegistry).namespaces, ns) inst := newServiceInstance("Calc1", "192.168.0.1", 9080) payload, _ := json.Marshal(inst) data, _ := json.Marshal(&replicatedMsg{RepType: REGISTER, Payload: payload}) rep.(*mockupReplication).NotifyChannel <- &replication.InMessage{cluster.MemberID("192.1.1.3:6100"), ns, data} catalog, err := r.GetCatalog(auth.NamespaceFrom("ns1")) // NOTICE, it may fail, since a race between the registry and the test... time.Sleep(time.Duration(5) * time.Second) assert.NoError(t, err) instances1, err1 := catalog.List("Calc1", protocolPredicate) assert.NoError(t, err1) assert.Len(t, instances1, 1) }
func TestServerHelp(t *testing.T) { x := runFull(t, "hyperkube test1 --help") assert.NoError(t, x.err) assert.Contains(t, x.output, "A simple server named test1") assert.Contains(t, x.output, "-h, --help help for hyperkube") assert.NotContains(t, x.output, "test1 Run") }
func TestServerFlagsBad(t *testing.T) { x := runFull(t, "hyperkube test1 --bad-flag") assert.EqualError(t, x.err, "unknown flag: --bad-flag") assert.Contains(t, x.output, "A simple server named test1") assert.Contains(t, x.output, "-h, --help help for hyperkube") assert.NotContains(t, x.output, "test1 Run") }
func TestAgent_OmitHostname(t *testing.T) { c := config.NewConfig() c.Agent.OmitHostname = true _, err := NewAgent(c) assert.NoError(t, err) assert.NotContains(t, c.Tags, "host") }
func TestTopFlags(t *testing.T) { x := runFull(t, "hyperkube --help test1") assert.NoError(t, x.err) assert.Contains(t, x.output, "all-in-one") assert.Contains(t, x.output, "A simple server named test1") assert.NotContains(t, x.output, "test1 Run") }
func TestHiddenCommand(t *testing.T) { templates := []struct{ name, template string }{ {"default", DefaultUsageTemplate}, {"Compact", CompactUsageTemplate}, {"Long", LongHelpTemplate}, {"Man", ManPageTemplate}, } var buf bytes.Buffer t.Log("1") a := New("test", "Test").Writer(&buf).Terminate(nil) a.Command("visible", "visible") a.Command("hidden", "hidden").Hidden() for _, tp := range templates { buf.Reset() a.UsageTemplate(tp.template) a.Parse(nil) // a.Parse([]string{"--help"}) usage := buf.String() t.Logf("Usage for %s is:\n%s\n", tp.name, usage) assert.NotContains(t, usage, "hidden") assert.Contains(t, usage, "visible") } }
func TestMessageHTML(t *testing.T) { const caddyFile = `mailout { to [email protected] bcc [email protected] subject " HTML Email via {{ .Form.Get \"firstname\" }} {{.Form.Get \"lastname\"}}" body testdata/mail_tpl.html }` buf := new(bytes.Buffer) srv := testMessageServer(t, caddyFile, buf, 1) defer srv.Close() data := make(url.Values) data.Set("firstname", "Ken") data.Set("lastname", "Thompson") data.Set("email", "*****@*****.**") data.Set("name", "Ken S. Thompson") testDoPost(t, srv.URL, data) assert.True(t, buf.Len() > 10000) // whenever you change the template, change also here assert.Contains(t, buf.String(), "<h3>Thank you for contacting us, Ken Thompson</h3>") assert.Contains(t, buf.String(), "<h3>Sir Ken S. Thompson") assert.Contains(t, buf.String(), "Subject: =?UTF-8?q?=EF=A3=BF_HTML_Email_via_Ken_Thompson?=") assert.NotContains(t, buf.String(), "Bcc: [email protected]") }
func TestPresignRequest(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, headers, err := req.PresignRequest(5 * time.Minute) assert.NoError(t, err) expectedDate := "19700101T000000Z" expectedHeaders := "content-disposition;host;x-amz-acl" expectedSig := "2d76a414208c0eac2a23ef9c834db9635ecd5a0fbb447a00ad191f82d854f55b" expectedCred := "AKID/19700101/mock-region/s3/aws4_request" expectedHeaderMap := http.Header{ "x-amz-acl": []string{"public-read"}, "content-disposition": []string{"a+b c$d"}, } 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, expectedHeaderMap, headers) assert.Equal(t, "300", urlQ.Get("X-Amz-Expires")) assert.NotContains(t, urlstr, "+") // + encoded as %20 }
func TestPresignHandler(t *testing.T) { svc := s3.New(nil) 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 }
func TestTargetOrganizationWhenUserHasAccess(t *testing.T) { configRepo := &testhelpers.FakeConfigRepository{} configRepo.Login() config, err := configRepo.Get() assert.NoError(t, err) config.Space = cf.Space{Name: "my-space", Guid: "my-space-guid"} orgs := []cf.Organization{ cf.Organization{Name: "my-organization", Guid: "my-organization-guid"}, } orgRepo := &testhelpers.FakeOrgRepository{ Organizations: orgs, OrganizationByName: orgs[0], } spaceRepo := &testhelpers.FakeSpaceRepository{} ui := callTarget([]string{"-o", "my-organization"}, configRepo, orgRepo, spaceRepo) assert.Equal(t, orgRepo.OrganizationName, "my-organization") assert.Contains(t, ui.Outputs[2], "org:") assert.Contains(t, ui.Outputs[2], "my-organization") assert.Contains(t, ui.Outputs[3], "No space targeted.") ui = callTarget([]string{}, configRepo, orgRepo, spaceRepo) assert.Contains(t, ui.Outputs[2], "my-organization") assert.NotContains(t, ui.Outputs[3], "my-space") }
func TestCustomParse(t *testing.T) { c := new(Custom) c.Files = []string{ "../_example/simple/public/", } c.Base = "../_example/simple/" c.Prefix = "prefix_test/" c.Exclude = []string{ "public/assets/data/exclude_me.txt", } c.Replace = []Replacer{ { File: "public/assets/data/test*.json", Replace: map[string]string{ "{world}": "earth", "{EMAIL}": "*****@*****.**", }, }, } files := make(map[string]*file.File) dirs := new(dir.Dir) err := c.Parse(&files, &dirs) assert.NoError(t, err) assert.NotNil(t, files) assert.NotNil(t, dirs) // insert \r on windows var isWindows string if runtime.GOOS == "windows" { isWindows = "\r" } for _, f := range files { assert.True(t, strings.HasPrefix(f.Path, c.Prefix)) assert.NotEqual(t, "exclude_me.txt", f.Name) if f.Name == "test1.json" { e := "{" + isWindows + "\n \"he\": \"llo\"," + isWindows + "\n \"replace_test\": \"earth\"" + isWindows + "\n}" assert.Equal(t, e, data2str(f.Data)) } else if f.Name == "test2.json" { e := "{" + isWindows + "\n \"email\": \"[email protected]\"" + isWindows + "\n}" assert.Equal(t, e, data2str(f.Data)) } } ds := dirs.Clean() var blacklist []string for _, d := range ds { assert.True(t, strings.HasPrefix(d, c.Prefix)) assert.NotContains(t, blacklist, d) blacklist = append(blacklist, d) } }
func TestPreResignRequestExpiredCreds(t *testing.T) { provider := &credentials.StaticProvider{Value: credentials.Value{ AccessKeyID: "AKID", SecretAccessKey: "SECRET", SessionToken: "SESSION", }} creds := credentials.NewCredentials(provider) svc := awstesting.NewClient(&aws.Config{Credentials: creds}) r := svc.NewRequest( &request.Operation{ Name: "BatchGetItem", HTTPMethod: "POST", HTTPPath: "/", }, nil, nil, ) r.ExpireTime = time.Minute * 10 Sign(r) querySig := r.HTTPRequest.URL.Query().Get("X-Amz-Signature") signedHeaders := r.HTTPRequest.URL.Query().Get("X-Amz-SignedHeaders") assert.NotEmpty(t, signedHeaders) creds.Expire() r.Time = time.Now().Add(time.Hour * 48) Sign(r) assert.NotEqual(t, querySig, r.HTTPRequest.URL.Query().Get("X-Amz-Signature")) resignedHeaders := r.HTTPRequest.URL.Query().Get("X-Amz-SignedHeaders") assert.Equal(t, signedHeaders, resignedHeaders) assert.NotContains(t, signedHeaders, "x-amz-signedHeaders") }
func TestPresignRequest(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, headers, err := req.PresignRequest(5 * time.Minute) assert.NoError(t, err) expectedDate := "19700101T000000Z" expectedHeaders := "content-disposition;host;x-amz-acl" expectedSig := "b2754ba8ffeb74a40b94767017e24c4672107d6d5a894648d5d332ca61f5ffe4" expectedCred := "AKID/19700101/mock-region/s3/aws4_request" expectedHeaderMap := http.Header{ "x-amz-acl": []string{"public-read"}, "content-disposition": []string{"a+b c$d"}, } 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, expectedHeaderMap, headers) assert.Equal(t, "300", urlQ.Get("X-Amz-Expires")) assert.NotContains(t, urlstr, "+") // + encoded as %20 }
func TestSetupSettings(t *testing.T) { clearDb() defer clearDb() var err error db, err = OpenDatabase(testDbPath) assert.Nil(t, err) defer db.Close() eventSettings, _ = db.GetEventSettings() // Check the default setting values. recorder := getHttpResponse("/setup/settings") assert.Equal(t, 200, recorder.Code) assert.Contains(t, recorder.Body.String(), "Untitled Event") assert.Contains(t, recorder.Body.String(), "UE") assert.Contains(t, recorder.Body.String(), "#00ff00") assert.Contains(t, recorder.Body.String(), "8") assert.NotContains(t, recorder.Body.String(), "tbaPublishingEnabled\" checked") // Change the settings and check the response. recorder = postHttpResponse("/setup/settings", "name=Chezy Champs&code=CC&displayBackgroundColor=#ff00ff&"+ "numElimAlliances=16&tbaPublishingEnabled=on&tbaEventCode=2014cc&tbaSecretId=secretId&tbaSecret=tbasec&"+ "initialTowerStrength=9001") assert.Equal(t, 302, recorder.Code) recorder = getHttpResponse("/setup/settings") assert.Contains(t, recorder.Body.String(), "Chezy Champs") assert.Contains(t, recorder.Body.String(), "CC") assert.Contains(t, recorder.Body.String(), "#ff00ff") assert.Contains(t, recorder.Body.String(), "16") assert.Contains(t, recorder.Body.String(), "tbaPublishingEnabled\" checked") assert.Contains(t, recorder.Body.String(), "2014cc") assert.Contains(t, recorder.Body.String(), "secretId") assert.Contains(t, recorder.Body.String(), "tbasec") assert.Contains(t, recorder.Body.String(), "9001") }
func TestEndpointCopy(t *testing.T) { c := &Container{id: "foo"} s := &Scope{ gateway: net.ParseIP("10.10.10.1"), subnet: &net.IPNet{IP: net.ParseIP("10.10.10.0"), Mask: net.CIDRMask(24, 32)}, } e := Endpoint{ container: c, scope: s, ip: net.ParseIP("10.10.10.10"), static: true, ports: make(map[Port]interface{}), } p, err := ParsePort("80/tcp") assert.NoError(t, err, "") e.ports[p] = nil other := e.copy() assert.Equal(t, other.ID(), e.ID()) assert.Equal(t, other.container, c) assert.Equal(t, other.container, e.container) assert.Equal(t, other.scope, s) assert.Equal(t, other.scope, e.scope) assert.True(t, other.ip.Equal(e.ip), "other.ip (%s) != e.ip (%s)", other.ip, e.ip) assert.True(t, other.Gateway().Equal(e.Gateway()), "other.Gateway() (%s) != e.Gateway() (%s)", other.Gateway(), e.Gateway()) assert.True(t, other.Subnet().IP.Equal(e.Subnet().IP), "other.Subnet() (%s) != e.Subnet() (%s)", other.Subnet(), e.Subnet()) assert.Equal(t, other.Subnet().Mask, e.Subnet().Mask, "other.Subnet() (%s) != e.Subnet() (%s)", other.Subnet(), e.Subnet()) assert.EqualValues(t, other.ports, e.ports) // make sure .ports is a copy other.ports["foo"] = nil assert.NotContains(t, e.ports, "foo") }
func TestConstrainteFilter(t *testing.T) { var ( f = ConstraintFilter{} nodes = testFixtures() result []*node.Node err error ) // Without constraints we should get the unfiltered list of nodes back. result, err = f.Filter(&cluster.ContainerConfig{}, nodes, true) assert.NoError(t, err) assert.Equal(t, result, nodes) // Set a constraint that cannot be fulfilled and expect an error back. result, err = f.Filter(cluster.BuildContainerConfig(containertypes.Config{Env: []string{"constraint:does_not_exist==true"}}, containertypes.HostConfig{}, networktypes.NetworkingConfig{}), nodes, true) assert.Error(t, err) // Set a contraint that can only be filled by a single node. result, err = f.Filter(cluster.BuildContainerConfig(containertypes.Config{Env: []string{"constraint:name==node1"}}, containertypes.HostConfig{}, networktypes.NetworkingConfig{}), nodes, true) assert.NoError(t, err) assert.Len(t, result, 1) assert.Equal(t, result[0], nodes[1]) // This constraint can only be fulfilled by a subset of nodes. result, err = f.Filter(cluster.BuildContainerConfig(containertypes.Config{Env: []string{"constraint:group==1"}}, containertypes.HostConfig{}, networktypes.NetworkingConfig{}), nodes, true) assert.NoError(t, err) assert.Len(t, result, 2) assert.NotContains(t, result, nodes[2]) // Validate node pinning by id. result, err = f.Filter(cluster.BuildContainerConfig(containertypes.Config{Env: []string{"constraint:node==node-2-id"}}, containertypes.HostConfig{}, networktypes.NetworkingConfig{}), nodes, true) assert.NoError(t, err) assert.Len(t, result, 1) assert.Equal(t, result[0], nodes[2]) // Validate node pinning by name. result, err = f.Filter(cluster.BuildContainerConfig(containertypes.Config{Env: []string{"constraint:node==node-1-name"}}, containertypes.HostConfig{}, networktypes.NetworkingConfig{}), nodes, true) assert.NoError(t, err) assert.Len(t, result, 1) assert.Equal(t, result[0], nodes[1]) // Make sure constraints are evaluated as logical ANDs. result, err = f.Filter(cluster.BuildContainerConfig(containertypes.Config{Env: []string{"constraint:name==node0", "constraint:group==1"}}, containertypes.HostConfig{}, networktypes.NetworkingConfig{}), nodes, true) assert.NoError(t, err) assert.Len(t, result, 1) assert.Equal(t, result[0], nodes[0]) // Check matching result, err = f.Filter(cluster.BuildContainerConfig(containertypes.Config{Env: []string{"constraint:region==us"}}, containertypes.HostConfig{}, networktypes.NetworkingConfig{}), nodes, true) assert.Error(t, err) assert.Len(t, result, 0) result, err = f.Filter(cluster.BuildContainerConfig(containertypes.Config{Env: []string{"constraint:region==us*"}}, containertypes.HostConfig{}, networktypes.NetworkingConfig{}), nodes, true) assert.NoError(t, err) assert.Len(t, result, 2) result, err = f.Filter(cluster.BuildContainerConfig(containertypes.Config{Env: []string{"constraint:region==*us*"}}, containertypes.HostConfig{}, networktypes.NetworkingConfig{}), nodes, true) assert.NoError(t, err) assert.Len(t, result, 2) }