File: fluent_test.go

package info (click to toggle)
golang-github-fluent-fluent-logger-golang 1.9.0-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bookworm-proposed-updates, forky, sid, trixie
  • size: 208 kB
  • sloc: makefile: 4
file content (946 lines) | stat: -rw-r--r-- 26,188 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
package fluent

import (
	"bytes"
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"io/ioutil"
	"net"
	"reflect"
	"runtime"
	"testing"
	"time"

	"github.com/bmizerany/assert"
	"github.com/tinylib/msgp/msgp"
)

func init() {
	// randomGenerator points to rand.Uint64 by default. Unfortunately, even when it's
	// seeded, it produces different values from time to time and thus is not fully
	// deterministic. This prevents writing stable tests for RequestAck config option.
	// Thus we need to change it to ensure the hashes are stable during tests.
	randomGenerator = func() uint64 {
		return 1
	}
}

func newTestDialer() *testDialer {
	return &testDialer{
		dialCh: make(chan *Conn),
	}
}

// testDialer is a stub for net.Dialer. It implements the Dial() method used by
// the logger to connect to Fluentd. It uses a *Conn channel to let the tests
// synchronize with calls to Dial() and let them define what each call to Dial()
// should return. This is especially useful for testing edge cases like
// transient connection failures.
// To help write test cases with succeeding or failing connection dialing, testDialer
// provides waitForNextDialing(). Any call to Dial() from the logger should be matched
// with a call to waitForNextDialing() in the test cases.
//
// For instance, to test an async logger that have to dial 4 times before succeeding,
// the test should look like this:
//
//   d := newTestDialer() // Create a new stubbed dialer
//   cfg := Config{
//       Async: true,
//  	   // ...
//   }
//   f := newWithDialer(cfg, d) // Create a fluent logger using the stubbed dialer
//   f.EncodeAndPostData("tag_name", time.Unix(1482493046, 0), map[string]string{"foo": "bar"})
//
//   d.waitForNextDialing(false, false) // 1st dialing attempt fails
//   d.waitForNextDialing(false, false) // 2nd attempt fails too
//   d.waitForNextDialing(false, false) // 3rd attempt fails too
//   d.waitForNextDialing(true, false) // Finally the 4th attempt succeeds
//
// Note that in the above example, the logger operates in async mode. As such,
// a call to Post, PostWithTime or EncodeAndPostData is needed *before* calling
// waitForNextDialing(), as in async mode the logger initializes its connection
// lazily, in a separate goroutine.
// This also means non-async loggers can't be tested exactly the same way, as the
// dialing isn't done lazily but during the logger initialization. To test such
// case, you have to put the calls to newWithDialer() and to EncodeAndPostData()
// into their own goroutine. An example:
//
//   d := newTestDialer() // Create a new stubbed dialer
//   cfg := Config{
//       Async: false,
//  	   // ...
//   }
//   go func() {
//       f := newWithDialer(cfg, d) // Create a fluent logger using the stubbed dialer
//       f.Close()
//   }()
//
//   d.waitForNextDialing(false, false) // 1st dialing attempt fails
//   d.waitForNextDialing(false, false) // 2nd attempt fails too
//   d.waitForNextDialing(false, false) // 3rd attempt fails too
//   d.waitForNextDialing(true, false) // Finally the 4th attempt succeeds
//
// Moreover, waitForNextDialing() returns a *Conn which extends net.Conn to provide testing
// facilities. For instance, you can call waitForNextWrite() on these connections, to
// specify how the next Conn.Write() call behaves (e.g. accept or reject it, or make a
// specific ack checksum available) and to assert what is sent to Fluentd (when the write
// is accepted). Again, any call to Write() on the logger side have to be matched with
// a call to waitForNextWrite() in the test cases.
//
// Here's a full example:
//
//   d := newTestDialer()
//   cfg := Config{Async: true}
//
//   f := newWithDialer(cfg, d)
//   f.EncodeAndPostData("tag_name", time.Unix(1482493046, 0), map[string]string{"foo": "bar"})
//
//   conn := d.waitForNextDialing(true, false) // Accept the dialing
//   conn.waitForNextWrite(false, "") // Discard the 1st attempt to write the message
//
//   conn := d.waitForNextDialing(true, false)
//   assertReceived(t, // t is *testing.T
//       conn.waitForNextWrite(true, ""),
//       "[\"tag_name\",1482493046,{\"foo\":\"bar\"},{}]")
//
//   f.EncodeAndPostData("something_else", time.Unix(1482493050, 0), map[string]string{"bar": "baz"})
//   assertReceived(t, // t is *testing.T
//       conn.waitForNextWrite(true, ""),
//       "[\"something_else\",1482493050,{\"bar\":\"baz\"},{}]")
//
// In this example, the 1st connection dialing succeeds but the 1st attempt to write the
// message is discarded. As the logger discards the connection whenever a message
// couldn't be written, it tries to re-dial and thus we need to accept the dialing again.
// Then the write is retried and accepted. When a second message is written, the write is
// accepted straightaway. Moreover, the messages written to the connections are asserted
// using assertReceived() to make sure the logger encodes the messages properly.
//
// Again, the example above is using async mode thus, calls to f and conn are running in
// the same goroutine. However in sync mode, all calls to f.EncodeAndPostData() as well
// as the logger initialization shall be placed in a separate goroutine or the code
// allowing the dialing and writing attempts (eg. waitForNextDialing() & waitForNextWrite())
// would never be reached.
type testDialer struct {
	dialCh chan *Conn
}

