Best Go-testdeep code snippet using test.Log
logrus_test.go
Source:logrus_test.go
...16 . "github.com/sirupsen/logrus/internal/testutils"17)18// TestReportCaller verifies that when ReportCaller is set, the 'func' field19// is added, and when it is unset it is not set or modified20// Verify that functions within the Logrus package aren't considered when21// discovering the caller.22func TestReportCallerWhenConfigured(t *testing.T) {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))...
resource_aws_cloudwatch_log_group_test.go
Source:resource_aws_cloudwatch_log_group_test.go
...7 "github.com/hashicorp/terraform/helper/acctest"8 "github.com/hashicorp/terraform/helper/resource"9 "github.com/hashicorp/terraform/terraform"10)11func TestAccAWSCloudWatchLogGroup_basic(t *testing.T) {12 var lg cloudwatchlogs.LogGroup13 rInt := acctest.RandInt()14 resource.Test(t, resource.TestCase{15 PreCheck: func() { testAccPreCheck(t) },16 Providers: testAccProviders,17 CheckDestroy: testAccCheckAWSCloudWatchLogGroupDestroy,18 Steps: []resource.TestStep{19 {20 Config: testAccAWSCloudWatchLogGroupConfig(rInt),21 Check: resource.ComposeTestCheckFunc(22 testAccCheckCloudWatchLogGroupExists("aws_cloudwatch_log_group.foobar", &lg),23 resource.TestCheckResourceAttr("aws_cloudwatch_log_group.foobar", "retention_in_days", "0"),24 ),25 },26 },27 })28}29func TestAccAWSCloudWatchLogGroup_namePrefix(t *testing.T) {30 var lg cloudwatchlogs.LogGroup31 resource.Test(t, resource.TestCase{32 PreCheck: func() { testAccPreCheck(t) },33 Providers: testAccProviders,34 CheckDestroy: testAccCheckAWSCloudWatchLogGroupDestroy,35 Steps: []resource.TestStep{36 {37 Config: testAccAWSCloudWatchLogGroup_namePrefix,38 Check: resource.ComposeTestCheckFunc(39 testAccCheckCloudWatchLogGroupExists("aws_cloudwatch_log_group.test", &lg),40 resource.TestMatchResourceAttr("aws_cloudwatch_log_group.test", "name", regexp.MustCompile("^tf-test-")),41 ),42 },43 },44 })45}46func TestAccAWSCloudWatchLogGroup_generatedName(t *testing.T) {47 var lg cloudwatchlogs.LogGroup48 resource.Test(t, resource.TestCase{49 PreCheck: func() { testAccPreCheck(t) },50 Providers: testAccProviders,51 CheckDestroy: testAccCheckAWSCloudWatchLogGroupDestroy,52 Steps: []resource.TestStep{53 {54 Config: testAccAWSCloudWatchLogGroup_generatedName,55 Check: resource.ComposeTestCheckFunc(56 testAccCheckCloudWatchLogGroupExists("aws_cloudwatch_log_group.test", &lg),57 ),58 },59 },60 })61}62func TestAccAWSCloudWatchLogGroup_retentionPolicy(t *testing.T) {63 var lg cloudwatchlogs.LogGroup64 rInt := acctest.RandInt()65 resource.Test(t, resource.TestCase{66 PreCheck: func() { testAccPreCheck(t) },67 Providers: testAccProviders,68 CheckDestroy: testAccCheckAWSCloudWatchLogGroupDestroy,69 Steps: []resource.TestStep{70 {71 Config: testAccAWSCloudWatchLogGroupConfig_withRetention(rInt),72 Check: resource.ComposeTestCheckFunc(73 testAccCheckCloudWatchLogGroupExists("aws_cloudwatch_log_group.foobar", &lg),74 resource.TestCheckResourceAttr("aws_cloudwatch_log_group.foobar", "retention_in_days", "365"),75 ),76 },77 {78 Config: testAccAWSCloudWatchLogGroupConfigModified_withRetention(rInt),79 Check: resource.ComposeTestCheckFunc(80 testAccCheckCloudWatchLogGroupExists("aws_cloudwatch_log_group.foobar", &lg),81 resource.TestCheckResourceAttr("aws_cloudwatch_log_group.foobar", "retention_in_days", "0"),82 ),83 },84 },85 })86}87func TestAccAWSCloudWatchLogGroup_multiple(t *testing.T) {88 var lg cloudwatchlogs.LogGroup89 rInt := acctest.RandInt()90 resource.Test(t, resource.TestCase{91 PreCheck: func() { testAccPreCheck(t) },92 Providers: testAccProviders,93 CheckDestroy: testAccCheckAWSCloudWatchLogGroupDestroy,94 Steps: []resource.TestStep{95 {96 Config: testAccAWSCloudWatchLogGroupConfig_multiple(rInt),97 Check: resource.ComposeTestCheckFunc(98 testAccCheckCloudWatchLogGroupExists("aws_cloudwatch_log_group.alpha", &lg),99 resource.TestCheckResourceAttr("aws_cloudwatch_log_group.alpha", "retention_in_days", "14"),100 testAccCheckCloudWatchLogGroupExists("aws_cloudwatch_log_group.beta", &lg),101 resource.TestCheckResourceAttr("aws_cloudwatch_log_group.beta", "retention_in_days", "0"),102 testAccCheckCloudWatchLogGroupExists("aws_cloudwatch_log_group.charlie", &lg),103 resource.TestCheckResourceAttr("aws_cloudwatch_log_group.charlie", "retention_in_days", "3653"),104 ),105 },106 },107 })108}109func TestAccAWSCloudWatchLogGroup_disappears(t *testing.T) {110 var lg cloudwatchlogs.LogGroup111 rInt := acctest.RandInt()112 resource.Test(t, resource.TestCase{113 PreCheck: func() { testAccPreCheck(t) },114 Providers: testAccProviders,115 CheckDestroy: testAccCheckAWSCloudWatchLogGroupDestroy,116 Steps: []resource.TestStep{117 {118 Config: testAccAWSCloudWatchLogGroupConfig(rInt),119 Check: resource.ComposeTestCheckFunc(120 testAccCheckCloudWatchLogGroupExists("aws_cloudwatch_log_group.foobar", &lg),121 testAccCheckCloudWatchLogGroupDisappears(&lg),122 ),123 ExpectNonEmptyPlan: true,124 },125 },126 })127}128func TestAccAWSCloudWatchLogGroup_tagging(t *testing.T) {129 var lg cloudwatchlogs.LogGroup130 rInt := acctest.RandInt()131 resource.Test(t, resource.TestCase{132 PreCheck: func() { testAccPreCheck(t) },133 Providers: testAccProviders,134 CheckDestroy: testAccCheckAWSCloudWatchLogGroupDestroy,135 Steps: []resource.TestStep{136 {137 Config: testAccAWSCloudWatchLogGroupConfigWithTags(rInt),138 Check: resource.ComposeTestCheckFunc(139 testAccCheckCloudWatchLogGroupExists("aws_cloudwatch_log_group.foobar", &lg),140 resource.TestCheckResourceAttr("aws_cloudwatch_log_group.foobar", "tags.%", "3"),141 resource.TestCheckResourceAttr("aws_cloudwatch_log_group.foobar", "tags.Environment", "Production"),142 resource.TestCheckResourceAttr("aws_cloudwatch_log_group.foobar", "tags.Foo", "Bar"),143 resource.TestCheckResourceAttr("aws_cloudwatch_log_group.foobar", "tags.Empty", ""),144 ),145 },146 {147 Config: testAccAWSCloudWatchLogGroupConfigWithTagsAdded(rInt),148 Check: resource.ComposeTestCheckFunc(149 testAccCheckCloudWatchLogGroupExists("aws_cloudwatch_log_group.foobar", &lg),150 resource.TestCheckResourceAttr("aws_cloudwatch_log_group.foobar", "tags.%", "4"),151 resource.TestCheckResourceAttr("aws_cloudwatch_log_group.foobar", "tags.Environment", "Development"),152 resource.TestCheckResourceAttr("aws_cloudwatch_log_group.foobar", "tags.Foo", "Bar"),153 resource.TestCheckResourceAttr("aws_cloudwatch_log_group.foobar", "tags.Empty", ""),154 resource.TestCheckResourceAttr("aws_cloudwatch_log_group.foobar", "tags.Bar", "baz"),155 ),156 },157 {158 Config: testAccAWSCloudWatchLogGroupConfigWithTagsUpdated(rInt),159 Check: resource.ComposeTestCheckFunc(160 testAccCheckCloudWatchLogGroupExists("aws_cloudwatch_log_group.foobar", &lg),161 resource.TestCheckResourceAttr("aws_cloudwatch_log_group.foobar", "tags.%", "4"),162 resource.TestCheckResourceAttr("aws_cloudwatch_log_group.foobar", "tags.Environment", "Development"),163 resource.TestCheckResourceAttr("aws_cloudwatch_log_group.foobar", "tags.Empty", "NotEmpty"),164 resource.TestCheckResourceAttr("aws_cloudwatch_log_group.foobar", "tags.Foo", "UpdatedBar"),165 resource.TestCheckResourceAttr("aws_cloudwatch_log_group.foobar", "tags.Bar", "baz"),166 ),167 },168 {169 Config: testAccAWSCloudWatchLogGroupConfigWithTags(rInt),170 Check: resource.ComposeTestCheckFunc(171 testAccCheckCloudWatchLogGroupExists("aws_cloudwatch_log_group.foobar", &lg),172 resource.TestCheckResourceAttr("aws_cloudwatch_log_group.foobar", "tags.%", "3"),173 resource.TestCheckResourceAttr("aws_cloudwatch_log_group.foobar", "tags.Environment", "Production"),174 resource.TestCheckResourceAttr("aws_cloudwatch_log_group.foobar", "tags.Foo", "Bar"),175 resource.TestCheckResourceAttr("aws_cloudwatch_log_group.foobar", "tags.Empty", ""),176 ),177 },178 },179 })180}181func testAccCheckCloudWatchLogGroupDisappears(lg *cloudwatchlogs.LogGroup) resource.TestCheckFunc {182 return func(s *terraform.State) error {183 conn := testAccProvider.Meta().(*AWSClient).cloudwatchlogsconn184 opts := &cloudwatchlogs.DeleteLogGroupInput{185 LogGroupName: lg.LogGroupName,186 }187 if _, err := conn.DeleteLogGroup(opts); err != nil {188 return err189 }190 return nil191 }192}193func testAccCheckCloudWatchLogGroupExists(n string, lg *cloudwatchlogs.LogGroup) resource.TestCheckFunc {194 return func(s *terraform.State) error {195 rs, ok := s.RootModule().Resources[n]196 if !ok {197 return fmt.Errorf("Not found: %s", n)198 }199 conn := testAccProvider.Meta().(*AWSClient).cloudwatchlogsconn200 logGroup, exists, err := lookupCloudWatchLogGroup(conn, rs.Primary.ID, nil)201 if err != nil {202 return err203 }204 if !exists {205 return fmt.Errorf("Bad: LogGroup %q does not exist", rs.Primary.ID)206 }207 *lg = *logGroup208 return nil209 }210}211func testAccCheckAWSCloudWatchLogGroupDestroy(s *terraform.State) error {212 conn := testAccProvider.Meta().(*AWSClient).cloudwatchlogsconn213 for _, rs := range s.RootModule().Resources {214 if rs.Type != "aws_cloudwatch_log_group" {215 continue216 }217 _, exists, err := lookupCloudWatchLogGroup(conn, rs.Primary.ID, nil)218 if err != nil {219 return nil220 }221 if exists {222 return fmt.Errorf("Bad: LogGroup still exists: %q", rs.Primary.ID)223 }224 }225 return nil226}227func testAccAWSCloudWatchLogGroupConfig(rInt int) string {228 return fmt.Sprintf(`229resource "aws_cloudwatch_log_group" "foobar" {230 name = "foo-bar-%d"231}232`, rInt)233}234func testAccAWSCloudWatchLogGroupConfigWithTags(rInt int) string {235 return fmt.Sprintf(`236resource "aws_cloudwatch_log_group" "foobar" {237 name = "foo-bar-%d"238 tags {239 Environment = "Production"240 Foo = "Bar"241 Empty = ""242 }243}244`, rInt)245}246func testAccAWSCloudWatchLogGroupConfigWithTagsAdded(rInt int) string {247 return fmt.Sprintf(`248resource "aws_cloudwatch_log_group" "foobar" {249 name = "foo-bar-%d"250 tags {251 Environment = "Development"252 Foo = "Bar"253 Empty = ""254 Bar = "baz"255 }256}257`, rInt)258}259func testAccAWSCloudWatchLogGroupConfigWithTagsUpdated(rInt int) string {260 return fmt.Sprintf(`261resource "aws_cloudwatch_log_group" "foobar" {262 name = "foo-bar-%d"263 tags {264 Environment = "Development"265 Foo = "UpdatedBar"266 Empty = "NotEmpty"267 Bar = "baz"268 }269}270`, rInt)271}272func testAccAWSCloudWatchLogGroupConfigWithTagsRemoval(rInt int) string {273 return fmt.Sprintf(`274resource "aws_cloudwatch_log_group" "foobar" {275 name = "foo-bar-%d"276 tags {277 Environment = "Production"278 Foo = "Bar"279 Empty = ""280 }281}282`, rInt)283}284func testAccAWSCloudWatchLogGroupConfig_withRetention(rInt int) string {285 return fmt.Sprintf(`286resource "aws_cloudwatch_log_group" "foobar" {287 name = "foo-bar-%d"288 retention_in_days = 365289}290`, rInt)291}292func testAccAWSCloudWatchLogGroupConfigModified_withRetention(rInt int) string {293 return fmt.Sprintf(`294resource "aws_cloudwatch_log_group" "foobar" {295 name = "foo-bar-%d"296}297`, rInt)298}299func testAccAWSCloudWatchLogGroupConfig_multiple(rInt int) string {300 return fmt.Sprintf(`301resource "aws_cloudwatch_log_group" "alpha" {302 name = "foo-bar-%d"303 retention_in_days = 14304}305resource "aws_cloudwatch_log_group" "beta" {306 name = "foo-bar-%d"307}308resource "aws_cloudwatch_log_group" "charlie" {309 name = "foo-bar-%d"310 retention_in_days = 3653311}312`, rInt, rInt+1, rInt+2)313}314const testAccAWSCloudWatchLogGroup_namePrefix = `315resource "aws_cloudwatch_log_group" "test" {316 name_prefix = "tf-test-"317}318`319const testAccAWSCloudWatchLogGroup_generatedName = `320resource "aws_cloudwatch_log_group" "test" {}321`...
resource_aws_flow_log_test.go
Source:resource_aws_flow_log_test.go
...7 "github.com/hashicorp/terraform/helper/acctest"8 "github.com/hashicorp/terraform/helper/resource"9 "github.com/hashicorp/terraform/terraform"10)11func TestAccAWSFlowLog_basic(t *testing.T) {12 var flowLog ec2.FlowLog13 rInt := acctest.RandInt()14 resource.Test(t, resource.TestCase{15 PreCheck: func() { testAccPreCheck(t) },16 IDRefreshName: "aws_flow_log.test_flow_log",17 Providers: testAccProviders,18 CheckDestroy: testAccCheckFlowLogDestroy,19 Steps: []resource.TestStep{20 resource.TestStep{21 Config: testAccFlowLogConfig_basic(rInt),22 Check: resource.ComposeTestCheckFunc(23 testAccCheckFlowLogExists("aws_flow_log.test_flow_log", &flowLog),24 testAccCheckAWSFlowLogAttributes(&flowLog),25 ),26 },27 },28 })29}30func TestAccAWSFlowLog_subnet(t *testing.T) {31 var flowLog ec2.FlowLog32 rInt := acctest.RandInt()33 resource.Test(t, resource.TestCase{34 PreCheck: func() { testAccPreCheck(t) },35 IDRefreshName: "aws_flow_log.test_flow_log_subnet",36 Providers: testAccProviders,37 CheckDestroy: testAccCheckFlowLogDestroy,38 Steps: []resource.TestStep{39 resource.TestStep{40 Config: testAccFlowLogConfig_subnet(rInt),41 Check: resource.ComposeTestCheckFunc(42 testAccCheckFlowLogExists("aws_flow_log.test_flow_log_subnet", &flowLog),43 testAccCheckAWSFlowLogAttributes(&flowLog),44 ),45 },46 },47 })48}49func testAccCheckFlowLogExists(n string, flowLog *ec2.FlowLog) resource.TestCheckFunc {50 return func(s *terraform.State) error {51 rs, ok := s.RootModule().Resources[n]52 if !ok {53 return fmt.Errorf("Not found: %s", n)54 }55 if rs.Primary.ID == "" {56 return fmt.Errorf("No Flow Log ID is set")57 }58 conn := testAccProvider.Meta().(*AWSClient).ec2conn59 describeOpts := &ec2.DescribeFlowLogsInput{60 FlowLogIds: []*string{aws.String(rs.Primary.ID)},61 }62 resp, err := conn.DescribeFlowLogs(describeOpts)63 if err != nil {64 return err65 }66 if len(resp.FlowLogs) > 0 {67 *flowLog = *resp.FlowLogs[0]68 return nil69 }70 return fmt.Errorf("No Flow Logs found for id (%s)", rs.Primary.ID)71 }72}73func testAccCheckAWSFlowLogAttributes(flowLog *ec2.FlowLog) resource.TestCheckFunc {74 return func(s *terraform.State) error {75 if flowLog.FlowLogStatus != nil && *flowLog.FlowLogStatus == "ACTIVE" {76 return nil77 }78 if flowLog.FlowLogStatus == nil {79 return fmt.Errorf("Flow Log status is not ACTIVE, is nil")80 } else {81 return fmt.Errorf("Flow Log status is not ACTIVE, got: %s", *flowLog.FlowLogStatus)82 }83 }84}85func testAccCheckFlowLogDestroy(s *terraform.State) error {86 for _, rs := range s.RootModule().Resources {87 if rs.Type != "aws_flow_log" {88 continue89 }90 return nil91 }92 return nil93}94func testAccFlowLogConfig_basic(rInt int) string {95 return fmt.Sprintf(`96resource "aws_vpc" "default" {97 cidr_block = "10.0.0.0/16"98 tags {99 Name = "tf-flow-log-test"100 }101}102resource "aws_subnet" "test_subnet" {103 vpc_id = "${aws_vpc.default.id}"104 cidr_block = "10.0.1.0/24"105 tags {106 Name = "tf-flow-test"107 }108}109resource "aws_iam_role" "test_role" {110 name = "tf_test_flow_log_basic_%d"111 assume_role_policy = <<EOF112{113 "Version": "2012-10-17",114 "Statement": [115 {116 "Effect": "Allow",117 "Principal": {118 "Service": [119 "ec2.amazonaws.com"120 ]121 },122 "Action": [123 "sts:AssumeRole"124 ]125 }126 ]127}128EOF129}130resource "aws_cloudwatch_log_group" "foobar" {131 name = "tf-test-fl-%d"132}133resource "aws_flow_log" "test_flow_log" {134 log_group_name = "${aws_cloudwatch_log_group.foobar.name}"135 iam_role_arn = "${aws_iam_role.test_role.arn}"136 vpc_id = "${aws_vpc.default.id}"137 traffic_type = "ALL"138}139resource "aws_flow_log" "test_flow_log_subnet" {140 log_group_name = "${aws_cloudwatch_log_group.foobar.name}"141 iam_role_arn = "${aws_iam_role.test_role.arn}"142 subnet_id = "${aws_subnet.test_subnet.id}"143 traffic_type = "ALL"144}145`, rInt, rInt)146}147func testAccFlowLogConfig_subnet(rInt int) string {148 return fmt.Sprintf(`149resource "aws_vpc" "default" {150 cidr_block = "10.0.0.0/16"151 tags {152 Name = "tf-flow-log-test"153 }154}155resource "aws_subnet" "test_subnet" {156 vpc_id = "${aws_vpc.default.id}"157 cidr_block = "10.0.1.0/24"158 tags {159 Name = "tf-flow-test"160 }161}...
Log
Using AI Code Generation
1import "test"2func main() {3 test.Log("Hello World")4}5import "fmt"6func Log(msg string) {7 fmt.Println(msg)8}
Log
Using AI Code Generation
1func main() {2 test := new(test)3 test.Log("Hello World")4}5import (6type test struct {7}8func (t *test) Log(s string) {9 fmt.Println(s)10}11func (t *test) Log2(s string) {12 fmt.Println(s)13}14func main() {15 t := new(test)16 v := reflect.ValueOf(t).Elem()17 fmt.Println(v.NumMethod())18 for i := 0; i < v.NumMethod(); i++ {19 fmt.Println(v.Method(i).Type())20 }21}22func(*main.test, string)23func(*main.test, string)24You can use reflect.ValueOf(slice).Index(i) to get the ith element of the slice. You can then use reflect.ValueOf(slice).Index(i).Interface() to get the
Log
Using AI Code Generation
1import (2func main() {3 t := testing.T{}4 t.Log("Hello world")5}6How to use testing.TB.Log() method in Golang?7How to use testing.TB.Log() method in Golang?8How to use testing.TB.Fatal() method in Golang?9How to use testing.TB.Fatal() method in Golang?10How to use testing.TB.Fatal() method in Golang?11How to use testing.TB.Error() method in Golang?12How to use testing.TB.Error() method in Golang?13How to use testing.TB.Error() method in Golang?14How to use testing.TB.Helper() method in Golang?15How to use testing.TB.Helper() method in Golang?16How to use testing.TB.Helper() method in Golang?17How to use testing.TB.Skip() method in Golang?18How to use testing.TB.Skip() method in Golang?19How to use testing.TB.Skip() method in Golang?20How to use testing.TB.SkipNow() method in Golang?21How to use testing.TB.SkipNow() method in Golang?22How to use testing.TB.SkipNow() method in Golang?23How to use testing.TB.Fail() method in Golang?24How to use testing.TB.Fail() method in Golang?25How to use testing.TB.Fail() method in Golang?26How to use testing.TB.FailNow() method in Golang?27How to use testing.TB.FailNow() method in Golang?28How to use testing.TB.FailNow() method in Golang?29How to use testing.TB.Parallel() method in Golang?30How to use testing.TB.Parallel() meth
Log
Using AI Code Generation
1import (2func main() {3 test.Log("Hello")4}5Go supports the following types of import statements:6The following is the syntax of the init() function:7func init() {8}9The following is the syntax of the main() function:10func main() {11}12The following is the syntax of the import statement:13import "package_name"
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!!