istio.io/istio@v0.0.0-20240520182934-d79c90f27776/pkg/ctrlz/ctrlz_test.go (about)

     1  // Copyright Istio Authors
     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 ctrlz
    16  
    17  import (
    18  	"fmt"
    19  	"net/http"
    20  	"os"
    21  	"os/signal"
    22  	"syscall"
    23  	"testing"
    24  	"time"
    25  )
    26  
    27  func TestStartStopEnabled(t *testing.T) {
    28  	server := startAndWaitForServer(t)
    29  	done := make(chan struct{}, 1)
    30  	go func() {
    31  		server.Close()
    32  		done <- struct{}{}
    33  	}()
    34  	select {
    35  	case <-done:
    36  	case <-time.After(5 * time.Second):
    37  		t.Fatal("Timed out waiting for listeningTestProbe to be called")
    38  	}
    39  }
    40  
    41  func TestSignals(t *testing.T) {
    42  	c := make(chan os.Signal, 1)
    43  	signal.Notify(c, syscall.SIGUSR1)
    44  	server := startAndWaitForServer(t)
    45  	defer server.Close()
    46  	reloadURL := fmt.Sprintf("http://%v/signalj/SIGUSR1", server.Address())
    47  	resp, err := http.DefaultClient.Post(reloadURL, "text/plain", nil)
    48  	if err != nil {
    49  		t.Fatalf("Run: %v", err)
    50  	}
    51  	if resp.StatusCode != http.StatusAccepted {
    52  		t.Fatalf("Got unexpected status code: %v", resp.StatusCode)
    53  	}
    54  	select {
    55  	case <-c:
    56  	case <-time.After(5 * time.Second):
    57  		t.Fatal("Timed out waiting for SIGUSR1")
    58  	}
    59  }
    60  
    61  func startAndWaitForServer(t *testing.T) *Server {
    62  	ready := make(chan struct{}, 1)
    63  	listeningTestProbe = func() {
    64  		ready <- struct{}{}
    65  	}
    66  	defer func() { listeningTestProbe = nil }()
    67  
    68  	// Start and wait for server
    69  	o := DefaultOptions()
    70  	o.Port = 0
    71  	s, err := Run(o, nil)
    72  	if err != nil {
    73  		t.Fatalf("Failed to start server: %v", err)
    74  	}
    75  	select {
    76  	case <-ready:
    77  	case <-time.After(5 * time.Second):
    78  		t.Fatal("Timed out waiting for server start")
    79  	}
    80  	return s
    81  }