// DialContext is the stubbed method called by the logger to establish the connection to
// Fluentd. It is paired with waitForNextDialing().
func (d *testDialer) DialContext(ctx context.Context, _, _ string) (net.Conn, error) {
	// It waits for a *Conn to be pushed into dialCh using waitForNextDialing(). When the
	// *Conn is nil, the Dial is deemed to fail.
	select {
	case conn := <-d.dialCh:
		if conn == nil {
			return nil, errors.New("failed to dial")
		}
		return conn, nil
	case <-ctx.Done():
		return nil, errors.New("failed to dial")
	}
}

// waitForNextDialing is the method used by test cases below to indicate whether the next
// dialing attempt made by the logger should succeed or not. See examples provided on
// testDialer docs.
func (d *testDialer) waitForNextDialing(accept bool, delayReads bool) *Conn {
	var conn *Conn
	if accept {
		conn = &Conn{
			nextWriteAttemptCh: make(chan nextWrite),
			writtenCh:          make(chan []byte),
		}

		if delayReads {
			conn.delayNextReadCh = make(chan struct{})
		}
	}

	d.dialCh <- conn
	return conn
}

// assertReceived is used below by test cases to assert the content written to a *Conn
// matches an expected string. This is generally used in conjunction with
// Conn.waitForNextWrite().
func assertReceived(t *testing.T, rcv []byte, expected string) {
	if string(rcv) != expected {
		t.Fatalf("got %s, expect %s", string(rcv), expected)
	}
}

// Conn extends net.Conn to add channels used to synchronise across goroutines, eg.
// between the goroutine doing the dialing (through newWithDialer in sync mode, or the
// first message logging in async mode) and the testing goroutine (making calls to
// Conn.waitForNextWrite()).
// This should be of low importance if you're not trying to understand/change how
// waitFor...() methods work. See examples provided in testDialer docs for higher
// level details.
type Conn struct {
	net.Conn
	buf           []byte
	writeDeadline time.Time
	// nextWriteAttemptCh is used by waitForNextWrite() to let Write() know if the next write
	// attempt should succeed or fail.
	nextWriteAttemptCh chan nextWrite
	// writtenCh is used by Write() to signal to waitForNextWrite() when a write
	// happened.
	writtenCh chan []byte
	// delayNextReadCh is used to delay next conn.Read() attempt when testing ack resp.
	delayNextReadCh chan struct{}
}

// nextWrite is the struct passed by Conn.waitForNextWrite() to Conn.Write() through
// Conn.nextWriteAttemptCh to let Write() know if it should accept or discard the next write
// operation and what ack checksum should be made readable from the connection.
// This should be of low importance if you're not trying to understand/change how
// waitFor...() methods work. See examples provided in testDialer docs for higher
// level details.
type nextWrite struct {
	accept bool
	ack    string
}

// waitForNextWrite is the method used to tell how the next write made by the logger
// should behave. It can either accept or discard the next write operation. Moreover
// an ack checksum can be passed such that the next Write operation will make it
// readable from the connection, as the logger will try to read it to ack the Write
// operation. See examples provided in testDialer docs.
func (c *Conn) waitForNextWrite(accept bool, ack string) []byte {
	c.nextWriteAttemptCh <- nextWrite{accept, ack}
	if accept {
		return <-c.writtenCh
	}
	return []byte{}
}

