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 TestNewHydre(t *testing.T) { h, err := NewHydre("test/good-conf.yml") assert.Nil(t, err) assert.Equal(t, 10, h.Timeout) assert.Len(t, h.Daemons, 2) assert.Contains(t, h.Daemons, &Daemon{ Name: "daemon1", Command: []string{"start", "daemon1"}, StopCommand: []string{"stop", "daemon1"}, PidFile: "path/to/pidfile", LogFiles: []string{"1.log", "2.log"}, }) assert.Contains(t, h.Daemons, &Daemon{ Name: "daemon2", Command: []string{"start", "daemon2"}, }) h, err = NewHydre("test/bad-conf.yml") assert.NotNil(t, err) assert.Nil(t, h) h, err = NewHydre("does-not-exist.yml") assert.NotNil(t, err) assert.Nil(t, h) }
func Test_client_buildMkdirRequest(t *testing.T) { c := client{ options: ClientOptions{ Locale: "init__locale", Root: "init__root", Token: "init__token", }} r, e := c.buildMkdirRequest("somepath") assert.NoError(t, e) assert.Equal(t, r.Method, "POST") auth := r.Header.Get("Authorization") assert.Contains(t, auth, "Bearer") assert.Contains(t, auth, "init__token") u := r.URL assert.Equal(t, u.Scheme, "https") assert.Equal(t, u.Host, "api.dropbox.com") assert.Equal(t, u.Path, "/1/fileops/create_folder") p := u.Query() assert.Equal(t, p.Get("root"), "init__root") assert.Equal(t, p.Get("path"), "somepath") assert.Equal(t, p.Get("locale"), "init__locale") assert.Equal(t, len(p), 3) }
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") }
// TestSuccessCodeAndInfoForComplexMessage sends out a complex message to the pubnub channel func TestSuccessCodeAndInfoForComplexMessage(t *testing.T) { assert := assert.New(t) stop, _ := NewVCRNonSubscribe( "fixtures/publish/successCodeAndInfoForComplexMessage", []string{"uuid"}) defer stop() pubnubInstance := messaging.NewPubnub(PubKey, SubKey, "", "", false, "") channel := "successCodeAndInfoForComplexMessage" customStruct := CustomStruct{ Foo: "hi!", Bar: []int{1, 2, 3, 4, 5}, } successChannel := make(chan []byte) errorChannel := make(chan []byte) go pubnubInstance.Publish(channel, customStruct, successChannel, errorChannel) select { case msg := <-successChannel: assert.Contains(string(msg), "1,") assert.Contains(string(msg), "\"Sent\",") case err := <-errorChannel: assert.Fail(string(err)) case <-timeout(): assert.Fail("Publish timeout") } }
// If there is one key, asking to remove it will ask for confirmation. Passing // anything other than 'yes'/'y'/'' response will abort the deletion and // not delete the key. func TestRemoveOneKeyAbort(t *testing.T) { nos := []string{"no", "NO", "AAAARGH", " N "} store := trustmanager.NewKeyMemoryStore(ret) key, err := trustmanager.GenerateED25519Key(rand.Reader) assert.NoError(t, err) err = store.AddKey(key.ID(), "root", key) assert.NoError(t, err) stores := []trustmanager.KeyStore{store} for _, noAnswer := range nos { var out bytes.Buffer in := bytes.NewBuffer([]byte(noAnswer + "\n")) err := removeKeyInteractively(stores, key.ID(), in, &out) assert.NoError(t, err) text, err := ioutil.ReadAll(&out) assert.NoError(t, err) output := string(text) assert.Contains(t, output, "Are you sure") assert.Contains(t, output, "Aborting action") assert.Len(t, store.ListKeys(), 1) } }
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 TestLoggerWritesEntriesOfAppropriateLevel(t *testing.T) { logDir := os.TempDir() logFile := logger.FILE_NAME log, err := logger.NewLogger("info", logDir, logFile) assert.NoError(t, err, "Expected new logger not to fail") filename := path.Join(logDir, logFile) log.InfoF("TestLog: %s", "InfoLog") log.ErrorF("TestLog: %s", "ErrorLog") fileContents, err := readFileContents(filename) assert.NoError(t, err, "Expected to read created file") scanner := bufio.NewScanner(bytes.NewBuffer([]byte(fileContents))) if scanner.Scan() { line := scanner.Text() println("text:", line[:4]) assert.Equal(t, line[:4], "INFO") } if scanner.Scan() { assert.Equal(t, scanner.Text()[:4], "ERRO") } assert.Contains(t, fileContents, "TestLog: InfoLog", "Expected file to contain log entry") assert.Contains(t, fileContents, "TestLog: ErrorLog", "Expected file to contain log entry") }
func TestFindPlaceAllBas(t *testing.T) { pod1 := BuildTestPod("p1", 300, 500000) new1 := BuildTestPod("p2", 600, 500000) new2 := BuildTestPod("p3", 500, 500000) new3 := BuildTestPod("p4", 700, 500000) nodeInfos := map[string]*schedulercache.NodeInfo{ "n1": schedulercache.NewNodeInfo(pod1), "n2": schedulercache.NewNodeInfo(), "nbad": schedulercache.NewNodeInfo(), } nodebad := BuildTestNode("nbad", 1000, 2000000) node1 := BuildTestNode("n1", 1000, 2000000) node2 := BuildTestNode("n2", 1000, 2000000) nodeInfos["n1"].SetNode(node1) nodeInfos["n2"].SetNode(node2) nodeInfos["nbad"].SetNode(nodebad) oldHints := make(map[string]string) newHints := make(map[string]string) tracker := NewUsageTracker() err := findPlaceFor( "nbad", []*kube_api.Pod{new1, new2, new3}, []*kube_api.Node{nodebad, node1, node2}, nodeInfos, NewTestPredicateChecker(), oldHints, newHints, tracker, time.Now()) assert.Error(t, err) assert.True(t, len(newHints) == 2) assert.Contains(t, newHints, new1.Namespace+"/"+new1.Name) assert.Contains(t, newHints, new2.Namespace+"/"+new2.Name) }
func TestGroupSubscriptionToNotExistingChannelGroup(t *testing.T) { assert := assert.New(t) stop, sleep := NewVCRBoth( "fixtures/groups/notExistingCG", []string{"uuid"}) defer stop() group := "Group_NotExistingCG" uuid := "UUID_NotExistingCG" pubnub := messaging.NewPubnub(PubKey, SubKey, "", "", false, uuid) successChannel := make(chan []byte) errorChannel := make(chan []byte) unsubscribeSuccessChannel := make(chan []byte) unsubscribeErrorChannel := make(chan []byte) removeChannelGroups(pubnub, []string{group}) sleep(2) go pubnub.ChannelGroupSubscribe(group, successChannel, errorChannel) select { case response := <-successChannel: assert.Fail("Received success message while expecting error", string(response)) case err := <-errorChannel: assert.Contains(string(err), "Channel group or groups result in empty subscription set") assert.Contains(string(err), group) } go pubnub.ChannelGroupUnsubscribe(group, unsubscribeSuccessChannel, unsubscribeErrorChannel) ExpectUnsubscribedEvent(t, "", group, unsubscribeSuccessChannel, unsubscribeErrorChannel) }
func TestUpdateServiceBroker(t *testing.T) { reqFactory := &testreq.FakeReqFactory{LoginSuccess: true} repo := &testapi.FakeServiceBrokerRepo{ FindByNameServiceBroker: cf.ServiceBroker{Name: "my-found-broker", Guid: "my-found-broker-guid"}, } args := []string{"my-broker", "new-username", "new-password", "new-url"} ui := callUpdateServiceBroker(t, args, reqFactory, repo) assert.Equal(t, repo.FindByNameName, "my-broker") assert.Contains(t, ui.Outputs[0], "Updating service broker") assert.Contains(t, ui.Outputs[0], "my-found-broker") assert.Contains(t, ui.Outputs[0], "my-user") expectedServiceBroker := cf.ServiceBroker{ Name: "my-found-broker", Username: "******", Password: "******", Url: "new-url", Guid: "my-found-broker-guid", } assert.Equal(t, repo.UpdatedServiceBroker, expectedServiceBroker) assert.Contains(t, ui.Outputs[1], "OK") }
func TestGroupSubscriptionNotSubscribed(t *testing.T) { assert := assert.New(t) stop, sleep := NewVCRNonSubscribe( "fixtures/groups/notSubscribed", []string{"uuid"}) defer stop() group := "Group_NotSubscribed" uuid := "UUID_NotSubscribed" pubnub := messaging.NewPubnub(PubKey, SubKey, "", "", false, uuid) createChannelGroups(pubnub, []string{group}) defer removeChannelGroups(pubnub, []string{group}) sleep(2) successChannel := make(chan []byte) errorChannel := make(chan []byte) go pubnub.ChannelGroupUnsubscribe(group, successChannel, errorChannel) select { case response := <-successChannel: assert.Fail("Received success message while expecting error", string(response)) case err := <-errorChannel: assert.Contains(string(err), "Subscription to channel group") assert.Contains(string(err), "not subscribed") } pubnub.CloseExistingConnection() }
func TestMessagePlainTextAllFormFields(t *testing.T) { const caddyFile = `mailout { to [email protected] cc "[email protected], [email protected]" subject "Email from {{ .Form.Get \"firstname\" }} {{.Form.Get \"lastname\"}}" body testdata/mail_plainTextMessage.txt }` 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 Thompson") testDoPost(t, srv.URL, data) assert.Len(t, buf.String(), 424) // whenever you change the template, change also here assert.Contains(t, buf.String(), "Email [email protected]") assert.Contains(t, buf.String(), `From: "Ken Thompson" <*****@*****.**>`) assert.Contains(t, buf.String(), "Subject: Email from Ken Thompson") assert.Contains(t, buf.String(), "Cc: [email protected], [email protected]") //t.Log(buf.String()) }
func TestMessagePlainPGPSingleKey(t *testing.T) { const caddyFile = `mailout { to [email protected] cc "*****@*****.**" subject "Encrypted contact 🔑" body testdata/mail_plainTextMessage.txt [email protected] testdata/B06469EE_nopw.pub.asc }` buf := new(bytes.Buffer) srv := testMessageServer(t, caddyFile, buf, 2) defer srv.Close() data := make(url.Values) data.Set("firstname", "Ken") data.Set("lastname", "Thompson") data.Set("email", "*****@*****.**") data.Set("name", "Ken Thompson") testDoPost(t, srv.URL, data) assert.Len(t, buf.String(), 2710) // whenever you change the template, change also here assert.Contains(t, buf.String(), "Subject: =?UTF-8?q?Encrypted_contact_=F0=9F=94=91?=") assert.Contains(t, buf.String(), "Cc: [email protected]") assert.Exactly(t, 1, bytes.Count(buf.Bytes(), maillog.MultiMessageSeparator)) assert.Contains(t, buf.String(), `This shows the content of a text template.`) //t.Log(buf.String()) }
func TestApps(t *testing.T) { app1Urls := []string{"app1.cfapps.io", "app1.example.com"} app2Urls := []string{"app2.cfapps.io"} apps := []cf.Application{ cf.Application{Name: "Application-1", State: "started", Instances: 1, Memory: 512, Urls: app1Urls}, cf.Application{Name: "Application-2", State: "started", Instances: 2, Memory: 256, Urls: app2Urls}, } spaceRepo := &testhelpers.FakeSpaceRepository{ CurrentSpace: cf.Space{Name: "development", Guid: "development-guid"}, SummarySpace: cf.Space{Applications: apps}, } reqFactory := &testhelpers.FakeReqFactory{LoginSuccess: true, TargetedSpaceSuccess: true} ui := callApps(spaceRepo, reqFactory) assert.True(t, testhelpers.CommandDidPassRequirements) assert.Contains(t, ui.Outputs[0], "Getting applications in development") assert.Contains(t, ui.Outputs[1], "OK") assert.Contains(t, ui.Outputs[3], "Application-1") assert.Contains(t, ui.Outputs[3], "running") assert.Contains(t, ui.Outputs[3], "1 x 512M") assert.Contains(t, ui.Outputs[3], "app1.cfapps.io, app1.example.com") assert.Contains(t, ui.Outputs[4], "Application-2") assert.Contains(t, ui.Outputs[4], "running") assert.Contains(t, ui.Outputs[4], "2 x 256M") assert.Contains(t, ui.Outputs[4], "app2.cfapps.io") }
func TestSubVolumeCreateValidation(t *testing.T) { subvol := btrfs.NewIoctl().Subvolume() cmd := subvol.Create() err := cmd.Execute() assert.Error(t, err) assert.Contains(t, err.Error(), "destination is empty") cmd = subvol.Create() err = cmd.Destination(strings.Repeat("s", 512)).Execute() assert.Error(t, err) assert.Contains(t, err.Error(), "subvolume name too long") assert.Contains(t, err.Error(), "max length is 255") // cmd = subvol.Create() // err = cmd.Name("/name").Execute() // assert.Error(t, err) // assert.Contains(t, err.Error(), "incorrect subvolume name '/name'") cmd = subvol.Create() err = cmd.Destination(".").Execute() assert.Contains(t, err.Error(), "incorrect subvolume name '.'") cmd = subvol.Create() err = cmd.Destination("..").Execute() assert.Error(t, err) assert.Contains(t, err.Error(), "incorrect subvolume name '..'") }
// If there is more than one key, removeKeyInteractively will ask which key to // delete. Then it will confirm whether they want to delete, and the user can // abort at that confirmation. func TestRemoveMultikeysAbortChoice(t *testing.T) { in := bytes.NewBuffer([]byte("1\nn\n")) key, err := trustmanager.GenerateED25519Key(rand.Reader) assert.NoError(t, err) stores := []trustmanager.KeyStore{ trustmanager.NewKeyMemoryStore(ret), trustmanager.NewKeyMemoryStore(ret), } err = stores[0].AddKey(key.ID(), "root", key) assert.NoError(t, err) err = stores[1].AddKey("gun/"+key.ID(), "target", key) assert.NoError(t, err) var out bytes.Buffer err = removeKeyInteractively(stores, key.ID(), in, &out) assert.NoError(t, err) // no error to abort deleting text, err := ioutil.ReadAll(&out) assert.NoError(t, err) assert.Len(t, stores[0].ListKeys(), 1) assert.Len(t, stores[1].ListKeys(), 1) // It should have listed the keys, asked whether the user really wanted to // delete, and then aborted. output := string(text) assert.Contains(t, output, "Found the following matching keys") assert.Contains(t, output, "Are you sure") assert.Contains(t, output, "Aborting action") }
func TestDecompressFileToDir(t *testing.T) { fs, cmdRunner := getCompressorDependencies() dc := NewTarballCompressor(cmdRunner, fs) dstDir := createdTmpDir(t, fs) defer os.RemoveAll(dstDir) err := dc.DecompressFileToDir(fixtureSrcTgz(t), dstDir) assert.NoError(t, err) // regular files content, err := fs.ReadFile(dstDir + "/not-nested-file") assert.NoError(t, err) assert.Contains(t, content, "not-nested-file") // nested directory with a file content, err = fs.ReadFile(dstDir + "/dir/nested-file") assert.NoError(t, err) assert.Contains(t, content, "nested-file") // nested directory with a file inside another directory content, err = fs.ReadFile(dstDir + "/dir/nested-dir/double-nested-file") assert.NoError(t, err) assert.Contains(t, content, "double-nested-file") // directory without a file (empty) content, err = fs.ReadFile(dstDir + "/empty-dir") assert.Error(t, err) assert.Contains(t, err.Error(), "is a directory") // nested directory without a file (empty) inside another directory content, err = fs.ReadFile(dstDir + "/dir/empty-nested-dir") assert.Error(t, err) assert.Contains(t, err.Error(), "is a directory") }
// If there is one key, asking to remove it will ask for confirmation. Passing // 'yes'/'y'/'' response will continue the deletion. func TestRemoveOneKeyConfirm(t *testing.T) { yesses := []string{"yes", " Y ", "yE", " ", ""} for _, yesAnswer := range yesses { store := trustmanager.NewKeyMemoryStore(ret) key, err := trustmanager.GenerateED25519Key(rand.Reader) assert.NoError(t, err) err = store.AddKey(key.ID(), "root", key) assert.NoError(t, err) var out bytes.Buffer in := bytes.NewBuffer([]byte(yesAnswer + "\n")) err = removeKeyInteractively( []trustmanager.KeyStore{store}, key.ID(), in, &out) assert.NoError(t, err) text, err := ioutil.ReadAll(&out) assert.NoError(t, err) output := string(text) assert.Contains(t, output, "Are you sure") assert.Contains(t, output, "Deleted "+key.ID()) assert.Len(t, store.ListKeys(), 0) } }
func TestThatItSendsAllMessageToKnownDrains(t *testing.T) { client1ReceivedChan := make(chan []byte) fakeSyslogDrain, err := NewFakeService(client1ReceivedChan, "127.0.0.1:34566") defer fakeSyslogDrain.Stop() assert.NoError(t, err) go fakeSyslogDrain.Serve() <-fakeSyslogDrain.ReadyChan expectedMessageString := "Some Data" logEnvelope1 := messagetesthelpers.MarshalledLogEnvelopeForMessage(t, expectedMessageString, "myApp", SECRET, "syslog://localhost:34566") expectedSecondMessageString := "Some Data Without a drainurl" logEnvelope2 := messagetesthelpers.MarshalledLogEnvelopeForMessage(t, expectedSecondMessageString, "myApp", SECRET, "syslog://localhost:34566") dataReadChannel <- logEnvelope1 select { case <-time.After(200 * time.Millisecond): t.Errorf("Did not get the first message") case message := <-client1ReceivedChan: assert.Contains(t, string(message), expectedMessageString) } dataReadChannel <- logEnvelope2 select { case <-time.After(200 * time.Millisecond): t.Errorf("Did not get the second message") case message := <-client1ReceivedChan: assert.Contains(t, string(message), expectedSecondMessageString) } }
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 TestDebugInfo(t *testing.T) { fakeSink := NewFakeOpenTSDBSink(true, true) debugInfo := fakeSink.DebugInfo() assert.Contains(t, debugInfo, "Sink Type: OpenTSDB") assert.Contains(t, debugInfo, "client: Host "+fakeOpenTSDBHost) assert.Contains(t, debugInfo, "Number of write failures:") }
func TestGitHubGetBeginAuthURL(t *testing.T) { common.SetSecurityKey("ABC123") state := &common.State{Map: objx.MSI("after", "http://www.stretchr.com/")} g := New("clientID", "secret", "http://myapp.com/") url, err := g.GetBeginAuthURL(state, nil) if assert.NoError(t, err) { assert.Contains(t, url, "client_id=clientID") assert.Contains(t, url, "redirect_uri=http%3A%2F%2Fmyapp.com%2F") assert.Contains(t, url, "scope="+githubDefaultScope) assert.Contains(t, url, "access_type="+oauth2.OAuth2AccessTypeOnline) assert.Contains(t, url, "approval_prompt="+oauth2.OAuth2ApprovalPromptAuto) } state = &common.State{Map: objx.MSI("after", "http://www.stretchr.com/")} g = New("clientID", "secret", "http://myapp.com/") url, err = g.GetBeginAuthURL(state, objx.MSI(oauth2.OAuth2KeyScope, "avatar")) if assert.NoError(t, err) { assert.Contains(t, url, "client_id=clientID") assert.Contains(t, url, "redirect_uri=http%3A%2F%2Fmyapp.com%2F") assert.Contains(t, url, "scope=avatar+"+githubDefaultScope) assert.Contains(t, url, "access_type="+oauth2.OAuth2AccessTypeOnline) assert.Contains(t, url, "approval_prompt="+oauth2.OAuth2ApprovalPromptAuto) } }
func Test_datastore_buildGetSnapshotRequest(t *testing.T) { ds := datastore{ info: DatastoreInfo{ Handle: "UcBxkoM8nLbUY3AHrkcKsKCeg9LbVl"}, client: client{ options: ClientOptions{ Token: "init__token"}}} r, e := ds.buildGetSnapshotRequest() assert.NoError(t, e) assert.Equal(t, r.Method, "GET") auth := r.Header.Get("Authorization") assert.Contains(t, auth, "Bearer") assert.Contains(t, auth, "init__token") u := r.URL assert.Equal(t, u.Scheme, "https") assert.Equal(t, u.Host, "api.dropbox.com") assert.Equal(t, u.Path, "/r5/datastores/get_snapshot") p := u.Query() assert.Equal(t, p.Get("handle"), "UcBxkoM8nLbUY3AHrkcKsKCeg9LbVl") assert.Equal(t, len(p), 1) }
// TestSuccessCodeAndInfoWithEncryption sends out an encrypted // message to the pubnub channel func TestSuccessCodeAndInfoWithEncryption(t *testing.T) { assert := assert.New(t) stop, _ := NewVCRNonSubscribe( "fixtures/publish/successCodeAndInfoWithEncryption", []string{"uuid"}) defer stop() pubnubInstance := messaging.NewPubnub(PubKey, SubKey, "", "enigma", false, "") channel := "successCodeAndInfo" message := "Pubnub API Usage Example" successChannel := make(chan []byte) errorChannel := make(chan []byte) go pubnubInstance.Publish(channel, message, successChannel, errorChannel) select { case msg := <-successChannel: assert.Contains(string(msg), "1,") assert.Contains(string(msg), "\"Sent\",") case err := <-errorChannel: assert.Fail(string(err)) case <-timeout(): assert.Fail("Publish timeout") } }
func TestLoggingInWithoutOrg(t *testing.T) { configRepo := testhelpers.FakeConfigRepository{} configRepo.Delete() config, _ := configRepo.Get() ui := new(testhelpers.FakeUI) ui.Inputs = []string{"*****@*****.**", "bar"} orgs := []cf.Organization{} spaces := []cf.Space{} callLogin( []string{}, ui, configRepo, &testhelpers.FakeOrgRepository{Organizations: orgs}, &testhelpers.FakeSpaceRepository{Spaces: spaces}, &testhelpers.FakeAuthenticator{ConfigRepo: configRepo}, ) assert.Contains(t, ui.Outputs[0], config.Target) assert.Contains(t, ui.Prompts[0], "Username") assert.Contains(t, ui.Prompts[1], "Password") assert.Contains(t, ui.Outputs[2], "OK") assert.Contains(t, ui.Outputs[3], "No orgs found.") savedConfig := testhelpers.SavedConfiguration assert.Equal(t, cf.Organization{}, savedConfig.Organization) assert.Equal(t, cf.Space{}, savedConfig.Space) }
func test_Databases(t *testing.T) { res, err := testClient.Databases() assert.Equal(t, nil, err) assert.Contains(t, res, "booktown") assert.Contains(t, res, "postgres") }
func TestSuccessfullyLoggingInWithUsernameAsArgument(t *testing.T) { configRepo := testhelpers.FakeConfigRepository{} configRepo.Delete() config, _ := configRepo.Get() ui := new(testhelpers.FakeUI) ui.Inputs = []string{"bar"} auth := &testhelpers.FakeAuthenticator{ AccessToken: "my_access_token", RefreshToken: "my_refresh_token", ConfigRepo: configRepo, } callLogin( []string{"*****@*****.**"}, ui, configRepo, &testhelpers.FakeOrgRepository{}, &testhelpers.FakeSpaceRepository{}, auth, ) savedConfig := testhelpers.SavedConfiguration assert.Contains(t, ui.Outputs[0], config.Target) assert.Contains(t, ui.Outputs[2], "OK") assert.Contains(t, ui.Prompts[0], "Password") assert.Equal(t, savedConfig.AccessToken, "my_access_token") assert.Equal(t, savedConfig.RefreshToken, "my_refresh_token") assert.Equal(t, auth.Email, "*****@*****.**") assert.Equal(t, auth.Password, "bar") }
func TestLoggerIPAddress(t *testing.T) { e := echo.New() req, _ := http.NewRequest(echo.GET, "/", nil) rec := httptest.NewRecorder() c := echo.NewContext(req, echo.NewResponse(rec, e), e) buf := new(bytes.Buffer) e.Logger().SetOutput(buf) ip := "127.0.0.1" h := func(c *echo.Context) error { return c.String(http.StatusOK, "test") } mw := Logger() // With X-Real-IP req.Header.Add(echo.XRealIP, ip) mw(h)(c) assert.Contains(t, buf.String(), ip) // With X-Forwarded-For buf.Reset() req.Header.Del(echo.XRealIP) req.Header.Add(echo.XForwardedFor, ip) mw(h)(c) assert.Contains(t, buf.String(), ip) // with req.RemoteAddr buf.Reset() mw(h)(c) assert.Contains(t, buf.String(), ip) }
func TestGRPCLogger_Printf(t *testing.T) { b := bytes.NewBuffer(nil) l := log.NewJSONLogger(b) g := sklog.NewGRPCLogger(l) success := []struct { expected string format string args []interface{} }{ { expected: "message", format: "message", }, { expected: "message1, message2", format: "%s, %s", args: []interface{}{ "message1", "message2", }, }, } for _, data := range success { g.Printf(data.format, data.args...) assert.Contains(t, b.String(), sklog.LevelDebug) assert.Contains(t, b.String(), sklog.KeyLevel) assert.Contains(t, b.String(), data.expected) b.Reset() } }