Best K6 code snippet using js.ExitCode
go-horse_test.go
Source:go-horse_test.go
...40func TestRun(t *testing.T) {41 Convey("docker run --name e2e-test-container -d redis", t, func() {42 result := icmd.RunCommand("docker", "-H", "tcp://localhost:8080", "run", "--name", "e2e-test-container", "-d", "redis")43 So(len(strings.TrimSpace(result.Stdout())), ShouldEqual, 64)44 So(result.ExitCode, ShouldEqual, 0)45 })46}47func TestRemove(t *testing.T) {48 Convey("docker run -f e2e-test-container", t, func() {49 result := icmd.RunCommand("docker", "-H", "tcp://localhost:7070", "rm", "-f", "e2e-test-container")50 So(strings.TrimSpace(result.Stdout()), ShouldEqual, "e2e-test-container")51 So(result.ExitCode, ShouldEqual, 0)52 })53}54func TestAttach(t *testing.T) {55 Convey("docker run --name attach -d redis", t, func(c C) {56 var resultRun *icmd.Result57 var resultAttach *icmd.Result58 var resultStop *icmd.Result59 done := make(chan bool)60 resultRun = icmd.RunCommand("docker", "-H", "tcp://localhost:7070", "run", "--name", "attach", "-d", "redis")61 go func() {62 resultAttach = icmd.RunCommand("docker", "-H", "tcp://localhost:7070", "attach", "attach")63 }()64 go func() {65 resultStop = icmd.RunCommand("docker", "-H", "tcp://localhost:7070", "container", "stop", "attach")66 time.Sleep(1 * time.Second)67 done <- true68 }()69 <-done70 So(resultAttach.ExitCode, ShouldEqual, 1)71 So(resultRun.ExitCode, ShouldEqual, 0)72 So(resultStop.ExitCode, ShouldEqual, 0)73 // So(resultAttach.Stdout(), ShouldEndWith, "# Redis is now ready to exit, bye bye...\n")74 resultStop = icmd.RunCommand("docker", "-H", "tcp://localhost:7070", "rm", "-f", "attach")75 })76}77func TestBuild(t *testing.T) {78 Convey("docker build -t image-teste-build ./buildtest", t, func() {79 resultBuild := icmd.RunCommand("docker", "-H", "tcp://localhost:7070", "build", "-t", "image-teste-build", "build/")80 So(resultBuild.ExitCode, ShouldEqual, 0)81 So(resultBuild.Stdout(), ShouldContainSubstring, "Successfully built")82 resultRun := icmd.RunCommand("docker", "-H", "tcp://localhost:7070", "run", "-d", "image-teste-build")83 resultLogs := icmd.RunCommand("docker", "-H", "tcp://localhost:7070", "logs", strings.TrimSpace(resultRun.Stdout()))84 So(resultLogs.Stdout(), ShouldEqual, "GO-HORSE build command test\n")85 resultRm := icmd.RunCommand("docker", "-H", "tcp://localhost:7070", "rm", "-f", strings.TrimSpace(resultRun.Stdout()))86 So(resultRm.ExitCode, ShouldEqual, 0)87 })88}89func TestCommit(t *testing.T) {90 Convey("docker commit", t, func() {91 resultRun := icmd.RunCommand("docker", "-H", "tcp://localhost:7070", "run", "-d", "redis")92 So(resultRun.ExitCode, ShouldEqual, 0)93 containerID := strings.TrimSpace(resultRun.Stdout())94 resultExec := icmd.RunCommand("docker", "-H", "tcp://localhost:7070", "exec", containerID, "bash", "-c", "echo go-horse_commit_test > /test.test")95 So(resultExec.ExitCode, ShouldEqual, 0)96 resultCommit := icmd.RunCommand("docker", "-H", "tcp://localhost:7070", "commit", containerID, "commit_test")97 So(resultCommit.ExitCode, ShouldEqual, 0)98 resultRunCommit := icmd.RunCommand("docker", "-H", "tcp://localhost:7070", "run", "-d", "commit_test")99 containerCommitID := strings.TrimSpace(resultRunCommit.Stdout())100 So(resultRunCommit.ExitCode, ShouldEqual, 0)101 resultExecCommit := icmd.RunCommand("docker", "-H", "tcp://localhost:7070", "exec", containerCommitID, "bash", "-c", "cat /test.test")102 So(resultExecCommit.ExitCode, ShouldEqual, 0)103 So(strings.TrimSpace(resultExecCommit.Stdout()), ShouldEqual, "go-horse_commit_test")104 resultRMs := icmd.RunCommand("docker", "-H", "tcp://localhost:7070", "rm", "-f", containerCommitID, containerID)105 So(resultRMs.ExitCode, ShouldEqual, 0)106 })107}108func TestCP(t *testing.T) {109 Convey("docker cp", t, func() {110 resultRun := icmd.RunCommand("docker", "-H", "tcp://localhost:7070", "run", "--name", "cp_test", "-d", "redis")111 So(resultRun.ExitCode, ShouldEqual, 0)112 resultCp := icmd.RunCommand("docker", "-H", "tcp://localhost:7070", "cp", "build/Dockerfile", "cp_test:/data")113 So(resultCp.ExitCode, ShouldEqual, 0)114 resultExec := icmd.RunCommand("docker", "-H", "tcp://localhost:7070", "exec", "cp_test", "ls")115 So(resultExec.ExitCode, ShouldEqual, 0)116 So(strings.TrimSpace(resultExec.Stdout()), ShouldEqual, "Dockerfile")117 resultRM := icmd.RunCommand("docker", "-H", "tcp://localhost:7070", "rm", "-f", strings.TrimSpace(resultRun.Stdout()))118 So(resultRM.ExitCode, ShouldEqual, 0)119 })120}121func TestContainerStats(t *testing.T) {122 Convey("docker container stats", t, func() {123 resultRun := icmd.RunCommand("docker", "-H", "tcp://localhost:7070", "run", "--name", "stats_container", "-d", "redis")124 So(resultRun.ExitCode, ShouldEqual, 0)125 var resultStats *icmd.Result126 done := make(chan string)127 go func() {128 command := icmd.Cmd{Command: append([]string{"docker", "-H", "tcp://localhost:7070", "stats", "stats_container"}), Timeout: 5 * time.Second}129 resultStats = icmd.StartCmd(command)130 time.Sleep(5 * time.Second)131 resultStats.Cmd.Process.Signal(os.Interrupt)132 done <- resultStats.Combined()133 }()134 msg := <-done135 So(msg, ShouldContainSubstring, "CONTAINER ID")136 So(msg, ShouldContainSubstring, "CPU %")137 So(msg, ShouldContainSubstring, "MEM USAGE / LIMIT")138 So(msg, ShouldContainSubstring, "NET I/O")139 So(msg, ShouldContainSubstring, "stats_container")140 So(resultStats.ExitCode, ShouldEqual, 0)141 resultRM := icmd.RunCommand("docker", "-H", "tcp://localhost:7070", "rm", "-f", strings.TrimSpace(resultRun.Stdout()))142 So(resultRM.ExitCode, ShouldEqual, 0)143 })144}145// func TestStackDeploy(t *testing.T) {146// Convey("docker swarm all-in-one test suite", t, func() {147// resultSwarmInit := icmd.RunCommand("docker", "-H", "tcp://localhost:7070", "swarm", "init")148// So(resultSwarmInit.ExitCode, ShouldEqual, 0)149// So(strings.TrimSpace(resultSwarmInit.Stdout()), ShouldStartWith, "Swarm initialized")150// // fmt.Println("swarm init :: ", resultSwarmInit.Combined())151// resultStackDeploy := icmd.RunCommand("docker", "-H", "tcp://localhost:7070", "stack", "deploy", "--compose-file", "stack-deploy/docker-compose.yml", "stack-test")152// So(resultStackDeploy.ExitCode, ShouldEqual, 0)153// // fmt.Println("stack deploy :: ", resultStackDeploy.Combined())154// resultStackLs := icmd.RunCommand("docker", "-H", "tcp://localhost:7070", "stack", "ls")155// So(resultStackLs.ExitCode, ShouldEqual, 0)156// // fmt.Println("stack ls :: ", resultStackLs.Combined())157// resultServiceLs := icmd.RunCommand("docker", "-H", "tcp://localhost:7070", "service", "ls")158// So(resultServiceLs.ExitCode, ShouldEqual, 0)159// // fmt.Println("service ls :: ", resultServiceLs.Combined())160// var resultServiceLogs *icmd.Result161// done := make(chan string)162// go func() {163// command := icmd.Cmd{Command: append([]string{"docker", "-H", "tcp://localhost:7070", "service", "logs", "stack-test_redis"})}164// resultServiceLogs = icmd.StartCmd(command)165// time.Sleep(3 * time.Second)166// resultServiceLogs.Cmd.Process.Signal(os.Interrupt)167// done <- resultServiceLogs.Stdout()168// }()169// logs := <-done170// So(resultServiceLogs.ExitCode, ShouldEqual, 0)171// So(logs, ShouldContainSubstring, "Redis version")172// So(logs, ShouldContainSubstring, "Server initialized")173// So(logs, ShouldContainSubstring, "Ready to accept connections")174// // fmt.Println("service logs :: ", logs)175// resultStackRm := icmd.RunCommand("docker", "-H", "tcp://localhost:7070", "stack", "rm", "stack-test")176// So(resultStackRm.ExitCode, ShouldEqual, 0)177// // fmt.Println("stack rm :: ", resultStackRm.Combined())178// resultSwarmLeave := icmd.RunCommand("docker", "-H", "tcp://localhost:7070", "swarm", "leave", "--force")179// So(resultSwarmLeave.ExitCode, ShouldEqual, 0)180// So(strings.TrimSpace(resultSwarmLeave.Stdout()), ShouldEqual, "Node left the swarm.")181// // fmt.Println("swarm leave :: ", resultSwarmLeave.Combined())182// })183// }184func TestGoHorseNoFilters(t *testing.T) {185 Convey("go horse : no active filters", t, func() {186 removeContents(config.JsFiltersPath)187 time.Sleep(time.Second) // see list.go line 140188 response, err := http.Get("http://localhost:7070/active-filters")189 So(err, ShouldBeNil)190 So(response, ShouldNotBeNil)191 defer response.Body.Close()192 bodyBytes, er := ioutil.ReadAll(response.Body)193 So(er, ShouldBeNil)194 So(bodyBytes, ShouldNotBeNil)195 json := string(bodyBytes)196 requestFilters := gjson.Get(json, "request")197 responseFilters := gjson.Get(json, "response")198 resultPS := icmd.RunCommand("docker", "-H", "tcp://localhost:7070", "ps")199 So(requestFilters.Raw, ShouldBeIn, []string{"null", "[]"})200 So(responseFilters.Raw, ShouldBeIn, []string{"null", "[]"})201 So(resultPS.ExitCode, ShouldEqual, 0)202 So(strings.TrimSpace(resultPS.Stdout()), ShouldEndWith, "NAMES")203 })204}205func TestGoHorseOneResponseFilterRewritePsCommandBody(t *testing.T) {206 Convey("go horse : one active filter -> rewriting docker ps daemon response body", t, func() {207 er := removeContents(config.JsFiltersPath)208 So(er, ShouldBeNil)209 er = copy("jsFilters/000.response.rewrite_body_ps_command.js", config.JsFiltersPath+"/000.response.rewrite_body_ps_command.js")210 So(er, ShouldBeNil)211 time.Sleep(time.Second) // DirWatcher interval : 1 second loop212 response, err := http.Get("http://localhost:7070/active-filters")213 So(err, ShouldBeNil)214 So(response, ShouldNotBeNil)215 defer response.Body.Close()216 bodyBytes, er := ioutil.ReadAll(response.Body)217 So(er, ShouldBeNil)218 So(bodyBytes, ShouldNotBeNil)219 json := string(bodyBytes)220 requestFilters := gjson.Get(json, "request")221 responseFilters := gjson.Get(json, "response")222 resultPS := icmd.RunCommand("docker", "-H", "tcp://localhost:7070", "ps")223 So(requestFilters.Raw, ShouldBeIn, []string{"null", "[]"})224 So(responseFilters.Raw, ShouldStartWith, "[{\"Name\":\"rewrite_body_ps_command\",\"Order\":0,\"PathPattern\":\"containers/json")225 So(resultPS.ExitCode, ShouldEqual, 0)226 So(strings.TrimSpace(resultPS.Stdout()), ShouldContainSubstring, "go-horse")227 So(strings.TrimSpace(resultPS.Stdout()), ShouldContainSubstring, "go-horse.sh")228 So(strings.TrimSpace(resultPS.Stdout()), ShouldContainSubstring, "go-horse-image")229 So(strings.TrimSpace(resultPS.Stdout()), ShouldContainSubstring, "go-horse-name")230 So(strings.TrimSpace(resultPS.Stdout()), ShouldContainSubstring, "About a go-horse ago")231 removeContents(config.JsFiltersPath)232 })233}234func TestGoHorseFilterScope(t *testing.T) {235 Convey("go horse : 2 active filters -> one filter sets a variable and change a container label, another filter reads and verify that variable stored in request scope", t, func() {236 er := removeContents(config.JsFiltersPath)237 So(er, ShouldBeNil)238 er = copy("jsFilters/000.request.setVar.js", config.JsFiltersPath+"/000.request.setVar.js")239 er = copy("jsFilters/000.response.getVar.js", config.JsFiltersPath+"/000.response.getVar.js")240 time.Sleep(time.Second)241 resultRun := icmd.RunCommand("docker", "-H", "tcp://localhost:7070", "run", "-d", "--label", "test_label=go-horse-label", "redis")242 So(resultRun.ExitCode, ShouldEqual, 0)243 containerID := strings.TrimSpace(resultRun.Stdout())244 resultInspect := icmd.RunCommand("docker", "-H", "tcp://localhost:7070", "inspect", containerID)245 So(resultInspect.ExitCode, ShouldEqual, 0)246 So(resultInspect.Stdout(), ShouldContainSubstring, "go-horse-label_edited_by_filter_set_var")247 resultRM := icmd.RunCommand("docker", "-H", "tcp://localhost:7070", "rm", "-f", containerID)248 So(strings.TrimSpace(resultRM.Stdout()), ShouldEqual, containerID)249 So(resultRM.ExitCode, ShouldEqual, 0)250 removeContents(config.JsFiltersPath)251 })252}253func TestGoHorseGolangFilter(t *testing.T) {254 Convey("go horse : Golang filter", t, func() {255 })256}257func removeContents(dir string) error {258 d, err := os.Open(dir)259 if err != nil {260 return err261 }262 defer d.Close()263 names, err := d.Readdirnames(-1)...
emergency.go
Source:emergency.go
1package cli2import (3 "encoding/base64"4 "encoding/json"5 "fmt"6 "io/ioutil"7 "os"8 "strings"9 "path/filepath"10 "os/exec"11 "github.com/declan94/cfcryptfs/cffuse"12 "github.com/declan94/cfcryptfs/internal/exitcode"13 "github.com/declan94/cfcryptfs/internal/tlog"14 "github.com/declan94/cfcryptfs/keycrypter"15)16// EmergencyConfig is the content of a emergency file.17type EmergencyConfig struct {18 CipherConfig19 EmergencyKey string20}21// ExportEmergencyFile read information and key of a cipher directory22// save them to an outer file specified by user23func ExportEmergencyFile(cipherDir, outpath string) {24 conf := LoadConf(cipherDir)25 key := LoadKey(cipherDir, "", "")26 cipherKey, err := keycrypter.EncryptKey(key, emergencyPassword)27 if err != nil {28 tlog.Fatal.Printf("Encryption key faild: %v", err)29 }30 encKey := base64.StdEncoding.EncodeToString(cipherKey)31 econf := EmergencyConfig{32 CipherConfig: conf,33 EmergencyKey: encKey,34 }35 js, err := json.MarshalIndent(econf, "", "\t")36 if err != nil {37 tlog.Fatal.Printf("Failed to marshal emergency configs")38 os.Exit(exitcode.Config)39 }40 js = append(js, '\n')41 if outpath == "" {42 for true {43 outpath = ""44 fmt.Printf("path to store emergency file: ")45 fmt.Scanln(&outpath)46 outpath = strings.Trim(outpath, " \t")47 outpath = expandPath(outpath)48 if strings.HasPrefix(outpath, cipherDir) {49 tlog.Warn.Println("You shouldn't save your emergency file in the cipher directory!")50 tlog.Warn.Println("You must keep it SAFE and SECRET.")51 continue52 }53 if _, err := os.Stat(outpath); err == nil {54 fmt.Printf("file exists, overwirte? (y/N)")55 var input string56 fmt.Scanln(&input)57 if strings.ToUpper(strings.Trim(input, " \t")) != "Y" {58 continue59 }60 }61 break62 }63 }64 fd, err := os.OpenFile(outpath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)65 if err != nil {66 tlog.Fatal.Printf("Error open file [%s]: %v", outpath, err)67 os.Exit(exitcode.Config)68 }69 _, err = fd.Write(js)70 if err != nil {71 tlog.Fatal.Printf("Error write file [%s]: %v", outpath, err)72 os.Exit(exitcode.Config)73 }74 fmt.Printf("Emergency file exported: %s\n", outpath)75 fmt.Println("Make sure you keep it SAFE and SECRET")76 fmt.Printf("Use `%scfcryptfs -emergency_file THIS_FILE CIPHERDIR MOUNTPOINT%s`"+77 " when config or keyfile are damaged or you forget passowrd.\n", tlog.ColorGreen, tlog.ColorReset)78}79// LoadEmergencyFile load conf and key from a emergency file80func LoadEmergencyFile(path string) (CipherConfig, []byte) {81 // Read from disk82 js, err := ioutil.ReadFile(path)83 if err != nil {84 tlog.Fatal.Printf("Read from config file error: %v", err)85 os.Exit(exitcode.Config)86 }87 // Unmarshal88 var ecf EmergencyConfig89 err = json.Unmarshal(js, &ecf)90 if err != nil {91 tlog.Fatal.Printf("Failed to parse emergency file")92 os.Exit(exitcode.Config)93 }94 cf := ecf.CipherConfig95 cf.CryptType = str2CryptType(cf.CryptTypeStr)96 if cf.CryptType == 0 {97 tlog.Fatal.Printf("Wrong crypt type: %s", cf.CryptTypeStr)98 os.Exit(exitcode.Config)99 }100 cipherKey, err := base64.StdEncoding.DecodeString(ecf.EmergencyKey)101 if err != nil {102 tlog.Fatal.Printf("Decode emergency key failed: %v", err)103 os.Exit(exitcode.Config)104 }105 key, err := keycrypter.DecrytKey(cipherKey, emergencyPassword)106 if err != nil {107 tlog.Fatal.Printf("Decrypt emergency key failed.")108 os.Exit(exitcode.Config)109 }110 return cf, key111}112// RecoverCipherDir recovers the cipher dir using emergency file113func RecoverCipherDir(cipherDir, emerFile string) {114 if emerFile == "" {115 for true {116 emerFile = ""117 fmt.Printf("path of emergency file: ")118 fmt.Scanln(&emerFile)119 emerFile = strings.Trim(emerFile, " \t")120 emerFile = expandPath(emerFile)121 if _, err := os.Stat(emerFile); err != nil {122 tlog.Warn.Println("File dose not exist.")123 continue124 }125 break126 }127 }128 conf, key := LoadEmergencyFile(emerFile)129 fmt.Printf("You'd better use `%scfcryptfs -emergency_file %s %s MOUNTPOINT%s`"+130 " to check if everything works well.\n", tlog.ColorGreen, emerFile, cipherDir, tlog.ColorReset)131 fmt.Printf("Are you sure to recover [%s] with the emergency file [%s]? (y/N)", cipherDir, emerFile)132 var input string133 fmt.Scanln(&input)134 input = strings.Trim(input, " \t")135 if strings.ToUpper(input) != "Y" {136 return137 }138 exec.Command("cp", filepath.Join(cipherDir, cffuse.ConfFile), "/tmp/.cfcryptfs.cfg.bk").Run()139 exec.Command("cp", filepath.Join(cipherDir, cffuse.KeyFile), "/tmp/.cfcryptfs.key.bk").Run()140 err := SaveConf(filepath.Join(cipherDir, cffuse.ConfFile), conf)141 if err != nil {142 tlog.Fatal.Printf("Save config file failed: %v", err)143 os.Exit(exitcode.Config)144 }145 fmt.Println("Set new password")146 SaveKey(cipherDir, key)147 fmt.Printf("\nCipher directory recovered: %s\n", cipherDir)148}...
query.go
Source:query.go
...73 if js.SignalNum > 0 {74 sigStr = js.SignalNum.String()75 }76 exitCode := ""77 if js.ExitCode >= 0 {78 exitCode = strconv.FormatInt(int64(js.ExitCode), 10)79 }80 pid := ""81 if js.Pid > 0 {82 pid = strconv.FormatInt(int64(js.Pid), 10)83 }84 columns := make([]string, 0, 8)85 if isAdmin {86 columns = append(columns, js.Owner)87 }88 columns = append(columns, js.Name)89 columns = append(columns, js.ID)90 columns = append(columns, strconv.FormatBool(js.Running))91 columns = append(columns, pid)92 columns = append(columns, exitCode)...
ExitCode
Using AI Code Generation
1func main() {2 js.Global().Set("ExitCode", js.FuncOf(func(this js.Value, args []js.Value) interface{} {3 os.Exit(args[0].Int())4 }))5}6func main() {7 js.Global().Get("ExitCode").Invoke(1)8}9func main() {10 js.Global().Get("ExitCode").Invoke(1)11}12func main() {13 js.Global().Get("ExitCode").Invoke(1)14}15func main() {16 js.Global().Get("ExitCode").Invoke(1)17}18func main() {19 js.Global().Get("ExitCode").Invoke(1)20}21func main() {22 js.Global().Get("ExitCode").Invoke(1)23}24func main() {25 js.Global().Get("ExitCode").Invoke(1)26}27func main() {28 js.Global().Get("ExitCode").Invoke(1)29}30func main() {31 js.Global().Get("ExitCode").Invoke(1)32}33func main() {34 js.Global().Get("ExitCode").Invoke(1)35}36func main() {37 js.Global().Get("ExitCode").Invoke(1)38}39func main() {40 js.Global().Get("ExitCode").Invoke(1)41}42func main()
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!