Best Gauge code snippet using execution.Connection
connection_factory_test.go
Source:connection_factory_test.go
...26 req := &access.PingRequest{}27 expected := &access.PingResponse{}28 cn.handler.On("Ping", testifymock.Anything, req).Return(expected, nil)29 // create the factory30 connectionFactory := new(ConnectionFactoryImpl)31 // set the collection grpc port32 connectionFactory.CollectionGRPCPort = cn.port33 // set the connection pool cache size34 cache, _ := lru.New(5)35 connectionFactory.ConnectionsCache = cache36 // set metrics reporting37 connectionFactory.AccessMetrics = metrics.NewNoopCollector()38 proxyConnectionFactory := ProxyConnectionFactory{39 ConnectionFactory: connectionFactory,40 targetAddress: cn.listener.Addr().String(),41 }42 // get a collection API client43 client, closer, err := proxyConnectionFactory.GetAccessAPIClient("foo")44 assert.NoError(t, err)45 defer closer.Close()46 ctx := context.Background()47 // make the call to the collection node48 resp, err := client.Ping(ctx, req)49 assert.NoError(t, err)50 assert.Equal(t, resp, expected)51}52func TestProxyExecutionAPI(t *testing.T) {53 // create an execution node54 en := new(executionNode)55 en.start(t)56 defer en.stop(t)57 req := &execution.PingRequest{}58 expected := &execution.PingResponse{}59 en.handler.On("Ping", testifymock.Anything, req).Return(expected, nil)60 // create the factory61 connectionFactory := new(ConnectionFactoryImpl)62 // set the execution grpc port63 connectionFactory.ExecutionGRPCPort = en.port64 // set the connection pool cache size65 cache, _ := lru.New(5)66 connectionFactory.ConnectionsCache = cache67 // set metrics reporting68 connectionFactory.AccessMetrics = metrics.NewNoopCollector()69 proxyConnectionFactory := ProxyConnectionFactory{70 ConnectionFactory: connectionFactory,71 targetAddress: en.listener.Addr().String(),72 }73 // get an execution API client74 client, closer, err := proxyConnectionFactory.GetExecutionAPIClient("foo")75 assert.NoError(t, err)76 defer closer.Close()77 ctx := context.Background()78 // make the call to the execution node79 resp, err := client.Ping(ctx, req)80 assert.NoError(t, err)81 assert.Equal(t, resp, expected)82}83func TestProxyAccessAPIConnectionReuse(t *testing.T) {84 // create a collection node85 cn := new(collectionNode)86 cn.start(t)87 defer cn.stop(t)88 req := &access.PingRequest{}89 expected := &access.PingResponse{}90 cn.handler.On("Ping", testifymock.Anything, req).Return(expected, nil)91 // create the factory92 connectionFactory := new(ConnectionFactoryImpl)93 // set the collection grpc port94 connectionFactory.CollectionGRPCPort = cn.port95 // set the connection pool cache size96 cache, _ := lru.New(5)97 connectionFactory.ConnectionsCache = cache98 // set metrics reporting99 connectionFactory.AccessMetrics = metrics.NewNoopCollector()100 proxyConnectionFactory := ProxyConnectionFactory{101 ConnectionFactory: connectionFactory,102 targetAddress: cn.listener.Addr().String(),103 }104 // get a collection API client105 _, closer, err := proxyConnectionFactory.GetAccessAPIClient("foo")106 assert.Equal(t, connectionFactory.ConnectionsCache.Len(), 1)107 assert.NoError(t, err)108 defer closer.Close()109 var conn *grpc.ClientConn110 res, ok := connectionFactory.ConnectionsCache.Get(proxyConnectionFactory.targetAddress)111 assert.True(t, ok)112 conn = res.(*grpc.ClientConn)113 // check if api client can be rebuilt with retrieved connection114 accessAPIClient := access.NewAccessAPIClient(conn)115 ctx := context.Background()116 resp, err := accessAPIClient.Ping(ctx, req)117 assert.NoError(t, err)118 assert.Equal(t, resp, expected)119}120func TestProxyExecutionAPIConnectionReuse(t *testing.T) {121 // create an execution node122 en := new(executionNode)123 en.start(t)124 defer en.stop(t)125 req := &execution.PingRequest{}126 expected := &execution.PingResponse{}127 en.handler.On("Ping", testifymock.Anything, req).Return(expected, nil)128 // create the factory129 connectionFactory := new(ConnectionFactoryImpl)130 // set the execution grpc port131 connectionFactory.ExecutionGRPCPort = en.port132 // set the connection pool cache size133 cache, _ := lru.New(5)134 connectionFactory.ConnectionsCache = cache135 // set metrics reporting136 connectionFactory.AccessMetrics = metrics.NewNoopCollector()137 proxyConnectionFactory := ProxyConnectionFactory{138 ConnectionFactory: connectionFactory,139 targetAddress: en.listener.Addr().String(),140 }141 // get an execution API client142 _, closer, err := proxyConnectionFactory.GetExecutionAPIClient("foo")143 assert.Equal(t, connectionFactory.ConnectionsCache.Len(), 1)144 assert.NoError(t, err)145 defer closer.Close()146 var conn *grpc.ClientConn147 res, ok := connectionFactory.ConnectionsCache.Get(proxyConnectionFactory.targetAddress)148 assert.True(t, ok)149 conn = res.(*grpc.ClientConn)150 // check if api client can be rebuilt with retrieved connection151 executionAPIClient := execution.NewExecutionAPIClient(conn)152 ctx := context.Background()153 resp, err := executionAPIClient.Ping(ctx, req)154 assert.NoError(t, err)155 assert.Equal(t, resp, expected)156}157// TestExecutionNodeClientTimeout tests that the execution API client times out after the timeout duration158func TestExecutionNodeClientTimeout(t *testing.T) {159 timeout := 10 * time.Millisecond160 // create an execution node161 en := new(executionNode)162 en.start(t)163 defer en.stop(t)164 // setup the handler mock to not respond within the timeout165 req := &execution.PingRequest{}166 resp := &execution.PingResponse{}167 en.handler.On("Ping", testifymock.Anything, req).After(timeout+time.Second).Return(resp, nil)168 // create the factory169 connectionFactory := new(ConnectionFactoryImpl)170 // set the execution grpc port171 connectionFactory.ExecutionGRPCPort = en.port172 // set the execution grpc client timeout173 connectionFactory.ExecutionNodeGRPCTimeout = timeout174 // set the connection pool cache size175 cache, _ := lru.New(5)176 connectionFactory.ConnectionsCache = cache177 // set metrics reporting178 connectionFactory.AccessMetrics = metrics.NewNoopCollector()179 // create the execution API client180 client, closer, err := connectionFactory.GetExecutionAPIClient(en.listener.Addr().String())181 assert.NoError(t, err)182 defer closer.Close()183 ctx := context.Background()184 // make the call to the execution node185 _, err = client.Ping(ctx, req)186 // assert that the client timed out187 assert.Equal(t, codes.DeadlineExceeded, status.Code(err))188}189// TestCollectionNodeClientTimeout tests that the collection API client times out after the timeout duration190func TestCollectionNodeClientTimeout(t *testing.T) {191 timeout := 10 * time.Millisecond192 // create a collection node193 cn := new(collectionNode)194 cn.start(t)195 defer cn.stop(t)196 // setup the handler mock to not respond within the timeout197 req := &access.PingRequest{}198 resp := &access.PingResponse{}199 cn.handler.On("Ping", testifymock.Anything, req).After(timeout+time.Second).Return(resp, nil)200 // create the factory201 connectionFactory := new(ConnectionFactoryImpl)202 // set the collection grpc port203 connectionFactory.CollectionGRPCPort = cn.port204 // set the collection grpc client timeout205 connectionFactory.CollectionNodeGRPCTimeout = timeout206 // set the connection pool cache size207 cache, _ := lru.New(5)208 connectionFactory.ConnectionsCache = cache209 // set metrics reporting210 connectionFactory.AccessMetrics = metrics.NewNoopCollector()211 // create the collection API client212 client, closer, err := connectionFactory.GetAccessAPIClient(cn.listener.Addr().String())213 assert.NoError(t, err)214 defer closer.Close()215 ctx := context.Background()216 // make the call to the execution node217 _, err = client.Ping(ctx, req)218 // assert that the client timed out219 assert.Equal(t, codes.DeadlineExceeded, status.Code(err))220}221// TestConnectionPoolFull tests that the LRU cache replaces connections when full222func TestConnectionPoolFull(t *testing.T) {223 // create a collection node224 cn1, cn2, cn3 := new(collectionNode), new(collectionNode), new(collectionNode)225 cn1.start(t)226 cn2.start(t)227 cn3.start(t)228 defer cn1.stop(t)229 defer cn2.stop(t)230 defer cn3.stop(t)231 req := &access.PingRequest{}232 expected := &access.PingResponse{}233 cn1.handler.On("Ping", testifymock.Anything, req).Return(expected, nil)234 cn2.handler.On("Ping", testifymock.Anything, req).Return(expected, nil)235 cn3.handler.On("Ping", testifymock.Anything, req).Return(expected, nil)236 // create the factory237 connectionFactory := new(ConnectionFactoryImpl)238 // set the collection grpc port239 connectionFactory.CollectionGRPCPort = cn1.port240 // set the connection pool cache size241 cache, _ := lru.New(2)242 connectionFactory.ConnectionsCache = cache243 // set metrics reporting244 connectionFactory.AccessMetrics = metrics.NewNoopCollector()245 cn1Address := "foo1:123"246 cn2Address := "foo2:123"247 cn3Address := "foo3:123"248 // get a collection API client249 _, closer, err := connectionFactory.GetAccessAPIClient(cn1Address)250 assert.Equal(t, connectionFactory.ConnectionsCache.Len(), 1)251 assert.NoError(t, err)252 defer closer.Close()253 _, closer, err = connectionFactory.GetAccessAPIClient(cn2Address)254 assert.Equal(t, connectionFactory.ConnectionsCache.Len(), 2)255 assert.NoError(t, err)256 defer closer.Close()257 _, closer, err = connectionFactory.GetAccessAPIClient(cn1Address)258 assert.Equal(t, connectionFactory.ConnectionsCache.Len(), 2)259 assert.NoError(t, err)260 defer closer.Close()261 // Expecting to replace cn2 because cn1 was accessed more recently262 _, closer, err = connectionFactory.GetAccessAPIClient(cn3Address)263 assert.Equal(t, connectionFactory.ConnectionsCache.Len(), 2)264 assert.NoError(t, err)265 defer closer.Close()266 var hostnameOrIP string267 hostnameOrIP, _, err = net.SplitHostPort(cn1Address)268 assert.NoError(t, err)269 grpcAddress1 := fmt.Sprintf("%s:%d", hostnameOrIP, connectionFactory.CollectionGRPCPort)270 hostnameOrIP, _, err = net.SplitHostPort(cn2Address)271 assert.NoError(t, err)272 grpcAddress2 := fmt.Sprintf("%s:%d", hostnameOrIP, connectionFactory.CollectionGRPCPort)273 hostnameOrIP, _, err = net.SplitHostPort(cn3Address)274 assert.NoError(t, err)275 grpcAddress3 := fmt.Sprintf("%s:%d", hostnameOrIP, connectionFactory.CollectionGRPCPort)276 contains1 := connectionFactory.ConnectionsCache.Contains(grpcAddress1)277 contains2 := connectionFactory.ConnectionsCache.Contains(grpcAddress2)278 contains3 := connectionFactory.ConnectionsCache.Contains(grpcAddress3)279 assert.True(t, contains1)280 assert.False(t, contains2)281 assert.True(t, contains3)282}283// TestConnectionPoolStale tests that a new connection will be established if the old one cached is stale284func TestConnectionPoolStale(t *testing.T) {285 // create a collection node286 cn := new(collectionNode)287 cn.start(t)288 defer cn.stop(t)289 req := &access.PingRequest{}290 expected := &access.PingResponse{}291 cn.handler.On("Ping", testifymock.Anything, req).Return(expected, nil)292 // create the factory293 connectionFactory := new(ConnectionFactoryImpl)294 // set the collection grpc port295 connectionFactory.CollectionGRPCPort = cn.port296 // set the connection pool cache size297 cache, _ := lru.New(5)298 connectionFactory.ConnectionsCache = cache299 // set metrics reporting300 connectionFactory.AccessMetrics = metrics.NewNoopCollector()301 proxyConnectionFactory := ProxyConnectionFactory{302 ConnectionFactory: connectionFactory,303 targetAddress: cn.listener.Addr().String(),304 }305 // get a collection API client306 client, closer, err := proxyConnectionFactory.GetAccessAPIClient("foo")307 assert.Equal(t, connectionFactory.ConnectionsCache.Len(), 1)308 assert.NoError(t, err)309 // close connection to simulate something "going wrong" with our stored connection310 closer.Close()311 // check if key still exists312 assert.True(t, connectionFactory.ConnectionsCache.Contains(proxyConnectionFactory.targetAddress))313 ctx := context.Background()314 // make the call to the collection node (should fail, connection closed)315 _, err = client.Ping(ctx, req)316 assert.Error(t, err)317 // re-access, should replace stale connection in cache with new one318 _, closer, _ = proxyConnectionFactory.GetAccessAPIClient("foo")319 assert.Equal(t, connectionFactory.ConnectionsCache.Len(), 1)320 defer closer.Close()321 var conn *grpc.ClientConn322 res, ok := connectionFactory.ConnectionsCache.Get(proxyConnectionFactory.targetAddress)323 assert.True(t, ok)324 conn = res.(*grpc.ClientConn)325 // check if api client can be rebuilt with retrieved connection326 accessAPIClient := access.NewAccessAPIClient(conn)327 ctx = context.Background()328 resp, err := accessAPIClient.Ping(ctx, req)329 assert.NoError(t, err)330 assert.Equal(t, resp, expected)331}332// node mocks a flow node that runs a GRPC server333type node struct {334 server *grpc.Server335 listener net.Listener336 port uint...
execution.go
Source:execution.go
...10)11// Execution is the configuration for execution12type Execution struct {13 LimitPerTest int64 `mapstructure:"executionLimitPerTest"`14 ConnectionRetries int `mapstructure:"executionConnectionRetries"`15 RetryDelay time.Duration `mapstructure:"executionRetryDelay"`16 TimeLimit time.Duration `mapstructure:"executionTimeLimit"`17 // DebugMode causes Fatal errors to be replaced with trapping errors, which do18 // not signal completion19 DebugMode bool `mapstructure:"debugMode"`20 DMCompletionDelay time.Duration `mapstructure:"dmCompletionDelay"`21}22// NewExecution creates a new Execution config from the given viper23func NewExecution(v *viper.Viper) (out Execution, err error) {24 return out, v.Unmarshal(&out)25}26func setExecutionBindings(v *viper.Viper) error {27 err := v.BindEnv("executionLimitPerTest", "EXECUTION_LIMIT_PER_TEST")28 if err != nil {29 return err30 }31 err = v.BindEnv("executionRetryDelay", "EXECUTION_RETRY_DELAY")32 if err != nil {33 return err34 }35 err = v.BindEnv("executionTimeLimit", "EXECUTION_TIME_LIMIT")36 if err != nil {37 return err38 }39 err = v.BindEnv("debugMode", "DEBUG_MODE")40 if err != nil {41 return err42 }43 err = v.BindEnv("dmCompletionDelay", "DM_COMPLETION_DELAY")44 if err != nil {45 return err46 }47 return v.BindEnv("executionConnectionRetries", "EXECUTION_CONNECTION_RETRIES")48}49func setExecutionDefaults(v *viper.Viper) {50 v.SetDefault("executionLimitPerTest", 40)51 v.SetDefault("executionConnectionRetries", 5)52 v.SetDefault("executionRetryDelay", "10s")53 v.SetDefault("executionTimeLimit", 10*time.Minute)54 v.SetDefault("debugMode", false)55 v.SetDefault("dmCompletionDelay", 2*time.Hour)56}...
Connection
Using AI Code Generation
1import (2func main() {3 if len(os.Args) != 3 {4 fmt.Println("Usage: ", os.Args[0], "host", "port")5 os.Exit(1)6 }7 port, err := strconv.Atoi(os.Args[2])8 if err != nil {9 fmt.Println("Error:", err)10 os.Exit(1)11 }12 address := os.Args[1] + ":" + strconv.Itoa(port)13 conn, err := net.Dial("tcp", address)14 if err != nil {15 fmt.Println("Error:", err)16 os.Exit(1)17 }18 defer conn.Close()19 currentTime := time.Now().Local()20 timeString := currentTime.Format("15:04:05")21 _, err = conn.Write([]byte(timeString))22 if err != nil {23 fmt.Println("Error:", err)24 os.Exit(1)25 }26 buffer := make([]byte, 1024)27 _, err = conn.Read(buffer)28 if err != nil {29 fmt.Println("Error:", err)30 os.Exit(1)31 }32 fmt.Println("Response from server:", string(buffer))33 os.Exit(0)34}
Connection
Using AI Code Generation
1import (2func main() {3 runtime.GOMAXPROCS(2)4 ch := make(chan string)5 go sendData(ch)6 go getData(ch)7 time.Sleep(1e9)8 fmt.Println("main terminated")9}10func sendData(ch chan string) {11}12func getData(ch chan string) {13 for {14 fmt.Printf("%s ", input)15 }16}
Connection
Using AI Code Generation
1import (2func main() {3 runtime.GOMAXPROCS(4)4 fmt.Println("Before Connection")5 go Connection()6 fmt.Println("After Connection")7 time.Sleep(10 * time.Second)8 fmt.Println("Exiting")9}10func Connection() {11 for {12 fmt.Println("Connection", count)13 time.Sleep(1 * time.Second)14 if count == 5 {15 }16 }17}
Connection
Using AI Code Generation
1import (2type Execution struct {3}4func (e *Execution) Connection() {5 fmt.Println("Executing Connection method")6}7func main() {8 fmt.Println("Type of e is: ", reflect.TypeOf(e))9 fmt.Println("Value of e is: ", reflect.ValueOf(e))10 fmt.Println("Address of e is: ", &e)11 fmt.Println("Type of e is: ", reflect.TypeOf(&e))12 fmt.Println("Value of e is: ", reflect.ValueOf(&e))13 fmt.Println("Address of e is: ", &e)14 fmt.Println("Type of e is: ", reflect.TypeOf(e))15 fmt.Println("Value of e is: ", reflect.ValueOf(e))16 fmt.Println("Address of e is: ", &e)17}
Connection
Using AI Code Generation
1import (2type execution struct {3 Connection func() string4}5func main() {6 exec := execution{}7 exec.Connection = func() string {8 }9 value := reflect.ValueOf(exec).FieldByName("Connection")10 if value.IsValid() {11 if value.Kind() == reflect.Func {12 values := value.Call(nil)13 if len(values) > 0 {14 if result.IsValid() {15 if result.Kind() == reflect.String {16 fmt.Println(result.String())17 }18 }19 }20 }21 }22}
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!!