trpc.group/trpc-go/trpc-cmdline@v1.0.9/plugin/swagger_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  	"errors"
    14  	"os"
    15  	"path/filepath"
    16  	"testing"
    17  
    18  	"github.com/agiledragon/gomonkey"
    19  	"github.com/stretchr/testify/require"
    20  
    21  	"trpc.group/trpc-go/trpc-cmdline/descriptor"
    22  	"trpc.group/trpc-go/trpc-cmdline/params"
    23  	"trpc.group/trpc-go/trpc-cmdline/util/apidocs/swagger"
    24  )
    25  
    26  func TestPlugin_Swagger(t *testing.T) {
    27  	u := &Swagger{}
    28  	require.Equal(t, "swagger", u.Name())
    29  
    30  	opt := params.Option{
    31  		SwaggerOn: true,
    32  	}
    33  
    34  	// swaggeron=false, do not process.
    35  	t.Run("!swagger", func(t *testing.T) {
    36  		opt := opt
    37  		opt.SwaggerOn = false
    38  		require.False(t, u.Check(nil, &opt))
    39  	})
    40  
    41  	// swaggeron=true, process normally.
    42  	t.Run("swagger", func(t *testing.T) {
    43  		//os.chdir
    44  		pbf, fd, err := parseSampleProtofile()
    45  		if err != nil {
    46  			panic(err)
    47  		}
    48  		wd, _ := os.Getwd()
    49  		defer os.Chdir(wd)
    50  		os.Chdir(filepath.Dir(pbf))
    51  
    52  		opt := opt
    53  		opt.Protodirs = []string{filepath.Dir(pbf)}
    54  		opt.Protofile = pbf
    55  		opt.SwaggerOut = filepath.Join(os.TempDir(), "xxxxxx.json")
    56  		defer os.RemoveAll(opt.SwaggerOut)
    57  
    58  		require.True(t, u.Check(nil, &opt))
    59  		require.Nil(t, u.Run(fd, &opt))
    60  	})
    61  
    62  	t.Run("swagger fail", func(t *testing.T) {
    63  		p := gomonkey.ApplyFunc(swagger.GenSwagger, func(*descriptor.FileDescriptor, *params.Option) error {
    64  			return errors.New("gen error")
    65  		})
    66  		defer p.Reset()
    67  
    68  		opt := opt
    69  		require.True(t, u.Check(nil, &opt))
    70  		require.NotNil(t, u.Run(nil, &opt))
    71  	})
    72  }