// Read is a stubbed version of net.Conn Read() that returns the ack checksum of the last
// Write operation.
func (c *Conn) Read(b []byte) (int, error) {
	if c.delayNextReadCh != nil {
		select {
		case _, ok := <-c.delayNextReadCh:
			if !ok {
				return 0, errors.New("connection has been closed")
			}
		default:
		}
	}

	copy(b, c.buf)
	return len(c.buf), nil
}

// Write is a stubbed version of net.Conn Write(). Its behavior is determined by the last
// call to waitForNextWrite(). See examples provided in testDialer docs.
func (c *Conn) Write(b []byte) (int, error) {
	next, ok := nextWrite{true, ""}, true
	if c.nextWriteAttemptCh != nil {
		next, ok = <-c.nextWriteAttemptCh
	}
	if !next.accept || !ok {
		return 0, errors.New("transient write failure")
	}

	// Write the acknowledgment to c.buf to make it available to subsequent
	// call to Read().
	c.buf = make([]byte, len(next.ack))
	copy(c.buf, next.ack)

	// Write the payload received to writtenCh to assert on it.
	if c.writtenCh != nil {
		c.writtenCh <- b
	}

	return len(b), nil
}

func (c *Conn) SetWriteDeadline(t time.Time) error {
	c.writeDeadline = t
	return nil
}

func (c *Conn) Close() error {
	if c.delayNextReadCh != nil {
		close(c.delayNextReadCh)
	}

	return nil
}

func Test_New_itShouldUseDefaultConfigValuesIfNoOtherProvided(t *testing.T) {
	f, _ := New(Config{})
	assert.Equal(t, f.Config.FluentPort, defaultPort)
	assert.Equal(t, f.Config.FluentHost, defaultHost)
	assert.Equal(t, f.Config.Timeout, defaultTimeout)
	assert.Equal(t, f.Config.WriteTimeout, defaultWriteTimeout)
	assert.Equal(t, f.Config.BufferLimit, defaultBufferLimit)
	assert.Equal(t, f.Config.FluentNetwork, defaultNetwork)
	assert.Equal(t, f.Config.FluentSocketPath, defaultSocketPath)
}

func Test_New_itShouldUseUnixDomainSocketIfUnixSocketSpecified(t *testing.T) {
	if runtime.GOOS == "windows" {
		t.Skip("windows not supported")
	}
	socketFile := "/tmp/fluent-logger-golang.sock"
	network := "unix"
	l, err := net.Listen(network, socketFile)
	if err != nil {
		t.Error(err)
		return
	}
	defer l.Close()

	f, err := New(Config{
		FluentNetwork:    network,
		FluentSocketPath: socketFile})
	if err != nil {
		t.Error(err)
		return
	}
	defer f.Close()
	assert.Equal(t, f.Config.FluentNetwork, network)
	assert.Equal(t, f.Config.FluentSocketPath, socketFile)

	socketFile = "/tmp/fluent-logger-golang-xxx.sock"
	network = "unixxxx"
	fUnknown, err := New(Config{
		FluentNetwork:    network,
		FluentSocketPath: socketFile})
	if _, ok := err.(*ErrUnknownNetwork); !ok {
		t.Errorf("err type: %T", err)
	}
	if err == nil {
		t.Error(err)
		fUnknown.Close()
		return
	}
}

func Test_New_itShouldUseConfigValuesFromArguments(t *testing.T) {
	f, _ := New(Config{FluentPort: 6666, FluentHost: "foobarhost"})
	assert.Equal(t, f.Config.FluentPort, 6666)
	assert.Equal(t, f.Config.FluentHost, "foobarhost")
}

func Test_New_itShouldUseConfigValuesFromMashalAsJSONArgument(t *testing.T) {
	f, _ := New(Config{MarshalAsJSON: true})
	assert.Equal(t, f.Config.MarshalAsJSON, true)
}

