How to use NewUI method of ui Package

Best Testkube code snippet using ui.NewUI

commands.go

Source:commands.go Github

copy

Full Screen

1package textui2import (3 "bufio"4 "encoding/json"5 "fmt"6 "github.com/piotrnar/gocoin"7 "github.com/piotrnar/gocoin/client/common"8 "github.com/piotrnar/gocoin/client/network"9 "github.com/piotrnar/gocoin/client/usif"10 "github.com/piotrnar/gocoin/lib/btc"11 "github.com/piotrnar/gocoin/lib/others/peersdb"12 "github.com/piotrnar/gocoin/lib/others/qdb"13 "github.com/piotrnar/gocoin/lib/others/sys"14 "io/ioutil"15 "os"16 "runtime"17 "runtime/debug"18 "sort"19 "strconv"20 "strings"21 "sync/atomic"22 "time"23)24type oneUiCmd struct {25 cmds []string // command name26 help string // a helf for this command27 sync bool // shall be executed in the blochcina therad28 handler func(pars string)29}30var (31 uiCmds []*oneUiCmd32 show_prompt bool = true33)34// newUi adds a new UI commend handler.35func newUi(cmds string, sync bool, hn func(string), help string) {36 cs := strings.Split(cmds, " ")37 if len(cs[0]) > 0 {38 var c = new(oneUiCmd)39 for i := range cs {40 c.cmds = append(c.cmds, cs[i])41 }42 c.sync = sync43 c.help = help44 c.handler = hn45 if len(uiCmds) > 0 {46 var i int47 for i = 0; i < len(uiCmds); i++ {48 if uiCmds[i].cmds[0] > c.cmds[0] {49 break // lets have them sorted50 }51 }52 tmp := make([]*oneUiCmd, len(uiCmds)+1)53 copy(tmp[:i], uiCmds[:i])54 tmp[i] = c55 copy(tmp[i+1:], uiCmds[i:])56 uiCmds = tmp57 } else {58 uiCmds = []*oneUiCmd{c}59 }60 } else {61 panic("empty command string")62 }63}64func readline() string {65 li, _, _ := bufio.NewReader(os.Stdin).ReadLine()66 return string(li)67}68func AskYesNo(msg string) bool {69 for {70 fmt.Print(msg, " (y/n) : ")71 l := strings.ToLower(readline())72 if l == "y" {73 return true74 } else if l == "n" {75 return false76 }77 }78 return false79}80func ShowPrompt() {81 fmt.Print("> ")82}83func MainThread() {84 time.Sleep(1e9) // hold on for 1 sencond before showing the show_prompt85 for !usif.Exit_now.Get() {86 if show_prompt {87 ShowPrompt()88 }89 show_prompt = true90 li := strings.Trim(readline(), " \n\t\r")91 if len(li) > 0 {92 cmdpar := strings.SplitN(li, " ", 2)93 cmd := cmdpar[0]94 param := ""95 if len(cmdpar) == 2 {96 param = cmdpar[1]97 }98 found := false99 for i := range uiCmds {100 for j := range uiCmds[i].cmds {101 if cmd == uiCmds[i].cmds[j] {102 found = true103 if uiCmds[i].sync {104 usif.ExecUiReq(&usif.OneUiReq{Param: param, Handler: uiCmds[i].handler})105 show_prompt = false106 } else {107 uiCmds[i].handler(param)108 }109 }110 }111 }112 if !found {113 fmt.Printf("Unknown command '%s'. Type 'help' for help.\n", cmd)114 }115 }116 }117}118func show_info(par string) {119 fmt.Println("main.go last seen in line:", common.BusyIn())120 network.MutexRcv.Lock()121 discarded := len(network.DiscardedBlocks)122 cached := network.CachedBlocksLen.Get()123 b2g_len := len(network.BlocksToGet)124 b2g_idx_len := len(network.IndexToBlocksToGet)125 network.MutexRcv.Unlock()126 fmt.Printf("Gocoin: %s, Synced: %t (%d), Uptime %s, Peers: %d, ECDSAs: %d\n",127 gocoin.Version, common.GetBool(&common.BlockChainSynchronized), network.HeadersReceived.Get(),128 time.Now().Sub(common.StartTime).String(), peersdb.PeerDB.Count(), btc.EcdsaVerifyCnt())129 // Memory used130 al, sy := sys.MemUsed()131 fmt.Printf("Heap_used: %d MB, System_used: %d MB, UTXO-X-mem: %d MB in %d recs, Saving: %t\n", al>>20, sy>>20,132 common.Memory.Bytes>>20, common.Memory.Allocs, common.BlockChain.Unspent.WritingInProgress.Get())133 network.MutexRcv.Lock()134 fmt.Println("Last Header:", network.LastCommitedHeader.BlockHash.String(), "@", network.LastCommitedHeader.Height)135 network.MutexRcv.Unlock()136 common.Last.Mutex.Lock()137 fmt.Println("Last Block :", common.Last.Block.BlockHash.String(), "@", common.Last.Block.Height)138 fmt.Printf(" Time: %s (~%s), Diff: %.0f, Rcvd: %s ago\n",139 time.Unix(int64(common.Last.Block.Timestamp()), 0).Format("2006/01/02 15:04:05"),140 time.Unix(int64(common.Last.Block.GetMedianTimePast()), 0).Format("15:04:05"),141 btc.GetDifficulty(common.Last.Block.Bits()), time.Now().Sub(common.Last.Time).String())142 common.Last.Mutex.Unlock()143 network.Mutex_net.Lock()144 fmt.Printf("Blocks Queued: %d, Cached: %d, Discarded: %d, To Get: %d/%d, UTXO.db on disk: %d\n",145 len(network.NetBlocks), cached, discarded, b2g_len, b2g_idx_len,146 atomic.LoadUint32(&common.BlockChain.Unspent.CurrentHeightOnDisk))147 network.Mutex_net.Unlock()148 network.TxMutex.Lock()149 var sw_cnt, sw_bts uint64150 for _, v := range network.TransactionsToSend {151 if v.SegWit != nil {152 sw_cnt++153 sw_bts += uint64(v.Size)154 }155 }156 fmt.Printf("Txs in mempool: %d (%sB), Using SegWit: %d (%sB), Rejected: %d (%sB)\n",157 len(network.TransactionsToSend), common.UintToString(network.TransactionsToSendSize),158 sw_cnt, common.UintToString(sw_bts),159 len(network.TransactionsRejected), common.UintToString(network.TransactionsRejectedSize))160 fmt.Printf(" Wait4Input: %d (%sB), SpentOuts: %d, AvgFee: %.1f SpB, Pending:%d/%d\n",161 len(network.WaitingForInputs), common.UintToString(network.WaitingForInputsSize),162 len(network.SpentOutputs), common.GetAverageFee(),163 len(network.TransactionsPending), len(network.NetTxs))164 network.TxMutex.Unlock()165 var gs debug.GCStats166 debug.ReadGCStats(&gs)167 usif.BlockFeesMutex.Lock()168 fmt.Println("Go version:", runtime.Version(), " LastGC:", time.Now().Sub(gs.LastGC).String(),169 " NumGC:", gs.NumGC,170 " PauseTotal:", gs.PauseTotal.String())171 usif.BlockFeesMutex.Unlock()172}173func show_counters(par string) {174 common.CounterMutex.Lock()175 ck := make([]string, 0)176 for k, _ := range common.Counter {177 if par == "" || strings.HasPrefix(k, par) {178 ck = append(ck, k)179 }180 }181 sort.Strings(ck)182 var li string183 for i := range ck {184 k := ck[i]185 v := common.Counter[k]186 s := fmt.Sprint(k, ": ", v)187 if len(li)+len(s) >= 80 {188 fmt.Println(li)189 li = ""190 } else if li != "" {191 li += ", "192 }193 li += s194 }195 if li != "" {196 fmt.Println(li)197 }198 common.CounterMutex.Unlock()199}200func show_pending(par string) {201 network.MutexRcv.Lock()202 out := make([]string, len(network.BlocksToGet))203 var idx int204 for _, v := range network.BlocksToGet {205 out[idx] = fmt.Sprintf(" * %d / %s / %d in progress", v.Block.Height, v.Block.Hash.String(), v.InProgress)206 idx++207 }208 network.MutexRcv.Unlock()209 sort.Strings(out)210 for _, s := range out {211 fmt.Println(s)212 }213}214func show_help(par string) {215 fmt.Println("The following", len(uiCmds), "commands are supported:")216 for i := range uiCmds {217 fmt.Print(" ")218 for j := range uiCmds[i].cmds {219 if j > 0 {220 fmt.Print(", ")221 }222 fmt.Print(uiCmds[i].cmds[j])223 }224 fmt.Println(" -", uiCmds[i].help)225 }226 fmt.Println("All the commands are case sensitive.")227}228func show_mem(p string) {229 al, sy := sys.MemUsed()230 fmt.Println("Allocated:", al>>20, "MB")231 fmt.Println("SystemMem:", sy>>20, "MB")232 if p == "" {233 return234 }235 if p == "free" {236 fmt.Println("Freeing the mem...")237 sys.FreeMem()238 show_mem("")239 return240 }241 if p == "gc" {242 fmt.Println("Running GC...")243 runtime.GC()244 fmt.Println("Done.")245 return246 }247 i, e := strconv.ParseInt(p, 10, 64)248 if e != nil {249 println(e.Error())250 return251 }252 debug.SetGCPercent(int(i))253 fmt.Println("GC treshold set to", i, "percent")254}255func dump_block(s string) {256 h := btc.NewUint256FromString(s)257 if h == nil {258 println("Specify block's hash")259 return260 }261 crec, _, er := common.BlockChain.Blocks.BlockGetExt(btc.NewUint256(h.Hash[:]))262 if er != nil {263 println("BlockGetExt:", er.Error())264 return265 }266 ioutil.WriteFile(h.String()+".bin", crec.Data, 0700)267 fmt.Println("Block saved")268 if crec.Block == nil {269 crec.Block, _ = btc.NewBlock(crec.Data)270 }271 /*272 if crec.Block.NoWitnessData == nil {273 crec.Block.BuildNoWitnessData()274 }275 if !bytes.Equal(crec.Data, crec.Block.NoWitnessData) {276 ioutil.WriteFile(h.String()+".old", crec.Block.NoWitnessData, 0700)277 fmt.Println("Old block saved")278 }279 */280}281func ui_quit(par string) {282 usif.Exit_now.Set()283}284func blchain_stats(par string) {285 fmt.Println(common.BlockChain.Stats())286}287func blchain_utxodb(par string) {288 fmt.Println(common.BlockChain.Unspent.UTXOStats())289}290func set_ulmax(par string) {291 v, e := strconv.ParseUint(par, 10, 64)292 if e == nil {293 common.SetUploadLimit(v << 10)294 }295 if common.UploadLimit() != 0 {296 fmt.Printf("Current upload limit is %d KB/s\n", common.UploadLimit()>>10)297 } else {298 fmt.Println("The upload speed is not limited")299 }300}301func set_dlmax(par string) {302 v, e := strconv.ParseUint(par, 10, 64)303 if e == nil {304 common.SetDownloadLimit(v << 10)305 }306 if common.DownloadLimit() != 0 {307 fmt.Printf("Current download limit is %d KB/s\n", common.DownloadLimit()>>10)308 } else {309 fmt.Println("The download speed is not limited")310 }311}312func set_config(s string) {313 common.LockCfg()314 defer common.UnlockCfg()315 if s != "" {316 new := common.CFG317 e := json.Unmarshal([]byte("{"+s+"}"), &new)318 if e != nil {319 println(e.Error())320 } else {321 common.CFG = new322 common.Reset()323 fmt.Println("Config changed. Execute configsave, if you want to save it.")324 }325 }326 dat, _ := json.MarshalIndent(&common.CFG, "", " ")327 fmt.Println(string(dat))328}329func load_config(s string) {330 d, e := ioutil.ReadFile(common.ConfigFile)331 if e != nil {332 println(e.Error())333 return334 }335 common.LockCfg()336 defer common.UnlockCfg()337 e = json.Unmarshal(d, &common.CFG)338 if e != nil {339 println(e.Error())340 return341 }342 common.Reset()343 fmt.Println("Config reloaded")344}345func save_config(s string) {346 common.LockCfg()347 if common.SaveConfig() {348 fmt.Println("Current settings saved to", common.ConfigFile)349 }350 common.UnlockCfg()351}352func show_addresses(par string) {353 fmt.Println(peersdb.PeerDB.Count(), "peers in the database")354 if par == "list" {355 cnt := 0356 peersdb.PeerDB.Browse(func(k qdb.KeyType, v []byte) uint32 {357 cnt++358 fmt.Printf("%4d) %s\n", cnt, peersdb.NewPeer(v).String())359 return 0360 })361 } else if par == "ban" {362 cnt := 0363 peersdb.PeerDB.Browse(func(k qdb.KeyType, v []byte) uint32 {364 pr := peersdb.NewPeer(v)365 if pr.Banned != 0 {366 cnt++367 fmt.Printf("%4d) %s\n", cnt, pr.String())368 }369 return 0370 })371 if cnt == 0 {372 fmt.Println("No banned peers in the DB")373 }374 } else if par != "" {375 limit, er := strconv.ParseUint(par, 10, 32)376 if er != nil {377 fmt.Println("Specify number of best peers to display")378 return379 }380 prs := peersdb.GetBestPeers(uint(limit), nil)381 for i := range prs {382 fmt.Printf("%4d) %s", i+1, prs[i].String())383 if network.ConnectionActive(prs[i]) {384 fmt.Print(" CONNECTED")385 }386 fmt.Print("\n")387 }388 } else {389 fmt.Println("Use 'peers list' to list them")390 fmt.Println("Use 'peers ban' to list the benned ones")391 fmt.Println("Use 'peers <number>' to show the most recent ones")392 }393}394func unban_peer(par string) {395 if par == "" {396 fmt.Println("Specify IP of the peer to unban or use 'unban all'")397 return398 }399 var ad *peersdb.PeerAddr400 if par != "all" {401 var er error402 ad, er = peersdb.NewAddrFromString(par, false)403 if er != nil {404 fmt.Println(par, er.Error())405 return406 }407 fmt.Println("Unban", ad.Ip(), "...")408 } else {409 fmt.Println("Unban all peers ...")410 }411 var keys []qdb.KeyType412 var vals [][]byte413 peersdb.PeerDB.Browse(func(k qdb.KeyType, v []byte) uint32 {414 peer := peersdb.NewPeer(v)415 if peer.Banned != 0 {416 if ad == nil || peer.Ip() == ad.Ip() {417 fmt.Println(" -", peer.NetAddr.String())418 peer.Banned = 0419 keys = append(keys, k)420 vals = append(vals, peer.Bytes())421 }422 }423 return 0424 })425 for i := range keys {426 peersdb.PeerDB.Put(keys[i], vals[i])427 }428 fmt.Println(len(keys), "peer(s) un-baned")429}430func show_cached(par string) {431 var hi, lo uint32432 for _, v := range network.CachedBlocks {433 //fmt.Printf(" * %s -> %s\n", v.Hash.String(), btc.NewUint256(v.ParentHash()).String())434 if hi == 0 {435 hi = v.Block.Height436 lo = v.Block.Height437 } else if v.Block.Height > hi {438 hi = v.Block.Height439 } else if v.Block.Height < lo {440 lo = v.Block.Height441 }442 }443 fmt.Println(len(network.CachedBlocks), "block cached with heights", lo, "to", hi, hi-lo)444}445func send_inv(par string) {446 cs := strings.Split(par, " ")447 if len(cs) != 2 {448 println("Specify hash and type")449 return450 }451 ha := btc.NewUint256FromString(cs[1])452 if ha == nil {453 println("Incorrect hash")454 return455 }456 v, e := strconv.ParseInt(cs[0], 10, 32)457 if e != nil {458 println("Incorrect type:", e.Error())459 return460 }461 network.NetRouteInv(uint32(v), ha, nil)462 fmt.Println("Inv sent to all peers")463}464func analyze_bip9(par string) {465 all := par == "all"466 n := common.BlockChain.BlockTreeRoot467 for n != nil {468 var i uint469 start_block := uint(n.Height)470 start_time := n.Timestamp()471 bits := make(map[byte]uint32)472 for i = 0; i < 2016 && n != nil; i++ {473 ver := n.BlockVersion()474 if (ver & 0x20000000) != 0 {475 for bit := byte(0); bit <= 28; bit++ {476 if (ver & (1 << bit)) != 0 {477 bits[bit]++478 }479 }480 }481 n = n.FindPathTo(common.BlockChain.LastBlock())482 }483 if len(bits) > 0 {484 var s string485 for k, v := range bits {486 if all || v >= common.BlockChain.Consensus.BIP9_Treshold {487 if s != "" {488 s += " | "489 }490 s += fmt.Sprint(v, " x bit(", k, ")")491 }492 }493 if s != "" {494 fmt.Println("Period from", time.Unix(int64(start_time), 0).Format("2006/01/02 15:04"),495 " block #", start_block, "-", start_block+i-1, ":", s, " - active from", start_block+2*2016)496 }497 }498 }499}500func switch_trust(par string) {501 if par == "0" {502 common.FLAG.TrustAll = false503 } else if par == "1" {504 common.FLAG.TrustAll = true505 }506 fmt.Println("Assume blocks trusted:", common.FLAG.TrustAll)507}508func save_utxo(par string) {509 //common.BlockChain.Unspent.HurryUp()510 common.BlockChain.Unspent.Save()511}512func purge_utxo(par string) {513 common.BlockChain.Unspent.PurgeUnspendable(true)514 if !common.CFG.Memory.PurgeUnspendableUTXO {515 fmt.Println("Save your config file (cs) to have all the futher records purged automatically.")516 common.CFG.Memory.PurgeUnspendableUTXO = true517 }518}519func init() {520 newUi("bchain b", true, blchain_stats, "Display blockchain statistics")521 newUi("bip9", true, analyze_bip9, "Analyze current blockchain for BIP9 bits (add 'all' to see more)")522 newUi("cache", true, show_cached, "Show blocks cached in memory")523 newUi("configload cl", false, load_config, "Re-load settings from the common file")524 newUi("configsave cs", false, save_config, "Save current settings to a common file")525 newUi("configset cfg", false, set_config, "Set a specific common value - use JSON, omit top {}")526 newUi("counters c", false, show_counters, "Show all kind of debug counters")527 newUi("dlimit dl", false, set_dlmax, "Set maximum download speed. The value is in KB/second - 0 for unlimited")528 newUi("help h ?", false, show_help, "Shows this help")529 newUi("info i", false, show_info, "Shows general info about the node")530 newUi("inv", false, send_inv, "Send inv message to all the peers - specify type & hash")531 newUi("mem", false, show_mem, "Show detailed memory stats (optionally free, gc or a numeric param)")532 newUi("peers", false, show_addresses, "Dump pers database (specify number)")533 newUi("pend", false, show_pending, "Show pending blocks, to be fetched")534 newUi("purge", true, purge_utxo, "Purge all unspendable outputs from UTXO database")535 newUi("quit q", false, ui_quit, "Quit the node")536 newUi("savebl", false, dump_block, "Saves a block with a given hash to a binary file")537 newUi("saveutxo s", true, save_utxo, "Save UTXO database now")538 newUi("trust t", true, switch_trust, "Assume all donwloaded blocks trusted (1) or un-trusted (0)")539 newUi("ulimit ul", false, set_ulmax, "Set maximum upload speed. The value is in KB/second - 0 for unlimited")540 newUi("unban", false, unban_peer, "Unban a peer specified by IP[:port] (or 'unban all')")541 newUi("utxo u", true, blchain_utxodb, "Display UTXO-db statistics")542}...

Full Screen

Full Screen

ui_test.go

Source:ui_test.go Github

copy

Full Screen

...31 printer := NewTeePrinter()32 printer.SetOutputBucket(bucket)33 io_helpers.SimulateStdin("", func(reader io.Reader) {34 output := io_helpers.CaptureOutput(func() {35 ui := NewUI(reader, printer, fakeLogger)36 ui.PrintCapturingNoOutput("Hello")37 })38 Expect("Hello").To(Equal(strings.Join(output, "")))39 Expect(bucket.Contents()).To(HaveLen(0))40 })41 })42 })43 Describe("Printing message to stdout with Say", func() {44 It("prints strings", func() {45 io_helpers.SimulateStdin("", func(reader io.Reader) {46 output := io_helpers.CaptureOutput(func() {47 ui := NewUI(reader, NewTeePrinter(), fakeLogger)48 ui.Say("Hello")49 })50 Expect("Hello").To(Equal(strings.Join(output, "")))51 })52 })53 It("prints formatted strings", func() {54 io_helpers.SimulateStdin("", func(reader io.Reader) {55 output := io_helpers.CaptureOutput(func() {56 ui := NewUI(reader, NewTeePrinter(), fakeLogger)57 ui.Say("Hello %s", "World!")58 })59 Expect("Hello World!").To(Equal(strings.Join(output, "")))60 })61 })62 It("does not format strings when provided no args", func() {63 output := io_helpers.CaptureOutput(func() {64 ui := NewUI(os.Stdin, NewTeePrinter(), fakeLogger)65 ui.Say("Hello %s World!") // whoops66 })67 Expect(strings.Join(output, "")).To(Equal("Hello %s World!"))68 })69 })70 Describe("Asking user for input", func() {71 It("allows string with whitespaces", func() {72 io_helpers.CaptureOutput(func() {73 io_helpers.SimulateStdin("foo bar\n", func(reader io.Reader) {74 ui := NewUI(reader, NewTeePrinter(), fakeLogger)75 Expect(ui.Ask("?")).To(Equal("foo bar"))76 })77 })78 })79 It("returns empty string if an error occured while reading string", func() {80 io_helpers.CaptureOutput(func() {81 io_helpers.SimulateStdin("string without expected delimiter", func(reader io.Reader) {82 ui := NewUI(reader, NewTeePrinter(), fakeLogger)83 Expect(ui.Ask("?")).To(Equal(""))84 })85 })86 })87 It("always outputs the prompt, even when output is disabled", func() {88 output := io_helpers.CaptureOutput(func() {89 io_helpers.SimulateStdin("things are great\n", func(reader io.Reader) {90 printer := NewTeePrinter()91 printer.DisableTerminalOutput(true)92 ui := NewUI(reader, printer, fakeLogger)93 ui.Ask("You like things?")94 })95 })96 Expect(strings.Join(output, "")).To(ContainSubstring("You like things?"))97 })98 })99 Describe("Confirming user input", func() {100 It("treats 'y' as an affirmative confirmation", func() {101 io_helpers.SimulateStdin("y\n", func(reader io.Reader) {102 out := io_helpers.CaptureOutput(func() {103 ui := NewUI(reader, NewTeePrinter(), fakeLogger)104 Expect(ui.Confirm("Hello World?")).To(BeTrue())105 })106 Expect(out).To(ContainSubstrings([]string{"Hello World?"}))107 })108 })109 It("treats 'yes' as an affirmative confirmation when default language is not en_US", func() {110 oldLang := os.Getenv("LC_ALL")111 defer os.Setenv("LC_ALL", oldLang)112 oldT := i18n.T113 defer func() {114 i18n.T = oldT115 }()116 os.Setenv("LC_ALL", "fr_FR")117 config := configuration.NewRepositoryWithDefaults()118 i18n.T = i18n.Init(config)119 io_helpers.SimulateStdin("yes\n", func(reader io.Reader) {120 out := io_helpers.CaptureOutput(func() {121 ui := NewUI(reader, NewTeePrinter(), fakeLogger)122 Expect(ui.Confirm("Hello World?")).To(BeTrue())123 })124 Expect(out).To(ContainSubstrings([]string{"Hello World?"}))125 })126 })127 It("treats 'yes' as an affirmative confirmation", func() {128 io_helpers.SimulateStdin("yes\n", func(reader io.Reader) {129 out := io_helpers.CaptureOutput(func() {130 ui := NewUI(reader, NewTeePrinter(), fakeLogger)131 Expect(ui.Confirm("Hello World?")).To(BeTrue())132 })133 Expect(out).To(ContainSubstrings([]string{"Hello World?"}))134 })135 })136 It("treats other input as a negative confirmation", func() {137 io_helpers.SimulateStdin("wat\n", func(reader io.Reader) {138 out := io_helpers.CaptureOutput(func() {139 ui := NewUI(reader, NewTeePrinter(), fakeLogger)140 Expect(ui.Confirm("Hello World?")).To(BeFalse())141 })142 Expect(out).To(ContainSubstrings([]string{"Hello World?"}))143 })144 })145 })146 Describe("Confirming deletion", func() {147 It("formats a nice output string with exactly one prompt", func() {148 io_helpers.SimulateStdin("y\n", func(reader io.Reader) {149 out := io_helpers.CaptureOutput(func() {150 ui := NewUI(reader, NewTeePrinter(), fakeLogger)151 Expect(ui.ConfirmDelete("fizzbuzz", "bizzbump")).To(BeTrue())152 })153 Expect(out).To(ContainSubstrings([]string{154 "Really delete the fizzbuzz",155 "bizzbump",156 "?> ",157 }))158 })159 })160 It("treats 'yes' as an affirmative confirmation", func() {161 io_helpers.SimulateStdin("yes\n", func(reader io.Reader) {162 out := io_helpers.CaptureOutput(func() {163 ui := NewUI(reader, NewTeePrinter(), fakeLogger)164 Expect(ui.ConfirmDelete("modelType", "modelName")).To(BeTrue())165 })166 Expect(out).To(ContainSubstrings([]string{"modelType modelName"}))167 })168 })169 It("treats other input as a negative confirmation and warns the user", func() {170 io_helpers.SimulateStdin("wat\n", func(reader io.Reader) {171 out := io_helpers.CaptureOutput(func() {172 ui := NewUI(reader, NewTeePrinter(), fakeLogger)173 Expect(ui.ConfirmDelete("modelType", "modelName")).To(BeFalse())174 })175 Expect(out).To(ContainSubstrings([]string{"Delete cancelled"}))176 })177 })178 })179 Describe("Confirming deletion with associations", func() {180 It("warns the user that associated objects will also be deleted", func() {181 io_helpers.SimulateStdin("wat\n", func(reader io.Reader) {182 out := io_helpers.CaptureOutput(func() {183 ui := NewUI(reader, NewTeePrinter(), fakeLogger)184 Expect(ui.ConfirmDeleteWithAssociations("modelType", "modelName")).To(BeFalse())185 })186 Expect(out).To(ContainSubstrings([]string{"Delete cancelled"}))187 })188 })189 })190 Context("when user is not logged in", func() {191 var config core_config.Reader192 BeforeEach(func() {193 config = testconfig.NewRepository()194 })195 It("prompts the user to login", func() {196 output := io_helpers.CaptureOutput(func() {197 ui := NewUI(os.Stdin, NewTeePrinter(), fakeLogger)198 ui.ShowConfiguration(config)199 })200 Expect(output).ToNot(ContainSubstrings([]string{"API endpoint:"}))201 Expect(output).To(ContainSubstrings([]string{"Not logged in", "Use", "log in"}))202 })203 })204 Context("when an api endpoint is set and the user logged in", func() {205 var config core_config.ReadWriter206 BeforeEach(func() {207 accessToken := core_config.TokenInfo{208 UserGuid: "my-user-guid",209 Username: "my-user",210 Email: "my-user-email",211 }212 config = testconfig.NewRepositoryWithAccessToken(accessToken)213 config.SetApiEndpoint("https://test.example.org")214 config.SetApiVersion("☃☃☃")215 })216 Describe("tells the user what is set in the config", func() {217 var output []string218 JustBeforeEach(func() {219 output = io_helpers.CaptureOutput(func() {220 ui := NewUI(os.Stdin, NewTeePrinter(), fakeLogger)221 ui.ShowConfiguration(config)222 })223 })224 It("tells the user which api endpoint is set", func() {225 Expect(output).To(ContainSubstrings([]string{"API endpoint:", "https://test.example.org"}))226 })227 It("tells the user the api version", func() {228 Expect(output).To(ContainSubstrings([]string{"API version:", "☃☃☃"}))229 })230 It("tells the user which user is logged in", func() {231 Expect(output).To(ContainSubstrings([]string{"User:", "my-user-email"}))232 })233 Context("when an org is targeted", func() {234 BeforeEach(func() {235 config.SetOrganizationFields(models.OrganizationFields{236 Name: "org-name",237 Guid: "org-guid",238 })239 })240 It("tells the user which org is targeted", func() {241 Expect(output).To(ContainSubstrings([]string{"Org:", "org-name"}))242 })243 })244 Context("when a space is targeted", func() {245 BeforeEach(func() {246 config.SetSpaceFields(models.SpaceFields{247 Name: "my-space",248 Guid: "space-guid",249 })250 })251 It("tells the user which space is targeted", func() {252 Expect(output).To(ContainSubstrings([]string{"Space:", "my-space"}))253 })254 })255 })256 It("prompts the user to target an org and space when no org or space is targeted", func() {257 output := io_helpers.CaptureOutput(func() {258 ui := NewUI(os.Stdin, NewTeePrinter(), fakeLogger)259 ui.ShowConfiguration(config)260 })261 Expect(output).To(ContainSubstrings([]string{"No", "org", "space", "targeted", "-o ORG", "-s SPACE"}))262 })263 It("prompts the user to target an org when no org is targeted", func() {264 sf := models.SpaceFields{}265 sf.Guid = "guid"266 sf.Name = "name"267 output := io_helpers.CaptureOutput(func() {268 ui := NewUI(os.Stdin, NewTeePrinter(), fakeLogger)269 ui.ShowConfiguration(config)270 })271 Expect(output).To(ContainSubstrings([]string{"No", "org", "targeted", "-o ORG"}))272 })273 It("prompts the user to target a space when no space is targeted", func() {274 of := models.OrganizationFields{}275 of.Guid = "of-guid"276 of.Name = "of-name"277 output := io_helpers.CaptureOutput(func() {278 ui := NewUI(os.Stdin, NewTeePrinter(), fakeLogger)279 ui.ShowConfiguration(config)280 })281 Expect(output).To(ContainSubstrings([]string{"No", "space", "targeted", "-s SPACE"}))282 })283 })284 Describe("failing", func() {285 It("panics with a specific string", func() {286 io_helpers.CaptureOutput(func() {287 testassert.AssertPanic(QuietPanic, func() {288 NewUI(os.Stdin, NewTeePrinter(), fakeLogger).Failed("uh oh")289 })290 })291 })292 Context("when 'T' func is not initialized", func() {293 var t go_i18n.TranslateFunc294 BeforeEach(func() {295 t = i18n.T296 i18n.T = nil297 })298 AfterEach(func() {299 i18n.T = t300 })301 It("does not use 'T' func to translate", func() {302 io_helpers.CaptureOutput(func() {303 testassert.AssertPanic(QuietPanic, func() {304 NewUI(os.Stdin, NewTeePrinter(), fakeLogger).Failed("uh oh")305 })306 })307 })308 It("does not duplicate output if logger is set to stdout", func() {309 output := io_helpers.CaptureOutput(func() {310 testassert.AssertPanic(QuietPanic, func() {311 logger := trace.NewWriterPrinter(os.Stdout, true)312 NewUI(os.Stdin, NewTeePrinter(), logger).Failed("this should print only once")313 })314 })315 Expect(output).To(HaveLen(3))316 Expect(output[0]).To(Equal("FAILED"))317 Expect(output[1]).To(Equal("this should print only once"))318 Expect(output[2]).To(Equal(""))319 })320 })321 Context("when 'T' func is initialized", func() {322 It("does not duplicate output if logger is set to stdout", func() {323 output := io_helpers.CaptureOutput(func() {324 testassert.AssertPanic(QuietPanic, func() {325 logger := trace.NewWriterPrinter(os.Stdout, true)326 NewUI(os.Stdin, NewTeePrinter(), logger).Failed("this should print only once")327 })328 })329 Expect(output).To(HaveLen(3))330 Expect(output[0]).To(Equal("FAILED"))331 Expect(output[1]).To(Equal("this should print only once"))332 Expect(output[2]).To(Equal(""))333 })334 })335 })336 Describe("NotifyUpdateIfNeeded", func() {337 var (338 output []string339 config core_config.ReadWriter340 )341 BeforeEach(func() {342 config = testconfig.NewRepository()343 })344 It("Prints a notification to user if current version < min cli version", func() {345 config.SetMinCliVersion("6.0.0")346 config.SetMinRecommendedCliVersion("6.5.0")347 config.SetApiVersion("2.15.1")348 cf.Version = "5.0.0"349 output = io_helpers.CaptureOutput(func() {350 ui := NewUI(os.Stdin, NewTeePrinter(), fakeLogger)351 ui.NotifyUpdateIfNeeded(config)352 })353 Expect(output).To(ContainSubstrings([]string{"Cloud Foundry API version",354 "requires CLI version 6.0.0",355 "You are currently on version 5.0.0",356 "To upgrade your CLI, please visit: https://github.com/cloudfoundry/cli#downloads",357 }))358 })359 It("Doesn't print a notification to user if current version >= min cli version", func() {360 config.SetMinCliVersion("6.0.0")361 config.SetMinRecommendedCliVersion("6.5.0")362 config.SetApiVersion("2.15.1")363 cf.Version = "6.0.0"364 output = io_helpers.CaptureOutput(func() {365 ui := NewUI(os.Stdin, NewTeePrinter(), fakeLogger)366 ui.NotifyUpdateIfNeeded(config)367 })368 Expect(output[0]).To(Equal(""))369 })370 })371})...

Full Screen

Full Screen

format_test.go

Source:format_test.go Github

copy

Full Screen

1package command2import (3 "bytes"4 "os"5 "strings"6 "testing"7 "github.com/ghodss/yaml"8 "github.com/hashicorp/vault/api"9 "github.com/hashicorp/vault/sdk/helper/jsonutil"10)11var output string12type mockUi struct {13 t *testing.T14 SampleData string15}16func (m mockUi) Ask(_ string) (string, error) {17 m.t.FailNow()18 return "", nil19}20func (m mockUi) AskSecret(_ string) (string, error) {21 m.t.FailNow()22 return "", nil23}24func (m mockUi) Output(s string) { output = s }25func (m mockUi) Info(s string) { m.t.Log(s) }26func (m mockUi) Error(s string) { m.t.Log(s) }27func (m mockUi) Warn(s string) { m.t.Log(s) }28func TestJsonFormatter(t *testing.T) {29 os.Setenv(EnvVaultFormat, "json")30 ui := mockUi{t: t, SampleData: "something"}31 if err := outputWithFormat(ui, nil, ui); err != 0 {32 t.Fatal(err)33 }34 var newUi mockUi35 if err := jsonutil.DecodeJSON([]byte(output), &newUi); err != nil {36 t.Fatal(err)37 }38 if newUi.SampleData != ui.SampleData {39 t.Fatalf(`values not equal ("%s" != "%s")`,40 newUi.SampleData,41 ui.SampleData)42 }43}44func TestYamlFormatter(t *testing.T) {45 os.Setenv(EnvVaultFormat, "yaml")46 ui := mockUi{t: t, SampleData: "something"}47 if err := outputWithFormat(ui, nil, ui); err != 0 {48 t.Fatal(err)49 }50 var newUi mockUi51 err := yaml.Unmarshal([]byte(output), &newUi)52 if err != nil {53 t.Fatal(err)54 }55 if newUi.SampleData != ui.SampleData {56 t.Fatalf(`values not equal ("%s" != "%s")`,57 newUi.SampleData,58 ui.SampleData)59 }60}61func TestTableFormatter(t *testing.T) {62 os.Setenv(EnvVaultFormat, "table")63 ui := mockUi{t: t}64 s := api.Secret{Data: map[string]interface{}{"k": "something"}}65 if err := outputWithFormat(ui, &s, &s); err != 0 {66 t.Fatal(err)67 }68 if !strings.Contains(output, "something") {69 t.Fatal("did not find 'something'")70 }71}72func Test_Format_Parsing(t *testing.T) {73 defer func() {74 os.Setenv(EnvVaultCLINoColor, "")75 os.Setenv(EnvVaultFormat, "")76 }()77 cases := []struct {78 name string79 args []string80 out string81 code int82 }{83 {84 "format",85 []string{"token", "renew", "-format", "json"},86 "{",87 0,88 },89 {90 "format_bad",91 []string{"token", "renew", "-format", "nope-not-real"},92 "Invalid output format",93 1,94 },95 }96 for _, tc := range cases {97 tc := tc98 t.Run(tc.name, func(t *testing.T) {99 client, closer := testVaultServer(t)100 defer closer()101 stdout := bytes.NewBuffer(nil)102 stderr := bytes.NewBuffer(nil)103 runOpts := &RunOptions{104 Stdout: stdout,105 Stderr: stderr,106 Client: client,107 }108 // Login with the token so we can renew-self.109 token, _ := testTokenAndAccessor(t, client)110 client.SetToken(token)111 code := RunCustom(tc.args, runOpts)112 if code != tc.code {113 t.Errorf("expected %d to be %d", code, tc.code)114 }115 combined := stdout.String() + stderr.String()116 if !strings.Contains(combined, tc.out) {117 t.Errorf("expected %q to contain %q", combined, tc.out)118 }119 })120 }121}...

Full Screen

Full Screen

NewUI

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 err := termui.Init()4 if err != nil {5 panic(err)6 }7 defer termui.Close()8 termui.UseTheme("helloworld")9 p := termui.NewPar("This is a paragraph")10 termui.Render(p)11 termui.Handle("/sys/kbd/q", func(termui.Event) {12 termui.StopLoop()13 })14 termui.Loop()15}16import (17func main() {18 err := termui.Init()19 if err != nil {20 panic(err)21 }22 defer termui.Close()23 termui.UseTheme("helloworld")24 p := termui.NewPar("This is a paragraph")25 termui.Render(p)26 termui.Handle("/sys/kbd/q", func(termui.Event) {27 termui.StopLoop()28 })29 termui.Loop()30}31import (32func main() {33 err := termui.Init()34 if err != nil {35 panic(err)36 }37 defer termui.Close()38 termui.UseTheme("helloworld")39 p := termui.NewPar("This is a paragraph")40 termui.Render(p)41 termui.Handle("/sys/kbd/q", func(termui.Event) {42 termui.StopLoop()43 })44 termui.Loop()45}46import (

Full Screen

Full Screen

NewUI

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 err := ui.Main(func() {4 name := ui.NewEntry()5 button := ui.NewButton("Greet")6 greeting := ui.NewLabel("")7 box := ui.NewVerticalBox()8 box.Append(ui.NewLabel("Enter your name:"), false)9 box.Append(name, false)10 box.Append(button, false)11 box.Append(greeting, false)12 window := ui.NewWindow("Hello", 200, 100, false)13 window.SetChild(box)14 button.OnClicked(func(*ui.Button) {15 greeting.SetText("Hello, " + name.Text() + "!")16 })17 window.OnClosing(func(*ui.Window) bool {18 ui.Quit()19 })20 window.Show()21 })22 if err != nil {23 panic(err)24 }25}26import (27func main() {28 err := ui.Main(func() {29 name := ui.NewEntry()30 button := ui.NewButton("Greet")31 greeting := ui.NewLabel("")32 box := ui.NewVerticalBox()33 box.Append(ui.NewLabel("Enter your name:"), false)34 box.Append(name, false)35 box.Append(button, false)36 box.Append(greeting, false)37 window := ui.NewWindow("Hello", 200, 100, false)38 window.SetChild(box)39 button.OnClicked(func(*ui.Button) {40 greeting.SetText("Hello, " + name.Text() + "!")41 })42 window.OnClosing(func(*ui.Window) bool {43 ui.Quit()44 })45 window.Show()46 })47 if err != nil {48 panic(err)49 }50}51import (52func main() {53 err := ui.Main(func() {54 name := ui.NewEntry()55 button := ui.NewButton("Greet")56 greeting := ui.NewLabel("")57 box := ui.NewVerticalBox()58 box.Append(ui.NewLabel("Enter your name:"), false)59 box.Append(name, false)60 box.Append(button

Full Screen

Full Screen

NewUI

Using AI Code Generation

copy

Full Screen

1import (2const (3func main() {4 opts := []selenium.ServiceOption{5 }6 selenium.SetDebug(true)7 service, err := selenium.NewSeleniumService(seleniumPath, port, opts...)8 if err != nil {9 }10 defer service.Stop()11 caps := selenium.Capabilities{"browserName": "chrome"}12 caps.AddChrome(chrome.Capabilities{13 Args: []string{14 },15 })16 if err != nil {17 panic(err)18 }19 defer wd.Quit()20 panic(err)21 }22 if err := wd.WaitWithTimeout(selenium.Condition{23 Func: func(wd selenium.WebDriver) (bool, error) {24 return wd.Title() == "The Go Playground", nil25 },26 }, 10*time.Second); err != nil {27 panic(err)28 }29 elem, err := wd.FindElement(selenium.ByID, "code")30 if err != nil {31 panic(err)32 }

Full Screen

Full Screen

NewUI

Using AI Code Generation

copy

Full Screen

1import "fmt"2func main() {3 fmt.Println("Hello, playground")4}5import "fmt"6func main() {7 fmt.Println("Hello, playground")8}9import "fmt"10func main() {11 fmt.Println("Hello, playground")12}13import "fmt"14func main() {15 fmt.Println("Hello, playground")16}17import "fmt"18func main() {19 fmt.Println("Hello, playground")20}21import "fmt"22func main() {23 fmt.Println("Hello, playground")24}25import "fmt"26func main() {27 fmt.Println("Hello, playground")28}29import "fmt"30func main() {31 fmt.Println("Hello, playground")32}33import "fmt"34func main() {35 fmt.Println("Hello, playground")36}37import "fmt"38func main() {39 fmt.Println("Hello, playground")40}41import "fmt"42func main() {43 fmt.Println("Hello, playground")44}45import "fmt"46func main() {47 fmt.Println("Hello, playground")48}49import "fmt"50func main() {51 fmt.Println("Hello, playground")52}53import

Full Screen

Full Screen

NewUI

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println("Hello, playground")4 ui.NewUI()5}6import (7func main() {8 fmt.Println("Hello, playground")9 ui.NewUI()10}11import (12func main() {13 fmt.Println("Hello, playground")14 ui.NewUI()15}16import (17func main() {18 fmt.Println("Hello, playground")19 ui.NewUI()20}21import (22func main() {23 fmt.Println("Hello, playground")24 ui.NewUI()25}26import (27func main() {28 fmt.Println("Hello, playground")29 ui.NewUI()30}31import (32func main() {33 fmt.Println("Hello, playground")34 ui.NewUI()35}36import (37func main() {38 fmt.Println("Hello, playground")39 ui.NewUI()40}41import (42func main() {43 fmt.Println("Hello, playground")44 ui.NewUI()45}46import (47func main() {48 fmt.Println("Hello, playground")49 ui.NewUI()50}51import (52func main() {53 fmt.Println("Hello, playground")54 ui.NewUI()

Full Screen

Full Screen

NewUI

Using AI Code Generation

copy

Full Screen

1import "fmt"2func main() {3 ui := NewUI()4 ui.Start()5}6import "fmt"7type UI struct {8}9func NewUI() *UI {10 return &UI{}11}12func (ui *UI) Start() {13 fmt.Println("UI started")14}15import "testing"16func TestUI(t *testing.T) {17 ui := NewUI()18 if ui == nil {19 t.Error("ui is nil")20 }21}22import "testing"23func TestUI(t *testing.T) {24 ui := NewUI()25 if ui == nil {26 t.Error("ui is nil")27 }28}29import "fmt"30type UI struct {31}32func NewUI() *UI {33 return &UI{}34}35func (ui *UI) Start() {36 fmt.Println("UI started")37}38import "fmt"39func main() {40 ui := NewUI()41 ui.Start()42}43import "testing"44func TestUI(t *testing.T) {45 ui := NewUI()46 if ui == nil {47 t.Error("ui is nil")48 }49}50import "fmt"51type UI struct {52}53func NewUI() *UI {54 return &UI{}55}56func (ui *UI) Start() {57 fmt.Println("UI started")58}59import "testing"60func TestUI(t *testing.T) {61 ui := NewUI()62 if ui == nil {63 t.Error("ui is nil")64 }65}66import "fmt"67func main() {68 ui := NewUI()69 ui.Start()70}

Full Screen

Full Screen

NewUI

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 ui := NewUI()4 ui.Print("Hello")5}6import (7func main() {8 ui := NewUI()9 ui.Print("Hello")10}11import (12func main() {13 ui := NewUI()14 ui.Print("Hello")15}16import (17func main() {18 ui := NewUI()19 ui.Print("Hello")20}21import (22func main() {23 ui := NewUI()24 ui.Print("Hello")25}26import (27func main() {28 ui := NewUI()29 ui.Print("Hello")30}31import (32func main() {33 ui := NewUI()34 ui.Print("Hello")35}36import (37func main() {38 ui := NewUI()39 ui.Print("Hello")40}41import (42func main() {43 ui := NewUI()44 ui.Print("Hello")45}46import (

Full Screen

Full Screen

NewUI

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 ui := ui.NewUI()4 fmt.Println(ui)5}6import (7func main() {8 ui := ui.NewUI()9 fmt.Println(ui)10}11import (12func main() {13 ui := ui.NewUI()14 fmt.Println(ui)15}16import (17func main() {18 ui := ui.NewUI()19 fmt.Println(ui)20}21import (22func main() {23 ui := ui.NewUI()24 fmt.Println(ui)25}26import (27func main() {28 ui := ui.NewUI()29 fmt.Println(ui)30}31import (32func main() {33 ui := ui.NewUI()34 fmt.Println(ui)35}

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful