knative.dev/pkg@v0.0.0-20260602142205-ac97e43f6622/test/cleanup_test.go (about)

     1  /*
     2  Copyright 2021 The Knative 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 test
    18  
    19  import (
    20  	"bytes"
    21  	"context"
    22  	"errors"
    23  	"fmt"
    24  	"os"
    25  	"os/exec"
    26  	"strings"
    27  	"testing"
    28  	"time"
    29  
    30  	"k8s.io/apimachinery/pkg/util/wait"
    31  )
    32  
    33  func TestCleanupOnInterrupt(t *testing.T) {
    34  	if os.Getenv("CLEANUP") == "1" {
    35  		OnInterrupt(func() { fmt.Println("cleanup 1") })
    36  		OnInterrupt(func() { fmt.Println("cleanup 2") })
    37  		OnInterrupt(func() { fmt.Println("cleanup 3") })
    38  
    39  		// This signals to the parent test that it should proceed
    40  		os.Remove(os.Getenv("READY_FILE"))
    41  
    42  		time.Sleep(5 * time.Second)
    43  		return
    44  	}
    45  
    46  	readyFile, err := os.CreateTemp("", "")
    47  	if err != nil {
    48  		t.Fatalf("failed to setup tests")
    49  	}
    50  	readyFile.Close()
    51  
    52  	cmd := exec.Command(os.Args[0], "-test.run=TestCleanupOnInterrupt", "-test.v=true")
    53  	cmd.Env = append(os.Environ(), "CLEANUP=1", "READY_FILE="+readyFile.Name())
    54  
    55  	var output bytes.Buffer
    56  	cmd.Stdout = &output
    57  	cmd.Stderr = &output
    58  
    59  	if err := cmd.Start(); err != nil {
    60  		t.Fatal("Running test failed", err)
    61  	}
    62  
    63  	p, err := os.FindProcess(cmd.Process.Pid)
    64  	if err != nil {
    65  		t.Fatal("Failed to find process", err)
    66  	}
    67  
    68  	// poll until the ready file is gone - indicating the subtest has been set up
    69  	// with the cleanup functions
    70  	err = wait.PollUntilContextTimeout(context.Background(), 100*time.Millisecond, 2*time.Second, true, func(ctx context.Context) (bool, error) {
    71  		_, err := os.Stat(readyFile.Name())
    72  		if os.IsNotExist(err) {
    73  			return true, nil
    74  		}
    75  		return false, err
    76  	})
    77  	if err != nil {
    78  		t.Fatal("Test subprocess never became ready", err)
    79  	}
    80  
    81  	if err := p.Signal(os.Interrupt); err != nil {
    82  		t.Fatal("Failed to interrupt", err)
    83  	}
    84  
    85  	err = cmd.Wait()
    86  	var exitErr *exec.ExitError
    87  	if ok := errors.As(err, &exitErr); err != nil && !ok {
    88  		t.Fatal("Running test had abnormal exit", err)
    89  	}
    90  
    91  	testOutput := output.String()
    92  
    93  	idx1 := strings.Index(testOutput, "cleanup 1")
    94  	idx2 := strings.Index(testOutput, "cleanup 2")
    95  	idx3 := strings.Index(testOutput, "cleanup 3")
    96  
    97  	// Order is first in first out (3, 2, 1)
    98  	if idx3 > idx2 || idx2 > idx1 || idx1 == -1 {
    99  		t.Errorf("Cleanup functions were not invoked in the proper order")
   100  	}
   101  }