How to use LogContains method of testutils Package

Best K6 code snippet using testutils.LogContains

integration_test.go

Source:integration_test.go Github

copy

Full Screen

...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}232func TestThresholdDeprecationWarnings(t *testing.T) {233 t.Parallel()234 // TODO: adjust this test after we actually make url, error, iter and vu non-indexable235 ts := newGlobalTestState(t)236 ts.args = []string{"k6", "run", "--system-tags", "url,error,vu,iter", "-"}237 ts.stdIn = bytes.NewReader([]byte(`238 export const options = {239 thresholds: {240 'http_req_duration{url:https://test.k6.io}': ['p(95)<500', 'p(99)<1000'],241 'http_req_duration{error:foo}': ['p(99)<1000'],242 'iterations{vu:1,iter:0}': ['count == 1'],243 },244 };245 export default function () { }`,246 ))247 newRootCommand(ts.globalState).execute()248 logs := ts.loggerHook.Drain()249 assert.True(t, testutils.LogContains(logs, logrus.WarnLevel,250 "Thresholds like 'http_req_duration{url:https://test.k6.io}', based on the high-cardinality 'url' metric tag, are deprecated",251 ))252 assert.True(t, testutils.LogContains(logs, logrus.WarnLevel,253 "Thresholds like 'http_req_duration{error:foo}', based on the high-cardinality 'error' metric tag, are deprecated",254 ))255 assert.True(t, testutils.LogContains(logs, logrus.WarnLevel,256 "Thresholds like 'iterations{vu:1,iter:0}', based on the high-cardinality 'vu' metric tag, are deprecated",257 ))258 assert.True(t, testutils.LogContains(logs, logrus.WarnLevel,259 "Thresholds like 'iterations{vu:1,iter:0}', based on the high-cardinality 'iter' metric tag, are deprecated",260 ))261}262// TODO: add a hell of a lot more integration tests, including some that spin up263// a test HTTP server and actually check if k6 hits it264// TODO: also add a test that starts multiple k6 "instances", for example:265// - one with `k6 run --paused` and another with `k6 resume`266// - one with `k6 run` and another with `k6 stats` or `k6 status`267func TestExecutionTestOptionsDefaultValues(t *testing.T) {268 t.Parallel()269 script := `270 import exec from 'k6/execution';271 export default function () {272 console.log(exec.test.options)...

Full Screen

Full Screen

root_test.go

Source:root_test.go Github

copy

Full Screen

...80 export default function() { console.log('bar'); };81 `))82 newRootCommand(ts.globalState).execute()83 logMsgs := ts.loggerHook.Drain()84 assert.True(t, testutils.LogContains(logMsgs, logrus.InfoLevel, "foo"))85 assert.True(t, testutils.LogContains(logMsgs, logrus.InfoLevel, "bar"))86 assert.Contains(t, ts.stdErr.String(), `"level":"info","msg":"foo","source":"console"`)87 assert.Contains(t, ts.stdErr.String(), `"level":"info","msg":"bar","source":"console"`)88 // TODO: after we get rid of cobra, actually emit this message to stderr89 // and, ideally, through the log, not just print it...90 assert.False(t, testutils.LogContains(logMsgs, logrus.InfoLevel, "logformat"))91 assert.Contains(t, ts.stdOut.String(), `--logformat has been deprecated`)92}...

Full Screen

Full Screen

LogContains

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 logFile := flag.String("logFile", "C:\\Users\\rohit\\go\\src\\github.com\\cockroachdb\\cockroach\\pkg\\testutils\\log.txt", "Log file location")4 flag.Parse()5 f, err := os.Create(*logFile)6 if err != nil {7 fmt.Println("Error while creating the log file")8 }9 defer f.Close()10 log.SetOutput(f)11 log.SetLevel(log.InfoLog)12 log.Info("This is a test message")13 log.Info("This is a test message with a word that we want to search for")14 if testutils.LogContains(f, "search") {15 fmt.Println("Search word found")16 } else {17 fmt.Println("Search word not found")18 }19}

Full Screen

Full Screen

LogContains

Using AI Code Generation

copy

Full Screen

1func TestMain(m *testing.M) {2}3func TestLogContains(t *testing.T) {4}5func TestLogContainsRegex(t *testing.T) {6}7func TestLogDoesNotContain(t *testing.T) {8}9func TestLogDoesNotContainRegex(t *testing.T) {10}11func TestLogContainsStr(t *testing.T) {

Full Screen

Full Screen

LogContains

Using AI Code Generation

copy

Full Screen

1func TestLogContains(t *testing.T) {2 if !testutils.LogContains(t, "foo") {3 t.Fatal("log does not contain 'foo'")4 }5}6func TestLogDoesNotContain(t *testing.T) {7 if testutils.LogDoesNotContain(t, "foo") {8 t.Fatal("log contains 'foo'")9 }10}11func TestLogMatches(t *testing.T) {12 if !testutils.LogMatches(t, "foo+") {13 t.Fatal("log does not match 'foo+'")14 }15}16func TestLogDoesNotMatch(t *testing.T) {17 if testutils.LogDoesNotMatch(t, "foo+") {18 t.Fatal("log matches 'foo+'")19 }20}21func TestLogIs(t *testing.T) {22 if !testutils.LogIs(t, "foo") {23 t.Fatal("log is not 'foo'")

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.

Run K6 automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful