Best Venom code snippet using venom.tempDir
exec.go
Source:exec.go
1package exec2import (3 "bufio"4 "context"5 "fmt"6 "os"7 "os/exec"8 "runtime"9 "strconv"10 "strings"11 "syscall"12 "time"13 "github.com/fsamin/go-dump"14 "github.com/mitchellh/mapstructure"15 "github.com/ovh/venom"16)17// Name for test exec18const Name = "exec"19// New returns a new Test Exec20func New() venom.Executor {21 return &Executor{}22}23// Executor represents a Test Exec24type Executor struct {25 Script *string `json:"script,omitempty" yaml:"script,omitempty"`26}27// Result represents a step result28type Result struct {29 Systemout string `json:"systemout,omitempty" yaml:"systemout,omitempty"`30 SystemoutJSON interface{} `json:"systemoutjson,omitempty" yaml:"systemoutjson,omitempty"`31 Systemerr string `json:"systemerr,omitempty" yaml:"systemerr,omitempty"`32 SystemerrJSON interface{} `json:"systemerrjson,omitempty" yaml:"systemerrjson,omitempty"`33 Err string `json:"err,omitempty" yaml:"err,omitempty"`34 Code string `json:"code,omitempty" yaml:"code,omitempty"`35 TimeSeconds float64 `json:"timeseconds,omitempty" yaml:"timeseconds,omitempty"`36}37// ZeroValueResult return an empty implementation of this executor result38func (Executor) ZeroValueResult() interface{} {39 return Result{}40}41// GetDefaultAssertions return default assertions for type exec42func (Executor) GetDefaultAssertions() *venom.StepAssertions {43 return &venom.StepAssertions{Assertions: []venom.Assertion{"result.code ShouldEqual 0"}}44}45// Run execute TestStep of type exec46func (Executor) Run(ctx context.Context, step venom.TestStep) (interface{}, error) {47 var e Executor48 if err := mapstructure.Decode(step, &e); err != nil {49 return nil, err50 }51 if e.Script != nil && *e.Script == "" {52 return nil, fmt.Errorf("Invalid command")53 }54 scriptContent := *e.Script55 // Default shell is sh56 shell := "/bin/sh"57 var opts []string58 // If user wants a specific shell, use it59 if strings.HasPrefix(scriptContent, "#!") {60 t := strings.SplitN(scriptContent, "\n", 2)61 shell = strings.TrimPrefix(t[0], "#!")62 shell = strings.TrimRight(shell, " \t\r\n")63 }64 // except on windows where it's powershell65 if runtime.GOOS == "windows" {66 shell = "PowerShell"67 opts = append(opts, "-ExecutionPolicy", "Bypass", "-Command")68 }69 // Create a tmp file70 tmpscript, err := os.CreateTemp(os.TempDir(), "venom-")71 if err != nil {72 return nil, fmt.Errorf("cannot create tmp file: %s", err)73 }74 // Put script in file75 venom.Debug(ctx, "work with tmp file %s", tmpscript.Name())76 n, err := tmpscript.Write([]byte(scriptContent))77 if err != nil || n != len(scriptContent) {78 if err != nil {79 return nil, fmt.Errorf("cannot write script: %s", err)80 }81 return nil, fmt.Errorf("cannot write all script: %d/%d", n, len(scriptContent))82 }83 oldPath := tmpscript.Name()84 tmpscript.Close()85 var scriptPath string86 if runtime.GOOS == "windows" {87 // Remove all .txt Extensions, there is not always a .txt extension88 newPath := strings.ReplaceAll(oldPath, ".txt", "")89 // and add .PS1 extension90 newPath += ".PS1"91 if err := os.Rename(oldPath, newPath); err != nil {92 return nil, fmt.Errorf("cannot rename script to add powershell extension, aborting")93 }94 // This aims to stop a the very first error and return the right exit code95 psCommand := fmt.Sprintf("& { $ErrorActionPreference='Stop'; & %s ;exit $LastExitCode}", newPath)96 scriptPath = newPath97 opts = append(opts, psCommand)98 } else {99 scriptPath = oldPath100 opts = append(opts, scriptPath)101 }102 defer os.Remove(scriptPath)103 // Chmod file104 if err := os.Chmod(scriptPath, 0700); err != nil {105 return nil, fmt.Errorf("cannot chmod script %s: %s", scriptPath, err)106 }107 start := time.Now()108 cmd := exec.CommandContext(ctx, shell, opts...)109 venom.Debug(ctx, "teststep exec '%s %s'", shell, strings.Join(opts, " "))110 cmd.Dir = venom.StringVarFromCtx(ctx, "venom.testsuite.workdir")111 stdout, err := cmd.StdoutPipe()112 if err != nil {113 return nil, fmt.Errorf("runScriptAction: Cannot get stdout pipe: %s", err)114 }115 stderr, err := cmd.StderrPipe()116 if err != nil {117 return nil, fmt.Errorf("runScriptAction: Cannot get stderr pipe: %s", err)118 }119 stdoutreader := bufio.NewReader(stdout)120 stderrreader := bufio.NewReader(stderr)121 result := Result{}122 outchan := make(chan bool)123 go func() {124 for {125 line, errs := stdoutreader.ReadString('\n')126 if errs != nil {127 // ReadString returns what has been read even though an error was encoutered128 // ie. capture outputs with no '\n' at the end129 result.Systemout += line130 stdout.Close()131 close(outchan)132 return133 }134 result.Systemout += line135 venom.Debug(ctx, line)136 }137 }()138 errchan := make(chan bool)139 go func() {140 for {141 line, errs := stderrreader.ReadString('\n')142 if errs != nil {143 // ReadString returns what has been read even though an error was encoutered144 // ie. capture outputs with no '\n' at the end145 result.Systemerr += line146 stderr.Close()147 close(errchan)148 return149 }150 result.Systemerr += line151 venom.Debug(ctx, line)152 }153 }()154 if err := cmd.Start(); err != nil {155 result.Err = err.Error()156 result.Code = "127"157 venom.Debug(ctx, err.Error())158 return dump.ToMap(e, nil, dump.WithDefaultLowerCaseFormatter())159 }160 <-outchan161 <-errchan162 result.Code = "0"163 if err := cmd.Wait(); err != nil {164 if exiterr, ok := err.(*exec.ExitError); ok {165 if status, ok := exiterr.Sys().(syscall.WaitStatus); ok {166 result.Code = strconv.Itoa(status.ExitStatus())167 }168 }169 }170 elapsed := time.Since(start)171 result.TimeSeconds = elapsed.Seconds()172 result.Systemout = venom.RemoveNotPrintableChar(strings.TrimRight(result.Systemout, "\n"))173 result.Systemerr = venom.RemoveNotPrintableChar(strings.TrimRight(result.Systemerr, "\n"))174 var outJSON interface{}175 if err := venom.JSONUnmarshal([]byte(result.Systemout), &outJSON); err == nil {176 result.SystemoutJSON = outJSON177 }178 var errJSON interface{}179 if err := venom.JSONUnmarshal([]byte(result.Systemerr), &errJSON); err == nil {180 result.SystemerrJSON = errJSON181 }182 return result, nil183}...
process_files_test.go
Source:process_files_test.go
...9 "time"10 log "github.com/sirupsen/logrus"11 "github.com/stretchr/testify/require"12)13func tempDir(t *testing.T) (string, error) {14 dir := os.TempDir()15 name := path.Join(dir, randomString(5))16 if err := os.MkdirAll(name, os.FileMode(0744)); err != nil {17 return "", err18 }19 t.Logf("Creating directory %s", name)20 return name, nil21}22func randomString(n int) string {23 var letter = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")24 b := make([]rune, n)25 for i := range b {26 b[i] = letter[rand.Intn(len(letter))]27 }28 return string(b)29}30func Test_getFilesPath(t *testing.T) {31 InitTestLogger(t)32 rand.Seed(time.Now().UnixNano())33 log.SetLevel(log.DebugLevel)34 tests := []struct {35 init func(t *testing.T) ([]string, error)36 name string37 want []string38 wantErr bool39 }{40 {41 name: "Check an empty directory",42 init: func(t *testing.T) ([]string, error) {43 dir, err := tempDir(t)44 return []string{dir}, err45 },46 wantErr: true,47 },48 {49 name: "Check an directory with one yaml file",50 init: func(t *testing.T) ([]string, error) {51 dir, err := tempDir(t)52 if err != nil {53 return nil, err54 }55 d1 := []byte("hello")56 err = os.WriteFile(path.Join(dir, "d1.yml"), d1, 0644)57 return []string{dir}, err58 },59 want: []string{"d1.yml"},60 wantErr: false,61 },62 {63 name: "Check an directory with one yaml file and a subdirectory with another file",64 init: func(t *testing.T) ([]string, error) {65 dir1, err := tempDir(t)66 if err != nil {67 return nil, err68 }69 d1 := []byte("hello")70 if err = os.WriteFile(path.Join(dir1, "d1.yml"), d1, 0644); err != nil {71 return nil, err72 }73 dir2 := path.Join(dir1, randomString(10))74 t.Logf("Creating directory %s", dir2)75 if err := os.Mkdir(dir2, 0744); err != nil {76 return nil, err77 }78 d2 := []byte("hello")79 if err = os.WriteFile(path.Join(dir2, "d2.yml"), d2, 0644); err != nil {80 return nil, err81 }82 return []string{dir1, dir2}, err83 },84 want: []string{"d1.yml", "d2.yml"},85 wantErr: false,86 },87 {88 name: "Check globstars",89 init: func(t *testing.T) ([]string, error) {90 dir1, err := tempDir(t)91 if err != nil {92 return nil, err93 }94 d1 := []byte("hello")95 if err = os.WriteFile(path.Join(dir1, "d1.yml"), d1, 0644); err != nil {96 return nil, err97 }98 dir2 := path.Join(dir1, randomString(10))99 t.Logf("Creating directory %s", dir2)100 if err := os.Mkdir(dir2, 0744); err != nil {101 return nil, err102 }103 d2 := []byte("hello")104 if err = os.WriteFile(path.Join(dir2, "d2.yml"), d2, 0644); err != nil {105 return nil, err106 }107 dir3 := path.Join(dir2, randomString(10))108 t.Logf("Creating directory %s", dir3)109 if err := os.Mkdir(dir3, 0744); err != nil {110 return nil, err111 }112 d3 := []byte("hello")113 if err = os.WriteFile(path.Join(dir2, "d3.yml"), d3, 0644); err != nil {114 return nil, err115 }116 dir4 := path.Join(dir3, randomString(10))117 t.Logf("Creating directory %s", dir3)118 if err := os.Mkdir(dir4, 0744); err != nil {119 return nil, err120 }121 d4 := []byte("hello")122 if err = os.WriteFile(path.Join(dir4, "d4.yml"), d4, 0644); err != nil {123 return nil, err124 }125 return []string{fmt.Sprintf("%s/**/*.yml", dir1)}, err126 },127 want: []string{"d1.yml", "d2.yml", "d3.yml", "d4.yml"},128 wantErr: false,129 },130 {131 name: "Check globstars with duplicate files",132 init: func(t *testing.T) ([]string, error) {133 dir1, err := tempDir(t)134 if err != nil {135 return nil, err136 }137 d1 := []byte("hello")138 if err = os.WriteFile(path.Join(dir1, "d1.yml"), d1, 0644); err != nil {139 return nil, err140 }141 dir2 := path.Join(dir1, randomString(10))142 t.Logf("Creating directory %s", dir2)143 if err := os.Mkdir(dir2, 0744); err != nil {144 return nil, err145 }146 d2 := []byte("hello")147 if err = os.WriteFile(path.Join(dir2, "d2.yml"), d2, 0644); err != nil {148 return nil, err149 }150 dir3 := path.Join(dir2, randomString(10))151 t.Logf("Creating directory %s", dir3)152 if err := os.Mkdir(dir3, 0744); err != nil {153 return nil, err154 }155 d3 := []byte("hello")156 if err = os.WriteFile(path.Join(dir2, "d3.yml"), d3, 0644); err != nil {157 return nil, err158 }159 dir4 := path.Join(dir3, randomString(10))160 t.Logf("Creating directory %s", dir3)161 if err := os.Mkdir(dir4, 0744); err != nil {162 return nil, err163 }164 d4 := []byte("hello")165 if err = os.WriteFile(path.Join(dir4, "d4.yml"), d4, 0644); err != nil {166 return nil, err167 }168 return []string{dir2, dir3, fmt.Sprintf("%s/**/*.yml", dir1)}, err169 },170 want: []string{"d1.yml", "d2.yml", "d3.yml", "d4.yml"},171 wantErr: false,172 },173 }174 for i := range tests {175 tt := tests[i]176 t.Run(tt.name, func(t *testing.T) {177 path, err := tt.init(t)178 if err != nil {179 t.Fatal(err)180 }181 got, err := getFilesPath(path)182 if (err != nil) != tt.wantErr {183 t.Errorf("getFilesPath() name:%s error = %v, wantErr %v", tt.name, err, tt.wantErr)184 return185 }186 for _, f := range tt.want {187 var found bool188 for _, g := range got {189 if strings.HasSuffix(g, f) {190 found = true191 }192 }193 if !found {194 t.Errorf("getFilesPath() error want %v got %v", f, got)195 }196 }197 })198 }199}200func Test_getFilesPath_files_order(t *testing.T) {201 dir1, _ := tempDir(t)202 d1 := []byte("hello")203 os.WriteFile(path.Join(dir1, "a.yml"), d1, 0644)204 d2 := []byte("hello")205 os.WriteFile(path.Join(dir1, "A.yml"), d2, 0644)206 input := []string{dir1 + "/a.yml", dir1 + "/A.yml"}207 output, err := getFilesPath(input)208 require.NoError(t, err)209 require.Len(t, output, 2)210 t.Log(output)211 require.True(t, strings.HasSuffix(output[0], "a.yml"))212 require.True(t, strings.HasSuffix(output[1], "A.yml"))213}...
conf.go
Source:conf.go
1package cli2import (3 "fmt"4 "io/ioutil"5 "os"6 "path/filepath"7 "github.com/spf13/cobra"8 "github.com/spf13/viper"9)10func initConf() {11 rootCmd.AddCommand(confCmd)12 confCmd.AddCommand(confShowCmd)13}14var confCmd = &cobra.Command{15 Use: "config",16 Aliases: []string{"conf"},17 Short: "Manage configuration options",18 Hidden: false,19 Args: cobra.NoArgs,20}21var confShowCmd = &cobra.Command{22 Use: "show <extension>",23 Short: "Display the currently loaded configuration in specified format",24 Args: cobra.ExactArgs(1),25 ValidArgs: viper.SupportedExts,26 RunE: confShowCmdRun,27}28func confShowCmdRun(cmd *cobra.Command, args []string) error {29 filename := filepath.Join(os.TempDir(), fmt.Sprintf("%s-config.%s", cmd.Root().Name(), args[0]))30 err := venom.WriteConfigAs(filename)31 if err != nil {32 return err33 }34 b, err := ioutil.ReadFile(filename)35 if err != nil {36 return err37 }38 _, err = cmd.Root().OutOrStdout().Write(b)39 return err40}...
tempDir
Using AI Code Generation
1import (2func main() {3 fmt.Println(venom.TempDir())4}5import (6func main() {7 fmt.Println(venom.TempDir())8}9import (10func main() {11 fmt.Println(venom.TempDir())12}13import (14func main() {15 fmt.Println(venom.TempDir())16}17import (18func main() {19 fmt.Println(venom.TempDir())20}21import (22func main() {23 fmt.Println(venom.TempDir())24}25import (26func main() {27 fmt.Println(venom.TempDir())28}29import (30func main() {31 fmt.Println(venom.TempDir())32}33import (34func main() {35 fmt.Println(venom.TempDir())36}37import (38func main() {39 fmt.Println(venom.TempDir())40}
tempDir
Using AI Code Generation
1import "fmt"2import "Venom"3func main(){4 fmt.Println(Venom.TempDir())5}6import "fmt"7import "Venom"8func main(){9 fmt.Println(Venom.TempDir())10}11import "fmt"12import "Venom"13func main(){14 fmt.Println(Venom.TempDir())15}16import "fmt"17import "Venom"18func main(){19 fmt.Println(Venom.TempDir())20}21import "fmt"22import "Venom"23func main(){24 fmt.Println(Venom.TempDir())25}26import "fmt"27import "Venom"28func main(){29 fmt.Println(Venom.TempDir())30}31import "fmt"32import "Venom"33func main(){34 fmt.Println(Venom.TempDir())35}36import "fmt"37import "Venom"38func main(){39 fmt.Println(Venom.TempDir())40}41import "fmt"42import "Venom"43func main(){44 fmt.Println(Venom.TempDir())45}46import "fmt"47import "Venom"48func main(){49 fmt.Println(Venom.TempDir())50}51### TempDir()52func TempDir() string53### TempFile()54func TempFile(dir, prefix string) (f *os.File, err error)
tempDir
Using AI Code Generation
1import (2func main() {3 v, err := venom.New()4 if err != nil {5 panic(err)6 }7 dir, err := v.TempDir()8 if err != nil {9 panic(err)10 }11 fmt.Printf("Temp dir: %s\n", dir)12}13import (14func main() {15 v, err := venom.New()16 if err != nil {17 panic(err)18 }19 file, err := v.TempFile()20 if err != nil {21 panic(err)22 }23 fmt.Printf("Temp file: %s\n", file)24}25import (26func main() {27 v, err := venom.New()28 if err != nil {29 panic(err)30 }31 file, err := v.TempFile()32 if err != nil {33 panic(err)34 }35 fmt.Printf("Temp file: %s\n", file)36}37import (38func main() {39 v, err := venom.New()40 if err != nil {41 panic(err)42 }43 file, err := v.TempFile()44 if err != nil {45 panic(err)46 }47 fmt.Printf("Temp file: %s\n", file)48}
tempDir
Using AI Code Generation
1import (2func main() {3 fmt.Println(venom.TempDir())4}5venom.TempDir() returns the path of temporary directory of the system6import (7func main() {8 fmt.Println(venom.TempFile())9}10venom.TempFile() returns the path of temporary file of the system11import (12func main() {13 fmt.Println(venom.UserHomeDir())14}15venom.UserHomeDir() returns the path of user home directory of the system16import (17func main() {18 fmt.Println(venom.UserConfigDir())19}20venom.UserConfigDir() returns the path of user config directory of the system21import (22func main() {23 fmt.Println(venom.UserDataDir())24}25venom.UserDataDir() returns the path of user data directory of the system26import (27func main() {28 fmt.Println(
tempDir
Using AI Code Generation
1import (2func main() {3 dir, err := os.MkdirTemp("", "tempDir")4 if err != nil {5 fmt.Println(err)6 }7 fmt.Println("Temp directory created:", dir)8}9import (10func main() {11 file, err := os.CreateTemp("", "tempFile")12 if err != nil {13 fmt.Println(err)14 }15 fmt.Println("Temp file created:", file.Name())16}17import (18func main() {19 dir, err := os.MkdirTemp("", "tempDir")20 if err != nil {21 fmt.Println(err)22 }23 fmt.Println("Temp directory created:", dir)24 file, err := ioutil.TempFile(dir, "tempFile")25 if err != nil {26 fmt.Println(err)27 }28 fmt.Println("Temp file created:", file.Name())29}30import (31func main() {32 dir, err := os.MkdirTemp("", "tempDir")33 if err != nil {34 fmt.Println(err)35 }36 fmt.Println("Temp directory created:", dir)37 file, err := ioutil.TempFile(dir, "tempFile")38 if err != nil {39 fmt.Println(err)40 }
tempDir
Using AI Code Generation
1import (2func main() {3 tempDir := venom.TempDir()4 fmt.Println(tempDir)5}6import (7func main() {8 tempDir := venom.TempDir()9 fmt.Println(tempDir)10}11import (12func main() {13 tempDir := venom.TempDir()14 fmt.Println(tempDir)15}16import (17func main() {18 tempDir := venom.TempDir()19 fmt.Println(tempDir)20}21import (22func main() {23 tempDir := venom.TempDir()24 fmt.Println(tempDir)25}26import (27func main() {28 tempDir := venom.TempDir()29 fmt.Println(tempDir)30}31import (32func main() {33 tempDir := venom.TempDir()34 fmt.Println(tempDir)35}36import (37func main() {38 tempDir := venom.TempDir()39 fmt.Println(tempDir)40}41import (
tempDir
Using AI Code Generation
1import "fmt"2import "venom"3func main(){4 fmt.Println(venom.TempDir())5}6import "fmt"7import "venom"8func main(){9 fmt.Println(venom.CurrentDir())10}11import "fmt"12import "venom"13func main(){14 fmt.Println(venom.CurrentUser())15}16import "fmt"17import "venom"18func main(){19 fmt.Println(venom.HomeDir())20}21import "fmt"22import "venom"23func main(){24 fmt.Println(venom.UserName())25}26import "fmt"27import "venom"28func main(){29 fmt.Println(venom.UserID())30}31import "fmt"32import "venom"33func main(){34 fmt.Println(venom.GroupID())35}36import "fmt"37import "venom"38func main(){39 fmt.Println(venom.GroupName())40}41import "fmt"42import "venom"43func main(){44 fmt.Println(venom.UserHomeDir())45}
tempDir
Using AI Code Generation
1import (2func main() {3 venom := venom.New()4 fmt.Println(venom.TempDir())5}6import (7func main() {8 venom := venom.New()9 fmt.Println(venom.TempFile())10}11import (12func main() {13 venom := venom.New()14 fmt.Println(venom.TempName())15}16import (17func main() {18 venom := venom.New()19 fmt.Println(venom.TempDir())20}21import (22func main() {23 venom := venom.New()24 fmt.Println(venom.TempDir())25}26import (27func main() {28 venom := venom.New()29 fmt.Println(venom.TempDir())30}31import (32func main() {33 venom := venom.New()34 fmt.Println(venom.TempDir())35}36import (37func main() {38 venom := venom.New()39 fmt.Println(venom.TempDir())40}
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!!