github.com/speedoops/go-gqlrest-demo@v0.0.0-20220710122636-5c6460aeab4f/graph/utils/i18n/i18n_test.go (about)

     1  package i18n
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"os"
     7  	"path"
     8  	"path/filepath"
     9  	"runtime"
    10  	"testing"
    11  
    12  	ki18n "github.com/kataras/i18n"
    13  	"github.com/stretchr/testify/require"
    14  )
    15  
    16  func FindPathForFile(fileName string) (string, error) {
    17  	_, progName, _, _ := runtime.Caller(0)
    18  	lastDir := path.Dir(progName)
    19  	for {
    20  		tryPath := filepath.Join(lastDir, fileName)
    21  		if fi, err := os.Stat(tryPath); err == nil {
    22  			if mode := fi.Mode(); mode.IsRegular() {
    23  				return lastDir, nil
    24  			}
    25  		}
    26  
    27  		newDir := filepath.Dir(lastDir)
    28  		if newDir == "/" || newDir == lastDir {
    29  			return "", fmt.Errorf("file '%s' not found", fileName)
    30  		}
    31  		lastDir = newDir
    32  	}
    33  }
    34  
    35  // https://pkg.go.dev/testing
    36  func TestMain(m *testing.M) {
    37  	// Write code here to run before tests
    38  	root, err := FindPathForFile("main.go")
    39  	if err != nil {
    40  		panic(err)
    41  	}
    42  
    43  	err = os.Chdir(root)
    44  	if err != nil {
    45  		panic(err)
    46  	}
    47  
    48  	instance, err = ki18n.New(ki18n.Glob("./config/locales/**/*", ki18n.LoaderConfig{}), "en-US", "zh-CN")
    49  	if err != nil {
    50  		panic(err)
    51  	}
    52  
    53  	instance.SetDefault("zh-CN")
    54  
    55  	// Run tests
    56  	exitVal := m.Run()
    57  
    58  	// Write code here to run after tests
    59  
    60  	// Exit with exit value from tests
    61  	os.Exit(exitVal)
    62  }
    63  
    64  func TestHelloI18N(t *testing.T) {
    65  	if testing.Short() {
    66  		t.Skip("skipping testing in short mode")
    67  	}
    68  
    69  	ctx := context.Background()
    70  
    71  	ctx = context.WithValue(ctx, LangKey, "en-US")
    72  	en := T(ctx, "hello")
    73  	require.Equal(t, "Aloha", en)
    74  
    75  	ctx = context.WithValue(ctx, LangKey, "zh-CN")
    76  	cn := T(ctx, "hello")
    77  	require.Equal(t, "你好呀", cn)
    78  }