github.com/shoshinnikita/budget-manager@v0.7.1-0.20220131195411-8c46ff1c6778/tests/prepare.go (about)

     1  package tests
     2  
     3  import (
     4  	"os/exec"
     5  	"testing"
     6  	"time"
     7  
     8  	"github.com/stretchr/testify/require"
     9  
    10  	"github.com/ShoshinNikita/budget-manager/internal/app"
    11  	"github.com/ShoshinNikita/budget-manager/internal/logger"
    12  )
    13  
    14  func prepareApp(t *testing.T, cfg *app.Config, components ...StartComponentFn) {
    15  	t.Helper()
    16  
    17  	checkTestMode(t)
    18  	checkDocker(t)
    19  
    20  	require := require.New(t)
    21  
    22  	// Start components
    23  	for _, fn := range components {
    24  		component := fn(t, cfg)
    25  
    26  		t.Cleanup(func() {
    27  			t.Logf("stop component %q", component.GetName())
    28  
    29  			err := component.Cleanup()
    30  			require.NoError(err)
    31  		})
    32  	}
    33  
    34  	// Start app on a free port
    35  	serverPort := getFreePort(t)
    36  	t.Logf("use port %d for web server", serverPort)
    37  
    38  	cfg.Server.Port = serverPort
    39  
    40  	app := app.NewApp(*cfg, logger.New(cfg.Logger), "", "")
    41  	err := app.PrepareComponents()
    42  	require.NoError(err)
    43  
    44  	appErrCh := make(chan error, 1)
    45  	go func() {
    46  		appErrCh <- app.Run()
    47  	}()
    48  	t.Cleanup(func() {
    49  		t.Log("stop app")
    50  
    51  		app.Shutdown()
    52  
    53  		err := <-appErrCh
    54  		require.NoError(err)
    55  	})
    56  
    57  	// Make sure app is started
    58  	time.Sleep(100 * time.Millisecond)
    59  }
    60  
    61  // checkTestMode checks the test mode (whether the -short flag is set) and skips the test if needed
    62  func checkTestMode(t *testing.T) {
    63  	t.Helper()
    64  
    65  	if testing.Short() {
    66  		t.Skip("skip integration test")
    67  	}
    68  }
    69  
    70  func checkDocker(t *testing.T) {
    71  	t.Helper()
    72  
    73  	if _, err := exec.LookPath("docker"); err != nil {
    74  		t.Fatal("docker is required for integration tests")
    75  	}
    76  }