github.com/altstory/go-runner@v1.1.8/runner_test.go (about)

     1  package runner
     2  
     3  import (
     4  	"context"
     5  	"errors"
     6  	"os"
     7  	"path"
     8  	"testing"
     9  
    10  	"github.com/altstory/go-log"
    11  	"github.com/huandu/go-assert"
    12  )
    13  
    14  type testFoo struct {
    15  	Bar int `config:"bar"`
    16  }
    17  
    18  type testConfig struct {
    19  	Log log.Config `config:"log"`
    20  	Foo testFoo    `config:"foo"`
    21  }
    22  
    23  func TestRun(t *testing.T) {
    24  	a := assert.New(t)
    25  	cases := []struct {
    26  		Handler  Handler
    27  		Cwd      string
    28  		ExitCode int
    29  	}{
    30  		{
    31  			func() {},
    32  			"./internal/testdata",
    33  			ExitCodeInvalidHandler,
    34  		},
    35  		{
    36  			func(ctx context.Context, c *testConfig) {},
    37  			"",
    38  			ExitCodeInvalidConfig,
    39  		},
    40  		{
    41  			func(ctx context.Context, c *testConfig) { log.Fatalf(ctx, "intended") },
    42  			"./internal/testdata",
    43  			ExitCodeHandlerError,
    44  		},
    45  		{
    46  			func(ctx context.Context, c *testConfig) error { return errors.New("intended") },
    47  			"./internal/testdata",
    48  			ExitCodeHandlerError,
    49  		},
    50  		{
    51  			func(ctx context.Context, c *testConfig) {
    52  				a.Equal(c, &testConfig{
    53  					Log: log.Config{
    54  						LogPath:  "./log/test.log",
    55  						LogLevel: "debug",
    56  					},
    57  					Foo: testFoo{
    58  						Bar: 123,
    59  					},
    60  				})
    61  			},
    62  			"./internal/testdata",
    63  			ExitCodeOK,
    64  		},
    65  	}
    66  
    67  	cwd, err := os.Getwd()
    68  	a.NilError(err)
    69  	defer os.Chdir(cwd)
    70  	defer func() {
    71  		clientHandlers = nil
    72  	}()
    73  
    74  	for _, c := range cases {
    75  		if c.Cwd != "" {
    76  			a.NilError(os.Chdir(path.Join(cwd, c.Cwd)))
    77  		} else {
    78  			a.NilError(os.Chdir(cwd))
    79  		}
    80  
    81  		clientHandlers = nil
    82  		AddClient("", c.Handler)
    83  		a.Equal(run(), c.ExitCode)
    84  	}
    85  }
    86  
    87  func TestRunWithExtConfig(t *testing.T) {
    88  	a := assert.New(t)
    89  
    90  	cwd, err := os.Getwd()
    91  	a.NilError(err)
    92  	defer os.Chdir(cwd)
    93  	defer func() {
    94  		clientHandlers = nil
    95  	}()
    96  	a.NilError(os.Chdir("./internal/testdata"))
    97  
    98  	a.NilError(os.Setenv(envRunnerExtConfig, "./conf/service-ext.conf"))
    99  	AddClient("", func(ctx context.Context, c *testConfig) {
   100  		a.Equal(c, &testConfig{
   101  			Log: log.Config{
   102  				LogPath:  "./log/test.log",
   103  				LogLevel: "info",
   104  			},
   105  			Foo: testFoo{
   106  				Bar: 0,
   107  			},
   108  		})
   109  	})
   110  	a.Equal(run(), ExitCodeOK)
   111  }