func Test_MarshalAsMsgpack(t *testing.T) {
	f := &Fluent{Config: Config{}}

	tag := "tag"
	var data = map[string]string{
		"foo":  "bar",
		"hoge": "hoge"}
	tm := time.Unix(1267867237, 0)
	result, err := f.EncodeData(tag, tm, data)

	if err != nil {
		t.Error(err)
	}
	actual := string(result.data)

	// map entries are disordered in golang
	expected1 := "\x94\xA3tag\xD2K\x92\u001Ee\x82\xA3foo\xA3bar\xA4hoge\xA4hoge\x80"
	expected2 := "\x94\xA3tag\xD2K\x92\u001Ee\x82\xA4hoge\xA4hoge\xA3foo\xA3bar\x80"
	if actual != expected1 && actual != expected2 {
		t.Errorf("got %+v,\n         except %+v\n             or %+v", actual, expected1, expected2)
	}
}

func Test_SubSecondPrecision(t *testing.T) {
	// Setup the test subject
	fluent := &Fluent{
		Config: Config{
			SubSecondPrecision: true,
		},
	}
	fluent.conn = &Conn{}

	// Exercise the test subject
	timestamp := time.Unix(1267867237, 256)
	encodedData, err := fluent.EncodeData("tag", timestamp, map[string]string{
		"foo": "bar",
	})

	// Assert no encoding errors and that the timestamp has been encoded into
	// the message as expected.
	if err != nil {
		t.Error(err)
	}

	// 8 bytes timestamp can be represented using ext 8 or fixext 8
	expected1 := "\x94\xA3tag\xC7\x08\x00K\x92\u001Ee\x00\x00\x01\x00\x81\xA3foo\xA3bar\x80"
	expected2 := "\x94\xa3tag\xD7\x00K\x92\x1Ee\x00\x00\x01\x00\x81\xA3foo\xA3bar\x80"
	actual := string(encodedData.data)
	if actual != expected1 && actual != expected2 {
		t.Errorf("got %+v,\n         except %+v\n             or %+v", actual, expected1, expected2)
	}
}

func Test_MarshalAsJSON(t *testing.T) {
	f := &Fluent{Config: Config{MarshalAsJSON: true}}

	var data = map[string]string{
		"foo":  "bar",
		"hoge": "hoge"}
	tm := time.Unix(1267867237, 0)
	result, err := f.EncodeData("tag", tm, data)

	if err != nil {
		t.Error(err)
	}
	// json.Encode marshals map keys in the order, so this expectation is safe
	expected := `["tag",1267867237,{"foo":"bar","hoge":"hoge"},{}]`
	actual := string(result.data)
	if actual != expected {
		t.Errorf("got %s, except %s", actual, expected)
	}
}

func TestJsonConfig(t *testing.T) {
	b, err := ioutil.ReadFile(`testdata/config.json`)
	if err != nil {
		t.Error(err)
	}
	var got Config
	expect := Config{
		FluentPort:         8888,
		FluentHost:         "localhost",
		FluentNetwork:      "tcp",
		FluentSocketPath:   "/var/tmp/fluent.sock",
		Timeout:            3000,
		WriteTimeout:       6000,
		BufferLimit:        10,
		RetryWait:          5,
		MaxRetry:           3,
		TagPrefix:          "fluent",
		Async:              false,
		ForceStopAsyncSend: false,
		MarshalAsJSON:      true,
	}

	err = json.Unmarshal(b, &got)
	if err != nil {
		t.Error(err)
	}

	if !reflect.DeepEqual(expect, got) {
		t.Errorf("got %v, except %v", got, expect)
	}
}

func TestPostWithTime(t *testing.T) {
	testcases := map[string]Config{
		"with Async": {
			Async:         true,
			MarshalAsJSON: true,
			TagPrefix:     "acme",
		},
		"without Async": {
			Async:         false,
			MarshalAsJSON: true,
			TagPrefix:     "acme",
		},
	}

	for tcname := range testcases {
		t.Run(tcname, func(t *testing.T) {
			tc := testcases[tcname]
			t.Parallel()

			d := newTestDialer()
			var f *Fluent
			defer func() {
				if f != nil {
					f.Close()
				}
			}()

			go func() {
				var err error
				if f, err = newWithDialer(tc, d); err != nil {
					t.Errorf("Unexpected error: %v", err)
				}

				_ = f.PostWithTime("tag_name", time.Unix(1482493046, 0), map[string]string{"foo": "bar"})
				_ = f.PostWithTime("tag_name", time.Unix(1482493050, 0), map[string]string{"fluentd": "is awesome"})
				_ = f.PostWithTime("tag_name", time.Unix(1634263200, 0),
					struct {Welcome string `msg:"welcome"`; cannot string}{"to use", "see me"})
			}()

			conn := d.waitForNextDialing(true, false)
			assertReceived(t,
				conn.waitForNextWrite(true, ""),
				"[\"acme.tag_name\",1482493046,{\"foo\":\"bar\"},{}]")

			assertReceived(t,
				conn.waitForNextWrite(true, ""),
				"[\"acme.tag_name\",1482493050,{\"fluentd\":\"is awesome\"},{}]")
			assertReceived(t,
				conn.waitForNextWrite(true, ""),
				"[\"acme.tag_name\",1634263200,{\"welcome\":\"to use\"},{}]")
		})
	}
}

