github.com/astaxie/beego@v1.12.3/logs/conn_test.go (about)

     1  // Copyright 2014 beego Author. All Rights Reserved.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //      http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package logs
    16  
    17  import (
    18  	"net"
    19  	"os"
    20  	"testing"
    21  )
    22  
    23  // ConnTCPListener takes a TCP listener and accepts n TCP connections
    24  // Returns connections using connChan
    25  func connTCPListener(t *testing.T, n int, ln net.Listener, connChan chan<- net.Conn) {
    26  
    27  	// Listen and accept n incoming connections
    28  	for i := 0; i < n; i++ {
    29  		conn, err := ln.Accept()
    30  		if err != nil {
    31  			t.Log("Error accepting connection: ", err.Error())
    32  			os.Exit(1)
    33  		}
    34  
    35  		// Send accepted connection to channel
    36  		connChan <- conn
    37  	}
    38  	ln.Close()
    39  	close(connChan)
    40  }
    41  
    42  func TestConn(t *testing.T) {
    43  	log := NewLogger(1000)
    44  	log.SetLogger("conn", `{"net":"tcp","addr":":7020"}`)
    45  	log.Informational("informational")
    46  }
    47  
    48  func TestReconnect(t *testing.T) {
    49  	// Setup connection listener
    50  	newConns := make(chan net.Conn)
    51  	connNum := 2
    52  	ln, err := net.Listen("tcp", ":6002")
    53  	if err != nil {
    54  		t.Log("Error listening:", err.Error())
    55  		os.Exit(1)
    56  	}
    57  	go connTCPListener(t, connNum, ln, newConns)
    58  
    59  	// Setup logger
    60  	log := NewLogger(1000)
    61  	log.SetPrefix("test")
    62  	log.SetLogger(AdapterConn, `{"net":"tcp","reconnect":true,"level":6,"addr":":6002"}`)
    63  	log.Informational("informational 1")
    64  
    65  	// Refuse first connection
    66  	first := <-newConns
    67  	first.Close()
    68  
    69  	// Send another log after conn closed
    70  	log.Informational("informational 2")
    71  
    72  	// Check if there was a second connection attempt
    73  	select {
    74  	case second := <-newConns:
    75  		second.Close()
    76  	default:
    77  		t.Error("Did not reconnect")
    78  	}
    79  }