trpc.group/trpc-go/trpc-cmdline@v1.0.9/plugin/gomock_test.go (about)

     1  // Tencent is pleased to support the open source community by making tRPC available.
     2  //
     3  // Copyright (C) 2023 THL A29 Limited, a Tencent company.
     4  // All rights reserved.
     5  //
     6  // If you have downloaded a copy of the tRPC source code from Tencent,
     7  // please note that tRPC source code is licensed under the  Apache 2.0 License,
     8  // A copy of the Apache 2.0 License is included in this file.
     9  
    10  package plugin
    11  
    12  import (
    13  	"fmt"
    14  	"os"
    15  	"os/exec"
    16  	"path/filepath"
    17  	"testing"
    18  
    19  	"github.com/agiledragon/gomonkey"
    20  	"github.com/stretchr/testify/require"
    21  
    22  	"trpc.group/trpc-go/trpc-cmdline/descriptor"
    23  	"trpc.group/trpc-go/trpc-cmdline/params"
    24  )
    25  
    26  func TestPlugin_Mock(t *testing.T) {
    27  	if err := setup(); err != nil {
    28  		panic(err)
    29  	}
    30  
    31  	u := &GoMock{}
    32  	opt := params.Option{
    33  		Language:  "go",
    34  		OutputDir: filepath.Join(os.TempDir(), "trpc"),
    35  	}
    36  	os.MkdirAll(opt.OutputDir, os.ModePerm)
    37  	defer os.RemoveAll(opt.OutputDir)
    38  
    39  	t.Run("name", func(t *testing.T) {
    40  		require.Equal(t, "mockgen", u.Name())
    41  	})
    42  
    43  	// Non golang are not processed.
    44  	t.Run("lang !go", func(t *testing.T) {
    45  		u := &GoMock{}
    46  		opt := opt
    47  		opt.Language = "!go"
    48  		require.False(t, u.Check(nil, &opt))
    49  	})
    50  
    51  	// It is a Go language, but if the flag --mock=false is specified, it will not be processed.
    52  	t.Run("lang go && !mockgen", func(t *testing.T) {
    53  		u := &GoMock{}
    54  		opt := opt
    55  		require.False(t, u.Check(nil, &opt))
    56  	})
    57  
    58  	// If there is no service defined, it will not be processed even if it is a Go language.
    59  	t.Run("lang go && mockgen && service empty", func(t *testing.T) {
    60  		u := &GoMock{}
    61  		opt := opt
    62  		fd := &descriptor.FileDescriptor{
    63  			Services: nil,
    64  		}
    65  		require.False(t, u.Check(fd, &opt))
    66  	})
    67  
    68  	t.Run("go && mockgen && !rpconly", func(t *testing.T) {
    69  		u := &GoMock{}
    70  		opt := opt
    71  		opt.Mockgen = true
    72  		opt.RPCOnly = false
    73  		require.False(t, u.Check(nil, &opt))
    74  	})
    75  
    76  	t.Run("go && mockgen && !rpconly && mockgen not installed", func(t *testing.T) {
    77  		p := gomonkey.ApplyFunc(exec.LookPath, func(file string) (string, error) {
    78  			return "", fmt.Errorf("not exist mockgen")
    79  		})
    80  		defer p.Reset()
    81  
    82  		u := &GoMock{}
    83  		opt := opt
    84  		opt.Mockgen = true
    85  		opt.RPCOnly = false
    86  		require.False(t, u.Check(nil, &opt))
    87  	})
    88  }