func TestReconnectAndResendAfterTransientFailure(t *testing.T) {
	testcases := map[string]Config{
		"with Async": {
			Async:         true,
			MarshalAsJSON: true,
		},
		"without Async": {
			Async:         false,
			MarshalAsJSON: true,
		},
	}

	for tcname := range testcases {
		t.Run(tcname, func(t *testing.T) {
			tc := testcases[tcname]
			t.Parallel()

			d := newTestDialer()
			var f *Fluent
			defer func() {
				if f != nil {
					f.Close()
				}
			}()

			go func() {
				var err error
				if f, err = newWithDialer(tc, d); err != nil {
					t.Errorf("Unexpected error: %v", err)
				}

				_ = f.EncodeAndPostData("tag_name", time.Unix(1482493046, 0), map[string]string{"foo": "bar"})
				_ = f.EncodeAndPostData("tag_name", time.Unix(1482493050, 0), map[string]string{"fluentd": "is awesome"})
			}()

			// Accept the first connection dialing and write.
			conn := d.waitForNextDialing(true, false)
			assertReceived(t,
				conn.waitForNextWrite(true, ""),
				"[\"tag_name\",1482493046,{\"foo\":\"bar\"},{}]")

			// The next write will fail and the next connection dialing will be dropped
			// to test if the logger is reconnecting as expected.
			conn.waitForNextWrite(false, "")
			d.waitForNextDialing(false, false)

			// Next, we allow a new connection to be established and we allow the last message to be written.
			conn = d.waitForNextDialing(true, false)
			assertReceived(t,
				conn.waitForNextWrite(true, ""),
				"[\"tag_name\",1482493050,{\"fluentd\":\"is awesome\"},{}]")
		})
	}
}

func timeout(t *testing.T, duration time.Duration, fn func(), reason string) {
	done := make(chan struct{})
	go func() {
		fn()
		done <- struct{}{}
	}()

	select {
	case <-time.After(duration):
		t.Fatalf("time out after %s: %s", duration.String(), reason)
	case <-done:
		return
	}
}

func TestCloseOnFailingAsyncConnect(t *testing.T) {
	testcases := map[string]Config{
		"with ForceStopAsyncSend and with RequestAck": {
			Async:              true,
			ForceStopAsyncSend: true,
			RequestAck:         true,
		},
		"with ForceStopAsyncSend and without RequestAck": {
			Async:              true,
			ForceStopAsyncSend: true,
			RequestAck:         false,
		},
		"without ForceStopAsyncSend and with RequestAck": {
			Async:              true,
			ForceStopAsyncSend: false,
			RequestAck:         true,
		},
		"without ForceStopAsyncSend and without RequestAck": {
			Async:              true,
			ForceStopAsyncSend: false,
			RequestAck:         false,
		},
	}

	for tcname := range testcases {
		t.Run(tcname, func(t *testing.T) {
			tc := testcases[tcname]
			t.Parallel()

			d := newTestDialer()
			f, err := newWithDialer(tc, d)
			if err != nil {
				t.Errorf("Unexpected error: %v", err)
			}

			timeout(t, 1*time.Second, func() { f.Close() }, "failed to close the logger")
		})
	}
}

func ackRespMsgp(t *testing.T, ack string) string {
	msg := AckResp{ack}
	buf := &bytes.Buffer{}
	ackW := msgp.NewWriter(buf)
	if err := msg.EncodeMsg(ackW); err != nil {
		t.Fatalf("Unexpected error: %v", err)
	}
	ackW.Flush()
	return buf.String()
}

