get.pme.sh/pnats@v0.0.0-20240304004023-26bb5a137ed0/server/ping_test.go (about)

     1  // Copyright 2015-2019 The NATS Authors
     2  // Licensed under the Apache License, Version 2.0 (the "License");
     3  // you may not use this file except in compliance with the License.
     4  // You may obtain a copy of the License at
     5  //
     6  // http://www.apache.org/licenses/LICENSE-2.0
     7  //
     8  // Unless required by applicable law or agreed to in writing, software
     9  // distributed under the License is distributed on an "AS IS" BASIS,
    10  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    11  // See the License for the specific language governing permissions and
    12  // limitations under the License.
    13  
    14  package server
    15  
    16  import (
    17  	"bufio"
    18  	"fmt"
    19  	"net"
    20  	"testing"
    21  	"time"
    22  )
    23  
    24  const PING_CLIENT_PORT = 11228
    25  
    26  var DefaultPingOptions = Options{
    27  	Host:         "127.0.0.1",
    28  	Port:         PING_CLIENT_PORT,
    29  	NoLog:        true,
    30  	NoSigs:       true,
    31  	PingInterval: 50 * time.Millisecond,
    32  }
    33  
    34  func TestPing(t *testing.T) {
    35  	o := DefaultPingOptions
    36  	o.DisableShortFirstPing = true
    37  	s := RunServer(&o)
    38  	defer s.Shutdown()
    39  
    40  	c, err := net.Dial("tcp", fmt.Sprintf("127.0.0.1:%d", PING_CLIENT_PORT))
    41  	if err != nil {
    42  		t.Fatalf("Error connecting: %v", err)
    43  	}
    44  	defer c.Close()
    45  	br := bufio.NewReader(c)
    46  	// Wait for INFO
    47  	br.ReadLine()
    48  	// Send CONNECT
    49  	c.Write([]byte("CONNECT {\"verbose\":false}\r\nPING\r\n"))
    50  	// Wait for first PONG
    51  	br.ReadLine()
    52  	// Wait for PING
    53  	start := time.Now()
    54  	for i := 0; i < 3; i++ {
    55  		l, _, err := br.ReadLine()
    56  		if err != nil {
    57  			t.Fatalf("Error: %v", err)
    58  		}
    59  		if string(l) != "PING" {
    60  			t.Fatalf("Expected PING, got %q", l)
    61  		}
    62  		if dur := time.Since(start); dur < 25*time.Millisecond || dur > 75*time.Millisecond {
    63  			t.Fatalf("Pings duration off: %v", dur)
    64  		}
    65  		c.Write([]byte(pongProto))
    66  		start = time.Now()
    67  	}
    68  }