Best K6 code snippet using cmd.buildStages
config_consolidation_test.go
Source:config_consolidation_test.go
...91 }92}93// A helper function that accepts (duration in second, VUs) pairs and returns94// a valid slice of stage structs95func buildStages(durationsAndVUs ...int64) []executor.Stage {96 l := len(durationsAndVUs)97 if l%2 != 0 {98 panic("wrong len")99 }100 result := make([]executor.Stage, 0, l/2)101 for i := 0; i < l; i += 2 {102 result = append(result, executor.Stage{103 Duration: types.NullDurationFrom(time.Duration(durationsAndVUs[i]) * time.Second),104 Target: null.IntFrom(durationsAndVUs[i+1]),105 })106 }107 return result108}109func mostFlagSets() []flagSetInit {110 // TODO: make this unnecessary... currently these are the only commands in which111 // getConsolidatedConfig() is used, but they also have differences in their CLI flags :/112 // sigh... compromises...113 result := []flagSetInit{}114 for i, fsi := range []flagSetInit{runCmdFlagSet, archiveCmdFlagSet, cloudCmdFlagSet} {115 i, fsi := i, fsi // go...116 result = append(result, func() *pflag.FlagSet {117 flags := pflag.NewFlagSet(fmt.Sprintf("superContrivedFlags_%d", i), pflag.ContinueOnError)118 flags.AddFlagSet(rootCmdPersistentFlagSet())119 flags.AddFlagSet(fsi())120 return flags121 })122 }123 return result124}125type file struct {126 filepath, contents string127}128func getFS(files []file) afero.Fs {129 fs := afero.NewMemMapFs()130 for _, f := range files {131 must(afero.WriteFile(fs, f.filepath, []byte(f.contents), 0644)) // modes don't matter in the afero.MemMapFs132 }133 return fs134}135func defaultConfig(jsonConfig string) afero.Fs {136 return getFS([]file{{defaultConfigFilePath, jsonConfig}})137}138type flagSetInit func() *pflag.FlagSet139type opts struct {140 cli []string141 env []string142 runner *lib.Options143 fs afero.Fs144 // TODO: remove this when the configuration is more reproducible and sane...145 // We use a func, because initializing a FlagSet that points to variables146 // actually will change those variables to their default values :| In our147 // case, this happens only some of the time, for global variables that148 // are configurable only via CLI flags, but not environment variables.149 //150 // For the rest, their default value is their current value, since that151 // has been set from the environment variable. That has a bunch of other152 // issues on its own, and the func() doesn't help at all, and we need to153 // use the resetStickyGlobalVars() hack on top of that...154 cliFlagSetInits []flagSetInit155}156func resetStickyGlobalVars() {157 // TODO: remove after fixing the config, obviously a dirty hack158 exitOnRunning = false159 configFilePath = ""160 runType = ""161}162// exp contains the different events or errors we expect our test case to trigger.163// for space and clarity, we use the fact that by default, all of the struct values are false164type exp struct {165 cliParseError bool166 cliReadError bool167 consolidationError bool168 derivationError bool169 validationErrors bool170 logWarning bool171}172// A hell of a complicated test case, that still doesn't test things fully...173type configConsolidationTestCase struct {174 options opts175 expected exp176 customValidator func(t *testing.T, c Config)177}178func getConfigConsolidationTestCases() []configConsolidationTestCase {179 I := null.IntFrom // shortcut for "Valid" (i.e. user-specified) ints180 // This is a function, because some of these test cases actually need for the init() functions181 // to be executed, since they depend on defaultConfigFilePath182 return []configConsolidationTestCase{183 // Check that no options will result in 1 VU 1 iter value for execution184 {opts{}, exp{}, verifyOneIterPerOneVU},185 // Verify some CLI errors186 {opts{cli: []string{"--blah", "blah"}}, exp{cliParseError: true}, nil},187 {opts{cli: []string{"--duration", "blah"}}, exp{cliParseError: true}, nil},188 {opts{cli: []string{"--iterations", "blah"}}, exp{cliParseError: true}, nil},189 {opts{cli: []string{"--execution", ""}}, exp{cliParseError: true}, nil},190 {opts{cli: []string{"--stage", "10:20s"}}, exp{cliReadError: true}, nil},191 // Check if CLI shortcuts generate correct execution values192 {opts{cli: []string{"--vus", "1", "--iterations", "5"}}, exp{}, verifySharedIters(I(1), I(5))},193 {opts{cli: []string{"-u", "2", "-i", "6"}}, exp{}, verifySharedIters(I(2), I(6))},194 {opts{cli: []string{"-d", "123s"}}, exp{}, verifyConstLoopingVUs(null.NewInt(1, false), 123*time.Second)},195 {opts{cli: []string{"-u", "3", "-d", "30s"}}, exp{}, verifyConstLoopingVUs(I(3), 30*time.Second)},196 {opts{cli: []string{"-u", "4", "--duration", "60s"}}, exp{}, verifyConstLoopingVUs(I(4), 1*time.Minute)},197 {198 opts{cli: []string{"--stage", "20s:10", "-s", "3m:5"}}, exp{},199 verifyRampingVUs(null.NewInt(1, false), buildStages(20, 10, 180, 5)),200 },201 {202 opts{cli: []string{"-s", "1m6s:5", "--vus", "10"}}, exp{},203 verifyRampingVUs(null.NewInt(10, true), buildStages(66, 5)),204 },205 {opts{cli: []string{"-u", "1", "-i", "6", "-d", "10s"}}, exp{}, func(t *testing.T, c Config) {206 verifySharedIters(I(1), I(6))(t, c)207 sharedIterConfig := c.Scenarios[lib.DefaultScenarioName].(executor.SharedIterationsConfig)208 assert.Equal(t, time.Duration(sharedIterConfig.MaxDuration.Duration), 10*time.Second)209 }},210 // This should get a validation error since VUs are more than the shared iterations211 {opts{cli: []string{"--vus", "10", "-i", "6"}}, exp{validationErrors: true}, verifySharedIters(I(10), I(6))},212 {opts{cli: []string{"-s", "10s:5", "-s", "10s:"}}, exp{validationErrors: true}, nil},213 {opts{fs: defaultConfig(`{"stages": [{"duration": "20s"}], "vus": 10}`)}, exp{validationErrors: true}, nil},214 // These should emit a consolidation error215 {opts{cli: []string{"-u", "2", "-d", "10s", "-s", "10s:20"}}, exp{derivationError: true}, nil},216 {opts{cli: []string{"-u", "3", "-i", "5", "-s", "10s:20"}}, exp{derivationError: true}, nil},217 {opts{cli: []string{"-u", "3", "-d", "0"}}, exp{derivationError: true}, nil},218 {219 opts{runner: &lib.Options{220 VUs: null.IntFrom(5),221 Duration: types.NullDurationFrom(44 * time.Second),222 Stages: []lib.Stage{223 {Duration: types.NullDurationFrom(3 * time.Second), Target: I(20)},224 },225 }}, exp{derivationError: true}, nil,226 },227 {opts{fs: defaultConfig(`{"scenarios": {}}`)}, exp{logWarning: true}, verifyOneIterPerOneVU},228 // Test if environment variable shortcuts are working as expected229 {opts{env: []string{"K6_VUS=5", "K6_ITERATIONS=15"}}, exp{}, verifySharedIters(I(5), I(15))},230 {opts{env: []string{"K6_VUS=10", "K6_DURATION=20s"}}, exp{}, verifyConstLoopingVUs(I(10), 20*time.Second)},231 {232 opts{env: []string{"K6_STAGES=2m30s:11,1h1m:100"}}, exp{},233 verifyRampingVUs(null.NewInt(1, false), buildStages(150, 11, 3660, 100)),234 },235 {236 opts{env: []string{"K6_STAGES=100s:100,0m30s:0", "K6_VUS=0"}}, exp{},237 verifyRampingVUs(null.NewInt(0, true), buildStages(100, 100, 30, 0)),238 },239 // Test if JSON configs work as expected240 {opts{fs: defaultConfig(`{"iterations": 77, "vus": 7}`)}, exp{}, verifySharedIters(I(7), I(77))},241 {opts{fs: defaultConfig(`wrong-json`)}, exp{consolidationError: true}, nil},242 {opts{fs: getFS(nil), cli: []string{"--config", "/my/config.file"}}, exp{consolidationError: true}, nil},243 // Test combinations between options and levels244 {opts{cli: []string{"--vus", "1"}}, exp{}, verifyOneIterPerOneVU},245 {opts{cli: []string{"--vus", "10"}}, exp{logWarning: true}, verifyOneIterPerOneVU},246 {247 opts{248 fs: getFS([]file{{"/my/config.file", `{"vus": 8, "duration": "2m"}`}}),249 cli: []string{"--config", "/my/config.file"},250 }, exp{}, verifyConstLoopingVUs(I(8), 120*time.Second),251 },252 {253 opts{254 fs: defaultConfig(`{"stages": [{"duration": "20s", "target": 20}], "vus": 10}`),255 env: []string{"K6_DURATION=15s"},256 cli: []string{"--stage", ""},257 },258 exp{logWarning: true}, verifyOneIterPerOneVU,259 },260 {261 opts{262 runner: &lib.Options{VUs: null.IntFrom(5), Duration: types.NullDurationFrom(50 * time.Second)},263 cli: []string{"--stage", "5s:5"},264 },265 exp{}, verifyRampingVUs(I(5), buildStages(5, 5)),266 },267 {268 opts{269 fs: defaultConfig(`{"stages": [{"duration": "20s", "target": 10}]}`),270 runner: &lib.Options{VUs: null.IntFrom(5)},271 },272 exp{},273 verifyRampingVUs(I(5), buildStages(20, 10)),274 },275 {276 opts{277 fs: defaultConfig(`{"stages": [{"duration": "20s", "target": 10}]}`),278 runner: &lib.Options{VUs: null.IntFrom(5)},279 env: []string{"K6_VUS=15", "K6_ITERATIONS=17"},280 },281 exp{},282 verifySharedIters(I(15), I(17)),283 },284 {285 opts{286 fs: defaultConfig(`{"stages": [{"duration": "11s", "target": 11}]}`),287 runner: &lib.Options{VUs: null.IntFrom(22)},288 env: []string{"K6_VUS=33"},289 cli: []string{"--stage", "44s:44", "-s", "55s:55"},290 },291 exp{},292 verifyRampingVUs(null.NewInt(33, true), buildStages(44, 44, 55, 55)),293 },294 // TODO: test the future full overwriting of the duration/iterations/stages/execution options295 {296 opts{297 fs: defaultConfig(`{298 "scenarios": { "someKey": {299 "executor": "constant-vus", "vus": 10, "duration": "60s", "gracefulStop": "10s",300 "startTime": "70s", "env": {"test": "mest"}, "exec": "someFunc"301 }}}`),302 env: []string{"K6_ITERATIONS=25"},303 cli: []string{"--vus", "12"},304 },305 exp{}, verifySharedIters(I(12), I(25)),306 },...
buildStages
Using AI Code Generation
1import (2type cmd struct {3}4func (c *cmd) buildStages() []string {5 for i, arg := range c.args {6 if arg == "|" {7 stages = append(stages, strings.Join(args, " "))8 }9 }10 stages = append(stages, strings.Join(args, " "))11}12func main() {13 currentDir, err := os.Getwd()14 if err != nil {15 fmt.Println(err)16 os.Exit(1)17 }18 filePath := filepath.Join(currentDir, "1.txt")19 file, err := os.Create(filePath)20 if err != nil {21 fmt.Println(err)22 os.Exit(1)23 }24 defer file.Close()25 command := cmd{26 args: []string{"-l", "|", "grep", "main.go", "|", "wc", "-l"},27 }28 process := exec.Command(command.name, command.args...)29 output, err := process.Output()30 if err != nil {31 fmt.Println(err)32 os.Exit(1)33 }34 file.Write(output)35}
buildStages
Using AI Code Generation
1func main() {2 cmd := &cmd{}3 cmd.buildStages()4}5func main() {6 cmd := &cmd{}7 cmd.buildStages()8}9func main() {10 cmd := &cmd{}11 cmd.buildStages()12}13func main() {14 cmd := &cmd{}15 cmd.buildStages()16}17func main() {18 cmd := &cmd{}19 cmd.buildStages()20}21func main() {22 cmd := &cmd{}23 cmd.buildStages()24}25func main() {26 cmd := &cmd{}27 cmd.buildStages()28}29func main() {30 cmd := &cmd{}31 cmd.buildStages()32}33func main() {34 cmd := &cmd{}35 cmd.buildStages()36}37func main() {38 cmd := &cmd{}39 cmd.buildStages()40}41func main() {42 cmd := &cmd{}43 cmd.buildStages()44}45func main() {46 cmd := &cmd{}47 cmd.buildStages()48}49func main() {50 cmd := &cmd{}51 cmd.buildStages()52}53func main() {54 cmd := &cmd{}55 cmd.buildStages()56}
buildStages
Using AI Code Generation
1import (2func main() {3 cmd = Command{}4 cmd.buildStages()5}6import (7func main() {8 cmd = Command{}9 cmd.buildStages()10}11import (12func main() {13 cmd = Command{}14 cmd.buildStages()15}16import (17func main() {18 cmd = Command{}19 cmd.buildStages()20}21import (22func main() {23 cmd = Command{}24 cmd.buildStages()25}26import (27func main() {28 cmd = Command{}29 cmd.buildStages()30}31import (32func main() {33 cmd = Command{}34 cmd.buildStages()35}36import (37func main() {38 cmd = Command{}39 cmd.buildStages()40}41import (42func main() {43 cmd = Command{}44 cmd.buildStages()45}46import (47func main() {48 cmd = Command{}49 cmd.buildStages()50}
buildStages
Using AI Code Generation
1import (2type cmd struct {3}4func main() {5 c := &cmd{exec.Command("go", "version")}6 if err := c.Run(); err != nil {7 fmt.Printf("Error: %v8 }9}10func (c *cmd) Run() error {11 stages, err := c.buildStages()12 if err != nil {13 }14 for _, stage := range stages {15 if err := stage(); err != nil {16 }17 }18}19func (c *cmd) buildStages() ([]func() error, error) {20 var stages []func() error21 stages = append(stages, func() error {22 fmt.Printf("==> Executing: %s23", strings.Join(c.Args, " "))24 })25 stages = append(stages, func() error {26 return c.Cmd.Run()27 })28}29import (30type cmd struct {31}32func main() {33 c := &cmd{exec.Command("go", "version")}34 if err := c.Run(); err != nil {35 fmt.Printf("Error: %v36 }37}38func (c *cmd) Run() error {39 stages, err := c.buildStages()40 if err != nil {41 }42 for _, stage := range stages {43 if err := stage(); err != nil {44 }45 }46}47func (c *cmd) buildStages() ([]func() error, error) {
buildStages
Using AI Code Generation
1import (2func main() {3 c := cmd{4 stages: []string{"build", "test", "deploy"},5 }6 fmt.Println(c.buildStages())7}8import (9func main() {10 c := cmd{11 stages: []string{"build", "test", "deploy"},12 }13 fmt.Println(c.buildStages())14}15The problem is that you are not importing the package containing the cmd struct. You can either use the full path to the package or you can import it. For example:16import (17func main() {18 c := cmds.cmd{19 stages: []string{"build", "test", "deploy"},20 }21 fmt.Println(c.buildStages())22}23import (24func main() {25 c := cmds.cmd{26 stages: []string{"build", "test", "deploy"},27 }28 fmt.Println(c.buildStages())29}
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!!