func TestNoPanicOnAsyncClose(t *testing.T) {
	testcases := []struct {
		name        string
		config      Config
		shouldError bool
	}{
		{
			name: "Channel closed before write",
			config: Config{
				Async: true,
			},
			shouldError: true,
		},
		{
			name: "Channel not closed at all",
			config: Config{
				Async: true,
			},
			shouldError: false,
		},
	}
	for _, testcase := range testcases {
		t.Run(testcase.name, func(t *testing.T) {
			t.Parallel()
			d := newTestDialer()
			f, err := newWithDialer(testcase.config, d)
			if err != nil {
				t.Errorf("Unexpected error: %v", err)
			}
			if testcase.shouldError {
				f.Close()
			}
			e := f.EncodeAndPostData("tag_name", time.Unix(1482493046, 0), map[string]string{"foo": "bar"})
			if testcase.shouldError {
				assert.Equal(t, fmt.Errorf("fluent#appendBuffer: Logger already closed"), e)
			} else {
				assert.Equal(t, nil, e)
			}
		})
	}
}

func TestNoPanicOnAsyncMultipleClose(t *testing.T) {
	config := Config{
		Async: true,
	}
	d := newTestDialer()
	f, err := newWithDialer(config, d)
	if err != nil {
		t.Errorf("Unexpected error: %v", err)
	}
	f.Close()
	f.Close()
}

func TestCloseOnFailingAsyncReconnect(t *testing.T) {
	testcases := map[string]Config{
		"with RequestAck": {
			Async:              true,
			ForceStopAsyncSend: true,
			RequestAck:         true,
		},
		"without RequestAck": {
			Async:              true,
			ForceStopAsyncSend: true,
			RequestAck:         false,
		},
	}

	for tcname := range testcases {
		t.Run(tcname, func(t *testing.T) {
			tc := testcases[tcname]
			t.Parallel()

			d := newTestDialer()
			f, err := newWithDialer(tc, d)
			if err != nil {
				t.Errorf("Unexpected error: %v", err)
			}

			// Send a first message successfully.
			_ = f.EncodeAndPostData("tag_name", time.Unix(1482493046, 0), map[string]string{"foo": "bar"})
			conn := d.waitForNextDialing(true, false)
			conn.waitForNextWrite(true, ackRespMsgp(t, "dgxdWAAAAAABAAAAAAAAAA=="))

			// Then try to send one during a transient connection failure.
			_ = f.EncodeAndPostData("tag_name", time.Unix(1482493046, 0), map[string]string{"bar": "baz"})
			conn.waitForNextWrite(false, "")

			// And add some more logs to the log buffer.
			_ = f.EncodeAndPostData("tag_name", time.Unix(1482493046, 0), map[string]string{"acme": "corporation"})

			// But close the logger before it got sent. This is expected to not block.
			timeout(t, 60*time.Second, func() { f.Close() }, "failed to close the logger")
		})
	}
}

func TestCloseWhileWaitingForAckResponse(t *testing.T) {
	t.Parallel()

	d := newTestDialer()
	f, err := newWithDialer(Config{
		Async:              true,
		RequestAck:         true,
		ForceStopAsyncSend: true,
	}, d)
	if err != nil {
		t.Errorf("Unexpected error: %v", err)
	}

	_ = f.EncodeAndPostData("tag_name", time.Unix(1482493046, 0), map[string]string{"foo": "bar"})
	conn := d.waitForNextDialing(true, true)
	conn.waitForNextWrite(true, ackRespMsgp(t, "dgxdWAAAAAABAAAAAAAAAA=="))

	// Test if the logger can really by closed while the client waits for a ack message.
	timeout(t, 30*time.Second, func() {
		f.Close()
	}, "failed to close the logger")
}

func TestSyncWriteAfterCloseFails(t *testing.T) {
	d := newTestDialer()

	go func() {
		f, err := newWithDialer(Config{Async: false}, d)
		if err != nil {
			t.Errorf("Unexpected error: %v", err)
		}

		err = f.PostWithTime("tag_name", time.Unix(1482493046, 0), map[string]string{"foo": "bar"})
		if err != nil {
			t.Errorf("Unexpected error: %v", err)
		}

		err = f.Close()
		if err != nil {
			t.Errorf("Unexpected error: %v", err)
		}

		// Now let's post some event after Fluent.Close().
		err = f.PostWithTime("tag_name", time.Unix(1482493050, 0), map[string]string{"foo": "buzz"})

		// The event submission must fail,
		assert.NotEqual(t, err, nil);

		// and also must keep Fluentd closed.
		assert.NotEqual(t, f.closed, false);
	}()

	conn := d.waitForNextDialing(true, false)
	conn.waitForNextWrite(true, "")
}

