Best K6 code snippet using js.StackTrace
frontend_logging_test.go
Source:frontend_logging_test.go  
1package api2import (3	"errors"4	"io/ioutil"5	"net/url"6	"os"7	"strings"8	"testing"9	"time"10	"github.com/getsentry/sentry-go"11	"github.com/go-kit/log"12	"github.com/grafana/grafana/pkg/api/frontendlogging"13	"github.com/grafana/grafana/pkg/api/response"14	"github.com/grafana/grafana/pkg/api/routing"15	"github.com/grafana/grafana/pkg/infra/log/level"16	"github.com/grafana/grafana/pkg/models"17	"github.com/grafana/grafana/pkg/plugins"18	"github.com/grafana/grafana/pkg/setting"19	"github.com/stretchr/testify/assert"20	"github.com/stretchr/testify/require"21)22type SourceMapReadRecord struct {23	dir  string24	path string25}26type logScenarioFunc func(c *scenarioContext, logs map[string]interface{}, sourceMapReads []SourceMapReadRecord)27func logSentryEventScenario(t *testing.T, desc string, event frontendlogging.FrontendSentryEvent, fn logScenarioFunc) {28	t.Run(desc, func(t *testing.T) {29		var logcontent = make(map[string]interface{})30		logcontent["logger"] = "frontend"31		newfrontendLogger := log.Logger(log.LoggerFunc(func(keyvals ...interface{}) error {32			for i := 0; i < len(keyvals); i += 2 {33				logcontent[keyvals[i].(string)] = keyvals[i+1]34			}35			return nil36		}))37		origHandler := frontendLogger.GetLogger()38		frontendLogger.AddLogger(newfrontendLogger, "info", map[string]level.Option{})39		sourceMapReads := []SourceMapReadRecord{}40		t.Cleanup(func() {41			frontendLogger.SetLogger(origHandler)42		})43		sc := setupScenarioContext(t, "/log")44		cdnRootURL, e := url.Parse("https://storage.googleapis.com/grafana-static-assets")45		require.NoError(t, e)46		cfg := &setting.Cfg{47			StaticRootPath: "/staticroot",48			CDNRootURL:     cdnRootURL,49		}50		readSourceMap := func(dir string, path string) ([]byte, error) {51			sourceMapReads = append(sourceMapReads, SourceMapReadRecord{52				dir:  dir,53				path: path,54			})55			if strings.Contains(path, "error") {56				return nil, errors.New("epic hard drive failure")57			}58			if strings.HasSuffix(path, "foo.js.map") {59				f, err := ioutil.ReadFile("./frontendlogging/test-data/foo.js.map")60				require.NoError(t, err)61				return f, nil62			}63			return nil, os.ErrNotExist64		}65		// fake plugin route so we will try to find a source map there66		pm := fakePluginStaticRouteResolver{67			routes: []*plugins.StaticRoute{68				{69					Directory: "/usr/local/telepathic-panel",70					PluginID:  "telepathic",71				},72			},73		}74		sourceMapStore := frontendlogging.NewSourceMapStore(cfg, &pm, readSourceMap)75		loggingHandler := NewFrontendLogMessageHandler(sourceMapStore)76		handler := routing.Wrap(func(c *models.ReqContext) response.Response {77			sc.context = c78			c.Req.Body = mockRequestBody(event)79			return loggingHandler(c)80		})81		sc.m.Post(sc.url, handler)82		sc.fakeReqWithParams("POST", sc.url, map[string]string{}).exec()83		fn(sc, logcontent, sourceMapReads)84	})85}86func TestFrontendLoggingEndpoint(t *testing.T) {87	ts, err := time.Parse("2006-01-02T15:04:05.000Z", "2020-10-22T06:29:29.078Z")88	require.NoError(t, err)89	t.Run("FrontendLoggingEndpoint", func(t *testing.T) {90		request := sentry.Request{91			URL: "http://localhost:3000/",92			Headers: map[string]string{93				"User-Agent": "Chrome",94			},95		}96		user := sentry.User{97			Email: "geralt@kaermorhen.com",98			ID:    "45",99		}100		event := sentry.Event{101			EventID:   "123",102			Level:     sentry.LevelError,103			Request:   &request,104			Timestamp: ts,105		}106		errorEvent := frontendlogging.FrontendSentryEvent{107			Event: &event,108			Exception: &frontendlogging.FrontendSentryException{109				Values: []frontendlogging.FrontendSentryExceptionValue{110					{111						Type:  "UserError",112						Value: "Please replace user and try again",113						Stacktrace: sentry.Stacktrace{114							Frames: []sentry.Frame{115								{116									Function: "foofn",117									Filename: "foo.js",118									Lineno:   123,119									Colno:    23,120								},121								{122									Function: "barfn",123									Filename: "bar.js",124									Lineno:   113,125									Colno:    231,126								},127							},128						},129					},130				},131			},132		}133		logSentryEventScenario(t, "Should log received error event", errorEvent,134			func(sc *scenarioContext, logs map[string]interface{}, sourceMapReads []SourceMapReadRecord) {135				assert.Equal(t, 200, sc.resp.Code)136				assertContextContains(t, logs, "logger", "frontend")137				assertContextContains(t, logs, "url", errorEvent.Request.URL)138				assertContextContains(t, logs, "user_agent", errorEvent.Request.Headers["User-Agent"])139				assertContextContains(t, logs, "event_id", errorEvent.EventID)140				assertContextContains(t, logs, "original_timestamp", errorEvent.Timestamp)141				assertContextContains(t, logs, "stacktrace", `UserError: Please replace user and try again142  at foofn (foo.js:123:23)143  at barfn (bar.js:113:231)`)144				assert.NotContains(t, logs, "context")145			})146		messageEvent := frontendlogging.FrontendSentryEvent{147			Event: &sentry.Event{148				EventID:   "123",149				Level:     sentry.LevelInfo,150				Request:   &request,151				Timestamp: ts,152				Message:   "hello world",153				User:      user,154			},155			Exception: nil,156		}157		logSentryEventScenario(t, "Should log received message event", messageEvent,158			func(sc *scenarioContext, logs map[string]interface{}, sourceMapReads []SourceMapReadRecord) {159				assert.Equal(t, 200, sc.resp.Code)160				assert.Len(t, logs, 10)161				assertContextContains(t, logs, "logger", "frontend")162				assertContextContains(t, logs, "msg", "hello world")163				assertContextContains(t, logs, "lvl", level.InfoValue())164				assertContextContains(t, logs, "logger", "frontend")165				assertContextContains(t, logs, "url", messageEvent.Request.URL)166				assertContextContains(t, logs, "user_agent", messageEvent.Request.Headers["User-Agent"])167				assertContextContains(t, logs, "event_id", messageEvent.EventID)168				assertContextContains(t, logs, "original_timestamp", messageEvent.Timestamp)169				assert.NotContains(t, logs, "stacktrace")170				assert.NotContains(t, logs, "context")171				assertContextContains(t, logs, "user_email", user.Email)172				assertContextContains(t, logs, "user_id", user.ID)173			})174		eventWithContext := frontendlogging.FrontendSentryEvent{175			Event: &sentry.Event{176				EventID:   "123",177				Level:     sentry.LevelInfo,178				Request:   &request,179				Timestamp: ts,180				Message:   "hello world",181				User:      user,182				Contexts: map[string]interface{}{183					"foo": map[string]interface{}{184						"one":   "two",185						"three": 4,186					},187					"bar": "baz",188				},189			},190			Exception: nil,191		}192		logSentryEventScenario(t, "Should log event context", eventWithContext,193			func(sc *scenarioContext, logs map[string]interface{}, sourceMapReads []SourceMapReadRecord) {194				assert.Equal(t, 200, sc.resp.Code)195				assertContextContains(t, logs, "context_foo_one", "two")196				assertContextContains(t, logs, "context_foo_three", "4")197				assertContextContains(t, logs, "context_bar", "baz")198			})199		errorEventForSourceMapping := frontendlogging.FrontendSentryEvent{200			Event: &event,201			Exception: &frontendlogging.FrontendSentryException{202				Values: []frontendlogging.FrontendSentryExceptionValue{203					{204						Type:  "UserError",205						Value: "Please replace user and try again",206						Stacktrace: sentry.Stacktrace{207							Frames: []sentry.Frame{208								{209									Function: "foofn",210									Filename: "http://localhost:3000/public/build/moo/foo.js", // source map found and mapped, core211									Lineno:   2,212									Colno:    5,213								},214								{215									Function: "foofn",216									Filename: "http://localhost:3000/public/plugins/telepathic/foo.js", // plugin, source map found and mapped217									Lineno:   3,218									Colno:    10,219								},220								{221									Function: "explode",222									Filename: "http://localhost:3000/public/build/error.js", // reading source map throws error223									Lineno:   3,224									Colno:    10,225								},226								{227									Function: "wat",228									Filename: "http://localhost:3000/public/build/bar.js", // core, but source map not found on fs229									Lineno:   3,230									Colno:    10,231								},232								{233									Function: "nope",234									Filename: "http://localhost:3000/baz.js", // not core or plugin, wont even attempt to get source map235									Lineno:   3,236									Colno:    10,237								},238								{239									Function: "fake",240									Filename: "http://localhost:3000/public/build/../../secrets.txt", // path will be sanitized241									Lineno:   3,242									Colno:    10,243								},244								{245									Function: "cdn",246									Filename: "https://storage.googleapis.com/grafana-static-assets/grafana-oss/pre-releases/7.5.0-11925pre/public/build/foo.js", // source map found and mapped247									Lineno:   3,248									Colno:    10,249								},250							},251						},252					},253				},254			},255		}256		logSentryEventScenario(t, "Should load sourcemap and transform stacktrace line when possible",257			errorEventForSourceMapping, func(sc *scenarioContext, logs map[string]interface{}, sourceMapReads []SourceMapReadRecord) {258				assert.Equal(t, 200, sc.resp.Code)259				assert.Len(t, logs, 9)260				assertContextContains(t, logs, "stacktrace", `UserError: Please replace user and try again261  at ? (core|webpack:///./some_source.ts:2:2)262  at ? (telepathic|webpack:///./some_source.ts:3:2)263  at explode (http://localhost:3000/public/build/error.js:3:10)264  at wat (http://localhost:3000/public/build/bar.js:3:10)265  at nope (http://localhost:3000/baz.js:3:10)266  at fake (http://localhost:3000/public/build/../../secrets.txt:3:10)267  at ? (core|webpack:///./some_source.ts:3:2)`)268				assert.Len(t, sourceMapReads, 6)269				assert.Equal(t, "/staticroot", sourceMapReads[0].dir)270				assert.Equal(t, "build/moo/foo.js.map", sourceMapReads[0].path)271				assert.Equal(t, "/usr/local/telepathic-panel", sourceMapReads[1].dir)272				assert.Equal(t, "/foo.js.map", sourceMapReads[1].path)273				assert.Equal(t, "/staticroot", sourceMapReads[2].dir)274				assert.Equal(t, "build/error.js.map", sourceMapReads[2].path)275				assert.Equal(t, "/staticroot", sourceMapReads[3].dir)276				assert.Equal(t, "build/bar.js.map", sourceMapReads[3].path)277				assert.Equal(t, "/staticroot", sourceMapReads[4].dir)278				assert.Equal(t, "secrets.txt.map", sourceMapReads[4].path)279				assert.Equal(t, "/staticroot", sourceMapReads[5].dir)280				assert.Equal(t, "build/foo.js.map", sourceMapReads[5].path)281			})282	})283}284func assertContextContains(t *testing.T, logRecord map[string]interface{}, label string, value interface{}) {285	assert.Contains(t, logRecord, label)286	assert.Equal(t, value, logRecord[label])287}...stacktrace_test.go
Source:stacktrace_test.go  
...7	"strings"8	"testing"9	"github.com/newrelic/go-agent/internal/stacktracetest"10)11func TestGetStackTrace(t *testing.T) {12	stack := GetStackTrace()13	js, err := json.Marshal(stack)14	if nil != err {15		t.Fatal(err)16	}17	if nil == js {18		t.Fatal(string(js))19	}20}21func TestLongStackTraceLimitsFrames(t *testing.T) {22	st := stacktracetest.CountedCall(maxStackTraceFrames+20, func() []uintptr {23		return GetStackTrace()24	})25	if len(st) != maxStackTraceFrames {26		t.Error("Unexpected size of stacktrace", maxStackTraceFrames, len(st))27	}28	l := len(StackTrace(st).frames())29	if l != maxStackTraceFrames {30		t.Error("Unexpected number of frames", maxStackTraceFrames, l)31	}32}33func TestManyStackTraceFramesLimitsOutput(t *testing.T) {34	frames := make([]stacktraceFrame, maxStackTraceFrames+20)35	expect := `[36	{},{},{},{},{},{},{},{},{},{},37	{},{},{},{},{},{},{},{},{},{},38	{},{},{},{},{},{},{},{},{},{},	39	{},{},{},{},{},{},{},{},{},{},	40	{},{},{},{},{},{},{},{},{},{},	41	{},{},{},{},{},{},{},{},{},{},	42	{},{},{},{},{},{},{},{},{},{},	43	{},{},{},{},{},{},{},{},{},{},	44	{},{},{},{},{},{},{},{},{},{},	45	{},{},{},{},{},{},{},{},{},{}	46	]`47	estimate := 256 * len(frames)48	output := bytes.NewBuffer(make([]byte, 0, estimate))49	writeFrames(output, frames)50	if CompactJSONString(expect) != output.String() {51		t.Error("Unexpected JSON output", CompactJSONString(expect), output.String())52	}53}54func TestStacktraceFrames(t *testing.T) {55	// This stacktrace taken from Go 1.1156	inputFrames := []stacktraceFrame{57		{58			File: "/Users/will/Desktop/gopath/src/github.com/newrelic/go-agent/internal/stacktrace.go",59			Name: "github.com/newrelic/go-agent/internal.GetStackTrace",60			Line: 17,61		},62		{63			File: "/Users/will/Desktop/gopath/src/github.com/newrelic/go-agent/internal_txn.go",64			Name: "github.com/newrelic/go-agent.(*txn).NoticeError",65			Line: 696,66		},67		{68			File: "\u003cautogenerated\u003e",69			Name: "go.(*struct { github.com/newrelic/go-agent.threadWithExtras }).NoticeError",70			Line: 1,71		},72		{73			File: "/Users/will/Desktop/gopath/src/github.com/newrelic/go-agent/internal_attributes_test.go",74			Name: "github.com/newrelic/go-agent.TestAddAttributeSecurityPolicyDisablesInclude",75			Line: 68,76		},77		{78			File: "/Users/will/.gvm/gos/go1.11/src/testing/testing.go",79			Name: "testing.tRunner",80			Line: 827,81		},82		{83			File: "/Users/will/.gvm/gos/go1.11/src/runtime/asm_amd64.s",84			Name: "runtime.goexit",85			Line: 1333,86		},87	}88	buf := &bytes.Buffer{}89	writeFrames(buf, inputFrames)90	expectedJSON := `[91		{92			"name":"testing.tRunner",93			"filepath":"/Users/will/.gvm/gos/go1.11/src/testing/testing.go",94			"line":82795		},96		{97			"name":"runtime.goexit",98			"filepath":"/Users/will/.gvm/gos/go1.11/src/runtime/asm_amd64.s",99			"line":1333100		}101	]`102	testExpectedJSON(t, expectedJSON, buf.String())103}104func TestStackTraceTopFrame(t *testing.T) {105	// This test uses a separate package since the stacktrace code removes106	// the top stack frames which are in packages "newrelic" and "internal".107	stackJSON := stacktracetest.TopStackFrame(func() []byte {108		st := GetStackTrace()109		js, _ := json.Marshal(st)110		return js111	})112	stack := []struct {113		Name     string `json:"name"`114		FilePath string `json:"filepath"`115		Line     int    `json:"line"`116	}{}117	if err := json.Unmarshal(stackJSON, &stack); err != nil {118		t.Fatal(err)119	}120	if len(stack) < 2 {121		t.Fatal(string(stackJSON))122	}123	if stack[0].Name != "stacktracetest.TopStackFrame" {124		t.Error(string(stackJSON))125	}126	if stack[0].Line != 9 {127		t.Error(string(stackJSON))128	}129	if !strings.Contains(stack[0].FilePath, "go-agent/internal/stacktracetest/stacktracetest.go") {130		t.Error(string(stackJSON))131	}132}133func TestFramesCount(t *testing.T) {134	st := stacktracetest.CountedCall(3, func() []uintptr {135		return GetStackTrace()136	})137	frames := StackTrace(st).frames()138	if len(st) != len(frames) {139		t.Error("Invalid # of frames", len(st), len(frames))140	}141}...StackTrace
Using AI Code Generation
1import (2func main() {3	done := make(chan bool)4	js.Global().Set("printStackTrace", js.FuncOf(func(this js.Value, args []js.Value) interface{} {5		fmt.Println("Printing StackTrace")6	}))7	js.Global().Call("eval", `8		function printStackTrace() {9			console.log("StackTrace");10		}11}StackTrace
Using AI Code Generation
1import (2func main() {3	vm := otto.New()4	underscore.Define(vm)5	vm.Run(`6		function foo() {7			var err = new Error("foo");8			console.log(err.stack);9		}10		foo();11}StackTrace
Using AI Code Generation
1import (2func main() {3	err := js.Global().Get("Error").New("Test Error")4	fmt.Println(err.Get("stack").String())5}6import (7func main() {8	err := js.Global().Get("Error").New("Test Error")9	fmt.Println(err.Call("stackTrace").String())10}11import (12func main() {13	err := js.Global().Get("Error").New("Test Error")14	fmt.Println(err.Get("stackTrace").String())15}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!!
