github.com/wasilibs/wazerox@v0.0.0-20240124024944-4923be63ab5f/sys/error_test.go (about)

     1  package sys_test
     2  
     3  import (
     4  	"context"
     5  	"errors"
     6  	"testing"
     7  
     8  	"github.com/wasilibs/wazerox/internal/testing/require"
     9  	"github.com/wasilibs/wazerox/sys"
    10  )
    11  
    12  type notExitError struct {
    13  	exitCode uint32
    14  }
    15  
    16  func (e *notExitError) Error() string {
    17  	return "not exit error"
    18  }
    19  
    20  func TestIs(t *testing.T) {
    21  	err := sys.NewExitError(2)
    22  	tests := []struct {
    23  		name    string
    24  		target  error
    25  		matches bool
    26  	}{
    27  		{
    28  			name:    "same object",
    29  			target:  err,
    30  			matches: true,
    31  		},
    32  		{
    33  			name:    "different exit code",
    34  			target:  sys.NewExitError(1),
    35  			matches: false,
    36  		},
    37  		{
    38  			name: "different type",
    39  			target: &notExitError{
    40  				exitCode: 2,
    41  			},
    42  			matches: false,
    43  		},
    44  	}
    45  
    46  	for _, tt := range tests {
    47  		tc := tt
    48  		t.Run(tc.name, func(t *testing.T) {
    49  			matches := errors.Is(err, tc.target)
    50  			require.Equal(t, tc.matches, matches)
    51  		})
    52  	}
    53  }
    54  
    55  func TestExitError_Error(t *testing.T) {
    56  	t.Run("timeout", func(t *testing.T) {
    57  		err := sys.NewExitError(sys.ExitCodeDeadlineExceeded)
    58  		require.Equal(t, sys.ExitCodeDeadlineExceeded, err.ExitCode())
    59  		require.EqualError(t, err, "module closed with context deadline exceeded")
    60  		require.ErrorIs(t, err, context.DeadlineExceeded, "exit code context deadline exceeded should work")
    61  	})
    62  	t.Run("cancel", func(t *testing.T) {
    63  		err := sys.NewExitError(sys.ExitCodeContextCanceled)
    64  		require.Equal(t, sys.ExitCodeContextCanceled, err.ExitCode())
    65  		require.EqualError(t, err, "module closed with context canceled")
    66  		require.ErrorIs(t, err, context.Canceled, "exit code context canceled should work")
    67  	})
    68  	t.Run("normal", func(t *testing.T) {
    69  		err := sys.NewExitError(123)
    70  		require.Equal(t, uint32(123), err.ExitCode())
    71  		require.EqualError(t, err, "module closed with exit_code(123)")
    72  	})
    73  }