Best K6 code snippet using cmd.newGlobalTestState
integration_test.go
Source:integration_test.go
...24 `25)26func TestVersion(t *testing.T) {27 t.Parallel()28 ts := newGlobalTestState(t)29 ts.args = []string{"k6", "version"}30 newRootCommand(ts.globalState).execute()31 stdOut := ts.stdOut.String()32 assert.Contains(t, stdOut, "k6 v"+consts.Version)33 assert.Contains(t, stdOut, runtime.Version())34 assert.Contains(t, stdOut, runtime.GOOS)35 assert.Contains(t, stdOut, runtime.GOARCH)36 assert.NotContains(t, stdOut[:len(stdOut)-1], "\n")37 assert.Empty(t, ts.stdErr.Bytes())38 assert.Empty(t, ts.loggerHook.Drain())39}40func TestSimpleTestStdin(t *testing.T) {41 t.Parallel()42 ts := newGlobalTestState(t)43 ts.args = []string{"k6", "run", "-"}44 ts.stdIn = bytes.NewBufferString(noopDefaultFunc)45 newRootCommand(ts.globalState).execute()46 stdOut := ts.stdOut.String()47 assert.Contains(t, stdOut, "default: 1 iterations for each of 1 VUs")48 assert.Contains(t, stdOut, "1 complete and 0 interrupted iterations")49 assert.Empty(t, ts.stdErr.Bytes())50 assert.Empty(t, ts.loggerHook.Drain())51}52func TestStdoutAndStderrAreEmptyWithQuietAndHandleSummary(t *testing.T) {53 t.Parallel()54 ts := newGlobalTestState(t)55 ts.args = []string{"k6", "--quiet", "run", "-"}56 ts.stdIn = bytes.NewBufferString(noopDefaultFunc + noopHandleSummary)57 newRootCommand(ts.globalState).execute()58 assert.Empty(t, ts.stdErr.Bytes())59 assert.Empty(t, ts.stdOut.Bytes())60 assert.Empty(t, ts.loggerHook.Drain())61}62func TestStdoutAndStderrAreEmptyWithQuietAndLogsForwarded(t *testing.T) {63 t.Parallel()64 ts := newGlobalTestState(t)65 // TODO: add a test with relative path66 logFilePath := filepath.Join(ts.cwd, "test.log")67 ts.args = []string{68 "k6", "--quiet", "--log-output", "file=" + logFilePath,69 "--log-format", "raw", "run", "--no-summary", "-",70 }71 ts.stdIn = bytes.NewBufferString(fooLogDefaultFunc)72 newRootCommand(ts.globalState).execute()73 // The test state hook still catches this message74 assert.True(t, testutils.LogContains(ts.loggerHook.Drain(), logrus.InfoLevel, `foo`))75 // But it's not shown on stderr or stdout76 assert.Empty(t, ts.stdErr.Bytes())77 assert.Empty(t, ts.stdOut.Bytes())78 // Instead it should be in the log file79 logContents, err := afero.ReadFile(ts.fs, logFilePath)80 require.NoError(t, err)81 assert.Equal(t, "foo\n", string(logContents))82}83func TestRelativeLogPathWithSetupAndTeardown(t *testing.T) {84 t.Parallel()85 ts := newGlobalTestState(t)86 ts.args = []string{"k6", "--log-output", "file=test.log", "--log-format", "raw", "run", "-i", "2", "-"}87 ts.stdIn = bytes.NewBufferString(fooLogDefaultFunc + `88 export function setup() { console.log('bar'); };89 export function teardown() { console.log('baz'); };90 `)91 newRootCommand(ts.globalState).execute()92 // The test state hook still catches these messages93 logEntries := ts.loggerHook.Drain()94 assert.True(t, testutils.LogContains(logEntries, logrus.InfoLevel, `foo`))95 assert.True(t, testutils.LogContains(logEntries, logrus.InfoLevel, `bar`))96 assert.True(t, testutils.LogContains(logEntries, logrus.InfoLevel, `baz`))97 // And check that the log file also contains everything98 logContents, err := afero.ReadFile(ts.fs, filepath.Join(ts.cwd, "test.log"))99 require.NoError(t, err)100 assert.Equal(t, "bar\nfoo\nfoo\nbaz\n", string(logContents))101}102func TestWrongCliFlagIterations(t *testing.T) {103 t.Parallel()104 ts := newGlobalTestState(t)105 ts.args = []string{"k6", "run", "--iterations", "foo", "-"}106 ts.stdIn = bytes.NewBufferString(noopDefaultFunc)107 // TODO: check for exitcodes.InvalidConfig after https://github.com/loadimpact/k6/issues/883 is done...108 ts.expectedExitCode = -1109 newRootCommand(ts.globalState).execute()110 assert.True(t, testutils.LogContains(ts.loggerHook.Drain(), logrus.ErrorLevel, `invalid argument "foo"`))111}112func TestWrongEnvVarIterations(t *testing.T) {113 t.Parallel()114 ts := newGlobalTestState(t)115 ts.args = []string{"k6", "run", "--vus", "2", "-"}116 ts.envVars = map[string]string{"K6_ITERATIONS": "4"}117 ts.stdIn = bytes.NewBufferString(noopDefaultFunc)118 newRootCommand(ts.globalState).execute()119 stdOut := ts.stdOut.String()120 t.Logf(stdOut)121 assert.Contains(t, stdOut, "4 iterations shared among 2 VUs")122 assert.Contains(t, stdOut, "4 complete and 0 interrupted iterations")123 assert.Empty(t, ts.stdErr.Bytes())124 assert.Empty(t, ts.loggerHook.Drain())125}126func TestMetricsAndThresholds(t *testing.T) {127 t.Parallel()128 script := `129 import { Counter } from 'k6/metrics';130 var setupCounter = new Counter('setup_counter');131 var teardownCounter = new Counter('teardown_counter');132 var defaultCounter = new Counter('default_counter');133 let unusedCounter = new Counter('unused_counter');134 export const options = {135 scenarios: {136 sc1: {137 executor: 'per-vu-iterations',138 vus: 1,139 iterations: 1,140 },141 sc2: {142 executor: 'shared-iterations',143 vus: 1,144 iterations: 1,145 },146 },147 thresholds: {148 'setup_counter': ['count == 1'],149 'teardown_counter': ['count == 1'],150 'default_counter': ['count == 2'],151 'default_counter{scenario:sc1}': ['count == 1'],152 'default_counter{scenario:sc2}': ['count == 1'],153 'iterations': ['count == 2'],154 'iterations{scenario:sc1}': ['count == 1'],155 'iterations{scenario:sc2}': ['count == 1'],156 'default_counter{nonexistent:tag}': ['count == 0'],157 'unused_counter': ['count == 0'],158 'http_req_duration{status:200}': [' max == 0'], // no HTTP requests159 },160 };161 export function setup() {162 console.log('setup() start');163 setupCounter.add(1);164 console.log('setup() end');165 return { foo: 'bar' }166 }167 export default function (data) {168 console.log('default(' + JSON.stringify(data) + ')');169 defaultCounter.add(1);170 }171 export function teardown(data) {172 console.log('teardown(' + JSON.stringify(data) + ')');173 teardownCounter.add(1);174 }175 export function handleSummary(data) {176 console.log('handleSummary()');177 return { stdout: JSON.stringify(data, null, 4) }178 }179 `180 ts := newGlobalTestState(t)181 require.NoError(t, afero.WriteFile(ts.fs, filepath.Join(ts.cwd, "test.js"), []byte(script), 0o644))182 ts.args = []string{"k6", "run", "--quiet", "--log-format=raw", "test.js"}183 newRootCommand(ts.globalState).execute()184 expLogLines := []string{185 `setup() start`, `setup() end`, `default({"foo":"bar"})`,186 `default({"foo":"bar"})`, `teardown({"foo":"bar"})`, `handleSummary()`,187 }188 logHookEntries := ts.loggerHook.Drain()189 require.Len(t, logHookEntries, len(expLogLines))190 for i, expLogLine := range expLogLines {191 assert.Equal(t, expLogLine, logHookEntries[i].Message)192 }193 assert.Equal(t, strings.Join(expLogLines, "\n")+"\n", ts.stdErr.String())194 var summary map[string]interface{}195 require.NoError(t, json.Unmarshal(ts.stdOut.Bytes(), &summary))196 metrics, ok := summary["metrics"].(map[string]interface{})197 require.True(t, ok)198 teardownCounter, ok := metrics["teardown_counter"].(map[string]interface{})199 require.True(t, ok)200 teardownThresholds, ok := teardownCounter["thresholds"].(map[string]interface{})201 require.True(t, ok)202 expected := map[string]interface{}{"count == 1": map[string]interface{}{"ok": true}}203 require.Equal(t, expected, teardownThresholds)204}205func TestSSLKEYLOGFILE(t *testing.T) {206 t.Parallel()207 // TODO don't use insecureSkipTLSVerify when/if tlsConfig is given to the runner from outside208 tb := httpmultibin.NewHTTPMultiBin(t)209 ts := newGlobalTestState(t)210 ts.args = []string{"k6", "run", "-"}211 ts.envVars = map[string]string{"SSLKEYLOGFILE": "./ssl.log"}212 ts.stdIn = bytes.NewReader([]byte(tb.Replacer.Replace(`213 import http from "k6/http"214 export const options = {215 hosts: {216 "HTTPSBIN_DOMAIN": "HTTPSBIN_IP",217 },218 insecureSkipTLSVerify: true,219 }220 export default () => {221 http.get("HTTPSBIN_URL/get");222 }223 `)))224 newRootCommand(ts.globalState).execute()225 assert.True(t,226 testutils.LogContains(ts.loggerHook.Drain(), logrus.WarnLevel, "SSLKEYLOGFILE was specified"))227 sslloglines, err := afero.ReadFile(ts.fs, filepath.Join(ts.cwd, "ssl.log"))228 require.NoError(t, err)229 // TODO maybe have multiple depending on the ciphers used as that seems to change it230 require.Regexp(t, "^CLIENT_[A-Z_]+ [0-9a-f]+ [0-9a-f]+\n", string(sslloglines))231}232// TODO: add a hell of a lot more integration tests, including some that spin up233// a test HTTP server and actually check if k6 hits it234// TODO: also add a test that starts multiple k6 "instances", for example:235// - one with `k6 run --paused` and another with `k6 resume`236// - one with `k6 run` and another with `k6 stats` or `k6 status`237func TestExecutionTestOptionsDefaultValues(t *testing.T) {238 t.Parallel()239 script := `240 import exec from 'k6/execution';241 export default function () {242 console.log(exec.test.options)243 }244 `245 ts := newGlobalTestState(t)246 require.NoError(t, afero.WriteFile(ts.fs, filepath.Join(ts.cwd, "test.js"), []byte(script), 0o644))247 ts.args = []string{"k6", "run", "--iterations", "1", "test.js"}248 newRootCommand(ts.globalState).execute()249 loglines := ts.loggerHook.Drain()250 require.Len(t, loglines, 1)251 expected := `{"paused":null,"executionSegment":null,"executionSegmentSequence":null,"noSetup":null,"setupTimeout":null,"noTeardown":null,"teardownTimeout":null,"rps":null,"dns":{"ttl":null,"select":null,"policy":null},"maxRedirects":null,"userAgent":null,"batch":null,"batchPerHost":null,"httpDebug":null,"insecureSkipTLSVerify":null,"tlsCipherSuites":null,"tlsVersion":null,"tlsAuth":null,"throw":null,"thresholds":null,"blacklistIPs":null,"blockHostnames":null,"hosts":null,"noConnectionReuse":null,"noVUConnectionReuse":null,"minIterationDuration":null,"ext":null,"summaryTrendStats":["avg", "min", "med", "max", "p(90)", "p(95)"],"summaryTimeUnit":null,"systemTags":["check","error","error_code","expected_response","group","method","name","proto","scenario","service","status","subproto","tls_version","url"],"tags":null,"metricSamplesBufferSize":null,"noCookiesReset":null,"discardResponseBodies":null,"consoleOutput":null,"scenarios":{"default":{"vus":null,"iterations":1,"executor":"shared-iterations","maxDuration":null,"startTime":null,"env":null,"tags":null,"gracefulStop":null,"exec":null}},"localIPs":null}`252 assert.JSONEq(t, expected, loglines[0].Message)253}...
convert_test.go
Source:convert_test.go
...113 har, err := ioutil.ReadFile("testdata/example.har")114 require.NoError(t, err)115 expectedTestPlan, err := ioutil.ReadFile("testdata/example.js")116 require.NoError(t, err)117 testState := newGlobalTestState(t)118 require.NoError(t, afero.WriteFile(testState.fs, "correlate.har", har, 0o644))119 testState.args = []string{120 "k6", "convert", "--output=result.js", "--correlate=true", "--no-batch=true",121 "--enable-status-code-checks=true", "--return-on-failed-check=true", "correlate.har",122 }123 newRootCommand(testState.globalState).execute()124 result, err := afero.ReadFile(testState.fs, "result.js")125 require.NoError(t, err)126 // Sanitizing to avoid windows problems with carriage returns127 re := regexp.MustCompile(`\r`)128 expected := re.ReplaceAllString(string(expectedTestPlan), ``)129 resultStr := re.ReplaceAllString(string(result), ``)130 if assert.NoError(t, err) {131 // assert.Equal suppresses the diff it is too big, so we add it as the test error message manually as well.132 diff, _ := difflib.GetUnifiedDiffString(difflib.UnifiedDiff{133 A: difflib.SplitLines(expected),134 B: difflib.SplitLines(resultStr),135 FromFile: "Expected",136 FromDate: "",137 ToFile: "Actual",138 ToDate: "",139 Context: 1,140 })141 assert.Equal(t, expected, resultStr, diff)142 }143}144func TestConvertCmdStdout(t *testing.T) {145 t.Parallel()146 testState := newGlobalTestState(t)147 require.NoError(t, afero.WriteFile(testState.fs, "stdout.har", []byte(testHAR), 0o644))148 testState.args = []string{"k6", "convert", "stdout.har"}149 newRootCommand(testState.globalState).execute()150 assert.Equal(t, testHARConvertResult, testState.stdOut.String())151}152func TestConvertCmdOutputFile(t *testing.T) {153 t.Parallel()154 testState := newGlobalTestState(t)155 require.NoError(t, afero.WriteFile(testState.fs, "output.har", []byte(testHAR), 0o644))156 testState.args = []string{"k6", "convert", "--output", "result.js", "output.har"}157 newRootCommand(testState.globalState).execute()158 output, err := afero.ReadFile(testState.fs, "result.js")159 assert.NoError(t, err)160 assert.Equal(t, testHARConvertResult, string(output))161}162// TODO: test options injection; right now that's difficult because when there are multiple163// options, they can be emitted in different order in the JSON...
newGlobalTestState
Using AI Code Generation
1import (2func main() {3 cmd := newGlobalTestState()4 fmt.Println(cmd)5}6import (7func main() {8 cmd := newGlobalTestState()9 fmt.Println(cmd)10}
newGlobalTestState
Using AI Code Generation
1import (2func main() {3 stack, err := node.New(&node.Config{})4 if err != nil {5 utils.Fatalf("Failed to create the protocol stack: %v", err)6 }7 if eth.EthEnabled {8 if err := stack.Register(func(ctx *node.ServiceContext) (node.Service, error) {9 return eth.New(ctx, ð.Config{})10 }); err != nil {11 utils.Fatalf("Failed to register the Ethereum service: %v", err)12 }13 }14 utils.StartNode(stack)15 defer stack.Stop()16}17import (18func main() {19 stack, err := node.New(&node.Config{})20 if err != nil {21 utils.Fatalf("Failed to create the protocol stack: %v", err)22 }23 if eth.EthEnabled {24 if err := stack.Register(func(ctx *node.ServiceContext) (node.Service, error) {25 return eth.New(ctx, ð.Config{})26 }); err != nil {27 utils.Fatalf("Failed to register the Ethereum service: %v", err)28 }29 }30 utils.StartNode(stack)31 defer stack.Stop()32}33import (34func main() {35 stack, err := node.New(&node.Config{})36 if err != nil {37 utils.Fatalf("Failed to create the protocol stack: %v", err)
newGlobalTestState
Using AI Code Generation
1import (2func TestMain(m *testing.M) {3 os.Exit(testMain(m))4}5func testMain(m *testing.M) int {6 return m.Run()7}8func TestMain(m *testing.M) {9 os.Exit(testMain(m))10}11func testMain(m *testing.M) int {12 return m.Run()13}14func TestMain(m *testing.M) {15 os.Exit(testMain(m))16}17func testMain(m *testing.M) int {18 return m.Run()19}20func TestMain(m *testing.M) {21 os.Exit(testMain(m))22}23func testMain(m *testing.M) int {24 return m.Run()25}26func TestMain(m *testing.M) {
newGlobalTestState
Using AI Code Generation
1import "fmt"2func main() {3 fmt.Println("Hello, World!")4 cmd := new(cmd)5 cmd.newGlobalTestState()6}7import "fmt"8func main() {9 fmt.Println("Hello, World!")10 cmd := new(cmd)11 cmd.newGlobalTestState()12}13import "fmt"14func main() {15 fmt.Println("Hello, World!")16 cmd := new(cmd)17 cmd.newGlobalTestState()18}19import "fmt"20func main() {21 fmt.Println("Hello, World!")22 cmd := new(cmd)23 cmd.newGlobalTestState()24}25import "fmt"26func main() {27 fmt.Println("Hello, World!")28 cmd := new(cmd)29 cmd.newGlobalTestState()30}31import "fmt"32func main() {33 fmt.Println("Hello, World!")34 cmd := new(cmd)35 cmd.newGlobalTestState()36}37import "fmt"38func main() {39 fmt.Println("Hello, World!")40 cmd := new(cmd)41 cmd.newGlobalTestState()42}43import "fmt"44func main() {45 fmt.Println("Hello, World!")46 cmd := new(cmd)47 cmd.newGlobalTestState()48}49import "fmt"50func main() {51 fmt.Println("Hello, World!")52 cmd := new(cmd)53 cmd.newGlobalTestState()54}55import "fmt"56func main() {57 fmt.Println("Hello, World!")
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!!