func Benchmark_PostWithShortMessage(b *testing.B) {
	b.StopTimer()
	d := newTestDialer()
	f, err := newWithDialer(Config{}, d)
	if err != nil {
		panic(err)
	}

	b.StartTimer()
	data := map[string]string{"message": "Hello World"}
	for i := 0; i < b.N; i++ {
		if err := f.Post("tag", data); err != nil {
			panic(err)
		}
	}
}

func Benchmark_PostWithShortMessageMarshalAsJSON(b *testing.B) {
	b.StopTimer()
	f, err := New(Config{MarshalAsJSON: true})
	if err != nil {
		panic(err)
	}

	b.StartTimer()
	data := map[string]string{"message": "Hello World"}
	for i := 0; i < b.N; i++ {
		if err := f.Post("tag", data); err != nil {
			panic(err)
		}
	}
}

func Benchmark_LogWithChunks(b *testing.B) {
	b.StopTimer()
	f, err := New(Config{})
	if err != nil {
		panic(err)
	}

	b.StartTimer()
	data := map[string]string{"msg": "sdfsdsdfdsfdsddddfsdfsdsdfdsfdsddddfsdfsdsdfdsfdsddddfsdfsdsdfdsfdsddddfsdfsdsdfdsfdsddddfsdfsdsdfdsfdsddddfsdfsdsdfdsfdsddddfsdfsdsdfdsfdsddddf"}
	for i := 0; i < b.N; i++ {
		if err := f.Post("tag", data); err != nil {
			panic(err)
		}
	}
}

func Benchmark_PostWithStruct(b *testing.B) {
	b.StopTimer()
	f, err := New(Config{})
	if err != nil {
		panic(err)
	}

	b.StartTimer()
	data := struct {
		Name string `msg:"msgnamename"`
	}{
		"john smith",
	}
	for i := 0; i < b.N; i++ {
		if err := f.Post("tag", data); err != nil {
			panic(err)
		}
	}
}

func Benchmark_PostWithStructTaggedAsCodec(b *testing.B) {
	b.StopTimer()
	f, err := New(Config{})
	if err != nil {
		panic(err)
	}

	b.StartTimer()
	data := struct {
		Name string `codec:"codecname"`
	}{
		"john smith",
	}
	for i := 0; i < b.N; i++ {
		if err := f.Post("tag", data); err != nil {
			panic(err)
		}
	}
}

func Benchmark_PostWithStructWithoutTag(b *testing.B) {
	b.StopTimer()
	f, err := New(Config{})
	if err != nil {
		panic(err)
	}

	b.StartTimer()
	data := struct {
		Name string
	}{
		"john smith",
	}
	for i := 0; i < b.N; i++ {
		if err := f.Post("tag", data); err != nil {
			panic(err)
		}
	}
}

func Benchmark_PostWithMapString(b *testing.B) {
	b.StopTimer()
	f, err := New(Config{})
	if err != nil {
		panic(err)
	}

	b.StartTimer()
	data := map[string]string{
		"foo": "bar",
	}
	for i := 0; i < b.N; i++ {
		if err := f.Post("tag", data); err != nil {
			panic(err)
		}
	}
}

func Benchmark_PostWithMsgpMarshaler(b *testing.B) {
	b.StopTimer()
	f, err := New(Config{})
	if err != nil {
		panic(err)
	}

	b.StartTimer()
	data := &TestMessage{Foo: "bar"}
	for i := 0; i < b.N; i++ {
		if err := f.Post("tag", data); err != nil {
			panic(err)
		}
	}
}

func Benchmark_PostWithMapSlice(b *testing.B) {
	b.StopTimer()
	f, err := New(Config{})
	if err != nil {
		panic(err)
	}

	b.StartTimer()
	data := map[string][]int{
		"foo": {1, 2, 3},
	}
	for i := 0; i < b.N; i++ {
		if err := f.Post("tag", data); err != nil {
			panic(err)
		}
	}
}

func Benchmark_PostWithMapStringAndTime(b *testing.B) {
	b.StopTimer()
	f, err := New(Config{})
	if err != nil {
		panic(err)
	}

	b.StartTimer()
	data := map[string]string{
		"foo": "bar",
	}
	tm := time.Now()
	for i := 0; i < b.N; i++ {
		if err := f.PostWithTime("tag", tm, data); err != nil {
			panic(err)
		}
	}
}