github.com/117503445/github-action-example@v0.0.0-20230330151252-3d5ba77d6aad/test/api_test.go (about)

     1  package test
     2  
     3  import (
     4  	"encoding/json"
     5  	"fmt"
     6  	"io/ioutil"
     7  	"net/http"
     8  	"os"
     9  	"path/filepath"
    10  	"testing"
    11  	"time"
    12  
    13  	"github.com/117503445/github-action-example/src"
    14  	"github.com/stretchr/testify/assert"
    15  )
    16  
    17  // changeWorkDir change work dir to project root, in order to load config and other file
    18  func changeWorkDir() error {
    19  	const PROJECT_NAME = "github-action-example"
    20  
    21  	dir, err := os.Getwd()
    22  	if err != nil {
    23  		panic(err)
    24  	}
    25  
    26  	for {
    27  		if filepath.Base(dir) == PROJECT_NAME {
    28  			break
    29  		}
    30  		dir = filepath.Dir(dir)
    31  		if dir == "" {
    32  			return fmt.Errorf("Not Found '%v' in pwd", PROJECT_NAME)
    33  		}
    34  	}
    35  
    36  	err = os.Chdir(dir)
    37  	if err != nil {
    38  		panic(err)
    39  	}
    40  	return nil
    41  }
    42  
    43  func TestHello(t *testing.T) {
    44  	ast := assert.New(t)
    45  	changeWorkDir()
    46  	go src.Start()
    47  	time.Sleep(time.Millisecond * 100) // wait for server start
    48  
    49  	resp, err := http.Get("http://localhost:8080/")
    50  	ast.Nil(err)
    51  
    52  	respBytes, err := ioutil.ReadAll(resp.Body)
    53  	ast.Nil(err)
    54  
    55  	var respMap map[string]interface{}
    56  	err = json.Unmarshal(respBytes, &respMap)
    57  	ast.Nil(err)
    58  
    59  	ast.Equal(0, int(respMap["code"].(float64)))
    60  }