...

Source file src/github.com/cert-manager/issuer-lib/internal/tests/testcontext/context.go

Documentation: github.com/cert-manager/issuer-lib/internal/tests/testcontext

     1  /*
     2  Copyright 2023 The cert-manager Authors.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8      http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package testcontext
    18  
    19  import (
    20  	"context"
    21  	"os"
    22  	"os/signal"
    23  	"testing"
    24  	"time"
    25  )
    26  
    27  func ForTest(t *testing.T) context.Context {
    28  	t.Helper()
    29  
    30  	ctx, cancel := context.WithCancel(context.Background())
    31  	t.Cleanup(cancel)
    32  
    33  	shuttingDown := make(chan struct{})
    34  	finished := make(chan struct{})
    35  	t.Cleanup(func() {
    36  		close(shuttingDown)
    37  		<-finished
    38  	})
    39  
    40  	c := make(chan os.Signal, 2)
    41  	signal.Notify(c, shutdownSignals...)
    42  	go func() {
    43  		defer close(finished)
    44  
    45  		select {
    46  		case <-c:
    47  			cancel()
    48  		case <-shuttingDown:
    49  			return
    50  		}
    51  
    52  		select {
    53  		case <-c:
    54  			os.Exit(1) // second signal. Exit directly.
    55  		case <-shuttingDown:
    56  			return
    57  		}
    58  	}()
    59  
    60  	if deadline, ok := t.Deadline(); ok {
    61  		var cancel context.CancelFunc
    62  		// cancel context before panic ( give 5 seconds to shutdown )
    63  		ctx, cancel = context.WithDeadline(ctx, deadline.Add(-5*time.Second))
    64  		t.Cleanup(cancel)
    65  	}
    66  
    67  	return ctx
    68  }
    69  

View as plain text