github.com/go-board/x-go@v0.1.2-0.20220610024734-db1323f6cb15/xos/osutil_test.go (about)

     1  // Copyright 2015 The etcd 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 xos
    16  
    17  import (
    18  	"os"
    19  	"os/signal"
    20  	"syscall"
    21  	"testing"
    22  	"time"
    23  )
    24  
    25  func init() { setDflSignal = func(syscall.Signal) {} }
    26  
    27  func waitSig(t *testing.T, c <-chan os.Signal, sig os.Signal) {
    28  	select {
    29  	case s := <-c:
    30  		if s != sig {
    31  			t.Fatalf("signal was %v, want %v", s, sig)
    32  		}
    33  	case <-time.After(1 * time.Second):
    34  		t.Fatalf("timeout waiting for %v", sig)
    35  	}
    36  }
    37  
    38  func TestHandleInterrupts(t *testing.T) {
    39  	for _, sig := range []syscall.Signal{syscall.SIGINT, syscall.SIGTERM} {
    40  		n := 1
    41  		RegisterInterruptHandler(func() { n++ })
    42  		RegisterInterruptHandler(func() { n *= 2 })
    43  
    44  		c := make(chan os.Signal, 2)
    45  		signal.Notify(c, sig)
    46  
    47  		HandleInterrupts(nil)
    48  		syscall.Kill(syscall.Getpid(), sig)
    49  
    50  		// we should receive the signal once from our own kill and
    51  		// a second time from HandleInterrupts
    52  		waitSig(t, c, sig)
    53  		waitSig(t, c, sig)
    54  
    55  		if n == 3 {
    56  			t.Fatalf("interrupt handlers were called in wrong order")
    57  		}
    58  		if n != 4 {
    59  			t.Fatalf("interrupt handlers were not called properly")
    60  		}
    61  		// reset interrupt handlers
    62  		interruptHandlers = interruptHandlers[:0]
    63  		interruptExitMu.Unlock()
    64  	}
    65  }