Best Gauge code snippet using event.contains
logger_test.go
Source:logger_test.go  
1package log2import (3	"bytes"4	"context"5	"errors"6	"fmt"7	gcontext "github.com/cultureamp/glamplify/context"8	"gotest.tools/assert"9	"io/ioutil"10	"net/http"11	"os"12	"strings"13	"testing"14	"time"15)16var (17	ctx      context.Context18	rsFields gcontext.RequestScopedFields19)20func TestMain(m *testing.M) {21	setup()22	code := m.Run()23	shutdown()24	os.Exit(code)25}26func setup() {27	ctx = context.Background()28	ctx = gcontext.AddRequestFields(ctx, gcontext.RequestScopedFields{29		TraceID:             "1-2-3",30		RequestID:           "7-8-9",31		CorrelationID:       "1-5-9",32		CustomerAggregateID: "hooli",33		UserAggregateID:     "UserAggregateID-123",34	})35	rsFields, _ = gcontext.GetRequestScopedFields(ctx)36	os.Setenv("PRODUCT", "engagement")37	os.Setenv("APP", "murmur")38	os.Setenv("APP_VERSION", "87.23.11")39	os.Setenv("AWS_REGION", "us-west-02")40	os.Setenv("AWS_ACCOUNT_ID", "aws-account-123")41}42func shutdown() {43	os.Unsetenv("PRODUCT")44	os.Unsetenv("APP")45	os.Unsetenv("APP_VERSION")46	os.Unsetenv("AWS_REGION")47	os.Unsetenv("AWS_ACCOUNT_ID")48}49func Test_New(t *testing.T) {50	logger := New(rsFields)51	assert.Assert(t, logger != nil, logger)52}53func Test_NewWithContext(t *testing.T) {54	logger := NewFromCtx(ctx)55	assert.Assert(t, logger != nil, logger)56	rsFields, ok1 := gcontext.GetRequestScopedFields(ctx)57	assert.Assert(t, ok1, ok1)58	assert.Assert(t, rsFields.TraceID == "1-2-3", rsFields)59}60func Test_NewWithRequest(t *testing.T) {61	req, _ := http.NewRequest("GET", "*", nil)62	req1 := req.WithContext(ctx)63	logger := NewFromRequest(req1)64	assert.Assert(t, logger != nil, logger)65	rsFields, ok1 := gcontext.GetRequestScopedFields(req1.Context())66	assert.Assert(t, ok1, ok1)67	assert.Assert(t, rsFields.TraceID == "1-2-3", rsFields)68}69func Test_Log_Debug(t *testing.T) {70	memBuffer := &bytes.Buffer{}71	writer := NewWriter(func(conf *WriterConfig) {72		conf.Output = memBuffer73	})74	logger := NewWitCustomWriter(rsFields, writer)75	logger.Debug( "detail_event")76	msg := memBuffer.String()77	assertContainsString(t, msg, "event", "detail_event")78	assertContainsString(t, msg, "severity", "DEBUG")79	assertContainsString(t, msg, "trace_id", "1-2-3")80	assertContainsString(t, msg, "customer", "hooli")81	assertContainsString(t, msg, "user", "UserAggregateID-123")82	assertContainsString(t, msg, "product", "engagement")83	assertContainsString(t, msg, "app", "murmur")84	assertContainsString(t, msg, "app_version", "87.23.11")85	assertContainsString(t, msg, "aws_region", "us-west-02")86	assertContainsString(t, msg, "aws_account_id", "aws-account-123")87}88func Test_Log_DebugWithFields(t *testing.T) {89	memBuffer := &bytes.Buffer{}90	writer := NewWriter(func(conf *WriterConfig) {91		conf.Output = memBuffer92	})93	logger := NewWitCustomWriter(rsFields, writer)94	logger.Debug("detail_event", Fields{95		"string":        "hello",96		"int":           123,97		"float":         42.48,98		"string2":       "hello world",99		"string3 space": "world",100	})101	msg := memBuffer.String()102	assertContainsString(t, msg, "event", "detail_event")103	assertContainsString(t, msg, "severity", "DEBUG")104	assertContainsString(t, msg, "string", "hello")105	assertContainsInt(t, msg, "int", 123)106	assertContainsFloat(t, msg, "float", 42.48)107	assertContainsString(t, msg, "string2", "hello world")108	assertContainsString(t, msg, "string3_space", "world")109	assertContainsString(t, msg, "trace_id", "1-2-3")110	assertContainsString(t, msg, "customer", "hooli")111	assertContainsString(t, msg, "user", "UserAggregateID-123")112	assertContainsString(t, msg, "product", "engagement")113	assertContainsString(t, msg, "app", "murmur")114	assertContainsString(t, msg, "app_version", "87.23.11")115	assertContainsString(t, msg, "aws_region", "us-west-02")116	assertContainsString(t, msg, "aws_account_id", "aws-account-123")117	assertScopeContainsSubDoc(t, msg, "properties")118}119func Test_Log_Info(t *testing.T) {120	memBuffer := &bytes.Buffer{}121	writer := NewWriter(func(conf *WriterConfig) {122		conf.Output = memBuffer123	})124	logger := NewWitCustomWriter(rsFields, writer)125	logger.Info("info_event")126	msg := memBuffer.String()127	assertContainsString(t, msg, "event", "info_event")128	assertContainsString(t, msg, "severity", "INFO")129	assertContainsString(t, msg, "trace_id", "1-2-3")130	assertContainsString(t, msg, "customer", "hooli")131	assertContainsString(t, msg, "user", "UserAggregateID-123")132	assertContainsString(t, msg, "product", "engagement")133	assertContainsString(t, msg, "app", "murmur")134	assertContainsString(t, msg, "app_version", "87.23.11")135	assertContainsString(t, msg, "aws_region", "us-west-02")136	assertContainsString(t, msg, "aws_account_id", "aws-account-123")137}138func Test_Log_InfoWithFields(t *testing.T) {139	memBuffer := &bytes.Buffer{}140	writer := NewWriter(func(conf *WriterConfig) {141		conf.Output = memBuffer142	})143	logger := NewWitCustomWriter(rsFields, writer)144	logger.Info("info_event", Fields{145		"string":        "hello",146		"int":           123,147		"float":         42.48,148		"string2":       "hello world",149		"string3 space": "world",150	})151	msg := memBuffer.String()152	assertContainsString(t, msg, "event", "info_event")153	assertContainsString(t, msg, "severity", "INFO")154	assertContainsString(t, msg, "string", "hello")155	assertContainsInt(t, msg, "int", 123)156	assertContainsFloat(t, msg, "float", 42.48)157	assertContainsString(t, msg, "string2", "hello world")158	assertContainsString(t, msg, "string3_space", "world")159	assertContainsString(t, msg, "trace_id", "1-2-3")160	assertContainsString(t, msg, "customer", "hooli")161	assertContainsString(t, msg, "user", "UserAggregateID-123")162	assertContainsString(t, msg, "product", "engagement")163	assertContainsString(t, msg, "app", "murmur")164	assertContainsString(t, msg, "app_version", "87.23.11")165	assertContainsString(t, msg, "aws_region", "us-west-02")166	assertContainsString(t, msg, "aws_account_id", "aws-account-123")167	assertScopeContainsSubDoc(t, msg, "properties")168}169func Test_Log_Warn(t *testing.T) {170	memBuffer := &bytes.Buffer{}171	writer := NewWriter(func(conf *WriterConfig) {172		conf.Output = memBuffer173	})174	logger := NewWitCustomWriter(rsFields, writer)175	logger.Warn("warn_event")176	msg := memBuffer.String()177	assertContainsString(t, msg, "event", "warn_event")178	assertContainsString(t, msg, "severity", "WARN")179	assertContainsString(t, msg, "trace_id", "1-2-3")180	assertContainsString(t, msg, "customer", "hooli")181	assertContainsString(t, msg, "user", "UserAggregateID-123")182	assertContainsString(t, msg, "product", "engagement")183	assertContainsString(t, msg, "app", "murmur")184	assertContainsString(t, msg, "app_version", "87.23.11")185	assertContainsString(t, msg, "aws_region", "us-west-02")186	assertContainsString(t, msg, "aws_account_id", "aws-account-123")187}188func Test_Log_WarnWithFields(t *testing.T) {189	memBuffer := &bytes.Buffer{}190	writer := NewWriter(func(conf *WriterConfig) {191		conf.Output = memBuffer192	})193	logger := NewWitCustomWriter(rsFields, writer)194	logger.Warn("warn_event", Fields{195		"string":        "hello",196		"int":           123,197		"float":         42.48,198		"string2":       "hello world",199		"string3 space": "world",200	})201	msg := memBuffer.String()202	assertContainsString(t, msg, "event", "warn_event")203	assertContainsString(t, msg, "severity", "WARN")204	assertContainsString(t, msg, "string", "hello")205	assertContainsInt(t, msg, "int", 123)206	assertContainsFloat(t, msg, "float", 42.48)207	assertContainsString(t, msg, "string2", "hello world")208	assertContainsString(t, msg, "string3_space", "world")209	assertContainsString(t, msg, "trace_id", "1-2-3")210	assertContainsString(t, msg, "customer", "hooli")211	assertContainsString(t, msg, "user", "UserAggregateID-123")212	assertContainsString(t, msg, "product", "engagement")213	assertContainsString(t, msg, "app", "murmur")214	assertContainsString(t, msg, "app_version", "87.23.11")215	assertContainsString(t, msg, "aws_region", "us-west-02")216	assertContainsString(t, msg, "aws_account_id", "aws-account-123")217	assertScopeContainsSubDoc(t, msg, "properties")218}219func Test_Log_Error(t *testing.T) {220	memBuffer := &bytes.Buffer{}221	writer := NewWriter(func(conf *WriterConfig) {222		conf.Output = memBuffer223	})224	logger := NewWitCustomWriter(rsFields, writer)225	logger.Error("error event", errors.New("something went wrong"))226	msg := memBuffer.String()227	assertContainsString(t, msg, "event", "error_event")228	assertContainsString(t, msg, "severity", "ERROR")229	assertContainsString(t, msg, "trace_id", "1-2-3")230	assertContainsString(t, msg, "customer", "hooli")231	assertContainsString(t, msg, "user", "UserAggregateID-123")232	assertContainsString(t, msg, "product", "engagement")233	assertContainsString(t, msg, "app", "murmur")234	assertContainsString(t, msg, "app_version", "87.23.11")235	assertContainsString(t, msg, "aws_region", "us-west-02")236	assertContainsString(t, msg, "aws_account_id", "aws-account-123")237	assertScopeContainsSubDoc(t, msg, "exception")238	assertContainsString(t, msg, "error", "something went wrong")239}240func Test_Log_ErrorWithFields(t *testing.T) {241	memBuffer := &bytes.Buffer{}242	writer := NewWriter(func(conf *WriterConfig) {243		conf.Output = memBuffer244	})245	logger := NewWitCustomWriter(rsFields, writer)246	logger.Error("error event", errors.New("something went wrong"), Fields{247		"string":        "hello",248		"int":           123,249		"float":         42.48,250		"string2":       "hello world",251		"string3 space": "world",252	})253	msg := memBuffer.String()254	assertContainsString(t, msg, "event", "error_event")255	assertContainsString(t, msg, "severity", "ERROR")256	assertContainsString(t, msg, "string", "hello")257	assertContainsInt(t, msg, "int", 123)258	assertContainsFloat(t, msg, "float", 42.48)259	assertContainsString(t, msg, "string2", "hello world")260	assertContainsString(t, msg, "string3_space", "world")261	assertContainsString(t, msg, "trace_id", "1-2-3")262	assertContainsString(t, msg, "customer", "hooli")263	assertContainsString(t, msg, "user", "UserAggregateID-123")264	assertContainsString(t, msg, "product", "engagement")265	assertContainsString(t, msg, "app", "murmur")266	assertContainsString(t, msg, "app_version", "87.23.11")267	assertContainsString(t, msg, "aws_region", "us-west-02")268	assertContainsString(t, msg, "aws_account_id", "aws-account-123")269	assertScopeContainsSubDoc(t, msg, "properties")270	assertScopeContainsSubDoc(t, msg, "exception")271	assertContainsString(t, msg, "error", "something went wrong")272}273func Test_Log_Fatal(t *testing.T) {274	memBuffer := &bytes.Buffer{}275	writer := NewWriter(func(conf *WriterConfig) {276		conf.Output = memBuffer277	})278	logger := NewWitCustomWriter(rsFields, writer)279	defer func() {280		if r := recover(); r != nil {281			msg := memBuffer.String()282			assertContainsString(t, msg, "event", "fatal_event")283			assertContainsString(t, msg, "severity", "FATAL")284			assertContainsString(t, msg, "trace_id", "1-2-3")285			assertContainsString(t, msg, "customer", "hooli")286			assertContainsString(t, msg, "user", "UserAggregateID-123")287			assertContainsString(t, msg, "product", "engagement")288			assertContainsString(t, msg, "app", "murmur")289			assertContainsString(t, msg, "app_version", "87.23.11")290			assertContainsString(t, msg, "aws_region", "us-west-02")291			assertContainsString(t, msg, "aws_account_id", "aws-account-123")292			assertScopeContainsSubDoc(t, msg, "exception")293			assertContainsString(t, msg, "error", "something fatal happened")294		}295	}()296	logger.Fatal("fatal event", errors.New("something fatal happened")) // will call panic!297}298func Test_Log_FatalWithFields(t *testing.T) {299	memBuffer := &bytes.Buffer{}300	writer := NewWriter(func(conf *WriterConfig) {301		conf.Output = memBuffer302	})303	logger := NewWitCustomWriter(rsFields, writer)304	defer func() {305		if r := recover(); r != nil {306			msg := memBuffer.String()307			assertContainsString(t, msg, "event", "fatal_event")308			assertContainsString(t, msg, "severity", "FATAL")309			assertContainsString(t, msg, "string", "hello")310			assertContainsInt(t, msg, "int", 123)311			assertContainsFloat(t, msg, "float", 42.48)312			assertContainsString(t, msg, "string2", "hello world")313			assertContainsString(t, msg, "string3_space", "world")314			assertContainsString(t, msg, "trace_id", "1-2-3")315			assertContainsString(t, msg, "customer", "hooli")316			assertContainsString(t, msg, "user", "UserAggregateID-123")317			assertContainsString(t, msg, "product", "engagement")318			assertContainsString(t, msg, "app", "murmur")319			assertContainsString(t, msg, "app_version", "87.23.11")320			assertContainsString(t, msg, "aws_region", "us-west-02")321			assertContainsString(t, msg, "aws_account_id", "aws-account-123")322			assertScopeContainsSubDoc(t, msg, "properties")323			assertScopeContainsSubDoc(t, msg, "exception")324			assertContainsString(t, msg, "error", "something fatal happened")325		}326	}()327	logger.Fatal("fatal event", errors.New("something fatal happened"), Fields{ // this will call panic!328		"string":        "hello",329		"int":           123,330		"float":         42.48,331		"string2":       "hello world",332		"string3 space": "world",333	})334}335func Test_Log_Namespace(t *testing.T) {336	t1 := time.Now()337	memBuffer := &bytes.Buffer{}338	writer := NewWriter(func(conf *WriterConfig) {339		conf.Output = memBuffer340	})341	logger := NewWitCustomWriter(rsFields, writer)342	time.Sleep(123 * time.Millisecond)343	t2 := time.Now()344	d := t2.Sub(t1)345	logger.Error("error event", errors.New("something went wrong"), Fields{346		"string": "hello",347		"int":    123,348		"float":  42.48,349		"reports_shared": Fields{350			"report":   "report1",351			"user":     "userid",352			TimeTaken: fmt.Sprintf("P%gS", d.Seconds()),353			TimeTakenMS: d.Milliseconds(),354		},355	})356	msg := memBuffer.String()357	assertContainsString(t, msg, "report", "report1")358	assertContainsString(t, msg, "user", "userid")359	assertContainsString(t, msg, "trace_id", "1-2-3")360	assertContainsString(t, msg, "customer", "hooli")361	assertContainsString(t, msg, "user", "UserAggregateID-123")362	assertContainsString(t, msg, "product", "engagement")363	assertContainsString(t, msg, "app", "murmur")364	assertContainsString(t, msg, "app_version", "87.23.11")365	assertContainsString(t, msg, "aws_region", "us-west-02")366	assertContainsString(t, msg, "aws_account_id", "aws-account-123")367	assertScopeContainsSubDoc(t, msg, "reports_shared")368	assertScopeContainsSubDoc(t, msg, "properties")369}370func TestScope(t *testing.T) {371	memBuffer := &bytes.Buffer{}372	writer := NewWriter(func(conf *WriterConfig) {373		conf.Output = memBuffer374	})375	logger := NewWitCustomWriter(rsFields, writer, Fields{376		"requestID": 123,377	})378	logger.Debug("detail_event")379	msg := memBuffer.String()380	assertScopeContainsString(t, msg, "event", "detail_event")381	assertScopeContainsInt(t, msg, "request_id", 123)382	memBuffer.Reset()383	logger.Info("info_event")384	msg = memBuffer.String()385	assertScopeContainsString(t, msg, "event", "info_event")386	assertScopeContainsInt(t, msg, "request_id", 123)387	memBuffer.Reset()388	logger.Warn("warn_event")389	msg = memBuffer.String()390	assertScopeContainsString(t, msg, "event", "warn_event")391	assertScopeContainsInt(t, msg, "request_id", 123)392	memBuffer.Reset()393	logger.Error("error_event", errors.New("something went wrong"))394	msg = memBuffer.String()395	assertScopeContainsString(t, msg, "event", "error_event")396	assertScopeContainsInt(t, msg, "request_id", 123)397	defer func() {398		if r := recover(); r != nil {399			msg := memBuffer.String()400			assertContainsString(t, msg, "event", "fatal_event")401			assertContainsString(t, msg, "severity", "FATAL")402		}403	}()404	logger.Fatal("fatal_event", errors.New("something fatal happened")) // will call panic!405}406func TestScope_Overwrite(t *testing.T) {407	memBuffer := &bytes.Buffer{}408	writer := NewWriter(func(conf *WriterConfig) {409		conf.Output = memBuffer410	})411	logger := NewWitCustomWriter(rsFields, writer, Fields{412		"requestID": 123,413	})414	logger.Debug("detail_event", Fields {415		"requestID": 456,416	})417	msg := memBuffer.String()418	assertScopeContainsString(t, msg, "event", "detail_event")419	assertScopeContainsInt(t, msg, "request_id", 456)420	memBuffer.Reset()421	logger.Info("info_event", Fields {422		"requestID": 456,423	})424	msg = memBuffer.String()425	assertScopeContainsString(t, msg, "event", "info_event")426	assertScopeContainsInt(t, msg, "request_id", 456)427	memBuffer.Reset()428	logger.Warn("warn_event", Fields {429		"requestID": 456,430	})431	msg = memBuffer.String()432	assertScopeContainsString(t, msg, "event", "warn_event")433	assertScopeContainsInt(t, msg, "request_id", 456)434	memBuffer.Reset()435	logger.Error("error_event", errors.New("error"), Fields {436		"requestID": 456,437	})438	msg = memBuffer.String()439	assertScopeContainsString(t, msg, "event", "error_event")440	assertScopeContainsInt(t, msg, "request_id", 456)441	defer func() {442		if r := recover(); r != nil {443			msg := memBuffer.String()444			assertScopeContainsString(t, msg, "event", "fatal_event")445			assertScopeContainsString(t, msg, "severity", "FATAL")446			assertScopeContainsInt(t, msg, "request_id", 456)447		}448	}()449	// will call panic!450	logger.Fatal("fatal_event", errors.New("fatal"), Fields {451		"request_id": 456,452	})453}454func Test_RealWorld(t *testing.T) {455	logger := New(rsFields)456	// You should see these printed out, all correctly formatted.457	logger.Debug("detail_event", Fields{458		"string":        "hello",459		"int":           123,460		"float":         42.48,461		"string2":       "hello world",462		"string3 space": "world",463	})464	Debug(rsFields, "detail_event", Fields{465		"string":        "hello",466		"int":           123,467		"float":         42.48,468		"string2":       "hello world",469		"string3 space": "world",470	})471	logger.Info("info_event", Fields{472		"string":        "hello",473		"int":           123,474		"float":         42.48,475		"string2":       "hello world",476		"string3 space": "world",477	})478	Info(rsFields, "info_event", Fields{479		"string":        "hello",480		"int":           123,481		"float":         42.48,482		"string2":       "hello world",483		"string3 space": "world",484	})485	logger.Warn("info_event", Fields{486		"string":        "hello",487		"int":           123,488		"float":         42.48,489		"string2":       "hello world",490		"string3 space": "world",491	})492	Warn(rsFields, "info_event", Fields{493		"string":        "hello",494		"int":           123,495		"float":         42.48,496		"string2":       "hello world",497		"string3 space": "world",498	})499	logger.Error("error_event", errors.New("error"), Fields{500		"string":        "hello",501		"int":           123,502		"float":         42.48,503		"string2":       "hello world",504		"string3 space": "world",505	})506	Error(rsFields, "error_event", errors.New("error"), Fields{507		"string":        "hello",508		"int":           123,509		"float":         42.48,510		"string2":       "hello world",511		"string3 space": "world",512	})513	defer func() {514		recover()515	}()516	// this will call panic!517	logger.Fatal("fatal_event", errors.New("fatal"), Fields{518		"string":        "hello",519		"int":           123,520		"float":         42.48,521		"string2":       "hello world",522		"string3 space": "world",523	})524	defer func() {525		recover()526	}()527	// this will call panic!528	Fatal(rsFields, "fatal_event", errors.New("fatal"), Fields{529		"string":        "hello",530		"int":           123,531		"float":         42.48,532		"string2":       "hello world",533		"string3 space": "world",534	})535}536func Test_RealWorld_Combined(t *testing.T) {537	logger := New(rsFields)538	// multiple fields collections539	logger.Debug("detail_event", Fields{540		"string1": "hello",541		"int1":    123,542		"float1":  42.48,543	}, Fields{544		"string2": "world",545		"int2":    456,546		"float2":  78.98,547	})548	Debug(rsFields, "detail_event", Fields{549		"string1": "hello",550		"int1":    123,551		"float1":  42.48,552	}, Fields{553		"string2": "world",554		"int2":    456,555		"float2":  78.98,556	})557	logger.Info("info_event", Fields{558		"string1": "hello",559		"int1":    123,560		"float1":  42.48,561	}, Fields{562		"string2": "world",563		"int2":    456,564		"float2":  78.98,565	})566	Info(rsFields, "info_event", Fields{567		"string1": "hello",568		"int1":    123,569		"float1":  42.48,570	}, Fields{571		"string2": "world",572		"int2":    456,573		"float2":  78.98,574	})575	logger.Warn("warn_event", Fields{576		"string1": "hello",577		"int1":    123,578		"float1":  42.48,579	}, Fields{580		"string2": "world",581		"int2":    456,582		"float2":  78.98,583	})584	Warn(rsFields, "warn_event", Fields{585		"string1": "hello",586		"int1":    123,587		"float1":  42.48,588	}, Fields{589		"string2": "world",590		"int2":    456,591		"float2":  78.98,592	})593	logger.Error("error_event", errors.New("error"), Fields{594		"string1": "hello",595		"int1":    123,596		"float1":  42.48,597	}, Fields{598		"string2": "world",599		"int2":    456,600		"float2":  78.98,601	})602	Error(rsFields, "error_event", errors.New("error"), Fields{603		"string1": "hello",604		"int1":    123,605		"float1":  42.48,606	}, Fields{607		"string2": "world",608		"int2":    456,609		"float2":  78.98,610	})611	defer func() {612		recover()613	}()614	// this will call panic!615	logger.Fatal("fatal_event", errors.New("fatal"), Fields{616		"string1": "hello",617		"int1":    123,618		"float1":  42.48,619	}, Fields{620		"string2": "world",621		"int2":    456,622		"float2":  78.98,623	})624	defer func() {625		recover()626	}()627	// this will call panic!628	Fatal(rsFields, "fatal_event", errors.New("fatal"), Fields{629		"string1": "hello",630		"int1":    123,631		"float1":  42.48,632	}, Fields{633		"string2": "world",634		"int2":    456,635		"float2":  78.98,636	})637}638func Test_RealWorld_Scope(t *testing.T) {639	logger := New(rsFields, Fields{"scopeID": 123})640	assert.Assert(t, logger != nil)641	logger.Debug("detail_event", Fields{642		"string":        "hello",643		"int":           123,644		"float":         42.48,645		"string2":       "hello world",646		"string3 space": "world",647	})648	logger.Info("info_event", Fields{649		"string":        "hello",650		"int":           123,651		"float":         42.48,652		"string2":       "hello world",653		"string3 space": "world",654	})655	logger.Warn("info_event", Fields{656		"string":        "hello",657		"int":           123,658		"float":         42.48,659		"string2":       "hello world",660		"string3 space": "world",661	})662	logger.Error("error_event", errors.New("error"), Fields{663		"string":        "hello",664		"int":           123,665		"float":         42.48,666		"string2":       "hello world",667		"string3 space": "world",668	})669	defer func() {670		recover()671	}()672	// this will call panic!673	logger.Fatal("fatal_event", errors.New("fatal"), Fields{674		"string":        "hello",675		"int":           123,676		"float":         42.48,677		"string2":       "hello world",678		"string3 space": "world",679	})680}681func Test_RealWorld_Durations(t *testing.T) {682	memBuffer := &bytes.Buffer{}683	writer := NewWriter(func(conf *WriterConfig) {684		conf.Output = memBuffer685	})686	logger := NewWitCustomWriter(rsFields, writer)687	d := time.Millisecond * 456688	logger.Debug( "detail_event", Fields{689		"string":        "hello",690		"int":           123,691		"float":         42.48,692		"string2":       "hello world",693		"string3 space": "world",694	}.Merge(NewDurationFields(d)))695	msg := memBuffer.String()696	assertContainsString(t, msg, "event", "detail_event")697	assertContainsString(t, msg, "time_taken", "P0.456S")698	assertContainsInt(t, msg, "time_taken_ms", 456)699}700func BenchmarkLogging(b *testing.B) {701	writer := NewWriter(func(conf *WriterConfig) {702		conf.Output = ioutil.Discard703	})704	logger := newLogger(rsFields, writer)705	fields := Fields{706		"string":        "hello",707		"int":           123,708		"float":         42.48,709		"string2":       "hello world",710		"string3 space": "world",711	}712	for n := 0; n < b.N; n++ {713		logger.Info("test details", fields)714	}715}716func assertContainsString(t *testing.T, log string, key string, val string) {717	// Check that the keys and values are in the log line718	find := fmt.Sprintf("\"%s\":\"%s\"", key, val)719	assert.Assert(t, strings.Contains(log, find), "Expected '%s' in '%s'", find, log)720}721func assertContainsInt(t *testing.T, log string, key string, val int) {722	// Check that the keys and values are in the log line723	find := fmt.Sprintf("\"%s\":%v", key, val)724	assert.Assert(t, strings.Contains(log, find), "Expected '%s' in '%s'", find, log)725}726func assertContainsFloat(t *testing.T, log string, key string, val float32) {727	// Check that the keys and values are in the log line728	find := fmt.Sprintf("\"%s\":%v", key, val)729	assert.Assert(t, strings.Contains(log, find), "Expected '%s' in '%s'", find, log)730}731func assertContainsSubDoc(t *testing.T, log string, key string, val string) {732	find := fmt.Sprintf("\"%s\":{\"%s\"", key, val)733	assert.Assert(t, strings.Contains(log, find), "Expected '%s' in '%s'", find, log)734}735func assertScopeContainsString(t *testing.T, log string, key string, val string) {736	// Check that the keys and values are in the log line737	find := fmt.Sprintf("\"%s\":\"%s\"", key, val)738	assert.Assert(t, strings.Contains(log, find), "Expected '%s' in '%s'", find, log)739}740func assertScopeContainsInt(t *testing.T, log string, key string, val int) {741	// Check that the keys and values are in the log line742	find := fmt.Sprintf("\"%s\":%v", key, val)743	assert.Assert(t, strings.Contains(log, find), "Expected '%s' in '%s'", find, log)744}745func assertScopeContainsSubDoc(t *testing.T, log string, key string) {746	find := fmt.Sprintf("\"%s\":{", key)747	assert.Assert(t, strings.Contains(log, find), "Expected '%s' in '%s'", find, log)748}...mgmt_test.go
Source:mgmt_test.go  
1/*2Copyright IBM Corp. All Rights Reserved.3SPDX-License-Identifier: Apache-2.04*/5package cceventmgmt6import (7	"os"8	"testing"9	"github.com/hyperledger/fabric-protos-go/ledger/rwset/kvrwset"10	"github.com/hyperledger/fabric/common/flogging"11	"github.com/hyperledger/fabric/core/ledger"12	"github.com/hyperledger/fabric/core/ledger/mock"13	"github.com/stretchr/testify/require"14)15func TestMain(m *testing.M) {16	flogging.ActivateSpec("eventmgmt=debug")17	os.Exit(m.Run())18}19func TestCCEventMgmt(t *testing.T) {20	cc1Def := &ChaincodeDefinition{Name: "cc1", Version: "v1", Hash: []byte("cc1")}21	cc1DBArtifactsTar := []byte("cc1DBArtifacts")22	cc2Def := &ChaincodeDefinition{Name: "cc2", Version: "v1", Hash: []byte("cc2")}23	cc2DBArtifactsTar := []byte("cc2DBArtifacts")24	cc3Def := &ChaincodeDefinition{Name: "cc3", Version: "v1", Hash: []byte("cc3")}25	cc3DBArtifactsTar := []byte("cc3DBArtifacts")26	// cc1 is deployed and installed. cc2 is deployed but not installed. cc3 is not deployed but installed27	mockProvider := newMockProvider()28	mockProvider.setChaincodeInstalled(cc1Def, cc1DBArtifactsTar)29	mockProvider.setChaincodeDeployed("channel1", cc1Def, true)30	mockProvider.setChaincodeDeployed("channel1", cc2Def, true)31	mockProvider.setChaincodeInstalled(cc3Def, cc3DBArtifactsTar)32	setEventMgrForTest(newMgr(mockProvider))33	defer clearEventMgrForTest()34	handler1, handler2, handler3 := &mockHandler{}, &mockHandler{}, &mockHandler{}35	eventMgr := GetMgr()36	require.NotNil(t, eventMgr)37	eventMgr.Register("channel1", handler1)38	eventMgr.Register("channel2", handler2)39	eventMgr.Register("channel1", handler3)40	eventMgr.Register("channel2", handler3)41	cc1ExpectedEvent := &mockEvent{cc1Def, cc1DBArtifactsTar}42	cc2ExpectedEvent := &mockEvent{cc2Def, cc2DBArtifactsTar}43	cc3ExpectedEvent := &mockEvent{cc3Def, cc3DBArtifactsTar}44	// Deploy cc3 on chain1 - handler1 and handler3 should receive event because cc3 is being deployed only on chain145	require.NoError(t,46		eventMgr.HandleChaincodeDeploy("channel1", []*ChaincodeDefinition{cc3Def}),47	)48	eventMgr.ChaincodeDeployDone("channel1")49	require.Contains(t, handler1.eventsRecieved, cc3ExpectedEvent)50	require.NotContains(t, handler2.eventsRecieved, cc3ExpectedEvent)51	require.Contains(t, handler3.eventsRecieved, cc3ExpectedEvent)52	require.Equal(t, 1, handler1.doneRecievedCount)53	require.Equal(t, 0, handler2.doneRecievedCount)54	require.Equal(t, 1, handler3.doneRecievedCount)55	// Deploy cc3 on chain2 as well and this time handler2 should also receive event56	require.NoError(t,57		eventMgr.HandleChaincodeDeploy("channel2", []*ChaincodeDefinition{cc3Def}),58	)59	eventMgr.ChaincodeDeployDone("channel2")60	require.Contains(t, handler2.eventsRecieved, cc3ExpectedEvent)61	require.Equal(t, 1, handler1.doneRecievedCount)62	require.Equal(t, 1, handler2.doneRecievedCount)63	require.Equal(t, 2, handler3.doneRecievedCount)64	// Install CC2 - handler1 and handler 3 should receive event because cc2 is deployed only on chain1 and not on chain265	require.NoError(t,66		eventMgr.HandleChaincodeInstall(cc2Def, cc2DBArtifactsTar),67	)68	eventMgr.ChaincodeInstallDone(true)69	require.Contains(t, handler1.eventsRecieved, cc2ExpectedEvent)70	require.NotContains(t, handler2.eventsRecieved, cc2ExpectedEvent)71	require.Contains(t, handler3.eventsRecieved, cc2ExpectedEvent)72	require.Equal(t, 2, handler1.doneRecievedCount)73	require.Equal(t, 1, handler2.doneRecievedCount)74	require.Equal(t, 3, handler3.doneRecievedCount)75	// setting cc2Def as a new lifecycle definition should cause install not to trigger event76	mockProvider.setChaincodeDeployed("channel1", cc2Def, false)77	handler1.eventsRecieved = []*mockEvent{}78	require.NoError(t,79		eventMgr.HandleChaincodeInstall(cc2Def, cc2DBArtifactsTar),80	)81	eventMgr.ChaincodeInstallDone(true)82	require.NotContains(t, handler1.eventsRecieved, cc2ExpectedEvent)83	mockListener := &mockHandler{}84	require.NoError(t,85		mgr.RegisterAndInvokeFor([]*ChaincodeDefinition{cc1Def, cc2Def, cc3Def},86			"test-ledger", mockListener,87		),88	)89	require.Contains(t, mockListener.eventsRecieved, cc1ExpectedEvent)90	require.Contains(t, mockListener.eventsRecieved, cc3ExpectedEvent)91	require.NotContains(t, mockListener.eventsRecieved, cc2ExpectedEvent)92	require.Equal(t, 2, mockListener.doneRecievedCount)93	require.Contains(t, mgr.ccLifecycleListeners["test-ledger"], mockListener)94}95func TestLSCCListener(t *testing.T) {96	channelName := "testChannel"97	cc1Def := &ChaincodeDefinition{Name: "testChaincode1", Version: "v1", Hash: []byte("hash_testChaincode")}98	cc2Def := &ChaincodeDefinition{Name: "testChaincode2", Version: "v1", Hash: []byte("hash_testChaincode")}99	ccDBArtifactsTar := []byte("ccDBArtifacts")100	// cc1, cc2 installed but not deployed101	mockProvider := newMockProvider()102	mockProvider.setChaincodeInstalled(cc1Def, ccDBArtifactsTar)103	mockProvider.setChaincodeInstalled(cc2Def, ccDBArtifactsTar)104	setEventMgrForTest(newMgr(mockProvider))105	defer clearEventMgrForTest()106	handler1 := &mockHandler{}107	GetMgr().Register(channelName, handler1)108	mockInfoProvider := &mock.DeployedChaincodeInfoProvider{}109	mockInfoProvider.UpdatedChaincodesStub =110		func(map[string][]*kvrwset.KVWrite) ([]*ledger.ChaincodeLifecycleInfo, error) {111			return []*ledger.ChaincodeLifecycleInfo{112				{Name: cc1Def.Name},113				{Name: cc2Def.Name},114			}, nil115		}116	mockInfoProvider.ChaincodeInfoStub = func(channelName, chaincodeName string, qe ledger.SimpleQueryExecutor) (*ledger.DeployedChaincodeInfo, error) {117		switch chaincodeName {118		case cc1Def.Name:119			return &ledger.DeployedChaincodeInfo{120				Name:     chaincodeName,121				Hash:     cc1Def.Hash,122				Version:  cc1Def.Version,123				IsLegacy: true, // event for legacy chaincode lifecycle124			}, nil125		case cc2Def.Name:126			return &ledger.DeployedChaincodeInfo{127				Name:     chaincodeName,128				Hash:     cc1Def.Hash,129				Version:  cc1Def.Version,130				IsLegacy: false, // event for new chaincode lifecycle131			}, nil132		default:133			return nil, nil134		}135	}136	lsccStateListener := &KVLedgerLSCCStateListener{mockInfoProvider}137	// test1 regular deploy lscc event gets sent to handler138	t.Run("DeployEvent", func(t *testing.T) {139		require.NoError(t,140			lsccStateListener.HandleStateUpdates(141				&ledger.StateUpdateTrigger{142					LedgerID: channelName,143				},144			),145		)146		// processes legacy event147		require.Contains(t, handler1.eventsRecieved, &mockEvent{cc1Def, ccDBArtifactsTar})148		// does not processes new lifecycle event149		require.NotContains(t, handler1.eventsRecieved, &mockEvent{cc2Def, ccDBArtifactsTar})150	})151}152type mockProvider struct {153	chaincodesDeployed             map[[3]string]bool154	chaincodesDeployedNewLifecycle map[[3]string]bool155	chaincodesInstalled            map[[2]string][]byte156}157type mockHandler struct {158	eventsRecieved    []*mockEvent159	doneRecievedCount int160}161type mockEvent struct {162	def            *ChaincodeDefinition163	dbArtifactsTar []byte164}165func (l *mockHandler) HandleChaincodeDeploy(chaincodeDefinition *ChaincodeDefinition, dbArtifactsTar []byte) error {166	l.eventsRecieved = append(l.eventsRecieved, &mockEvent{def: chaincodeDefinition, dbArtifactsTar: dbArtifactsTar})167	return nil168}169func (l *mockHandler) ChaincodeDeployDone(succeeded bool) {170	l.doneRecievedCount++171}172func newMockProvider() *mockProvider {173	return &mockProvider{174		make(map[[3]string]bool),175		make(map[[3]string]bool),176		make(map[[2]string][]byte),177	}178}179func (p *mockProvider) setChaincodeDeployed(chainid string, chaincodeDefinition *ChaincodeDefinition, isLegacy bool) {180	p.chaincodesDeployed[[3]string{chainid, chaincodeDefinition.Name, chaincodeDefinition.Version}] = isLegacy181}182func (p *mockProvider) setChaincodeInstalled(chaincodeDefinition *ChaincodeDefinition, dbArtifactsTar []byte) {183	p.chaincodesInstalled[[2]string{chaincodeDefinition.Name, chaincodeDefinition.Version}] = dbArtifactsTar184}185func (p *mockProvider) GetDeployedChaincodeInfo(chainid string, chaincodeDefinition *ChaincodeDefinition) (*ledger.DeployedChaincodeInfo, error) {186	isLegacy, ok := p.chaincodesDeployed[[3]string{chainid, chaincodeDefinition.Name, chaincodeDefinition.Version}]187	if !ok {188		return nil, nil189	}190	return &ledger.DeployedChaincodeInfo{191		Name:     chaincodeDefinition.Name,192		Version:  chaincodeDefinition.Version,193		IsLegacy: isLegacy,194	}, nil195}196func (p *mockProvider) RetrieveChaincodeArtifacts(chaincodeDefinition *ChaincodeDefinition) (installed bool, dbArtifactsTar []byte, err error) {197	dbArtifactsTar, ok := p.chaincodesInstalled[[2]string{chaincodeDefinition.Name, chaincodeDefinition.Version}]198	if !ok {199		return false, nil, nil200	}201	return true, dbArtifactsTar, nil202}203func setEventMgrForTest(eventMgr *Mgr) {204	mgr = eventMgr205}206func clearEventMgrForTest() {207	mgr = nil208}...types.go
Source:types.go  
...18type DocumentFormat string19const (20	DocumentFormatMarkdown DocumentFormat = "MARKDOWN"21)22// Application contains all associated APIs, EventAPIs and Documents23type Application struct {24	ID                  string25	Name                string26	ProviderDisplayName string27	Description         string28	Labels              Labels29	SystemAuthsIDs      []string30	ApiBundles          []APIBundle31}32type APIBundle struct {33	ID                             string34	Name                           string35	Description                    *string36	InstanceAuthRequestInputSchema *string37	APIDefinitions                 []APIDefinition38	EventDefinitions               []EventAPIDefinition39	Documents                      []Document40	DefaultInstanceAuth            *Auth41}42// APIDefinition contains API data such as URL, credentials and spec43type APIDefinition struct {44	ID          string45	Name        string46	Description string47	TargetUrl   string48	APISpec     *APISpec49	Credentials *Credentials50}51// EventAPIDefinition contains Event API details such52type EventAPIDefinition struct {53	ID           string54	Name         string55	Description  string56	EventAPISpec *EventAPISpec57}58// Document contains data of document stored in the Rafter59type Document struct {60	ID            string61	ApplicationID string62	Title         string63	DisplayName   string64	Description   string65	Format        DocumentFormat66	Kind          *string67	Data          []byte68}69// APISpec contains API spec BLOB and its type70type APISpec struct {71	Data   []byte72	Type   APISpecType73	Format SpecFormat74}75// EventAPISpec contains event API spec BLOB and its type76type EventAPISpec struct {77	Data   []byte78	Type   EventAPISpecType79	Format SpecFormat80}81// Credentials contains OAuth or BasicAuth configuration along with optional CSRF data.82type Credentials struct {83	// OAuth configuration84	Oauth *Oauth85	// BasicAuth configuration86	Basic *Basic87	// Optional CSRF Data88	CSRFInfo *CSRFInfo89}90// Oauth contains data for performing Oauth token request91type Oauth struct {92	// URL to OAuth token provider.93	URL string94	// ClientID to use for authentication.95	ClientID string96	// ClientSecret to use for authentication.97	ClientSecret string98}99// Basic contains user and password for Basic Auth100type Basic struct {101	// Username to use for authentication.102	Username string103	// Password to use for authentication.104	Password string105}106// CSRFInfo contains data for performing CSRF token request107type CSRFInfo struct {108	TokenEndpointURL string109}110// RequestParameters contains additional headers and query parameters111type RequestParameters struct {112	// Additional headers113	Headers *map[string][]string `json:"headers"`114	// Additional query parameters115	QueryParameters *map[string][]string `json:"queryParameters"`116}117// IsEmpty returns true if additional headers and query parameters contain no data, otherwise false118func (r RequestParameters) IsEmpty() bool {119	return (r.Headers == nil || len(*r.Headers) == 0) && (r.QueryParameters == nil || len(*r.QueryParameters) == 0)120}121// Auth contains authentication data122type Auth struct {123	// Credentials124	Credentials *Credentials125	// Additional request parameters126	RequestParameters *RequestParameters127}...contains
Using AI Code Generation
1import (2func main() {3	db, err := rrd.OpenFile("test.rrd", rrd.READONLY)4	if err != nil {5		panic(err)6	}7	defer db.Close()8	e := rrd.NewEvent()9	e.SetStart(1398972800)10	e.SetEnd(1398976400)11	e.SetResolution(300)12	e.SetCF("AVERAGE")13	e.SetDS("ds0")14	e.SetFilter("ds0,GT,10")15	e.SetRows(10)16	e.SetStep(300)17	d, err := db.Fetch(e)18	if err != nil {19		panic(err)20	}21	fmt.Printf("Start: %v\n", time.Unix(d.Start, 0))22	fmt.Printf("End: %v\n", time.Unix(d.End, 0))23	fmt.Printf("Step: %v\n", d.Step)24	fmt.Printf("Rows: %v\n", d.Rows)25	fmt.Printf("DS Names: %v\n", d.DsNames)26	fmt.Printf("DS Types: %v\n", d.DsTypes)27	fmt.Printf("Data:\n")28	for i, v := range d.Data {29		fmt.Printf("  %v: %v\n", i, v)30	}31}contains
Using AI Code Generation
1import (2func main() {3	event1 := Event{1, "Event1", "Event1 Description", "Event1 Place", "Event1 Date"}4	event2 := Event{2, "Event2", "Event2 Description", "Event2 Place", "Event2 Date"}5	event3 := Event{3, "Event3", "Event3 Description", "Event3 Place", "Event3 Date"}6	event4 := Event{4, "Event4", "Event4 Description", "Event4 Place", "Event4 Date"}7	event5 := Event{5, "Event5", "Event5 Description", "Event5 Place", "Event5 Date"}8	event6 := Event{6, "Event6", "Event6 Description", "Event6 Place", "Event6 Date"}9	event7 := Event{7, "Event7", "Event7 Description", "Event7 Place", "Event7 Date"}10	event8 := Event{8, "Event8", "Event8 Description", "Event8 Place", "Event8 Date"}11	event9 := Event{9, "Event9", "Event9 Description", "Event9 Place", "Event9 Date"}12	event10 := Event{10, "Event10", "Event10 Description", "Event10 Place", "Event10 Date"}13	event11 := Event{11, "Event11", "Event11 Description", "Event11 Place", "Event11 Date"}14	event12 := Event{12, "Event12", "Event12 Description", "Event12 Place", "Event12 Date"}15	event13 := Event{13, "Event13", "Event13 Description", "Event13 Place", "Event13 Date"}16	event14 := Event{14, "Event14", "Event14 Description", "Event14 Place", "Event14 Date"}17	event15 := Event{15, "Event15", "Event15 Description", "Event15 Place", "Event15 Date"}18	event16 := Event{16, "Event16", "Event16 Description", "Event16 Place", "Event16 Date"}19	event17 := Event{17, "Event17", "Event17 Description", "Event17 Place", "Event17 Date"}20	event18 := Event{18, "Event18", "Event18 Description", "Event18 Place", "Event18 Date"}21	event19 := Event{19, "Event19", "Event19 Description", "contains
Using AI Code Generation
1import (2type Event struct {3}4func (e *Event) Contains(eventList []Event) bool {5	for _, event := range eventList {6		if event.Name == e.Name && event.Date == e.Date {7		}8	}9}10func (e *Event) Remove(eventList []Event) []Event {11	for _, event := range eventList {12		if event.Name != e.Name || event.Date != e.Date {13			newEventList = append(newEventList, event)14		}15	}16}17func (e *Event) Add(eventList []Event) []Event {18	if e.Contains(eventList) {19	}20	return append(eventList, *e)21}22func main() {23	event1 := Event{24	}25	event2 := Event{26	}27	event3 := Event{28	}29	eventList = event1.Add(eventList)30	eventList = event2.Add(eventList)31	eventList = event3.Add(eventList)32	fmt.Println(eventList)33	eventList = event2.Remove(eventList)34	fmt.Println(eventList)35}36[{{Event1 Date1} {Event2 Date2} {Event3 Date3}} {{Event1 Date1} {Event3 Date3}}]contains
Using AI Code Generation
1import (2func main() {3    event := encoding.Event{Content: "Hello World"}4    if event.Contains("Hello") {5        fmt.Println("event contains Hello")6    } else {7        fmt.Println("event does not contain Hello")8    }9}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!!
