Best K6 code snippet using common.MethodName
terminal.go
Source:terminal.go
1package cli2import (3 "bufio"4 "context"5 "crypto/tls"6 "errors"7 "fmt"8 "net/http"9 "os"10 "reflect"11 "strconv"12 "strings"13 figure "github.com/common-nighthawk/go-figure"14 "github.com/SummerCash/go-summercash/common"15 "github.com/SummerCash/go-summercash/config"16 accountsProto "github.com/SummerCash/go-summercash/intrnl/rpc/proto/accounts"17 chainProto "github.com/SummerCash/go-summercash/intrnl/rpc/proto/chain"18 commonProto "github.com/SummerCash/go-summercash/intrnl/rpc/proto/common"19 configProto "github.com/SummerCash/go-summercash/intrnl/rpc/proto/config"20 coordinationChainProto "github.com/SummerCash/go-summercash/intrnl/rpc/proto/coordinationchain"21 cryptoProto "github.com/SummerCash/go-summercash/intrnl/rpc/proto/crypto"22 p2pProto "github.com/SummerCash/go-summercash/intrnl/rpc/proto/p2p"23 transactionProto "github.com/SummerCash/go-summercash/intrnl/rpc/proto/transaction"24 upnpProto "github.com/SummerCash/go-summercash/intrnl/rpc/proto/upnp"25)26var (27 // ErrInvalidParams - error definition describing invalid input parameters28 ErrInvalidParams = errors.New("invalid parameters")29 // workingNetwork is the working network.30 workingNetwork = "main_net"31)32// NewTerminal - attempts to start handler for term commands33func NewTerminal(rpcPort uint, rpcAddress string, network string) {34 workingNetwork = network // Set network35 reader := bufio.NewScanner(os.Stdin) // Init reader36 transport := &http.Transport{ // Init transport37 TLSClientConfig: &tls.Config{InsecureSkipVerify: true},38 }39 logHeader() // Log header40 for {41 fmt.Print("\n> ") // Print prompt42 reader.Scan() // Scan43 input := reader.Text() // Fetch string input44 input = strings.TrimSuffix(input, "\n") // Trim newline45 receiver, methodname, params, err := common.ParseStringMethodCall(input) // Attempt to parse as method call46 if err != nil { // Check for errors47 fmt.Println(err.Error()) // Log found error48 continue // Continue49 }50 handleCommand(receiver, methodname, params, rpcPort, rpcAddress, transport) // Handle command51 }52}53// handleCommand - run handler for given receiver54func handleCommand(receiver string, methodname string, params []string, rpcPort uint, rpcAddress string, transport *http.Transport) {55 cryptoClient := cryptoProto.NewCryptoProtobufClient("https://"+rpcAddress+":"+strconv.Itoa(int(rpcPort)), &http.Client{Transport: transport}) // Init crypto client56 upnpClient := upnpProto.NewUpnpProtobufClient("https://"+rpcAddress+":"+strconv.Itoa(int(rpcPort)), &http.Client{Transport: transport}) // Init upnp client57 accountsClient := accountsProto.NewAccountsProtobufClient("https://"+rpcAddress+":"+strconv.Itoa(int(rpcPort)), &http.Client{Transport: transport}) // Init accounts client58 configClient := configProto.NewConfigProtobufClient("https://"+rpcAddress+":"+strconv.Itoa(int(rpcPort)), &http.Client{Transport: transport}) // Init config client59 transactionClient := transactionProto.NewTransactionProtobufClient("https://"+rpcAddress+":"+strconv.Itoa(int(rpcPort)), &http.Client{Transport: transport}) // Init transaction client60 chainClient := chainProto.NewChainProtobufClient("https://"+rpcAddress+":"+strconv.Itoa(int(rpcPort)), &http.Client{Transport: transport}) // Init chain client61 coordinationChainClient := coordinationChainProto.NewCoordinationChainProtobufClient("https://"+rpcAddress+":"+strconv.Itoa(int(rpcPort)), &http.Client{Transport: transport}) // Init coordinationChain client62 commonClient := commonProto.NewCommonProtobufClient("https://"+rpcAddress+":"+strconv.Itoa(int(rpcPort)), &http.Client{Transport: transport}) // Init common client63 p2pClient := p2pProto.NewP2PProtobufClient("https://"+rpcAddress+":"+strconv.Itoa(int(rpcPort)), &http.Client{Transport: transport}) // Init p2p client64 switch receiver {65 case "crypto":66 err := handleCrypto(&cryptoClient, methodname, params) // Handle crypto67 if err != nil { // Check for errors68 fmt.Println("\n" + err.Error()) // Log found error69 }70 case "upnp":71 err := handleUpnp(&upnpClient, methodname, params) // Handle upnp72 if err != nil { // Check for errors73 fmt.Println("\n" + err.Error()) // Log found error74 }75 case "accounts":76 err := handleAccounts(&accountsClient, methodname, params) // Handle accounts77 if err != nil { // Check for errors78 fmt.Println("\n" + err.Error()) // Log found error79 }80 case "config":81 err := handleConfig(&configClient, methodname, params) // Handle config82 if err != nil { // Check for errors83 fmt.Println("\n" + err.Error()) // Log found error84 }85 case "transaction":86 err := handleTransaction(&transactionClient, methodname, params) // Handle tx87 if err != nil { // Check for errors88 fmt.Println("\n" + err.Error()) // Log found error89 }90 case "chain":91 err := handleChain(&chainClient, methodname, params) // Handle chain92 if err != nil { // Check for errors93 fmt.Println("\n" + err.Error()) // Log found error94 }95 case "coordinationChain":96 err := handleCoordinationChain(&coordinationChainClient, methodname, params) // Handle coordination chain97 if err != nil { // Check for errors98 fmt.Println("\n" + err.Error()) // Log found error99 }100 case "common":101 err := handleCommon(&commonClient, methodname, params) // Handle common102 if err != nil { // Check for errors103 fmt.Println("\n" + err.Error()) // Log found error104 }105 case "p2p":106 err := handleP2P(&p2pClient, methodname, params) // Handle p2p107 if err != nil { // Check for errors108 fmt.Println("\n" + err.Error()) // Log found error109 }110 default:111 fmt.Println("\n" + "unrecognized namespace " + `"` + receiver + `"` + ", available namespaces: crypto, upnp, accounts, config, transaction, chain, coordinationChain, common") // Log invalid namespace112 }113}114// handleCrypto - handle crypto receiver115func handleCrypto(cryptoClient *cryptoProto.Crypto, methodname string, params []string) error {116 reflectParams := []reflect.Value{} // Init buffer117 reflectParams = append(reflectParams, reflect.ValueOf(context.Background())) // Append request context118 switch methodname { // Handle different methods119 case "Sha3", "Sha3String", "Sha3d", "Sha3dString":120 if len(params) != 1 { // Check for invalid params121 return ErrInvalidParams // Return error122 } else if methodname == "Sha3d" || methodname == "Sha3dString" {123 methodname = methodname[:4] + "D" + methodname[4+1:] // Correct namespace124 }125 reflectParams = append(reflectParams, reflect.ValueOf(&cryptoProto.GeneralRequest{Input: []byte(params[0])})) // Append params126 case "Sha3n", "Sha3nString":127 if len(params) != 2 { // Check for invalid params128 return ErrInvalidParams // return error129 }130 methodname = methodname[:4] + "N" + methodname[4+1:] // Correct namespace131 intVal, _ := strconv.Atoi(params[1]) // Convert to int132 reflectParams = append(reflectParams, reflect.ValueOf(&cryptoProto.GeneralRequest{Input: []byte(params[0]), N: uint32(intVal)})) // Append params133 default:134 return errors.New("illegal method: " + methodname + ", available methods: Sha3(), Sha3String(), Sha3d(), Sha3dString(), Sha3n(), Sha3nString()") // Return error135 }136 result := reflect.ValueOf(*cryptoClient).MethodByName(methodname).Call(reflectParams) // Call method137 response := result[0].Interface().(*cryptoProto.GeneralResponse) // Get response138 if result[1].Interface() != nil { // Check for errors139 return result[1].Interface().(error) // Return error140 }141 fmt.Println(response.Message) // Log response142 return nil // No error occurred, return nil143}144// handleUpnp - handle upnp receiver145func handleUpnp(upnpClient *upnpProto.Upnp, methodname string, params []string) error {146 reflectParams := []reflect.Value{} // Init buffer147 reflectParams = append(reflectParams, reflect.ValueOf(context.Background())) // Append request context148 switch methodname {149 case "GetGateway":150 reflectParams = append(reflectParams, reflect.ValueOf(&upnpProto.GeneralRequest{})) // Append params151 case "ForwardPortSilent", "ForwardPort", "RemoveForwarding":152 if len(params) != 1 { // Check for invalid parameters153 return errors.New("invalid parameters (requires uint32)") // Return error154 }155 port, err := strconv.Atoi(params[0]) // Convert to int156 if err != nil { // Check for errors157 return err // Return found error158 }159 reflectParams = append(reflectParams, reflect.ValueOf(&upnpProto.GeneralRequest{PortNumber: uint32(port)})) // Append params160 default:161 return errors.New("illegal method: " + methodname + ", available methods: GetGateway(), ForwardPortSilent(), ForwardPort(), RemoveForwarding()") // Return error162 }163 result := reflect.ValueOf(*upnpClient).MethodByName(methodname).Call(reflectParams) // Call method164 response := result[0].Interface().(*upnpProto.GeneralResponse) // Get response165 if result[1].Interface() != nil { // Check for errors166 return result[1].Interface().(error) // Return error167 }168 fmt.Println(response.Message) // Log response169 return nil // No error occurred, return nil170}171// handleAccounts - handle accounts receiver172func handleAccounts(accountsClient *accountsProto.Accounts, methodname string, params []string) error {173 reflectParams := []reflect.Value{} // Init buffer174 reflectParams = append(reflectParams, reflect.ValueOf(context.Background())) // Append request context175 switch methodname {176 case "NewAccount", "GetAllAccounts":177 reflectParams = append(reflectParams, reflect.ValueOf(&accountsProto.GeneralRequest{})) // Append params178 case "MakeEncodingSafe", "RecoverSafeEncoding", "String", "Bytes", "ReadAccountFromMemory", "GetAllContracts":179 if len(params) != 1 { // Check for invalid parameters180 return errors.New("invalid parameters (requires string)") // Return error181 }182 reflectParams = append(reflectParams, reflect.ValueOf(&accountsProto.GeneralRequest{Address: params[0]})) // Append params183 case "AccountFromKey":184 if len(params) != 1 { // Check for invalid parameters185 return errors.New("invalid parameters (requires string)") // Return error186 }187 reflectParams = append(reflectParams, reflect.ValueOf(&accountsProto.GeneralRequest{PrivateKey: params[0]})) // Append params188 case "NewContractAccount":189 if len(params) != 2 { // Check for invalid parameters190 return errors.New("invalid parameters (requires string, string)") // Return error191 }192 reflectParams = append(reflectParams, reflect.ValueOf(&accountsProto.GeneralRequest{Address: params[0], PrivateKey: params[1]})) // Append params193 default:194 return errors.New("illegal method: " + methodname + ", available methods: NewAccount(), NewContractAccount(), GetAllAccounts(), MakeEncodingSafe(), RecoverSafeEncoding(), String(), Bytes(), ReadAccountFromMemory()") // Return error195 }196 result := reflect.ValueOf(*accountsClient).MethodByName(methodname).Call(reflectParams) // Call method197 response := result[0].Interface().(*accountsProto.GeneralResponse) // Get response198 if result[1].Interface() != nil { // Check for errors199 return result[1].Interface().(error) // Return error200 }201 fmt.Println(response.Message) // Log response202 return nil // No error occurred, return nil203}204// handleConfig - handle config receiver205func handleConfig(configClient *configProto.Config, methodname string, params []string) error {206 reflectParams := []reflect.Value{} // Init buffer207 reflectParams = append(reflectParams, reflect.ValueOf(context.Background())) // Append request context208 switch methodname {209 case "NewChainConfig":210 if len(params) != 1 { // Check for invalid parameters211 return errors.New("invalid parameters (requires string)") // Return error212 }213 reflectParams = append(reflectParams, reflect.ValueOf(&configProto.GeneralRequest{GenesisPath: params[0]})) // Append params214 case "Bytes", "String", "WriteToMemory", "ReadChainConfigFromMemory", "GetTotalSupply", "GetInflationRate":215 if len(params) != 0 { // Check for invalid parameters216 return errors.New("invalid parameters (accepts 0 params)") // Return error217 }218 reflectParams = append(reflectParams, reflect.ValueOf(&configProto.GeneralRequest{})) // Append params219 default:220 return errors.New("illegal method: " + methodname + ", available methods: NewChainConfig(), Bytes(), String(), WriteToMemory(), ReadChainConfigFromMemory(), GetTotalSupply()") // Return error221 }222 result := reflect.ValueOf(*configClient).MethodByName(methodname).Call(reflectParams) // Call method223 response := result[0].Interface().(*configProto.GeneralResponse) // Get response224 if result[1].Interface() != nil { // Check for errors225 return result[1].Interface().(error) // Return error226 }227 fmt.Println(response.Message) // Log response228 return nil // No error occurred, return nil229}230// handleTransaction - handle transaction receiver231func handleTransaction(transactionClient *transactionProto.Transaction, methodname string, params []string) error {232 reflectParams := []reflect.Value{} // Init buffer233 reflectParams = append(reflectParams, reflect.ValueOf(context.Background())) // Append request context234 switch methodname {235 case "NewTransaction":236 if len(params) != 4 { // Check for invalid parameters237 return errors.New("invalid parameters (require string, string, float64, []byte)") // Return error238 }239 floatVal, _ := strconv.ParseFloat(params[2], 64) // Parse float240 reflectParams = append(reflectParams, reflect.ValueOf(&transactionProto.GeneralRequest{Address: params[0], Address2: params[1], Amount: floatVal, Payload: []byte(params[3])})) // Append params241 case "TransactionFromBytes":242 if len(params) != 1 { // Check for invalid parameters243 return errors.New("invalid parameters (require []byte)") // Return error244 }245 reflectParams = append(reflectParams, reflect.ValueOf(&transactionProto.GeneralRequest{Payload: []byte(params[0])})) // Append params246 case "Bytes", "String", "SignTransaction", "VerifyTransactionSignature":247 if len(params) != 1 {248 return errors.New("invalid parameters (requires string)") // Return error249 }250 reflectParams = append(reflectParams, reflect.ValueOf(&transactionProto.GeneralRequest{Address: params[0]})) // Append params251 case "Publish":252 if len(params) != 1 {253 return errors.New("invalid parameters (requires string)") // Return error254 }255 reflectParams = append(reflectParams, reflect.ValueOf(&transactionProto.GeneralRequest{Address: params[0], Address2: workingNetwork})) // Append params256 default:257 return errors.New("illegal method: " + methodname + ", available methods: NewTransaction(), TransactionFromBytes(), Publish(), Bytes(), String(), SignTransaction(), VerifyTransactionSignature()") // Return error258 }259 result := reflect.ValueOf(*transactionClient).MethodByName(methodname).Call(reflectParams) // Call method260 response := result[0].Interface().(*transactionProto.GeneralResponse) // Get response261 if result[1].Interface() != nil { // Check for errors262 return result[1].Interface().(error) // Return error263 }264 fmt.Println(response.Message) // Log response265 return nil // No error occurred, return nil266}267// handleChain - handle chain receiver268func handleChain(chainClient *chainProto.Chain, methodname string, params []string) error {269 reflectParams := []reflect.Value{} // Init buffer270 reflectParams = append(reflectParams, reflect.ValueOf(context.Background())) // Append request context271 switch methodname {272 case "GetBalance", "Bytes", "String", "ReadChainFromMemory", "QueryTransaction", "GetNumTransactions":273 if len(params) != 1 {274 return errors.New("invalid parameters (requires string)") // Return error275 }276 reflectParams = append(reflectParams, reflect.ValueOf(&chainProto.GeneralRequest{Address: params[0]})) // Append params277 default:278 return errors.New("illegal method: " + methodname + ", available methods: GetBalance(), Bytes(), String(), ReadChainFromMemory(), QueryTransaction(), GetNumTransactions()") // Return error279 }280 result := reflect.ValueOf(*chainClient).MethodByName(methodname).Call(reflectParams) // Call method281 response := result[0].Interface().(*chainProto.GeneralResponse) // Get response282 if result[1].Interface() != nil { // Check for errors283 return result[1].Interface().(error) // Return error284 }285 fmt.Println(response.Message) // Log response286 return nil // No error occurred, return nil287}288// handleCoordinationChain - handle chain receiver289func handleCoordinationChain(chainClient *coordinationChainProto.CoordinationChain, methodname string, params []string) error {290 reflectParams := []reflect.Value{} // Init buffer291 reflectParams = append(reflectParams, reflect.ValueOf(context.Background())) // Append request context292 switch methodname {293 case "SyncNetwork", "GetPeers", "Bytes", "String":294 if len(params) != 0 {295 return errors.New("invalid parameters (accepts no parameters)") // Return error296 }297 reflectParams = append(reflectParams, reflect.ValueOf(&coordinationChainProto.GeneralRequest{})) // Append params298 default:299 return errors.New("illegal method: " + methodname + ", available methods: SyncNetwork(), GetPeers(), Bytes(), String()") // Return error300 }301 result := reflect.ValueOf(*chainClient).MethodByName(methodname).Call(reflectParams) // Call method302 response := result[0].Interface().(*coordinationChainProto.GeneralResponse) // Get response303 if result[1].Interface() != nil { // Check for errors304 return result[1].Interface().(error) // Return error305 }306 fmt.Println(response.Message) // Log response307 return nil // No error occurred, return nil308}309// handleCommon - handle common receiver310func handleCommon(commonClient *commonProto.Common, methodname string, params []string) error {311 reflectParams := []reflect.Value{} // Init buffer312 reflectParams = append(reflectParams, reflect.ValueOf(context.Background())) // Append request context313 switch methodname {314 case "Encode", "EncodeString", "Decode":315 if len(params) == 0 { // Check for invalid params316 return errors.New("invalid parameters (requires []byte)") // Return error317 }318 reflectParams = append(reflectParams, reflect.ValueOf(&commonProto.GeneralRequest{Input: []byte(params[0])})) // Append params319 case "DecodeString":320 if len(params) != 1 { // Check for invalid params321 return errors.New("invalid parameters (requires string)") // Return error322 }323 reflectParams = append(reflectParams, reflect.ValueOf(&commonProto.GeneralRequest{S: params[0]}))324 default:325 return errors.New("illegal method: " + methodname + ", available methods: Encode(), EncodeString(), Decode(), DecodeString()") // Return error326 }327 result := reflect.ValueOf(*commonClient).MethodByName(methodname).Call(reflectParams) // Call method328 response := result[0].Interface().(*commonProto.GeneralResponse) // Get response329 if result[1].Interface() != nil { // Check for errors330 return result[1].Interface().(error) // Return error331 }332 fmt.Println(response.Message) // Log response333 return nil // No error occurred, return nil334}335// handleP2P - handle p2p receiver336func handleP2P(p2pClient *p2pProto.P2P, methodname string, params []string) error {337 reflectParams := []reflect.Value{} // Init buffer338 reflectParams = append(reflectParams, reflect.ValueOf(context.Background())) // Append request context339 switch methodname {340 case "NumConnectedPeers", "ConnectedPeers":341 reflectParams = append(reflectParams, reflect.ValueOf(&p2pProto.GeneralRequest{})) // Empty request342 case "SyncNetwork":343 if len(params) != 1 { // Check not enough params344 return errors.New("invalid parameters (requires string)") // Return error345 }346 reflectParams = append(reflectParams, reflect.ValueOf(&p2pProto.GeneralRequest{Network: params[0]})) // Empty request347 default:348 return errors.New("illegal method: " + methodname + ", available methods: NumConnectedPeers(), ConnectedPeers(), SyncNetwork()") // Return error349 }350 result := reflect.ValueOf(*p2pClient).MethodByName(methodname).Call(reflectParams) // Call method351 response := result[0].Interface().(*p2pProto.GeneralResponse) // Get response352 if result[1].Interface() != nil { // Check for errors353 return result[1].Interface().(error) // Return error354 }355 fmt.Println(response.Message) // Log response356 return nil // No error occurred, return nil357}358// logHeader - log contents of header file359func logHeader() {360 header := figure.NewFigure("SummerCash v"+config.Version, "slant", true) // Generate header text361 header.Print() // Log362 fmt.Println("") // Spacing363 fmt.Println("") // Spacing364}...
wrapper_test.go
Source:wrapper_test.go
1package datastore2import (3 "context"4 "errors"5 "reflect"6 "strings"7 "testing"8 "time"9 "github.com/spiffe/go-spiffe/v2/spiffeid"10 "github.com/spiffe/spire-api-sdk/proto/spire/api/types"11 "github.com/spiffe/spire/pkg/common/telemetry"12 "github.com/spiffe/spire/pkg/server/datastore"13 "github.com/spiffe/spire/proto/spire/common"14 "github.com/spiffe/spire/test/fakes/fakemetrics"15 "github.com/stretchr/testify/assert"16 "github.com/stretchr/testify/require"17 "google.golang.org/grpc/codes"18)19func TestWithMetrics(t *testing.T) {20 m := fakemetrics.New()21 ds := &fakeDataStore{}22 w := WithMetrics(ds, m)23 // This map ensures that a unit-test is added for any additional24 // datastore methods that are added.25 methodNames := make(map[string]struct{})26 wv := reflect.ValueOf(w)27 wt := reflect.TypeOf(w)28 for i := 0; i < wt.NumMethod(); i++ {29 methodNames[wt.Method(i).Name] = struct{}{}30 }31 for _, tt := range []struct {32 key string33 methodName string34 }{35 {36 key: "datastore.bundle.append",37 methodName: "AppendBundle",38 },39 {40 key: "datastore.node.count",41 methodName: "CountAttestedNodes",42 },43 {44 key: "datastore.bundle.count",45 methodName: "CountBundles",46 },47 {48 key: "datastore.registration_entry.count",49 methodName: "CountRegistrationEntries",50 },51 {52 key: "datastore.node.create",53 methodName: "CreateAttestedNode",54 },55 {56 key: "datastore.bundle.create",57 methodName: "CreateBundle",58 },59 {60 key: "datastore.federation_relationship.create",61 methodName: "CreateFederationRelationship",62 },63 {64 key: "datastore.join_token.create",65 methodName: "CreateJoinToken",66 },67 {68 key: "datastore.registration_entry.create",69 methodName: "CreateRegistrationEntry",70 },71 {72 key: "datastore.registration_entry.create",73 methodName: "CreateOrReturnRegistrationEntry",74 },75 {76 key: "datastore.node.delete",77 methodName: "DeleteAttestedNode",78 },79 {80 key: "datastore.bundle.delete",81 methodName: "DeleteBundle",82 },83 {84 key: "datastore.federation_relationship.delete",85 methodName: "DeleteFederationRelationship",86 },87 {88 key: "datastore.join_token.delete",89 methodName: "DeleteJoinToken",90 },91 {92 key: "datastore.registration_entry.delete",93 methodName: "DeleteRegistrationEntry",94 },95 {96 key: "datastore.node.fetch",97 methodName: "FetchAttestedNode",98 },99 {100 key: "datastore.bundle.fetch",101 methodName: "FetchBundle",102 },103 {104 key: "datastore.join_token.fetch",105 methodName: "FetchJoinToken",106 },107 {108 key: "datastore.registration_entry.fetch",109 methodName: "FetchRegistrationEntry",110 },111 {112 key: "datastore.federation_relationship.fetch",113 methodName: "FetchFederationRelationship",114 },115 {116 key: "datastore.node.selectors.fetch",117 methodName: "GetNodeSelectors",118 },119 {120 key: "datastore.node.list",121 methodName: "ListAttestedNodes",122 },123 {124 key: "datastore.bundle.list",125 methodName: "ListBundles",126 },127 {128 key: "datastore.node.selectors.list",129 methodName: "ListNodeSelectors",130 },131 {132 key: "datastore.registration_entry.list",133 methodName: "ListRegistrationEntries",134 },135 {136 key: "datastore.federation_relationship.list",137 methodName: "ListFederationRelationships",138 },139 {140 key: "datastore.bundle.prune",141 methodName: "PruneBundle",142 },143 {144 key: "datastore.join_token.prune",145 methodName: "PruneJoinTokens",146 },147 {148 key: "datastore.registration_entry.prune",149 methodName: "PruneRegistrationEntries",150 },151 {152 key: "datastore.bundle.set",153 methodName: "SetBundle",154 },155 {156 key: "datastore.node.selectors.set",157 methodName: "SetNodeSelectors",158 },159 {160 key: "datastore.node.update",161 methodName: "UpdateAttestedNode",162 },163 {164 key: "datastore.bundle.update",165 methodName: "UpdateBundle",166 },167 {168 key: "datastore.federation_relationship.update",169 methodName: "UpdateFederationRelationship",170 },171 {172 key: "datastore.registration_entry.update",173 methodName: "UpdateRegistrationEntry",174 },175 } {176 tt := tt177 methodType, ok := wt.MethodByName(tt.methodName)178 require.True(t, ok, "method %q does not exist on DataStore interface", tt.methodName)179 methodValue := wv.Method(methodType.Index)180 // Record that the method was tested. Methods that aren't tested181 // will fail the test below.182 delete(methodNames, methodType.Name)183 doCall := func(err error) interface{} {184 m.Reset()185 ds.SetError(err)186 numIn := methodValue.Type().NumIn()187 numOut := methodValue.Type().NumOut()188 args := []reflect.Value{reflect.ValueOf(context.Background())}189 for i := 1; i < numIn; i++ {190 args = append(args, reflect.New(methodValue.Type().In(i)).Elem())191 }192 out := methodValue.Call(args)193 require.Len(t, out, numOut)194 for i := 0; i < numOut-1; i++ {195 mv := methodValue.Type().Out(i)196 switch v := reflect.ValueOf(mv); v.Kind() {197 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:198 require.True(t, out[i].IsZero())199 default:200 require.NotNil(t, mv)201 }202 }203 return out[numOut-1].Interface()204 }205 expectedMetrics := func(code codes.Code) []fakemetrics.MetricItem {206 key := strings.Split(tt.key, ".")207 return []fakemetrics.MetricItem{208 {209 Type: fakemetrics.IncrCounterWithLabelsType,210 Key: key,211 Labels: []telemetry.Label{212 {Name: "status", Value: code.String()},213 },214 Val: 1,215 },216 {217 Type: fakemetrics.MeasureSinceWithLabelsType,218 Key: append(key, "elapsed_time"),219 Labels: []telemetry.Label{220 {Name: "status", Value: code.String()},221 },222 },223 }224 }225 t.Run(tt.key+"(success)", func(t *testing.T) {226 err := doCall(nil)227 assert.Nil(t, err, "error should be nil")228 assert.Equal(t, expectedMetrics(codes.OK), m.AllMetrics())229 })230 t.Run(tt.key+"(failure)", func(t *testing.T) {231 err := doCall(errors.New("ohno"))232 assert.NotNil(t, err, "error should be not nil")233 assert.Equal(t, expectedMetrics(codes.Unknown), m.AllMetrics())234 })235 }236 for methodName := range methodNames {237 t.Errorf("DataStore method %q was not tested", methodName)238 }239}240type fakeDataStore struct {241 err error242}243func (ds *fakeDataStore) SetError(err error) {244 ds.err = err245}246func (ds *fakeDataStore) AppendBundle(context.Context, *common.Bundle) (*common.Bundle, error) {247 return &common.Bundle{}, ds.err248}249func (ds *fakeDataStore) CountAttestedNodes(context.Context) (int32, error) {250 return 0, ds.err251}252func (ds *fakeDataStore) CountBundles(context.Context) (int32, error) {253 return 0, ds.err254}255func (ds *fakeDataStore) CountRegistrationEntries(context.Context) (int32, error) {256 return 0, ds.err257}258func (ds *fakeDataStore) CreateAttestedNode(context.Context, *common.AttestedNode) (*common.AttestedNode, error) {259 return &common.AttestedNode{}, ds.err260}261func (ds *fakeDataStore) CreateBundle(context.Context, *common.Bundle) (*common.Bundle, error) {262 return &common.Bundle{}, ds.err263}264func (ds *fakeDataStore) CreateFederationRelationship(context.Context, *datastore.FederationRelationship) (*datastore.FederationRelationship, error) {265 return &datastore.FederationRelationship{}, ds.err266}267func (ds *fakeDataStore) ListFederationRelationships(context.Context, *datastore.ListFederationRelationshipsRequest) (*datastore.ListFederationRelationshipsResponse, error) {268 return &datastore.ListFederationRelationshipsResponse{}, ds.err269}270func (ds *fakeDataStore) CreateJoinToken(context.Context, *datastore.JoinToken) error {271 return ds.err272}273func (ds *fakeDataStore) CreateRegistrationEntry(context.Context, *common.RegistrationEntry) (*common.RegistrationEntry, error) {274 return &common.RegistrationEntry{}, ds.err275}276func (ds *fakeDataStore) CreateOrReturnRegistrationEntry(context.Context, *common.RegistrationEntry) (*common.RegistrationEntry, bool, error) {277 return &common.RegistrationEntry{}, true, ds.err278}279func (ds *fakeDataStore) DeleteAttestedNode(context.Context, string) (*common.AttestedNode, error) {280 return &common.AttestedNode{}, ds.err281}282func (ds *fakeDataStore) DeleteBundle(context.Context, string, datastore.DeleteMode) error {283 return ds.err284}285func (ds *fakeDataStore) DeleteFederationRelationship(context.Context, spiffeid.TrustDomain) error {286 return ds.err287}288func (ds *fakeDataStore) DeleteJoinToken(context.Context, string) error {289 return ds.err290}291func (ds *fakeDataStore) DeleteRegistrationEntry(context.Context, string) (*common.RegistrationEntry, error) {292 return &common.RegistrationEntry{}, ds.err293}294func (ds *fakeDataStore) FetchAttestedNode(context.Context, string) (*common.AttestedNode, error) {295 return &common.AttestedNode{}, ds.err296}297func (ds *fakeDataStore) FetchBundle(context.Context, string) (*common.Bundle, error) {298 return &common.Bundle{}, ds.err299}300func (ds *fakeDataStore) FetchFederationRelationship(context.Context, spiffeid.TrustDomain) (*datastore.FederationRelationship, error) {301 return &datastore.FederationRelationship{}, ds.err302}303func (ds *fakeDataStore) FetchJoinToken(context.Context, string) (*datastore.JoinToken, error) {304 return &datastore.JoinToken{}, ds.err305}306func (ds *fakeDataStore) FetchRegistrationEntry(context.Context, string) (*common.RegistrationEntry, error) {307 return &common.RegistrationEntry{}, ds.err308}309func (ds *fakeDataStore) GetNodeSelectors(context.Context, string, datastore.DataConsistency) ([]*common.Selector, error) {310 return []*common.Selector{}, ds.err311}312func (ds *fakeDataStore) ListAttestedNodes(context.Context, *datastore.ListAttestedNodesRequest) (*datastore.ListAttestedNodesResponse, error) {313 return &datastore.ListAttestedNodesResponse{}, ds.err314}315func (ds *fakeDataStore) ListBundles(context.Context, *datastore.ListBundlesRequest) (*datastore.ListBundlesResponse, error) {316 return &datastore.ListBundlesResponse{}, ds.err317}318func (ds *fakeDataStore) ListNodeSelectors(context.Context, *datastore.ListNodeSelectorsRequest) (*datastore.ListNodeSelectorsResponse, error) {319 return &datastore.ListNodeSelectorsResponse{}, ds.err320}321func (ds *fakeDataStore) ListRegistrationEntries(context.Context, *datastore.ListRegistrationEntriesRequest) (*datastore.ListRegistrationEntriesResponse, error) {322 return &datastore.ListRegistrationEntriesResponse{}, ds.err323}324func (ds *fakeDataStore) PruneBundle(context.Context, string, time.Time) (bool, error) {325 return false, ds.err326}327func (ds *fakeDataStore) PruneJoinTokens(context.Context, time.Time) error {328 return ds.err329}330func (ds *fakeDataStore) PruneRegistrationEntries(context.Context, time.Time) error {331 return ds.err332}333func (ds *fakeDataStore) SetBundle(context.Context, *common.Bundle) (*common.Bundle, error) {334 return &common.Bundle{}, ds.err335}336func (ds *fakeDataStore) SetNodeSelectors(context.Context, string, []*common.Selector) error {337 return ds.err338}339func (ds *fakeDataStore) UpdateAttestedNode(context.Context, *common.AttestedNode, *common.AttestedNodeMask) (*common.AttestedNode, error) {340 return &common.AttestedNode{}, ds.err341}342func (ds *fakeDataStore) UpdateBundle(context.Context, *common.Bundle, *common.BundleMask) (*common.Bundle, error) {343 return &common.Bundle{}, ds.err344}345func (ds *fakeDataStore) UpdateRegistrationEntry(context.Context, *common.RegistrationEntry, *common.RegistrationEntryMask) (*common.RegistrationEntry, error) {346 return &common.RegistrationEntry{}, ds.err347}348func (ds *fakeDataStore) UpdateFederationRelationship(context.Context, *datastore.FederationRelationship, *types.FederationRelationshipMask) (*datastore.FederationRelationship, error) {349 return &datastore.FederationRelationship{}, ds.err350}...
tps_limiter_method_service_test.go
Source:tps_limiter_method_service_test.go
1/*2 * Licensed to the Apache Software Foundation (ASF) under one or more3 * contributor license agreements. See the NOTICE file distributed with4 * this work for additional information regarding copyright ownership.5 * The ASF licenses this file to You under the Apache License, Version 2.06 * (the "License"); you may not use this file except in compliance with7 * the License. You may obtain a copy of the License at8 *9 * http://www.apache.org/licenses/LICENSE-2.010 *11 * Unless required by applicable law or agreed to in writing, software12 * distributed under the License is distributed on an "AS IS" BASIS,13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.14 * See the License for the specific language governing permissions and15 * limitations under the License.16 */17package tps18import (19 "net/url"20 "testing"21)22import (23 "github.com/apache/dubbo-go/filter"24 "github.com/golang/mock/gomock"25 "github.com/stretchr/testify/assert"26)27import (28 "github.com/apache/dubbo-go/common"29 "github.com/apache/dubbo-go/common/constant"30 "github.com/apache/dubbo-go/common/extension"31 "github.com/apache/dubbo-go/protocol/invocation"32)33func TestMethodServiceTpsLimiterImpl_IsAllowable_Only_Service_Level(t *testing.T) {34 methodName := "hello"35 invoc := invocation.NewRPCInvocation(methodName, []interface{}{"OK"}, make(map[string]string, 0))36 ctrl := gomock.NewController(t)37 defer ctrl.Finish()38 invokeUrl := common.NewURLWithOptions(39 common.WithParams(url.Values{}),40 common.WithParamsValue(constant.INTERFACE_KEY, methodName),41 common.WithParamsValue(constant.TPS_LIMIT_RATE_KEY, "20"))42 mockStrategyImpl := NewMockTpsLimitStrategy(ctrl)43 mockStrategyImpl.EXPECT().IsAllowable().Return(true).Times(1)44 extension.SetTpsLimitStrategy(constant.DEFAULT_KEY, &mockStrategyCreator{45 rate: 20,46 interval: 60000,47 t: t,48 strategy: mockStrategyImpl,49 })50 limiter := GetMethodServiceTpsLimiter()51 result := limiter.IsAllowable(*invokeUrl, invoc)52 assert.True(t, result)53}54func TestMethodServiceTpsLimiterImpl_IsAllowable_No_Config(t *testing.T) {55 methodName := "hello1"56 invoc := invocation.NewRPCInvocation(methodName, []interface{}{"OK"}, make(map[string]string, 0))57 // ctrl := gomock.NewController(t)58 // defer ctrl.Finish()59 invokeUrl := common.NewURLWithOptions(60 common.WithParams(url.Values{}),61 common.WithParamsValue(constant.INTERFACE_KEY, methodName),62 common.WithParamsValue(constant.TPS_LIMIT_RATE_KEY, ""))63 limiter := GetMethodServiceTpsLimiter()64 result := limiter.IsAllowable(*invokeUrl, invoc)65 assert.True(t, result)66}67func TestMethodServiceTpsLimiterImpl_IsAllowable_Method_Level_Override(t *testing.T) {68 methodName := "hello2"69 methodConfigPrefix := "methods." + methodName + "."70 invoc := invocation.NewRPCInvocation(methodName, []interface{}{"OK"}, make(map[string]string, 0))71 ctrl := gomock.NewController(t)72 defer ctrl.Finish()73 invokeUrl := common.NewURLWithOptions(74 common.WithParams(url.Values{}),75 common.WithParamsValue(constant.INTERFACE_KEY, methodName),76 common.WithParamsValue(constant.TPS_LIMIT_RATE_KEY, "20"),77 common.WithParamsValue(constant.TPS_LIMIT_INTERVAL_KEY, "3000"),78 common.WithParamsValue(constant.TPS_LIMIT_STRATEGY_KEY, "invalid"),79 common.WithParamsValue(methodConfigPrefix+constant.TPS_LIMIT_RATE_KEY, "40"),80 common.WithParamsValue(methodConfigPrefix+constant.TPS_LIMIT_INTERVAL_KEY, "7000"),81 common.WithParamsValue(methodConfigPrefix+constant.TPS_LIMIT_STRATEGY_KEY, "default"),82 )83 mockStrategyImpl := NewMockTpsLimitStrategy(ctrl)84 mockStrategyImpl.EXPECT().IsAllowable().Return(true).Times(1)85 extension.SetTpsLimitStrategy(constant.DEFAULT_KEY, &mockStrategyCreator{86 rate: 40,87 interval: 7000,88 t: t,89 strategy: mockStrategyImpl,90 })91 limiter := GetMethodServiceTpsLimiter()92 result := limiter.IsAllowable(*invokeUrl, invoc)93 assert.True(t, result)94}95func TestMethodServiceTpsLimiterImpl_IsAllowable_Both_Method_And_Service(t *testing.T) {96 methodName := "hello3"97 methodConfigPrefix := "methods." + methodName + "."98 invoc := invocation.NewRPCInvocation(methodName, []interface{}{"OK"}, make(map[string]string, 0))99 ctrl := gomock.NewController(t)100 defer ctrl.Finish()101 invokeUrl := common.NewURLWithOptions(102 common.WithParams(url.Values{}),103 common.WithParamsValue(constant.INTERFACE_KEY, methodName),104 common.WithParamsValue(constant.TPS_LIMIT_RATE_KEY, "20"),105 common.WithParamsValue(constant.TPS_LIMIT_INTERVAL_KEY, "3000"),106 common.WithParamsValue(methodConfigPrefix+constant.TPS_LIMIT_RATE_KEY, "40"),107 )108 mockStrategyImpl := NewMockTpsLimitStrategy(ctrl)109 mockStrategyImpl.EXPECT().IsAllowable().Return(true).Times(1)110 extension.SetTpsLimitStrategy(constant.DEFAULT_KEY, &mockStrategyCreator{111 rate: 40,112 interval: 3000,113 t: t,114 strategy: mockStrategyImpl,115 })116 limiter := GetMethodServiceTpsLimiter()117 result := limiter.IsAllowable(*invokeUrl, invoc)118 assert.True(t, result)119}120type mockStrategyCreator struct {121 rate int122 interval int123 t *testing.T124 strategy filter.TpsLimitStrategy125}126func (creator *mockStrategyCreator) Create(rate int, interval int) filter.TpsLimitStrategy {127 assert.Equal(creator.t, creator.rate, rate)128 assert.Equal(creator.t, creator.interval, interval)129 return creator.strategy130}...
MethodName
Using AI Code Generation
1import "common"2func main() {3 var c = common.Common{}4 c.MethodName()5}6import "common"7func main() {8 var c = common.Common{}9 c.MethodName()10}11import "common"12func main() {13 var c = common.Common{}14 c.MethodName()15}16import "common"17func main() {18 var c = common.Common{}19 c.MethodName()20}21import "common"22func main() {23 var c = common.Common{}24 c.MethodName()25}26import "common"27func main() {28 var c = common.Common{}29 c.MethodName()30}31import "common"32func main() {33 var c = common.Common{}34 c.MethodName()35}36import "common"37func main() {38 var c = common.Common{}39 c.MethodName()40}41import "common"42func main() {43 var c = common.Common{}44 c.MethodName()45}46import "common"47func main() {48 var c = common.Common{}49 c.MethodName()50}51import "common"52func main() {53 var c = common.Common{}54 c.MethodName()55}56import "common"57func main() {58 var c = common.Common{}59 c.MethodName()60}61import "common"62func main() {63 var c = common.Common{}64 c.MethodName()65}
MethodName
Using AI Code Generation
1import (2func main() {3 common.MethodName()4}5import "fmt"6func MethodName() {7 fmt.Println("Hello, World!")8}
MethodName
Using AI Code Generation
1import (2func main() {3 common.MethodName()4}5import "fmt"6func MethodName() {7 fmt.Println("Hello World")8}9import (10func main() {11 common.MethodName()12}13import "fmt"14func MethodName() {15 fmt.Println("Hello World")16}17import (18func main() {19 common.MethodName()20}21import "fmt"22func MethodName() {23 fmt.Println("Hello World")24}25import (26func main() {27 common.MethodName()28}29import "fmt"30func MethodName() {31 fmt.Println("Hello World")32}33import (34func main() {35 common.MethodName()36}37import "fmt"38func MethodName() {39 fmt.Println("Hello World")40}41import (42func main() {43 common.MethodName()44}45import "fmt"
MethodName
Using AI Code Generation
1import (2func main() {3 fmt.Println(common.MethodName())4}5import "fmt"6func MethodName() string {7 return fmt.Sprintf("Hello from common package")8}9import (10func main() {11 fmt.Println(common.MethodName())12}13import "fmt"14func MethodName() string {15 return fmt.Sprintf("Hello from common package")16}17import (18func main() {19 fmt.Println(common.MethodName())20}21import "fmt"22func MethodName() string {23 return fmt.Sprintf("Hello from common package")24}25import (26func main() {27 fmt.Println(common.MethodName())28}29import "fmt"30func MethodName() string {31 return fmt.Sprintf("Hello from common package")32}33import (34func main() {35 fmt.Println(common.MethodName())36}37import "fmt"38func MethodName() string {39 return fmt.Sprintf("Hello from common package")40}41import (42func main() {43 fmt.Println(common.MethodName())44}45import "fmt"46func MethodName() string {47 return fmt.Sprintf("Hello from common package")48}49import (50func main() {51 fmt.Println(common.MethodName())52}53import "fmt"54func MethodName() string {55 return fmt.Sprintf("Hello from common package")56}57import (58func main() {59 fmt.Println(common
MethodName
Using AI Code Generation
1import (2func main() {3 fmt.Println(common.MethodName())4}5func MethodName() string {6}7import "testing"8func TestMethodName(t *testing.T) {9 if MethodName() != "common.MethodName" {10 t.Error("common.MethodName() != common.MethodName")11 }12}13import "testing"14func BenchmarkMethodName(b *testing.B) {15 for i := 0; i < b.N; i++ {16 MethodName()17 }18}19import "fmt"20func ExampleMethodName() {21 fmt.Println(MethodName())22}23import "testing"24func TestMethodName(t *testing.T) {25 if MethodName() != "common.MethodName" {26 t.Error("common.MethodName() != common.MethodName")27 }28}29import "testing"30func BenchmarkMethodName(b *testing.B) {31 for i := 0; i < b.N; i++ {32 MethodName()33 }34}35import "fmt"36func ExampleMethodName() {37 fmt.Println(MethodName())38}39import "testing"40func TestMethodName(t *testing.T) {41 if MethodName() != "common.MethodName" {42 t.Error("common.MethodName() != common.MethodName")43 }44}45import "testing"46func BenchmarkMethodName(b *testing.B) {47 for i := 0; i
MethodName
Using AI Code Generation
1import (2func main() {3 fmt.Println(common.MethodName())4}5 /usr/local/go/src/github.com/rajeshkumar1993/Go-Programs/common (from $GOROOT)6 /home/rajeshkumar1993/Documents/Go-Programs/src/github.com/rajeshkumar1993/Go-Programs/common (from $GOPATH)
MethodName
Using AI Code Generation
1import (2func main() {3 fmt.Println(common.MethodName())4}5func MethodName() string {6}7func MethodName() string {8}9func MethodName() string {10}11func MethodName() string {12}13func MethodName() string {14}15func MethodName() string {16}17func MethodName() string {18}19func MethodName() string {20}21func MethodName() string {22}23func MethodName() string {24}25func MethodName() string {26}27func MethodName() string {28}29func MethodName() string {30}31func MethodName() string {32}33func MethodName() string {34}35func MethodName() string {36}37func MethodName() string {38}
MethodName
Using AI Code Generation
1import (2func main() {3 fmt.Println("Hello World!")4 common.MethodName()5}6import "fmt"7func MethodName() {8 fmt.Println("Hello from common package")9}10import (11func main() {12 fmt.Println("Hello World!")13 common.MethodName()14}15import "fmt"16func MethodName() {17 fmt.Println("Hello from common package")18}19import (20func main() {21 fmt.Println("Hello World!")22 common.MethodName()23}
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!