Best Is code snippet using is.Equal
logrus_test.go
Source:logrus_test.go
...23 LogAndAssertJSON(t, func(log *Logger) {24 log.ReportCaller = false25 log.Print("testNoCaller")26 }, func(fields Fields) {27 assert.Equal(t, "testNoCaller", fields["msg"])28 assert.Equal(t, "info", fields["level"])29 assert.Equal(t, nil, fields["func"])30 })31 LogAndAssertJSON(t, func(log *Logger) {32 log.ReportCaller = true33 log.Print("testWithCaller")34 }, func(fields Fields) {35 assert.Equal(t, "testWithCaller", fields["msg"])36 assert.Equal(t, "info", fields["level"])37 assert.Equal(t,38 "github.com/sirupsen/logrus_test.TestReportCallerWhenConfigured.func3", fields[FieldKeyFunc])39 })40 LogAndAssertJSON(t, func(log *Logger) {41 log.ReportCaller = true42 log.Formatter.(*JSONFormatter).CallerPrettyfier = func(f *runtime.Frame) (string, string) {43 return "somekindoffunc", "thisisafilename"44 }45 log.Print("testWithCallerPrettyfier")46 }, func(fields Fields) {47 assert.Equal(t, "somekindoffunc", fields[FieldKeyFunc])48 assert.Equal(t, "thisisafilename", fields[FieldKeyFile])49 })50 LogAndAssertText(t, func(log *Logger) {51 log.ReportCaller = true52 log.Formatter.(*TextFormatter).CallerPrettyfier = func(f *runtime.Frame) (string, string) {53 return "somekindoffunc", "thisisafilename"54 }55 log.Print("testWithCallerPrettyfier")56 }, func(fields map[string]string) {57 assert.Equal(t, "somekindoffunc", fields[FieldKeyFunc])58 assert.Equal(t, "thisisafilename", fields[FieldKeyFile])59 })60}61func logSomething(t *testing.T, message string) Fields {62 var buffer bytes.Buffer63 var fields Fields64 logger := New()65 logger.Out = &buffer66 logger.Formatter = new(JSONFormatter)67 logger.ReportCaller = true68 entry := logger.WithFields(Fields{69 "foo": "bar",70 })71 entry.Info(message)72 err := json.Unmarshal(buffer.Bytes(), &fields)73 assert.Nil(t, err)74 return fields75}76// TestReportCallerHelperDirect - verify reference when logging from a regular function77func TestReportCallerHelperDirect(t *testing.T) {78 fields := logSomething(t, "direct")79 assert.Equal(t, "direct", fields["msg"])80 assert.Equal(t, "info", fields["level"])81 assert.Regexp(t, "github.com/.*/logrus_test.logSomething", fields["func"])82}83// TestReportCallerHelperDirect - verify reference when logging from a function called via pointer84func TestReportCallerHelperViaPointer(t *testing.T) {85 fptr := logSomething86 fields := fptr(t, "via pointer")87 assert.Equal(t, "via pointer", fields["msg"])88 assert.Equal(t, "info", fields["level"])89 assert.Regexp(t, "github.com/.*/logrus_test.logSomething", fields["func"])90}91func TestPrint(t *testing.T) {92 LogAndAssertJSON(t, func(log *Logger) {93 log.Print("test")94 }, func(fields Fields) {95 assert.Equal(t, "test", fields["msg"])96 assert.Equal(t, "info", fields["level"])97 })98}99func TestInfo(t *testing.T) {100 LogAndAssertJSON(t, func(log *Logger) {101 log.Info("test")102 }, func(fields Fields) {103 assert.Equal(t, "test", fields["msg"])104 assert.Equal(t, "info", fields["level"])105 })106}107func TestWarn(t *testing.T) {108 LogAndAssertJSON(t, func(log *Logger) {109 log.Warn("test")110 }, func(fields Fields) {111 assert.Equal(t, "test", fields["msg"])112 assert.Equal(t, "warning", fields["level"])113 })114}115func TestLog(t *testing.T) {116 LogAndAssertJSON(t, func(log *Logger) {117 log.Log(WarnLevel, "test")118 }, func(fields Fields) {119 assert.Equal(t, "test", fields["msg"])120 assert.Equal(t, "warning", fields["level"])121 })122}123func TestInfolnShouldAddSpacesBetweenStrings(t *testing.T) {124 LogAndAssertJSON(t, func(log *Logger) {125 log.Infoln("test", "test")126 }, func(fields Fields) {127 assert.Equal(t, "test test", fields["msg"])128 })129}130func TestInfolnShouldAddSpacesBetweenStringAndNonstring(t *testing.T) {131 LogAndAssertJSON(t, func(log *Logger) {132 log.Infoln("test", 10)133 }, func(fields Fields) {134 assert.Equal(t, "test 10", fields["msg"])135 })136}137func TestInfolnShouldAddSpacesBetweenTwoNonStrings(t *testing.T) {138 LogAndAssertJSON(t, func(log *Logger) {139 log.Infoln(10, 10)140 }, func(fields Fields) {141 assert.Equal(t, "10 10", fields["msg"])142 })143}144func TestInfoShouldAddSpacesBetweenTwoNonStrings(t *testing.T) {145 LogAndAssertJSON(t, func(log *Logger) {146 log.Infoln(10, 10)147 }, func(fields Fields) {148 assert.Equal(t, "10 10", fields["msg"])149 })150}151func TestInfoShouldNotAddSpacesBetweenStringAndNonstring(t *testing.T) {152 LogAndAssertJSON(t, func(log *Logger) {153 log.Info("test", 10)154 }, func(fields Fields) {155 assert.Equal(t, "test10", fields["msg"])156 })157}158func TestInfoShouldNotAddSpacesBetweenStrings(t *testing.T) {159 LogAndAssertJSON(t, func(log *Logger) {160 log.Info("test", "test")161 }, func(fields Fields) {162 assert.Equal(t, "testtest", fields["msg"])163 })164}165func TestWithFieldsShouldAllowAssignments(t *testing.T) {166 var buffer bytes.Buffer167 var fields Fields168 logger := New()169 logger.Out = &buffer170 logger.Formatter = new(JSONFormatter)171 localLog := logger.WithFields(Fields{172 "key1": "value1",173 })174 localLog.WithField("key2", "value2").Info("test")175 err := json.Unmarshal(buffer.Bytes(), &fields)176 assert.Nil(t, err)177 assert.Equal(t, "value2", fields["key2"])178 assert.Equal(t, "value1", fields["key1"])179 buffer = bytes.Buffer{}180 fields = Fields{}181 localLog.Info("test")182 err = json.Unmarshal(buffer.Bytes(), &fields)183 assert.Nil(t, err)184 _, ok := fields["key2"]185 assert.Equal(t, false, ok)186 assert.Equal(t, "value1", fields["key1"])187}188func TestUserSuppliedFieldDoesNotOverwriteDefaults(t *testing.T) {189 LogAndAssertJSON(t, func(log *Logger) {190 log.WithField("msg", "hello").Info("test")191 }, func(fields Fields) {192 assert.Equal(t, "test", fields["msg"])193 })194}195func TestUserSuppliedMsgFieldHasPrefix(t *testing.T) {196 LogAndAssertJSON(t, func(log *Logger) {197 log.WithField("msg", "hello").Info("test")198 }, func(fields Fields) {199 assert.Equal(t, "test", fields["msg"])200 assert.Equal(t, "hello", fields["fields.msg"])201 })202}203func TestUserSuppliedTimeFieldHasPrefix(t *testing.T) {204 LogAndAssertJSON(t, func(log *Logger) {205 log.WithField("time", "hello").Info("test")206 }, func(fields Fields) {207 assert.Equal(t, "hello", fields["fields.time"])208 })209}210func TestUserSuppliedLevelFieldHasPrefix(t *testing.T) {211 LogAndAssertJSON(t, func(log *Logger) {212 log.WithField("level", 1).Info("test")213 }, func(fields Fields) {214 assert.Equal(t, "info", fields["level"])215 assert.Equal(t, 1.0, fields["fields.level"]) // JSON has floats only216 })217}218func TestDefaultFieldsAreNotPrefixed(t *testing.T) {219 LogAndAssertText(t, func(log *Logger) {220 ll := log.WithField("herp", "derp")221 ll.Info("hello")222 ll.Info("bye")223 }, func(fields map[string]string) {224 for _, fieldName := range []string{"fields.level", "fields.time", "fields.msg"} {225 if _, ok := fields[fieldName]; ok {226 t.Fatalf("should not have prefixed %q: %v", fieldName, fields)227 }228 }229 })230}231func TestWithTimeShouldOverrideTime(t *testing.T) {232 now := time.Now().Add(24 * time.Hour)233 LogAndAssertJSON(t, func(log *Logger) {234 log.WithTime(now).Info("foobar")235 }, func(fields Fields) {236 assert.Equal(t, fields["time"], now.Format(time.RFC3339))237 })238}239func TestWithTimeShouldNotOverrideFields(t *testing.T) {240 now := time.Now().Add(24 * time.Hour)241 LogAndAssertJSON(t, func(log *Logger) {242 log.WithField("herp", "derp").WithTime(now).Info("blah")243 }, func(fields Fields) {244 assert.Equal(t, fields["time"], now.Format(time.RFC3339))245 assert.Equal(t, fields["herp"], "derp")246 })247}248func TestWithFieldShouldNotOverrideTime(t *testing.T) {249 now := time.Now().Add(24 * time.Hour)250 LogAndAssertJSON(t, func(log *Logger) {251 log.WithTime(now).WithField("herp", "derp").Info("blah")252 }, func(fields Fields) {253 assert.Equal(t, fields["time"], now.Format(time.RFC3339))254 assert.Equal(t, fields["herp"], "derp")255 })256}257func TestTimeOverrideMultipleLogs(t *testing.T) {258 var buffer bytes.Buffer259 var firstFields, secondFields Fields260 logger := New()261 logger.Out = &buffer262 formatter := new(JSONFormatter)263 formatter.TimestampFormat = time.StampMilli264 logger.Formatter = formatter265 llog := logger.WithField("herp", "derp")266 llog.Info("foo")267 err := json.Unmarshal(buffer.Bytes(), &firstFields)268 assert.NoError(t, err, "should have decoded first message")269 buffer.Reset()270 time.Sleep(10 * time.Millisecond)271 llog.Info("bar")272 err = json.Unmarshal(buffer.Bytes(), &secondFields)273 assert.NoError(t, err, "should have decoded second message")274 assert.NotEqual(t, firstFields["time"], secondFields["time"], "timestamps should not be equal")275}276func TestDoubleLoggingDoesntPrefixPreviousFields(t *testing.T) {277 var buffer bytes.Buffer278 var fields Fields279 logger := New()280 logger.Out = &buffer281 logger.Formatter = new(JSONFormatter)282 llog := logger.WithField("context", "eating raw fish")283 llog.Info("looks delicious")284 err := json.Unmarshal(buffer.Bytes(), &fields)285 assert.NoError(t, err, "should have decoded first message")286 assert.Equal(t, len(fields), 4, "should only have msg/time/level/context fields")287 assert.Equal(t, fields["msg"], "looks delicious")288 assert.Equal(t, fields["context"], "eating raw fish")289 buffer.Reset()290 llog.Warn("omg it is!")291 err = json.Unmarshal(buffer.Bytes(), &fields)292 assert.NoError(t, err, "should have decoded second message")293 assert.Equal(t, len(fields), 4, "should only have msg/time/level/context fields")294 assert.Equal(t, "omg it is!", fields["msg"])295 assert.Equal(t, "eating raw fish", fields["context"])296 assert.Nil(t, fields["fields.msg"], "should not have prefixed previous `msg` entry")297}298func TestNestedLoggingReportsCorrectCaller(t *testing.T) {299 var buffer bytes.Buffer300 var fields Fields301 logger := New()302 logger.Out = &buffer303 logger.Formatter = new(JSONFormatter)304 logger.ReportCaller = true305 llog := logger.WithField("context", "eating raw fish")306 llog.Info("looks delicious")307 _, _, line, _ := runtime.Caller(0)308 err := json.Unmarshal(buffer.Bytes(), &fields)309 require.NoError(t, err, "should have decoded first message")310 assert.Equal(t, 6, len(fields), "should have msg/time/level/func/context fields")311 assert.Equal(t, "looks delicious", fields["msg"])312 assert.Equal(t, "eating raw fish", fields["context"])313 assert.Equal(t,314 "github.com/sirupsen/logrus_test.TestNestedLoggingReportsCorrectCaller", fields["func"])315 cwd, err := os.Getwd()316 require.NoError(t, err)317 assert.Equal(t, filepath.ToSlash(fmt.Sprintf("%s/logrus_test.go:%d", cwd, line-1)), filepath.ToSlash(fields["file"].(string)))318 buffer.Reset()319 logger.WithFields(Fields{320 "Clyde": "Stubblefield",321 }).WithFields(Fields{322 "Jab'o": "Starks",323 }).WithFields(Fields{324 "uri": "https://www.youtube.com/watch?v=V5DTznu-9v0",325 }).WithFields(Fields{326 "func": "y drummer",327 }).WithFields(Fields{328 "James": "Brown",329 }).Print("The hardest workin' man in show business")330 _, _, line, _ = runtime.Caller(0)331 err = json.Unmarshal(buffer.Bytes(), &fields)332 assert.NoError(t, err, "should have decoded second message")333 assert.Equal(t, 11, len(fields), "should have all builtin fields plus foo,bar,baz,...")334 assert.Equal(t, "Stubblefield", fields["Clyde"])335 assert.Equal(t, "Starks", fields["Jab'o"])336 assert.Equal(t, "https://www.youtube.com/watch?v=V5DTznu-9v0", fields["uri"])337 assert.Equal(t, "y drummer", fields["fields.func"])338 assert.Equal(t, "Brown", fields["James"])339 assert.Equal(t, "The hardest workin' man in show business", fields["msg"])340 assert.Nil(t, fields["fields.msg"], "should not have prefixed previous `msg` entry")341 assert.Equal(t,342 "github.com/sirupsen/logrus_test.TestNestedLoggingReportsCorrectCaller", fields["func"])343 require.NoError(t, err)344 assert.Equal(t, filepath.ToSlash(fmt.Sprintf("%s/logrus_test.go:%d", cwd, line-1)), filepath.ToSlash(fields["file"].(string)))345 logger.ReportCaller = false // return to default value346}347func logLoop(iterations int, reportCaller bool) {348 var buffer bytes.Buffer349 logger := New()350 logger.Out = &buffer351 logger.Formatter = new(JSONFormatter)352 logger.ReportCaller = reportCaller353 for i := 0; i < iterations; i++ {354 logger.Infof("round %d of %d", i, iterations)355 }356}357// Assertions for upper bounds to reporting overhead358func TestCallerReportingOverhead(t *testing.T) {359 iterations := 5000360 before := time.Now()361 logLoop(iterations, false)362 during := time.Now()363 logLoop(iterations, true)364 after := time.Now()365 elapsedNotReporting := during.Sub(before).Nanoseconds()366 elapsedReporting := after.Sub(during).Nanoseconds()367 maxDelta := 1 * time.Second368 assert.WithinDuration(t, during, before, maxDelta,369 "%d log calls without caller name lookup takes less than %d second(s) (was %d nanoseconds)",370 iterations, maxDelta.Seconds(), elapsedNotReporting)371 assert.WithinDuration(t, after, during, maxDelta,372 "%d log calls without caller name lookup takes less than %d second(s) (was %d nanoseconds)",373 iterations, maxDelta.Seconds(), elapsedReporting)374}375// benchmarks for both with and without caller-function reporting376func BenchmarkWithoutCallerTracing(b *testing.B) {377 for i := 0; i < b.N; i++ {378 logLoop(1000, false)379 }380}381func BenchmarkWithCallerTracing(b *testing.B) {382 for i := 0; i < b.N; i++ {383 logLoop(1000, true)384 }385}386func TestConvertLevelToString(t *testing.T) {387 assert.Equal(t, "trace", TraceLevel.String())388 assert.Equal(t, "debug", DebugLevel.String())389 assert.Equal(t, "info", InfoLevel.String())390 assert.Equal(t, "warning", WarnLevel.String())391 assert.Equal(t, "error", ErrorLevel.String())392 assert.Equal(t, "fatal", FatalLevel.String())393 assert.Equal(t, "panic", PanicLevel.String())394}395func TestParseLevel(t *testing.T) {396 l, err := ParseLevel("panic")397 assert.Nil(t, err)398 assert.Equal(t, PanicLevel, l)399 l, err = ParseLevel("PANIC")400 assert.Nil(t, err)401 assert.Equal(t, PanicLevel, l)402 l, err = ParseLevel("fatal")403 assert.Nil(t, err)404 assert.Equal(t, FatalLevel, l)405 l, err = ParseLevel("FATAL")406 assert.Nil(t, err)407 assert.Equal(t, FatalLevel, l)408 l, err = ParseLevel("error")409 assert.Nil(t, err)410 assert.Equal(t, ErrorLevel, l)411 l, err = ParseLevel("ERROR")412 assert.Nil(t, err)413 assert.Equal(t, ErrorLevel, l)414 l, err = ParseLevel("warn")415 assert.Nil(t, err)416 assert.Equal(t, WarnLevel, l)417 l, err = ParseLevel("WARN")418 assert.Nil(t, err)419 assert.Equal(t, WarnLevel, l)420 l, err = ParseLevel("warning")421 assert.Nil(t, err)422 assert.Equal(t, WarnLevel, l)423 l, err = ParseLevel("WARNING")424 assert.Nil(t, err)425 assert.Equal(t, WarnLevel, l)426 l, err = ParseLevel("info")427 assert.Nil(t, err)428 assert.Equal(t, InfoLevel, l)429 l, err = ParseLevel("INFO")430 assert.Nil(t, err)431 assert.Equal(t, InfoLevel, l)432 l, err = ParseLevel("debug")433 assert.Nil(t, err)434 assert.Equal(t, DebugLevel, l)435 l, err = ParseLevel("DEBUG")436 assert.Nil(t, err)437 assert.Equal(t, DebugLevel, l)438 l, err = ParseLevel("trace")439 assert.Nil(t, err)440 assert.Equal(t, TraceLevel, l)441 l, err = ParseLevel("TRACE")442 assert.Nil(t, err)443 assert.Equal(t, TraceLevel, l)444 _, err = ParseLevel("invalid")445 assert.Equal(t, "not a valid logrus Level: \"invalid\"", err.Error())446}447func TestLevelString(t *testing.T) {448 var loggerlevel Level449 loggerlevel = 32000450 _ = loggerlevel.String()451}452func TestGetSetLevelRace(t *testing.T) {453 wg := sync.WaitGroup{}454 for i := 0; i < 100; i++ {455 wg.Add(1)456 go func(i int) {457 defer wg.Done()458 if i%2 == 0 {459 SetLevel(InfoLevel)460 } else {461 GetLevel()462 }463 }(i)464 }465 wg.Wait()466}467func TestLoggingRace(t *testing.T) {468 logger := New()469 var wg sync.WaitGroup470 wg.Add(100)471 for i := 0; i < 100; i++ {472 go func() {473 logger.Info("info")474 wg.Done()475 }()476 }477 wg.Wait()478}479func TestLoggingRaceWithHooksOnEntry(t *testing.T) {480 logger := New()481 hook := new(ModifyHook)482 logger.AddHook(hook)483 entry := logger.WithField("context", "clue")484 var wg sync.WaitGroup485 wg.Add(100)486 for i := 0; i < 100; i++ {487 go func() {488 entry.Info("info")489 wg.Done()490 }()491 }492 wg.Wait()493}494func TestReplaceHooks(t *testing.T) {495 old, cur := &TestHook{}, &TestHook{}496 logger := New()497 logger.SetOutput(ioutil.Discard)498 logger.AddHook(old)499 hooks := make(LevelHooks)500 hooks.Add(cur)501 replaced := logger.ReplaceHooks(hooks)502 logger.Info("test")503 assert.Equal(t, old.Fired, false)504 assert.Equal(t, cur.Fired, true)505 logger.ReplaceHooks(replaced)506 logger.Info("test")507 assert.Equal(t, old.Fired, true)508}509// Compile test510func TestLogrusInterfaces(t *testing.T) {511 var buffer bytes.Buffer512 // This verifies FieldLogger and Ext1FieldLogger work as designed.513 // Please don't use them. Use Logger and Entry directly.514 fn := func(xl Ext1FieldLogger) {515 var l FieldLogger = xl516 b := l.WithField("key", "value")517 b.Debug("Test")518 }519 // test logger520 logger := New()521 logger.Out = &buffer522 fn(logger)523 // test Entry524 e := logger.WithField("another", "value")525 fn(e)526}527// Implements io.Writer using channels for synchronization, so we can wait on528// the Entry.Writer goroutine to write in a non-racey way. This does assume that529// there is a single call to Logger.Out for each message.530type channelWriter chan []byte531func (cw channelWriter) Write(p []byte) (int, error) {532 cw <- p533 return len(p), nil534}535func TestEntryWriter(t *testing.T) {536 cw := channelWriter(make(chan []byte, 1))537 log := New()538 log.Out = cw539 log.Formatter = new(JSONFormatter)540 _, err := log.WithField("foo", "bar").WriterLevel(WarnLevel).Write([]byte("hello\n"))541 if err != nil {542 t.Error("unexecpted error", err)543 }544 bs := <-cw545 var fields Fields546 err = json.Unmarshal(bs, &fields)547 assert.Nil(t, err)548 assert.Equal(t, fields["foo"], "bar")549 assert.Equal(t, fields["level"], "warning")550}551func TestLogLevelEnabled(t *testing.T) {552 log := New()553 log.SetLevel(PanicLevel)554 assert.Equal(t, true, log.IsLevelEnabled(PanicLevel))555 assert.Equal(t, false, log.IsLevelEnabled(FatalLevel))556 assert.Equal(t, false, log.IsLevelEnabled(ErrorLevel))557 assert.Equal(t, false, log.IsLevelEnabled(WarnLevel))558 assert.Equal(t, false, log.IsLevelEnabled(InfoLevel))559 assert.Equal(t, false, log.IsLevelEnabled(DebugLevel))560 assert.Equal(t, false, log.IsLevelEnabled(TraceLevel))561 log.SetLevel(FatalLevel)562 assert.Equal(t, true, log.IsLevelEnabled(PanicLevel))563 assert.Equal(t, true, log.IsLevelEnabled(FatalLevel))564 assert.Equal(t, false, log.IsLevelEnabled(ErrorLevel))565 assert.Equal(t, false, log.IsLevelEnabled(WarnLevel))566 assert.Equal(t, false, log.IsLevelEnabled(InfoLevel))567 assert.Equal(t, false, log.IsLevelEnabled(DebugLevel))568 assert.Equal(t, false, log.IsLevelEnabled(TraceLevel))569 log.SetLevel(ErrorLevel)570 assert.Equal(t, true, log.IsLevelEnabled(PanicLevel))571 assert.Equal(t, true, log.IsLevelEnabled(FatalLevel))572 assert.Equal(t, true, log.IsLevelEnabled(ErrorLevel))573 assert.Equal(t, false, log.IsLevelEnabled(WarnLevel))574 assert.Equal(t, false, log.IsLevelEnabled(InfoLevel))575 assert.Equal(t, false, log.IsLevelEnabled(DebugLevel))576 assert.Equal(t, false, log.IsLevelEnabled(TraceLevel))577 log.SetLevel(WarnLevel)578 assert.Equal(t, true, log.IsLevelEnabled(PanicLevel))579 assert.Equal(t, true, log.IsLevelEnabled(FatalLevel))580 assert.Equal(t, true, log.IsLevelEnabled(ErrorLevel))581 assert.Equal(t, true, log.IsLevelEnabled(WarnLevel))582 assert.Equal(t, false, log.IsLevelEnabled(InfoLevel))583 assert.Equal(t, false, log.IsLevelEnabled(DebugLevel))584 assert.Equal(t, false, log.IsLevelEnabled(TraceLevel))585 log.SetLevel(InfoLevel)586 assert.Equal(t, true, log.IsLevelEnabled(PanicLevel))587 assert.Equal(t, true, log.IsLevelEnabled(FatalLevel))588 assert.Equal(t, true, log.IsLevelEnabled(ErrorLevel))589 assert.Equal(t, true, log.IsLevelEnabled(WarnLevel))590 assert.Equal(t, true, log.IsLevelEnabled(InfoLevel))591 assert.Equal(t, false, log.IsLevelEnabled(DebugLevel))592 assert.Equal(t, false, log.IsLevelEnabled(TraceLevel))593 log.SetLevel(DebugLevel)594 assert.Equal(t, true, log.IsLevelEnabled(PanicLevel))595 assert.Equal(t, true, log.IsLevelEnabled(FatalLevel))596 assert.Equal(t, true, log.IsLevelEnabled(ErrorLevel))597 assert.Equal(t, true, log.IsLevelEnabled(WarnLevel))598 assert.Equal(t, true, log.IsLevelEnabled(InfoLevel))599 assert.Equal(t, true, log.IsLevelEnabled(DebugLevel))600 assert.Equal(t, false, log.IsLevelEnabled(TraceLevel))601 log.SetLevel(TraceLevel)602 assert.Equal(t, true, log.IsLevelEnabled(PanicLevel))603 assert.Equal(t, true, log.IsLevelEnabled(FatalLevel))604 assert.Equal(t, true, log.IsLevelEnabled(ErrorLevel))605 assert.Equal(t, true, log.IsLevelEnabled(WarnLevel))606 assert.Equal(t, true, log.IsLevelEnabled(InfoLevel))607 assert.Equal(t, true, log.IsLevelEnabled(DebugLevel))608 assert.Equal(t, true, log.IsLevelEnabled(TraceLevel))609}610func TestReportCallerOnTextFormatter(t *testing.T) {611 l := New()612 l.Formatter.(*TextFormatter).ForceColors = true613 l.Formatter.(*TextFormatter).DisableColors = false614 l.WithFields(Fields{"func": "func", "file": "file"}).Info("test")615 l.Formatter.(*TextFormatter).ForceColors = false616 l.Formatter.(*TextFormatter).DisableColors = true617 l.WithFields(Fields{"func": "func", "file": "file"}).Info("test")618}619func TestSetReportCallerRace(t *testing.T) {620 l := New()621 l.Out = ioutil.Discard622 l.SetReportCaller(true)...
deepequal.go
Source:deepequal.go
...3// license that can be found in the LICENSE file.4// Deep equality test via reflection5package reflect6import "unsafe"7// During deepValueEqual, must keep track of checks that are8// in progress. The comparison algorithm assumes that all9// checks in progress are true when it reencounters them.10// Visited comparisons are stored in a map indexed by visit.11type visit struct {12 a1 unsafe.Pointer13 a2 unsafe.Pointer14 typ Type15}16// Tests for deep equality using reflected types. The map argument tracks17// comparisons that have already been seen, which allows short circuiting on18// recursive types.19func deepValueEqual(v1, v2 Value, visited map[visit]bool, depth int) bool {20 if !v1.IsValid() || !v2.IsValid() {21 return v1.IsValid() == v2.IsValid()22 }23 if v1.Type() != v2.Type() {24 return false25 }26 // if depth > 10 { panic("deepValueEqual") } // for debugging27 // We want to avoid putting more in the visited map than we need to.28 // For any possible reference cycle that might be encountered,29 // hard(t) needs to return true for at least one of the types in the cycle.30 hard := func(k Kind) bool {31 switch k {32 case Map, Slice, Ptr, Interface:33 return true34 }35 return false36 }37 if v1.CanAddr() && v2.CanAddr() && hard(v1.Kind()) {38 addr1 := unsafe.Pointer(v1.UnsafeAddr())39 addr2 := unsafe.Pointer(v2.UnsafeAddr())40 if uintptr(addr1) > uintptr(addr2) {41 // Canonicalize order to reduce number of entries in visited.42 // Assumes non-moving garbage collector.43 addr1, addr2 = addr2, addr144 }45 // Short circuit if references are already seen.46 typ := v1.Type()47 v := visit{addr1, addr2, typ}48 if visited[v] {49 return true50 }51 // Remember for later.52 visited[v] = true53 }54 switch v1.Kind() {55 case Array:56 for i := 0; i < v1.Len(); i++ {57 if !deepValueEqual(v1.Index(i), v2.Index(i), visited, depth+1) {58 return false59 }60 }61 return true62 case Slice:63 if v1.IsNil() != v2.IsNil() {64 return false65 }66 if v1.Len() != v2.Len() {67 return false68 }69 if v1.Pointer() == v2.Pointer() {70 return true71 }72 for i := 0; i < v1.Len(); i++ {73 if !deepValueEqual(v1.Index(i), v2.Index(i), visited, depth+1) {74 return false75 }76 }77 return true78 case Interface:79 if v1.IsNil() || v2.IsNil() {80 return v1.IsNil() == v2.IsNil()81 }82 return deepValueEqual(v1.Elem(), v2.Elem(), visited, depth+1)83 case Ptr:84 if v1.Pointer() == v2.Pointer() {85 return true86 }87 return deepValueEqual(v1.Elem(), v2.Elem(), visited, depth+1)88 case Struct:89 for i, n := 0, v1.NumField(); i < n; i++ {90 if !deepValueEqual(v1.Field(i), v2.Field(i), visited, depth+1) {91 return false92 }93 }94 return true95 case Map:96 if v1.IsNil() != v2.IsNil() {97 return false98 }99 if v1.Len() != v2.Len() {100 return false101 }102 if v1.Pointer() == v2.Pointer() {103 return true104 }105 for _, k := range v1.MapKeys() {106 val1 := v1.MapIndex(k)107 val2 := v2.MapIndex(k)108 if !val1.IsValid() || !val2.IsValid() || !deepValueEqual(v1.MapIndex(k), v2.MapIndex(k), visited, depth+1) {109 return false110 }111 }112 return true113 case Func:114 if v1.IsNil() && v2.IsNil() {115 return true116 }117 // Can't do better than this:118 return false119 default:120 // Normal equality suffices121 return valueInterface(v1, false) == valueInterface(v2, false)122 }123}124// DeepEqual reports whether x and y are ``deeply equal,'' defined as follows.125// Two values of identical type are deeply equal if one of the following cases applies.126// Values of distinct types are never deeply equal.127//128// Array values are deeply equal when their corresponding elements are deeply equal.129//130// Struct values are deeply equal if their corresponding fields,131// both exported and unexported, are deeply equal.132//133// Func values are deeply equal if both are nil; otherwise they are not deeply equal.134//135// Interface values are deeply equal if they hold deeply equal concrete values.136//137// Map values are deeply equal when all of the following are true:138// they are both nil or both non-nil, they have the same length,139// and either they are the same map object or their corresponding keys140// (matched using Go equality) map to deeply equal values.141//142// Pointer values are deeply equal if they are equal using Go's == operator143// or if they point to deeply equal values.144//145// Slice values are deeply equal when all of the following are true:146// they are both nil or both non-nil, they have the same length,147// and either they point to the same initial entry of the same underlying array148// (that is, &x[0] == &y[0]) or their corresponding elements (up to length) are deeply equal.149// Note that a non-nil empty slice and a nil slice (for example, []byte{} and []byte(nil))150// are not deeply equal.151//152// Other values - numbers, bools, strings, and channels - are deeply equal153// if they are equal using Go's == operator.154//155// In general DeepEqual is a recursive relaxation of Go's == operator.156// However, this idea is impossible to implement without some inconsistency.157// Specifically, it is possible for a value to be unequal to itself,158// either because it is of func type (uncomparable in general)159// or because it is a floating-point NaN value (not equal to itself in floating-point comparison),160// or because it is an array, struct, or interface containing161// such a value.162// On the other hand, pointer values are always equal to themselves,163// even if they point at or contain such problematic values,164// because they compare equal using Go's == operator, and that165// is a sufficient condition to be deeply equal, regardless of content.166// DeepEqual has been defined so that the same short-cut applies167// to slices and maps: if x and y are the same slice or the same map,168// they are deeply equal regardless of content.169func DeepEqual(x, y interface{}) bool {170 if x == nil || y == nil {171 return x == y172 }173 v1 := ValueOf(x)174 v2 := ValueOf(y)175 if v1.Type() != v2.Type() {176 return false177 }178 return deepValueEqual(v1, v2, make(map[visit]bool), 0)179}
tool_test.go
Source:tool_test.go
...8 "code.gitea.io/gitea/modules/setting"9 "github.com/stretchr/testify/assert"10)11func TestEncodeMD5(t *testing.T) {12 assert.Equal(t,13 "3858f62230ac3c915f300c664312c63f",14 EncodeMD5("foobar"),15 )16}17func TestEncodeSha1(t *testing.T) {18 assert.Equal(t,19 "8843d7f92416211de9ebb963ff4ce28125932878",20 EncodeSha1("foobar"),21 )22}23func TestEncodeSha256(t *testing.T) {24 assert.Equal(t,25 "c3ab8ff13720e8ad9047dd39466b3c8974e592c2fa383d4a3960714caef0c4f2",26 EncodeSha256("foobar"),27 )28}29func TestShortSha(t *testing.T) {30 assert.Equal(t, "veryverylo", ShortSha("veryverylong"))31}32func TestBasicAuthDecode(t *testing.T) {33 _, _, err := BasicAuthDecode("?")34 assert.Equal(t, "illegal base64 data at input byte 0", err.Error())35 user, pass, err := BasicAuthDecode("Zm9vOmJhcg==")36 assert.NoError(t, err)37 assert.Equal(t, "foo", user)38 assert.Equal(t, "bar", pass)39}40func TestBasicAuthEncode(t *testing.T) {41 assert.Equal(t, "Zm9vOmJhcg==", BasicAuthEncode("foo", "bar"))42}43// TODO: Test PBKDF2()44// TODO: Test VerifyTimeLimitCode()45// TODO: Test CreateTimeLimitCode()46func TestHashEmail(t *testing.T) {47 assert.Equal(t,48 "d41d8cd98f00b204e9800998ecf8427e",49 HashEmail(""),50 )51 assert.Equal(t,52 "353cbad9b58e69c96154ad99f92bedc7",53 HashEmail("gitea@example.com"),54 )55}56const gravatarSource = "https://secure.gravatar.com/avatar/"57func disableGravatar() {58 setting.EnableFederatedAvatar = false59 setting.LibravatarService = nil60 setting.DisableGravatar = true61}62func enableGravatar(t *testing.T) {63 setting.DisableGravatar = false64 var err error65 setting.GravatarSourceURL, err = url.Parse(gravatarSource)66 assert.NoError(t, err)67}68func TestSizedAvatarLink(t *testing.T) {69 disableGravatar()70 assert.Equal(t, "/img/avatar_default.png",71 SizedAvatarLink("gitea@example.com", 100))72 enableGravatar(t)73 assert.Equal(t,74 "https://secure.gravatar.com/avatar/353cbad9b58e69c96154ad99f92bedc7?d=identicon&s=100",75 SizedAvatarLink("gitea@example.com", 100),76 )77}78func TestFileSize(t *testing.T) {79 var size int64 = 51280 assert.Equal(t, "512 B", FileSize(size))81 size *= 102482 assert.Equal(t, "512 KiB", FileSize(size))83 size *= 102484 assert.Equal(t, "512 MiB", FileSize(size))85 size *= 102486 assert.Equal(t, "512 GiB", FileSize(size))87 size *= 102488 assert.Equal(t, "512 TiB", FileSize(size))89 size *= 102490 assert.Equal(t, "512 PiB", FileSize(size))91 size *= 492 assert.Equal(t, "2.0 EiB", FileSize(size))93}94func TestSubtract(t *testing.T) {95 toFloat64 := func(n interface{}) float64 {96 switch v := n.(type) {97 case int:98 return float64(v)99 case int8:100 return float64(v)101 case int16:102 return float64(v)103 case int32:104 return float64(v)105 case int64:106 return float64(v)107 case float32:108 return float64(v)109 case float64:110 return v111 default:112 return 0.0113 }114 }115 values := []interface{}{116 int(-3),117 int8(14),118 int16(81),119 int32(-156),120 int64(1528),121 float32(3.5),122 float64(-15.348),123 }124 for _, left := range values {125 for _, right := range values {126 expected := toFloat64(left) - toFloat64(right)127 sub := Subtract(left, right)128 assert.InDelta(t, expected, sub, 1e-3)129 }130 }131}132func TestEllipsisString(t *testing.T) {133 assert.Equal(t, "...", EllipsisString("foobar", 0))134 assert.Equal(t, "...", EllipsisString("foobar", 1))135 assert.Equal(t, "...", EllipsisString("foobar", 2))136 assert.Equal(t, "...", EllipsisString("foobar", 3))137 assert.Equal(t, "f...", EllipsisString("foobar", 4))138 assert.Equal(t, "fo...", EllipsisString("foobar", 5))139 assert.Equal(t, "foobar", EllipsisString("foobar", 6))140 assert.Equal(t, "foobar", EllipsisString("foobar", 10))141}142func TestTruncateString(t *testing.T) {143 assert.Equal(t, "", TruncateString("foobar", 0))144 assert.Equal(t, "f", TruncateString("foobar", 1))145 assert.Equal(t, "fo", TruncateString("foobar", 2))146 assert.Equal(t, "foo", TruncateString("foobar", 3))147 assert.Equal(t, "foob", TruncateString("foobar", 4))148 assert.Equal(t, "fooba", TruncateString("foobar", 5))149 assert.Equal(t, "foobar", TruncateString("foobar", 6))150 assert.Equal(t, "foobar", TruncateString("foobar", 7))151}152func TestStringsToInt64s(t *testing.T) {153 testSuccess := func(input []string, expected []int64) {154 result, err := StringsToInt64s(input)155 assert.NoError(t, err)156 assert.Equal(t, expected, result)157 }158 testSuccess([]string{}, []int64{})159 testSuccess([]string{"-1234"}, []int64{-1234})160 testSuccess([]string{"1", "4", "16", "64", "256"},161 []int64{1, 4, 16, 64, 256})162 _, err := StringsToInt64s([]string{"-1", "a", "$"})163 assert.Error(t, err)164}165func TestInt64sToStrings(t *testing.T) {166 assert.Equal(t, []string{}, Int64sToStrings([]int64{}))167 assert.Equal(t,168 []string{"1", "4", "16", "64", "256"},169 Int64sToStrings([]int64{1, 4, 16, 64, 256}),170 )171}172func TestInt64sToMap(t *testing.T) {173 assert.Equal(t, map[int64]bool{}, Int64sToMap([]int64{}))174 assert.Equal(t,175 map[int64]bool{1: true, 4: true, 16: true},176 Int64sToMap([]int64{1, 4, 16}),177 )178}179func TestIsLetter(t *testing.T) {180 assert.True(t, IsLetter('a'))181 assert.True(t, IsLetter('e'))182 assert.True(t, IsLetter('q'))183 assert.True(t, IsLetter('z'))184 assert.True(t, IsLetter('A'))185 assert.True(t, IsLetter('E'))186 assert.True(t, IsLetter('Q'))187 assert.True(t, IsLetter('Z'))188 assert.True(t, IsLetter('_'))...
Equal
Using AI Code Generation
1import "fmt"2type IntSet struct {3}4func main() {5 x.Add(1)6 x.Add(144)7 x.Add(9)8 y.Add(9)9 y.Add(42)10 x.UnionWith(&y)11 x.Clear()12 x.AddAll(9, 42, 1, 9, 42, 1, 9, 42, 1)13 y.AddAll(9, 42, 1, 9, 42, 1, 9, 42, 1)14 y.Add(144)15 z := x.Copy()16 x.Add(144)17 x.IntersectWith(&y)18 x.DifferenceWith(&y)19 x.AddAll(1, 9, 42, 144)20 y.AddAll(1, 9, 42, 144)21 x.SymmetricDifference(&y)22 x.AddAll(1, 9, 42, 144)23 y.AddAll(9,
Equal
Using AI Code Generation
1import (2func main() {3fmt.Println("Hello, playground")4}5import (6func main() {7fmt.Println("Hello, playground")8}9import (10func main() {11fmt.Println("Hello, playground")12}
Equal
Using AI Code Generation
1import (2func main() {3 fmt.Println("a == b is", reflect.DeepEqual(a, b))4 fmt.Println("a != b is", !reflect.DeepEqual(a, b))5}6import (7type Student struct {8}9func main() {10 var s1 = Student{"John", 23}11 var s2 = Student{"John", 23}12 fmt.Println("s1 == s2 is", reflect.DeepEqual(s1, s2))13 fmt.Println("s1 != s2 is", !reflect.DeepEqual(s1, s2))14}15import (16func main() {17 var a = [3]int{1, 2, 3}18 var b = [3]int{1, 2, 3}19 fmt.Println("a == b is", reflect.DeepEqual(a, b))20 fmt.Println("a != b is", !reflect.DeepEqual(a, b))21}22import (23func main() {24 var a = []int{1, 2, 3}25 var b = []int{1, 2, 3}26 fmt.Println("a == b is", reflect.DeepEqual(a, b))27 fmt.Println("a != b is", !reflect.DeepEqual(a, b))28}29import (30func main() {31 var a = map[string]int{"a":
Equal
Using AI Code Generation
1import "fmt"2func main() {3 fmt.Println(i1.Equal(i2))4}5import "fmt"6func main() {7 fmt.Println(i1.Equal(i2))8}9import "fmt"10func main() {11 fmt.Println(i1 == i2)12}
Equal
Using AI Code Generation
1import (2func main() {3 fmt.Println(eq.Equal("a", "a"))4 fmt.Println(eq.Equal("a", "b"))5 fmt.Println(eq.Equal(1, 1))6 fmt.Println(eq.Equal(1, 2))7 fmt.Println(eq.Equal(1.1, 1.1))8 fmt.Println(eq.Equal(1.1, 1.2))9}
Equal
Using AI Code Generation
1import (2func main() {3 fmt.Println(a.Equal(b))4}5import (6func main() {7 fmt.Println(a.Equal(b))8}9import (10func main() {11 fmt.Println(a.Equal(b))12}13Recommended Posts: Go | is() method14Go | GreaterThan() method15Go | LessThan() method16Go | LessThanOrEqual() method17Go | GreaterThanOrEqual() method18Go | NotEqual() method19Go | Equal() method20Go | Not() method21Go | Not() method22Go | Equal() method23Go | LessThan() method24Go | GreaterThan() method25Go | GreaterThanOrEqual() method26Go | LessThanOrEqual() method27Go | NotEqual() method28Go | Equal() method29Go | Not() method30Go | Equal() method31Go | LessThan() method32Go | GreaterThan() method33Go | GreaterThanOrEqual() method34Go | LessThanOrEqual() method35Go | NotEqual() method36Go | Equal() method37Go | Not() method38Go | Equal() method39Go | LessThan() method40Go | GreaterThan() method41Go | GreaterThanOrEqual() method42Go | LessThanOrEqual() method43Go | NotEqual() method44Go | Equal() method
Equal
Using AI Code Generation
1import "fmt"2func main() {3 i1 = is{1,2}4 i2 = is{1,2}5 fmt.Println(i1.Equal(i2))6}
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!!