Best K6 code snippet using js.New
jetstream_test.go
Source:jetstream_test.go
...74 defer testEnvironment.natsServer.Shutdown()75 defer testEnvironment.jsClient.natsConn.Close()76 initErr := jsBackend.Initialize(nil)77 require.NoError(t, initErr)78 // create New Subscriber79 subscriber := evtesting.NewSubscriber()80 defer subscriber.Shutdown()81 require.True(t, subscriber.IsRunning())82 defaultMaxInflight := 983 defaultSubsConfig := env.DefaultSubscriptionConfig{MaxInFlightMessages: defaultMaxInflight}84 // create a new Subscription85 sub := evtesting.NewSubscription("sub", "foo",86 evtesting.WithNotCleanFilter(),87 evtesting.WithSinkURL(subscriber.SinkURL),88 evtesting.WithStatusConfig(defaultSubsConfig),89 )90 addJSCleanEventTypesToStatus(sub, testEnvironment.cleaner, jsBackend)91 // when92 err := jsBackend.SyncSubscription(sub)93 // then94 require.NoError(t, err)95 data := "sampledata"96 require.NoError(t, SendEventToJetStream(jsBackend, data))97 expectedDataInStore := fmt.Sprintf("\"%s\"", data)98 require.NoError(t, subscriber.CheckEvent(expectedDataInStore))99 // when100 require.NoError(t, jsBackend.DeleteSubscription(sub))101 // then102 newData := "test-data"103 require.NoError(t, SendEventToJetStream(jsBackend, newData))104 // Check for the event that it did not reach subscriber105 notExpectedNewDataInStore := fmt.Sprintf("\"%s\"", newData)106 require.Error(t, subscriber.CheckEvent(notExpectedNewDataInStore))107}108// TestJetStreamSubAfterSync_NoChange tests the SyncSubscription method109// when there is no change in the subscription then the method should110// not re-create NATS subjects on nats-server.111func TestJetStreamSubAfterSync_NoChange(t *testing.T) {112 // given113 testEnvironment := setupTestEnvironment(t)114 jsBackend := testEnvironment.jsBackend115 defer testEnvironment.natsServer.Shutdown()116 defer testEnvironment.jsClient.natsConn.Close()117 initErr := jsBackend.Initialize(nil)118 require.NoError(t, initErr)119 // create New Subscribers120 subscriber1 := evtesting.NewSubscriber()121 defer subscriber1.Shutdown()122 require.True(t, subscriber1.IsRunning())123 defaultMaxInflight := 9124 defaultSubsConfig := env.DefaultSubscriptionConfig{MaxInFlightMessages: defaultMaxInflight}125 // create a new Subscription126 sub := evtesting.NewSubscription("sub", "foo",127 evtesting.WithNotCleanFilter(),128 evtesting.WithSinkURL(subscriber1.SinkURL),129 evtesting.WithStatusConfig(defaultSubsConfig),130 )131 addJSCleanEventTypesToStatus(sub, testEnvironment.cleaner, jsBackend)132 // when133 err := jsBackend.SyncSubscription(sub)134 // then135 require.NoError(t, err)136 // get cleaned subject137 subject, err := getCleanSubject(sub.Spec.Filter.Filters[0], testEnvironment.cleaner)138 require.NoError(t, err)139 require.NotEmpty(t, subject)140 // test if subscription is working properly by sending an event141 // and checking if it is received by the subscriber142 data := fmt.Sprintf("data-%s", time.Now().Format(time.RFC850))143 expectedDataInStore := fmt.Sprintf("\"%s\"", data)144 require.NoError(t, SendEventToJetStream(jsBackend, data))145 require.NoError(t, subscriber1.CheckEvent(expectedDataInStore))146 // set metadata on NATS subscriptions147 msgLimit, bytesLimit := 2048, 2048148 require.Len(t, jsBackend.subscriptions, 1)149 for _, jsSub := range jsBackend.subscriptions {150 require.True(t, jsSub.IsValid())151 require.NoError(t, jsSub.SetPendingLimits(msgLimit, bytesLimit))152 }153 // given154 // no change in subscription155 // when156 err = jsBackend.SyncSubscription(sub)157 // then158 require.NoError(t, err)159 // check if the NATS subscription are the same (have same metadata)160 // by comparing the metadata of nats subscription161 require.Len(t, jsBackend.subscriptions, 1)162 jsSubject := jsBackend.GetJsSubjectToSubscribe(subject)163 jsSubKey := jsBackend.GenerateJsSubKey(jsSubject, sub)164 jsSub := jsBackend.subscriptions[jsSubKey]165 require.NotNil(t, jsSub)166 require.True(t, jsSub.IsValid())167 // check the metadata, if they are now same then it means that NATS subscription168 // were not re-created by SyncSubscription method169 subMsgLimit, subBytesLimit, err := jsSub.PendingLimits()170 require.NoError(t, err)171 require.Equal(t, subMsgLimit, msgLimit)172 require.Equal(t, subBytesLimit, bytesLimit)173 // test if subscription is working properly by sending an event174 // and checking if it is received by the subscriber175 data = fmt.Sprintf("data-%s", time.Now().Format(time.RFC850))176 expectedDataInStore = fmt.Sprintf("\"%s\"", data)177 require.NoError(t, SendEventToJetStream(jsBackend, data))178 require.NoError(t, subscriber1.CheckEvent(expectedDataInStore))179}180// TestJetStreamSubAfterSync_SinkChange tests the SyncSubscription method181// when only the sink is changed in subscription, then it should not re-create182// NATS subjects on nats-server.183func TestJetStreamSubAfterSync_SinkChange(t *testing.T) {184 // given185 testEnvironment := setupTestEnvironment(t)186 jsBackend := testEnvironment.jsBackend187 defer testEnvironment.natsServer.Shutdown()188 defer testEnvironment.jsClient.natsConn.Close()189 initErr := jsBackend.Initialize(nil)190 require.NoError(t, initErr)191 // create New Subscribers192 subscriber1 := evtesting.NewSubscriber()193 defer subscriber1.Shutdown()194 require.True(t, subscriber1.IsRunning())195 subscriber2 := evtesting.NewSubscriber()196 defer subscriber2.Shutdown()197 require.True(t, subscriber2.IsRunning())198 defaultMaxInflight := 9199 defaultSubsConfig := env.DefaultSubscriptionConfig{MaxInFlightMessages: defaultMaxInflight}200 // create a new Subscription201 sub := evtesting.NewSubscription("sub", "foo",202 evtesting.WithNotCleanFilter(),203 evtesting.WithSinkURL(subscriber1.SinkURL),204 evtesting.WithStatusConfig(defaultSubsConfig),205 )206 addJSCleanEventTypesToStatus(sub, testEnvironment.cleaner, jsBackend)207 // when208 err := jsBackend.SyncSubscription(sub)209 // then210 require.NoError(t, err)211 // get cleaned subject212 subject, err := getCleanSubject(sub.Spec.Filter.Filters[0], testEnvironment.cleaner)213 require.NoError(t, err)214 require.NotEmpty(t, subject)215 // test if subscription is working properly by sending an event216 // and checking if it is received by the subscriber217 data := fmt.Sprintf("data-%s", time.Now().Format(time.RFC850))218 expectedDataInStore := fmt.Sprintf("\"%s\"", data)219 require.NoError(t, SendEventToJetStream(jsBackend, data))220 require.NoError(t, subscriber1.CheckEvent(expectedDataInStore))221 // set metadata on NATS subscriptions222 msgLimit, bytesLimit := 2048, 2048223 require.Len(t, jsBackend.subscriptions, 1)224 for _, jsSub := range jsBackend.subscriptions {225 require.True(t, jsSub.IsValid())226 require.NoError(t, jsSub.SetPendingLimits(msgLimit, bytesLimit))227 }228 // given229 // NATS subscription should not be re-created in sync when sink is changed.230 // change the sink231 sub.Spec.Sink = subscriber2.SinkURL232 // when233 err = jsBackend.SyncSubscription(sub)234 // then235 require.NoError(t, err)236 // check if the NATS subscription are the same (have same metadata)237 // by comparing the metadata of nats subscription238 require.Len(t, jsBackend.subscriptions, 1)239 jsSubject := jsBackend.GetJsSubjectToSubscribe(subject)240 jsSubKey := jsBackend.GenerateJsSubKey(jsSubject, sub)241 jsSub := jsBackend.subscriptions[jsSubKey]242 require.NotNil(t, jsSub)243 require.True(t, jsSub.IsValid())244 // check the metadata, if they are now same then it means that NATS subscription245 // were not re-created by SyncSubscription method246 subMsgLimit, subBytesLimit, err := jsSub.PendingLimits()247 require.NoError(t, err)248 require.Equal(t, subMsgLimit, msgLimit)249 require.Equal(t, subBytesLimit, bytesLimit)250 // Test if the subscription is working for new sink only251 data = fmt.Sprintf("data-%s", time.Now().Format(time.RFC850))252 expectedDataInStore = fmt.Sprintf("\"%s\"", data)253 require.NoError(t, SendEventToJetStream(jsBackend, data))254 // Old sink should not have received the event, the new sink should have255 require.Error(t, subscriber1.CheckEvent(expectedDataInStore))256 require.NoError(t, subscriber2.CheckEvent(expectedDataInStore))257}258// TestJetStreamSubAfterSync_FiltersChange tests the SyncSubscription method259// when the filters are changed in subscription.260func TestJetStreamSubAfterSync_FiltersChange(t *testing.T) {261 // given262 testEnvironment := setupTestEnvironment(t)263 jsBackend := testEnvironment.jsBackend264 defer testEnvironment.natsServer.Shutdown()265 defer testEnvironment.jsClient.natsConn.Close()266 initErr := jsBackend.Initialize(nil)267 require.NoError(t, initErr)268 subscriber := evtesting.NewSubscriber()269 defer subscriber.Shutdown()270 require.True(t, subscriber.IsRunning())271 defaultMaxInflight := 9272 defaultSubsConfig := env.DefaultSubscriptionConfig{MaxInFlightMessages: defaultMaxInflight}273 sub := evtesting.NewSubscription("sub", "foo",274 evtesting.WithNotCleanFilter(),275 evtesting.WithSinkURL(subscriber.SinkURL),276 evtesting.WithStatusConfig(defaultSubsConfig),277 )278 addJSCleanEventTypesToStatus(sub, testEnvironment.cleaner, jsBackend)279 // when280 err := jsBackend.SyncSubscription(sub)281 // then282 require.NoError(t, err)283 // get cleaned subject284 subject, err := getCleanSubject(sub.Spec.Filter.Filters[0], testEnvironment.cleaner)285 require.NoError(t, err)286 require.NotEmpty(t, subject)287 // test if subscription is working properly by sending an event288 // and checking if it is received by the subscriber289 data := fmt.Sprintf("data-%s", time.Now().Format(time.RFC850))290 expectedDataInStore := fmt.Sprintf("\"%s\"", data)291 require.NoError(t, SendEventToJetStream(jsBackend, data))292 require.NoError(t, subscriber.CheckEvent(expectedDataInStore))293 // set metadata on NATS subscriptions294 // so that we can later verify if the nats subscriptions are the same (not re-created by Sync)295 msgLimit, bytesLimit := 2048, 2048296 require.Len(t, jsBackend.subscriptions, 1)297 for _, jsSub := range jsBackend.subscriptions {298 require.True(t, jsSub.IsValid())299 require.NoError(t, jsSub.SetPendingLimits(msgLimit, bytesLimit))300 }301 // given302 // Now, change the filter in subscription303 sub.Spec.Filter.Filters[0].EventType.Value = fmt.Sprintf("%schanged", evtesting.OrderCreatedEventTypeNotClean)304 // Sync the subscription status305 addJSCleanEventTypesToStatus(sub, testEnvironment.cleaner, jsBackend)306 // when307 err = jsBackend.SyncSubscription(sub)308 // then309 require.NoError(t, err)310 // get new cleaned subject311 newSubject, err := getCleanSubject(sub.Spec.Filter.Filters[0], testEnvironment.cleaner)312 require.NoError(t, err)313 require.NotEmpty(t, newSubject)314 // check if the NATS subscription are NOT the same after sync315 // because the subscriptions should have being re-created for new subject316 require.Len(t, jsBackend.subscriptions, 1)317 jsSubject := jsBackend.GetJsSubjectToSubscribe(newSubject)318 jsSubKey := jsBackend.GenerateJsSubKey(jsSubject, sub)319 jsSub := jsBackend.subscriptions[jsSubKey]320 require.NotNil(t, jsSub)321 require.True(t, jsSub.IsValid())322 // check the metadata, if they are NOT same then it means that NATS subscription323 // were re-created by SyncSubscription method324 subMsgLimit, subBytesLimit, err := jsSub.PendingLimits()325 require.NoError(t, err)326 require.NotEqual(t, subMsgLimit, msgLimit)327 require.NotEqual(t, subBytesLimit, bytesLimit)328 // Test if subscription is working for new subject only329 data = fmt.Sprintf("data-%s", time.Now().Format(time.RFC850))330 expectedDataInStore = fmt.Sprintf("\"%s\"", data)331 // Send an event on old subject332 require.NoError(t, SendEventToJetStream(jsBackend, data))333 // The sink should not receive any event for old subject334 require.Error(t, subscriber.CheckEvent(expectedDataInStore))335 // Now, send an event on new subject336 require.NoError(t, SendEventToJetStreamOnEventType(jsBackend, newSubject, data))337 // The sink should receive the event for new subject338 require.NoError(t, subscriber.CheckEvent(expectedDataInStore))339}340// TestJetStreamSubAfterSync_FilterAdded tests the SyncSubscription method341// when a new filter is added in subscription.342func TestJetStreamSubAfterSync_FilterAdded(t *testing.T) {343 // given344 testEnvironment := setupTestEnvironment(t)345 jsBackend := testEnvironment.jsBackend346 defer testEnvironment.natsServer.Shutdown()347 defer testEnvironment.jsClient.natsConn.Close()348 initErr := jsBackend.Initialize(nil)349 require.NoError(t, initErr)350 // Create a new subscriber351 subscriber := evtesting.NewSubscriber()352 defer subscriber.Shutdown()353 require.True(t, subscriber.IsRunning())354 defaultMaxInflight := 9355 defaultSubsConfig := env.DefaultSubscriptionConfig{MaxInFlightMessages: defaultMaxInflight}356 // Create a subscription with single filter357 sub := evtesting.NewSubscription("sub", "foo",358 evtesting.WithNotCleanFilter(),359 evtesting.WithSinkURL(subscriber.SinkURL),360 evtesting.WithStatusConfig(defaultSubsConfig),361 )362 addJSCleanEventTypesToStatus(sub, testEnvironment.cleaner, jsBackend)363 // when364 err := jsBackend.SyncSubscription(sub)365 // then366 require.NoError(t, err)367 // get cleaned subject368 firstSubject, err := getCleanSubject(sub.Spec.Filter.Filters[0], testEnvironment.cleaner)369 require.NoError(t, err)370 require.NotEmpty(t, firstSubject)371 // set metadata on NATS subscriptions372 // so that we can later verify if the nats subscriptions are the same (not re-created by Sync)373 msgLimit, bytesLimit := 2048, 2048374 require.Len(t, jsBackend.subscriptions, 1)375 for _, jsSub := range jsBackend.subscriptions {376 require.True(t, jsSub.IsValid())377 require.NoError(t, jsSub.SetPendingLimits(msgLimit, bytesLimit))378 }379 // Now, add a new filter to subscription380 newFilter := sub.Spec.Filter.Filters[0].DeepCopy()381 newFilter.EventType.Value = fmt.Sprintf("%snew1", evtesting.OrderCreatedEventTypeNotClean)382 sub.Spec.Filter.Filters = append(sub.Spec.Filter.Filters, newFilter)383 // get new cleaned subject384 secondSubject, err := getCleanSubject(newFilter, testEnvironment.cleaner)385 require.NoError(t, err)386 require.NotEmpty(t, secondSubject)387 addJSCleanEventTypesToStatus(sub, testEnvironment.cleaner, jsBackend)388 // when389 err = jsBackend.SyncSubscription(sub)390 // then391 require.NoError(t, err)392 // Check if total existing NATS subscriptions are correct393 // Because we have two filters (i.e. two subjects)394 require.Len(t, jsBackend.subscriptions, 2)395 // Verify that the nats subscriptions for first subject was not re-created396 jsSubject := jsBackend.GetJsSubjectToSubscribe(firstSubject)397 jsSubKey := jsBackend.GenerateJsSubKey(jsSubject, sub)398 jsSub := jsBackend.subscriptions[jsSubKey]399 require.NotNil(t, jsSub)400 require.True(t, jsSub.IsValid())401 // check the metadata, if they are now same then it means that NATS subscription402 // were not re-created by SyncSubscription method403 subMsgLimit, subBytesLimit, err := jsSub.PendingLimits()404 require.NoError(t, err)405 require.Equal(t, subMsgLimit, msgLimit)406 require.Equal(t, subBytesLimit, bytesLimit)407 // Test if subscription is working for both subjects408 // Send an event on first subject409 data := fmt.Sprintf("data-%s", time.Now().Format(time.RFC850))410 expectedDataInStore := fmt.Sprintf("\"%s\"", data)411 require.NoError(t, SendEventToJetStream(jsBackend, data))412 // The sink should receive event for first subject413 require.NoError(t, subscriber.CheckEvent(expectedDataInStore))414 // Now, send an event on second subject415 data = fmt.Sprintf("data-%s", time.Now().Format(time.RFC850))416 expectedDataInStore = fmt.Sprintf("\"%s\"", data)417 require.NoError(t, SendEventToJetStreamOnEventType(jsBackend, secondSubject, data))418 // The sink should receive the event for second subject419 require.NoError(t, subscriber.CheckEvent(expectedDataInStore))420}421// TestJetStreamSubAfterSync_FilterRemoved tests the SyncSubscription method422// when a filter is removed from subscription.423func TestJetStreamSubAfterSync_FilterRemoved(t *testing.T) {424 // given425 testEnvironment := setupTestEnvironment(t)426 jsBackend := testEnvironment.jsBackend427 defer testEnvironment.natsServer.Shutdown()428 defer testEnvironment.jsClient.natsConn.Close()429 initErr := jsBackend.Initialize(nil)430 require.NoError(t, initErr)431 // Create a new subscriber432 subscriber := evtesting.NewSubscriber()433 defer subscriber.Shutdown()434 require.True(t, subscriber.IsRunning())435 defaultMaxInflight := 9436 defaultSubsConfig := env.DefaultSubscriptionConfig{MaxInFlightMessages: defaultMaxInflight}437 // Create a subscription with two filters438 sub := evtesting.NewSubscription("sub", "foo",439 evtesting.WithNotCleanFilter(),440 evtesting.WithSinkURL(subscriber.SinkURL),441 evtesting.WithStatusConfig(defaultSubsConfig),442 )443 // add a second filter444 newFilter := sub.Spec.Filter.Filters[0].DeepCopy()445 newFilter.EventType.Value = fmt.Sprintf("%snew1", evtesting.OrderCreatedEventTypeNotClean)446 sub.Spec.Filter.Filters = append(sub.Spec.Filter.Filters, newFilter)447 addJSCleanEventTypesToStatus(sub, testEnvironment.cleaner, jsBackend)448 // when449 err := jsBackend.SyncSubscription(sub)450 // then451 require.NoError(t, err)452 // get cleaned subjects453 firstSubject, err := getCleanSubject(sub.Spec.Filter.Filters[0], testEnvironment.cleaner)454 require.NoError(t, err)455 require.NotEmpty(t, firstSubject)456 secondSubject, err := getCleanSubject(sub.Spec.Filter.Filters[1], testEnvironment.cleaner)457 require.NoError(t, err)458 require.NotEmpty(t, secondSubject)459 // Check if total existing NATS subscriptions are correct460 // Because we have two filters (i.e. two subjects)461 require.Len(t, jsBackend.subscriptions, 2)462 // set metadata on NATS subscriptions463 // so that we can later verify if the nats subscriptions are the same (not re-created by Sync)464 msgLimit, bytesLimit := 2048, 2048465 for _, jsSub := range jsBackend.subscriptions {466 require.True(t, jsSub.IsValid())467 require.NoError(t, jsSub.SetPendingLimits(msgLimit, bytesLimit))468 }469 // given470 // Now, remove the second filter from subscription471 sub.Spec.Filter.Filters = sub.Spec.Filter.Filters[:1]472 addJSCleanEventTypesToStatus(sub, testEnvironment.cleaner, jsBackend)473 // when474 err = jsBackend.SyncSubscription(sub)475 // then476 require.NoError(t, err)477 // Check if total existing NATS subscriptions are correct478 require.Len(t, jsBackend.subscriptions, 1)479 // Verify that the nats subscriptions for first subject was not re-created480 jsSubject := jsBackend.GetJsSubjectToSubscribe(firstSubject)481 jsSubKey := jsBackend.GenerateJsSubKey(jsSubject, sub)482 jsSub := jsBackend.subscriptions[jsSubKey]483 require.NotNil(t, jsSub)484 require.True(t, jsSub.IsValid())485 // check the metadata, if they are now same then it means that NATS subscription486 // were not re-created by SyncSubscription method487 subMsgLimit, subBytesLimit, err := jsSub.PendingLimits()488 require.NoError(t, err)489 require.Equal(t, subMsgLimit, msgLimit)490 require.Equal(t, subBytesLimit, bytesLimit)491 // Test if subscription is working for first subject only492 // Send an event on first subject493 data := fmt.Sprintf("data-%s", time.Now().Format(time.RFC850))494 expectedDataInStore := fmt.Sprintf("\"%s\"", data)495 require.NoError(t, SendEventToJetStream(jsBackend, data))496 // The sink should receive event for first subject497 require.NoError(t, subscriber.CheckEvent(expectedDataInStore))498 // Now, send an event on second subject499 data = fmt.Sprintf("data-%s", time.Now().Format(time.RFC850))500 expectedDataInStore = fmt.Sprintf("\"%s\"", data)501 require.NoError(t, SendEventToJetStreamOnEventType(jsBackend, secondSubject, data))502 // The sink should NOT receive the event for second subject503 require.Error(t, subscriber.CheckEvent(expectedDataInStore))504}505// TestJetStreamSubAfterSync_MultipleSubs tests the SyncSubscription method506// when there are two subscriptions and the filter is changed in one subscription507// it should not affect the NATS subscriptions of other Kyma subscriptions.508func TestJetStreamSubAfterSync_MultipleSubs(t *testing.T) {509 // given510 testEnvironment := setupTestEnvironment(t)511 jsBackend := testEnvironment.jsBackend512 defer testEnvironment.natsServer.Shutdown()513 defer testEnvironment.jsClient.natsConn.Close()514 initErr := jsBackend.Initialize(nil)515 require.NoError(t, initErr)516 // Create a new subscriber517 subscriber := evtesting.NewSubscriber()518 defer subscriber.Shutdown()519 require.True(t, subscriber.IsRunning())520 defaultMaxInflight := 9521 defaultSubsConfig := env.DefaultSubscriptionConfig{MaxInFlightMessages: defaultMaxInflight}522 // Create two subscriptions with single filter523 sub := evtesting.NewSubscription("sub", "foo",524 evtesting.WithNotCleanFilter(),525 evtesting.WithSinkURL(subscriber.SinkURL),526 evtesting.WithStatusConfig(defaultSubsConfig),527 )528 addJSCleanEventTypesToStatus(sub, testEnvironment.cleaner, jsBackend)529 // when530 err := jsBackend.SyncSubscription(sub)531 // then532 require.NoError(t, err)533 // given534 sub2 := evtesting.NewSubscription("sub2", "foo",535 evtesting.WithNotCleanFilter(),536 evtesting.WithSinkURL(subscriber.SinkURL),537 evtesting.WithStatusConfig(defaultSubsConfig),538 )539 addJSCleanEventTypesToStatus(sub2, testEnvironment.cleaner, jsBackend)540 // when541 err = jsBackend.SyncSubscription(sub2)542 // then543 require.NoError(t, err)544 // Check if total existing NATS subscriptions are correct545 // Because we have two subscriptions546 require.Len(t, jsBackend.subscriptions, 2)547 // set metadata on NATS subscriptions548 // so that we can later verify if the nats subscriptions are the same (not re-created by Sync)549 msgLimit, bytesLimit := 2048, 2048550 for _, jsSub := range jsBackend.subscriptions {551 require.True(t, jsSub.IsValid())552 require.NoError(t, jsSub.SetPendingLimits(msgLimit, bytesLimit))553 }554 // Now, change the filter in subscription 1555 sub.Spec.Filter.Filters[0].EventType.Value = fmt.Sprintf("%schanged", evtesting.OrderCreatedEventTypeNotClean)556 addJSCleanEventTypesToStatus(sub, testEnvironment.cleaner, jsBackend)557 // when558 err = jsBackend.SyncSubscription(sub)559 // then560 require.NoError(t, err)561 // get new cleaned subject from subscription 1562 newSubject, err := getCleanSubject(sub.Spec.Filter.Filters[0], testEnvironment.cleaner)563 require.NoError(t, err)564 require.NotEmpty(t, newSubject)565 // Check if total existing NATS subscriptions are correct566 // Because we have two subscriptions567 require.Len(t, jsBackend.subscriptions, 2)568 // check if the NATS subscription are NOT the same after sync for subscription 1569 // because the subscriptions should have being re-created for new subject570 jsSubject := jsBackend.GetJsSubjectToSubscribe(newSubject)571 jsSubKey := jsBackend.GenerateJsSubKey(jsSubject, sub)572 jsSub := jsBackend.subscriptions[jsSubKey]573 require.NotNil(t, jsSub)574 require.True(t, jsSub.IsValid())575 // check the metadata, if they are now same then it means that NATS subscription576 // were not re-created by SyncSubscription method577 subMsgLimit, subBytesLimit, err := jsSub.PendingLimits()578 require.NoError(t, err)579 require.NotEqual(t, subMsgLimit, msgLimit)580 require.NotEqual(t, subBytesLimit, bytesLimit)581 // get cleaned subject for subscription 2582 cleanSubjectSub2, err := getCleanSubject(sub2.Spec.Filter.Filters[0], testEnvironment.cleaner)583 require.NoError(t, err)584 require.NotEmpty(t, cleanSubjectSub2)585 // check if the NATS subscription are same after sync for subscription 2586 // because the subscriptions should NOT have being re-created as587 // subscription 2 was not modified588 jsSubject = jsBackend.GetJsSubjectToSubscribe(cleanSubjectSub2)589 jsSubKey = jsBackend.GenerateJsSubKey(jsSubject, sub2)590 jsSub = jsBackend.subscriptions[jsSubKey]591 require.NotNil(t, jsSub)592 require.True(t, jsSub.IsValid())593 // check the metadata, if they are now same then it means that NATS subscription594 // were not re-created by SyncSubscription method595 subMsgLimit, subBytesLimit, err = jsSub.PendingLimits()596 require.NoError(t, err)597 require.Equal(t, subMsgLimit, msgLimit)598 require.Equal(t, subBytesLimit, bytesLimit)599}600// TestJetStream_isJsSubAssociatedWithKymaSub tests the isJsSubAssociatedWithKymaSub method.601func TestJetStream_isJsSubAssociatedWithKymaSub(t *testing.T) {602 // given603 testEnvironment := setupTestEnvironment(t)604 jsBackend := testEnvironment.jsBackend605 defer testEnvironment.natsServer.Shutdown()606 defer testEnvironment.jsClient.natsConn.Close()607 initErr := jsBackend.Initialize(nil)608 require.NoError(t, initErr)609 // create subscription 1 and its JetStream subscription610 cleanSubject1 := "subOne"611 sub1 := evtesting.NewSubscription(cleanSubject1, "foo", evtesting.WithNotCleanFilter())612 jsSub1Key := jsBackend.GenerateJsSubKey(613 jsBackend.GetJsSubjectToSubscribe(cleanSubject1),614 sub1)615 // create subscription 2 and its JetStream subscription616 cleanSubject2 := "subOneTwo"617 sub2 := evtesting.NewSubscription(cleanSubject2, "foo", evtesting.WithNotCleanFilter())618 jsSub2Key := jsBackend.GenerateJsSubKey(619 jsBackend.GetJsSubjectToSubscribe(cleanSubject2),620 sub2)621 testCases := []struct {622 name string623 givenJSSubKey string624 givenKymaSubKey *eventingv1alpha1.Subscription625 wantResult bool626 }{627 {628 name: "",629 givenJSSubKey: jsSub1Key,630 givenKymaSubKey: sub1,631 wantResult: true,632 },633 {634 name: "",635 givenJSSubKey: jsSub2Key,636 givenKymaSubKey: sub2,637 wantResult: true,638 },639 {640 name: "",641 givenJSSubKey: jsSub1Key,642 givenKymaSubKey: sub2,643 wantResult: false,644 },645 {646 name: "",647 givenJSSubKey: jsSub2Key,648 givenKymaSubKey: sub1,649 wantResult: false,650 },651 }652 for _, tC := range testCases {653 testCase := tC654 t.Run(testCase.name, func(t *testing.T) {655 gotResult, err := jsBackend.isJsSubAssociatedWithKymaSub(656 tC.givenJSSubKey,657 tC.givenKymaSubKey)658 require.Equal(t, gotResult, tC.wantResult)659 require.NoError(t, err)660 })661 }662}663// TestMultipleJSSubscriptionsToSameEvent tests the behaviour of JS664// when multiple subscriptions need to receive the same event.665func TestMultipleJSSubscriptionsToSameEvent(t *testing.T) {666 // given667 testEnvironment := setupTestEnvironment(t)668 jsBackend := testEnvironment.jsBackend669 defer testEnvironment.natsServer.Shutdown()670 defer testEnvironment.jsClient.natsConn.Close()671 initErr := jsBackend.Initialize(nil)672 require.NoError(t, initErr)673 defaultMaxInflight := 1674 defaultSubsConfig := env.DefaultSubscriptionConfig{MaxInFlightMessages: defaultMaxInflight}675 subscriber := evtesting.NewSubscriber()676 defer subscriber.Shutdown()677 require.True(t, subscriber.IsRunning())678 // Create 3 subscriptions having the same sink and the same event type679 var subs [3]*eventingv1alpha1.Subscription680 for i := 0; i < len(subs); i++ {681 subs[i] = evtesting.NewSubscription(fmt.Sprintf("sub-%d", i), "foo",682 evtesting.WithNotCleanFilter(),683 evtesting.WithSinkURL(subscriber.SinkURL),684 evtesting.WithStatusConfig(defaultSubsConfig),685 )686 addJSCleanEventTypesToStatus(subs[i], testEnvironment.cleaner, jsBackend)687 // when688 err := jsBackend.SyncSubscription(subs[i])689 // then690 require.NoError(t, err)691 }692 // Send only one event. It should be multiplexed to 3 by NATS, cause 3 subscriptions exist693 data := "sampledata"694 require.NoError(t, SendEventToJetStream(jsBackend, data))695 // Check for the 3 events that should be received by the subscriber696 expectedDataInStore := fmt.Sprintf("\"%s\"", data)697 for i := 0; i < len(subs); i++ {698 require.NoError(t, subscriber.CheckEvent(expectedDataInStore))699 }700 // Delete all 3 subscription701 for i := 0; i < len(subs); i++ {702 require.NoError(t, jsBackend.DeleteSubscription(subs[i]))703 }704 // Check if all subscriptions are deleted in NATS705 // Send an event again which should not be delivered to subscriber706 newData := "test-data"707 require.NoError(t, SendEventToJetStream(jsBackend, newData))708 // Check for the event that did not reach the subscriber709 // Store should never return newdata hence CheckEvent should fail to match newdata710 notExpectedNewDataInStore := fmt.Sprintf("\"%s\"", newData)711 require.Error(t, subscriber.CheckEvent(notExpectedNewDataInStore))712}713// TestJSSubscriptionWithDuplicateFilters tests the subscription behaviour714// when duplicate filters are added.715func TestJSSubscriptionWithDuplicateFilters(t *testing.T) {716 // given717 testEnvironment := setupTestEnvironment(t)718 jsBackend := testEnvironment.jsBackend719 defer testEnvironment.natsServer.Shutdown()720 defer testEnvironment.jsClient.natsConn.Close()721 initErr := jsBackend.Initialize(nil)722 require.NoError(t, initErr)723 defaultSubsConfig := env.DefaultSubscriptionConfig{MaxInFlightMessages: 9}724 subscriber := evtesting.NewSubscriber()725 defer subscriber.Shutdown()726 require.True(t, subscriber.IsRunning())727 sub := evtesting.NewSubscription("sub", "foo",728 evtesting.WithFilter("", evtesting.OrderCreatedEventType),729 evtesting.WithFilter("", evtesting.OrderCreatedEventType),730 evtesting.WithSinkURL(subscriber.SinkURL),731 evtesting.WithStatusConfig(defaultSubsConfig),732 )733 addJSCleanEventTypesToStatus(sub, testEnvironment.cleaner, jsBackend)734 // when735 err := jsBackend.SyncSubscription(sub)736 // then737 require.NoError(t, err)738 data := "sampledata"739 require.NoError(t, SendEventToJetStream(jsBackend, data))740 expectedDataInStore := fmt.Sprintf("\"%s\"", data)741 require.NoError(t, subscriber.CheckEvent(expectedDataInStore))742 // There should be no more!743 require.Error(t, subscriber.CheckEvent(expectedDataInStore))744}745// TestJSSubscriptionWithMaxInFlightChange tests the maxAckPending746// to be equal to the MaxInFlightMessages when the server is not running.747func TestJSSubscriptionWithMaxInFlightChange(t *testing.T) {748 // given749 testEnvironment := setupTestEnvironment(t)750 jsBackend := testEnvironment.jsBackend751 defer testEnvironment.natsServer.Shutdown()752 defer testEnvironment.jsClient.natsConn.Close()753 initErr := jsBackend.Initialize(nil)754 require.NoError(t, initErr)755 // create New Subscriber756 subscriber := evtesting.NewSubscriber()757 subscriber.Shutdown() // shutdown the subscriber intentionally here758 require.False(t, subscriber.IsRunning())759 defaultMaxInflight := 16760 defaultSubsConfig := env.DefaultSubscriptionConfig{MaxInFlightMessages: defaultMaxInflight}761 // create a new Subscription762 sub := evtesting.NewSubscription("sub", "foo",763 evtesting.WithNotCleanFilter(),764 evtesting.WithSinkURL(subscriber.SinkURL),765 evtesting.WithStatusConfig(defaultSubsConfig),766 )767 addJSCleanEventTypesToStatus(sub, testEnvironment.cleaner, jsBackend)768 // when769 err := jsBackend.SyncSubscription(sub)770 // then771 require.NoError(t, err)772 // when773 // send 2 * defaultMaxInflight number of events774 for i := 0; i < 2*defaultMaxInflight; i++ {775 data := fmt.Sprintf("sampledata%d", i)776 require.NoError(t, SendEventToJetStream(jsBackend, data))777 }778 // then779 require.Eventually(t, func() bool {780 consumerName := jsBackend.GenerateJsSubKey(sub.Status.CleanEventTypes[0], sub)781 // fetch consumer info from JetStream782 consumerInfo, err := jsBackend.jsCtx.ConsumerInfo(jsBackend.config.JSStreamName, consumerName)783 require.NoError(t, err)784 // since our subscriber is not in running state,785 // so these events will be pending for receiving an ACK from dispatchers786 // check consumer current maxAckPending787 return consumerInfo.NumAckPending == defaultMaxInflight788 }, 10*time.Second, 200*time.Millisecond)789}790// TestJSSubscriptionUsingCESDK tests that eventing works with Cloud events.791func TestJSSubscriptionUsingCESDK(t *testing.T) {792 // given793 testEnvironment := setupTestEnvironment(t)794 jsBackend := testEnvironment.jsBackend795 defer testEnvironment.natsServer.Shutdown()796 defer testEnvironment.jsClient.natsConn.Close()797 initErr := jsBackend.Initialize(nil)798 require.NoError(t, initErr)799 defaultSubsConfig := env.DefaultSubscriptionConfig{MaxInFlightMessages: 1}800 subscriber := evtesting.NewSubscriber()801 defer subscriber.Shutdown()802 require.True(t, subscriber.IsRunning())803 sub := evtesting.NewSubscription("sub", "foo",804 evtesting.WithOrderCreatedFilter(),805 evtesting.WithSinkURL(subscriber.SinkURL),806 evtesting.WithStatusConfig(defaultSubsConfig),807 )808 addJSCleanEventTypesToStatus(sub, testEnvironment.cleaner, jsBackend)809 // when810 err := jsBackend.SyncSubscription(sub)811 // then812 require.NoError(t, err)813 subject := evtesting.CloudEventType814 require.NoError(t, SendBinaryCloudEventToJetStream(jsBackend, jsBackend.GetJsSubjectToSubscribe(subject), evtesting.CloudEventData))815 require.NoError(t, subscriber.CheckEvent(evtesting.CloudEventData))816 require.NoError(t, SendStructuredCloudEventToJetStream(jsBackend, jsBackend.GetJsSubjectToSubscribe(subject), evtesting.StructuredCloudEvent))817 require.NoError(t, subscriber.CheckEvent("\""+evtesting.EventData+"\""))818 require.NoError(t, jsBackend.DeleteSubscription(sub))819}820func TestJetStreamServerRestart_WithReconnectDisabled(t *testing.T) {821 // given822 testEnvironment := setupTestEnvironment(t)823 jsBackend := testEnvironment.jsBackend824 defer testEnvironment.natsServer.Shutdown()825 defer testEnvironment.jsClient.natsConn.Close()826 // Do not reconnect once server is shutdown827 jsBackend.config.MaxReconnects = 0828 initErr := jsBackend.Initialize(nil)829 require.NoError(t, initErr)830 defaultSubsConfig := env.DefaultSubscriptionConfig{MaxInFlightMessages: 10}831 subscriber := evtesting.NewSubscriber()832 defer subscriber.Shutdown()833 require.True(t, subscriber.IsRunning())834 // Create a subscription835 sub := evtesting.NewSubscription("sub", "foo",836 evtesting.WithNotCleanFilter(),837 evtesting.WithSinkURL(subscriber.SinkURL),838 evtesting.WithStatusConfig(defaultSubsConfig),839 )840 addJSCleanEventTypesToStatus(sub, testEnvironment.cleaner, jsBackend)841 // when842 err := jsBackend.SyncSubscription(sub)843 // then844 require.NoError(t, err)845 ev1data := "sampledata"846 require.NoError(t, SendEventToJetStream(jsBackend, ev1data))847 expectedEv1Data := fmt.Sprintf("\"%s\"", ev1data)848 require.NoError(t, subscriber.CheckEvent(expectedEv1Data))849 testEnvironment.natsServer.Shutdown()850 require.Eventually(t, func() bool {851 return !jsBackend.conn.IsConnected()852 }, 30*time.Second, 2*time.Second)853 _ = evtesting.RunNatsServerOnPort(854 evtesting.WithPort(testEnvironment.natsPort),855 evtesting.WithJetStreamEnabled())856 _, err = testEnvironment.jsClient.StreamInfo(defaultStreamName)857 require.True(t, errors.Is(err, nats.ErrStreamNotFound))858 // sync the subscription again to reconnect and859 // recreate the stream and consumer860 err = jsBackend.SyncSubscription(sub)861 require.NoError(t, err)862 _, err = testEnvironment.jsClient.StreamInfo(defaultStreamName)863 require.NoError(t, err)864 ev2data := "newsampledata"865 require.NoError(t, SendEventToJetStream(jsBackend, ev2data))866 expectedEv2Data := fmt.Sprintf("\"%s\"", ev2data)867 require.NoError(t, subscriber.CheckEvent(expectedEv2Data))868}869func TestJetStreamServerRestart_WithReconnectEnabled(t *testing.T) {870 // given871 testEnvironment := setupTestEnvironment(t)872 jsBackend := testEnvironment.jsBackend873 defer testEnvironment.natsServer.Shutdown()874 defer testEnvironment.jsClient.natsConn.Close()875 initErr := jsBackend.Initialize(nil)876 require.NoError(t, initErr)877 defaultSubsConfig := env.DefaultSubscriptionConfig{MaxInFlightMessages: 10}878 subscriber := evtesting.NewSubscriber()879 defer subscriber.Shutdown()880 require.True(t, subscriber.IsRunning())881 // Create a subscription882 sub := evtesting.NewSubscription("sub", "foo",883 evtesting.WithNotCleanFilter(),884 evtesting.WithSinkURL(subscriber.SinkURL),885 evtesting.WithStatusConfig(defaultSubsConfig),886 )887 addJSCleanEventTypesToStatus(sub, testEnvironment.cleaner, jsBackend)888 // when889 err := jsBackend.SyncSubscription(sub)890 // then891 require.NoError(t, err)892 ev1data := "sampledata"893 require.NoError(t, SendEventToJetStream(jsBackend, ev1data))894 expectedEv1Data := fmt.Sprintf("\"%s\"", ev1data)895 require.NoError(t, subscriber.CheckEvent(expectedEv1Data))896 testEnvironment.natsServer.Shutdown()897 require.Eventually(t, func() bool {898 return !jsBackend.conn.IsConnected()899 }, 30*time.Second, 2*time.Second)900 _ = evtesting.RunNatsServerOnPort(901 evtesting.WithPort(testEnvironment.natsPort),902 evtesting.WithJetStreamEnabled())903 testEnvironment.natsServer.Shutdown()904 require.Eventually(t, func() bool {905 return jsBackend.conn.IsConnected()906 }, 30*time.Second, 2*time.Second)907 _, err = testEnvironment.jsClient.StreamInfo(defaultStreamName)908 require.NoError(t, err)909 // sync the subscription again to reconnect and sync consumers910 err = jsBackend.SyncSubscription(sub)911 require.NoError(t, err)912 ev2data := "newsampledata"913 require.NoError(t, SendEventToJetStream(jsBackend, ev2data))914 expectedEv2Data := fmt.Sprintf("\"%s\"", ev2data)915 require.NoError(t, subscriber.CheckEvent(expectedEv2Data))916}917func TestJetStreamServerRestart_WithFileStorage(t *testing.T) {918 // given919 testEnvironment := setupTestEnvironment(t)920 jsBackend := testEnvironment.jsBackend921 defer testEnvironment.natsServer.Shutdown()922 defer testEnvironment.jsClient.natsConn.Close()923 // use File storage to restore streams924 jsBackend.config.JSStreamStorageType = JetStreamStorageTypeFile925 initErr := jsBackend.Initialize(nil)926 require.NoError(t, initErr)927 defaultSubsConfig := env.DefaultSubscriptionConfig{MaxInFlightMessages: 10}928 subscriber := evtesting.NewSubscriber()929 defer subscriber.Shutdown()930 require.True(t, subscriber.IsRunning())931 // Create a subscription932 sub := evtesting.NewSubscription("sub", "foo",933 evtesting.WithNotCleanFilter(),934 evtesting.WithSinkURL(subscriber.SinkURL),935 evtesting.WithStatusConfig(defaultSubsConfig),936 )937 addJSCleanEventTypesToStatus(sub, testEnvironment.cleaner, jsBackend)938 // when939 err := jsBackend.SyncSubscription(sub)940 // then941 require.NoError(t, err)942 ev1data := "sampledata"943 require.NoError(t, SendEventToJetStream(jsBackend, ev1data))944 expectedEv1Data := fmt.Sprintf("\"%s\"", ev1data)945 require.NoError(t, subscriber.CheckEvent(expectedEv1Data))946 testEnvironment.natsServer.Shutdown()947 require.Eventually(t, func() bool {948 return !jsBackend.conn.IsConnected()949 }, 30*time.Second, 2*time.Second)950 _ = evtesting.RunNatsServerOnPort(951 evtesting.WithPort(testEnvironment.natsPort),952 evtesting.WithJetStreamEnabled())953 require.Eventually(t, func() bool {954 return jsBackend.conn.IsConnected()955 }, 60*time.Second, 2*time.Second)956 // check that the stream is still present957 _, err = testEnvironment.jsClient.StreamInfo(defaultStreamName)958 require.NoError(t, err)959 ev2data := "newsampledata"960 require.NoError(t, SendEventToJetStream(jsBackend, ev2data))961 expectedEv2Data := fmt.Sprintf("\"%s\"", ev2data)962 require.NoError(t, subscriber.CheckEvent(expectedEv2Data))963 // cleanup the stream from file storage964 err = testEnvironment.jsClient.DeleteStream(defaultStreamName)965 require.NoError(t, err)966}967func defaultNatsConfig(url string) env.NatsConfig {968 return env.NatsConfig{969 URL: url,970 MaxReconnects: 10,971 ReconnectWait: 3 * time.Second,972 JSStreamName: defaultStreamName,973 JSStreamStorageType: JetStreamStorageTypeMemory,974 JSStreamRetentionPolicy: JetStreamRetentionPolicyInterest,975 }976}977// getJetStreamClient creates a client with JetStream context, or fails the caller test.978func getJetStreamClient(t *testing.T, serverURL string) *jetStreamClient {979 conn, err := nats.Connect(serverURL)980 if err != nil {981 t.Error(err.Error())982 }983 jsCtx, err := conn.JetStream()984 if err != nil {985 conn.Close()986 t.Error(err.Error())987 }988 return &jetStreamClient{989 JetStreamContext: jsCtx,990 natsConn: conn,991 }992}993func addJSCleanEventTypesToStatus(sub *eventingv1alpha1.Subscription, cleaner eventtype.Cleaner, jsBackend *JetStream) {994 cleanedSubjects, _ := GetCleanSubjects(sub, cleaner)995 sub.Status.CleanEventTypes = jsBackend.GetJetStreamSubjects(cleanedSubjects)996}997// TestEnvironment provides mocked resources for tests.998type TestEnvironment struct {999 jsBackend *JetStream1000 logger *logger.Logger1001 natsServer *server.Server1002 jsClient *jetStreamClient1003 natsConfig env.NatsConfig1004 cleaner eventtype.Cleaner1005 natsPort int1006}1007// setupTestEnvironment is a TestEnvironment constructor1008func setupTestEnvironment(t *testing.T) *TestEnvironment {1009 natsServer, natsPort := startNATSServer(evtesting.WithJetStreamEnabled())1010 natsConfig := defaultNatsConfig(natsServer.ClientURL())1011 defaultLogger, err := logger.New(string(kymalogger.JSON), string(kymalogger.INFO))1012 require.NoError(t, err)1013 jsClient := getJetStreamClient(t, natsConfig.URL)1014 jsBackend := NewJetStream(natsConfig, defaultLogger)1015 cleaner := createEventTypeCleaner(evtesting.EventTypePrefix, evtesting.ApplicationNameNotClean, defaultLogger)1016 return &TestEnvironment{1017 jsBackend: jsBackend,1018 logger: defaultLogger,1019 natsServer: natsServer,1020 jsClient: jsClient,1021 natsConfig: natsConfig,1022 cleaner: cleaner,1023 natsPort: natsPort,1024 }1025}...
web3ext.go
Source:web3ext.go
1// Copyright 2015 The go-ethereum Authors2// This file is part of the go-ethereum library.3//4// The go-ethereum library is free software: you can redistribute it and/or modify5// it under the terms of the GNU Lesser General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.8//9// The go-ethereum library is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12// GNU Lesser General Public License for more details.13//14// You should have received a copy of the GNU Lesser General Public License15// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.16// package web3ext contains geth specific web3.js extensions.17package web3ext18var Modules = map[string]string{19 "admin": Admin_JS,20 "chequebook": Chequebook_JS,21 "clique": Clique_JS,22 "debug": Debug_JS,23 "eth": Eth_JS,24 "miner": Miner_JS,25 "net": Net_JS,26 "personal": Personal_JS,27 "rpc": RPC_JS,28 "shh": Shh_JS,29 "swarmfs": SWARMFS_JS,30 "txpool": TxPool_JS,31}32const Chequebook_JS = `33web3._extend({34 property: 'chequebook',35 methods: [36 new web3._extend.Method({37 name: 'deposit',38 call: 'chequebook_deposit',39 params: 1,40 inputFormatter: [null]41 }),42 new web3._extend.Property({43 name: 'balance',44 getter: 'chequebook_balance',45 outputFormatter: web3._extend.utils.toDecimal46 }),47 new web3._extend.Method({48 name: 'cash',49 call: 'chequebook_cash',50 params: 1,51 inputFormatter: [null]52 }),53 new web3._extend.Method({54 name: 'issue',55 call: 'chequebook_issue',56 params: 2,57 inputFormatter: [null, null]58 }),59 ]60});61`62const Clique_JS = `63web3._extend({64 property: 'clique',65 methods: [66 new web3._extend.Method({67 name: 'getSnapshot',68 call: 'clique_getSnapshot',69 params: 1,70 inputFormatter: [null]71 }),72 new web3._extend.Method({73 name: 'getSnapshotAtHash',74 call: 'clique_getSnapshotAtHash',75 params: 176 }),77 new web3._extend.Method({78 name: 'getSigners',79 call: 'clique_getSigners',80 params: 1,81 inputFormatter: [null]82 }),83 new web3._extend.Method({84 name: 'getSignersAtHash',85 call: 'clique_getSignersAtHash',86 params: 187 }),88 new web3._extend.Method({89 name: 'propose',90 call: 'clique_propose',91 params: 292 }),93 new web3._extend.Method({94 name: 'discard',95 call: 'clique_discard',96 params: 197 }),98 ],99 properties: [100 new web3._extend.Property({101 name: 'proposals',102 getter: 'clique_proposals'103 }),104 ]105});106`107const Admin_JS = `108web3._extend({109 property: 'admin',110 methods: [111 new web3._extend.Method({112 name: 'addPeer',113 call: 'admin_addPeer',114 params: 1115 }),116 new web3._extend.Method({117 name: 'removePeer',118 call: 'admin_removePeer',119 params: 1120 }),121 new web3._extend.Method({122 name: 'exportChain',123 call: 'admin_exportChain',124 params: 1,125 inputFormatter: [null]126 }),127 new web3._extend.Method({128 name: 'importChain',129 call: 'admin_importChain',130 params: 1131 }),132 new web3._extend.Method({133 name: 'sleepBlocks',134 call: 'admin_sleepBlocks',135 params: 2136 }),137 new web3._extend.Method({138 name: 'startRPC',139 call: 'admin_startRPC',140 params: 4,141 inputFormatter: [null, null, null, null]142 }),143 new web3._extend.Method({144 name: 'stopRPC',145 call: 'admin_stopRPC'146 }),147 new web3._extend.Method({148 name: 'startWS',149 call: 'admin_startWS',150 params: 4,151 inputFormatter: [null, null, null, null]152 }),153 new web3._extend.Method({154 name: 'stopWS',155 call: 'admin_stopWS'156 }),157 ],158 properties: [159 new web3._extend.Property({160 name: 'nodeInfo',161 getter: 'admin_nodeInfo'162 }),163 new web3._extend.Property({164 name: 'peers',165 getter: 'admin_peers'166 }),167 new web3._extend.Property({168 name: 'datadir',169 getter: 'admin_datadir'170 }),171 ]172});173`174const Debug_JS = `175web3._extend({176 property: 'debug',177 methods: [178 new web3._extend.Method({179 name: 'printBlock',180 call: 'debug_printBlock',181 params: 1182 }),183 new web3._extend.Method({184 name: 'getBlockRlp',185 call: 'debug_getBlockRlp',186 params: 1187 }),188 new web3._extend.Method({189 name: 'setHead',190 call: 'debug_setHead',191 params: 1192 }),193 new web3._extend.Method({194 name: 'seedHash',195 call: 'debug_seedHash',196 params: 1197 }),198 new web3._extend.Method({199 name: 'dumpBlock',200 call: 'debug_dumpBlock',201 params: 1202 }),203 new web3._extend.Method({204 name: 'chaindbProperty',205 call: 'debug_chaindbProperty',206 params: 1,207 outputFormatter: console.log208 }),209 new web3._extend.Method({210 name: 'chaindbCompact',211 call: 'debug_chaindbCompact',212 }),213 new web3._extend.Method({214 name: 'metrics',215 call: 'debug_metrics',216 params: 1217 }),218 new web3._extend.Method({219 name: 'verbosity',220 call: 'debug_verbosity',221 params: 1222 }),223 new web3._extend.Method({224 name: 'vmodule',225 call: 'debug_vmodule',226 params: 1227 }),228 new web3._extend.Method({229 name: 'backtraceAt',230 call: 'debug_backtraceAt',231 params: 1,232 }),233 new web3._extend.Method({234 name: 'stacks',235 call: 'debug_stacks',236 params: 0,237 outputFormatter: console.log238 }),239 new web3._extend.Method({240 name: 'freeOSMemory',241 call: 'debug_freeOSMemory',242 params: 0,243 }),244 new web3._extend.Method({245 name: 'setGCPercent',246 call: 'debug_setGCPercent',247 params: 1,248 }),249 new web3._extend.Method({250 name: 'memStats',251 call: 'debug_memStats',252 params: 0,253 }),254 new web3._extend.Method({255 name: 'gcStats',256 call: 'debug_gcStats',257 params: 0,258 }),259 new web3._extend.Method({260 name: 'cpuProfile',261 call: 'debug_cpuProfile',262 params: 2263 }),264 new web3._extend.Method({265 name: 'startCPUProfile',266 call: 'debug_startCPUProfile',267 params: 1268 }),269 new web3._extend.Method({270 name: 'stopCPUProfile',271 call: 'debug_stopCPUProfile',272 params: 0273 }),274 new web3._extend.Method({275 name: 'goTrace',276 call: 'debug_goTrace',277 params: 2278 }),279 new web3._extend.Method({280 name: 'startGoTrace',281 call: 'debug_startGoTrace',282 params: 1283 }),284 new web3._extend.Method({285 name: 'stopGoTrace',286 call: 'debug_stopGoTrace',287 params: 0288 }),289 new web3._extend.Method({290 name: 'blockProfile',291 call: 'debug_blockProfile',292 params: 2293 }),294 new web3._extend.Method({295 name: 'setBlockProfileRate',296 call: 'debug_setBlockProfileRate',297 params: 1298 }),299 new web3._extend.Method({300 name: 'writeBlockProfile',301 call: 'debug_writeBlockProfile',302 params: 1303 }),304 new web3._extend.Method({305 name: 'mutexProfile',306 call: 'debug_mutexProfile',307 params: 2308 }),309 new web3._extend.Method({310 name: 'setMutexProfileRate',311 call: 'debug_setMutexProfileRate',312 params: 1313 }),314 new web3._extend.Method({315 name: 'writeMutexProfile',316 call: 'debug_writeMutexProfile',317 params: 1318 }),319 new web3._extend.Method({320 name: 'writeMemProfile',321 call: 'debug_writeMemProfile',322 params: 1323 }),324 new web3._extend.Method({325 name: 'traceBlock',326 call: 'debug_traceBlock',327 params: 2,328 inputFormatter: [null, null]329 }),330 new web3._extend.Method({331 name: 'traceBlockFromFile',332 call: 'debug_traceBlockFromFile',333 params: 2,334 inputFormatter: [null, null]335 }),336 new web3._extend.Method({337 name: 'traceBlockByNumber',338 call: 'debug_traceBlockByNumber',339 params: 2,340 inputFormatter: [null, null]341 }),342 new web3._extend.Method({343 name: 'traceBlockByHash',344 call: 'debug_traceBlockByHash',345 params: 2,346 inputFormatter: [null, null]347 }),348 new web3._extend.Method({349 name: 'traceTransaction',350 call: 'debug_traceTransaction',351 params: 2,352 inputFormatter: [null, null]353 }),354 new web3._extend.Method({355 name: 'preimage',356 call: 'debug_preimage',357 params: 1,358 inputFormatter: [null]359 }),360 new web3._extend.Method({361 name: 'getBadBlocks',362 call: 'debug_getBadBlocks',363 params: 0,364 }),365 new web3._extend.Method({366 name: 'storageRangeAt',367 call: 'debug_storageRangeAt',368 params: 5,369 }),370 new web3._extend.Method({371 name: 'getModifiedAccountsByNumber',372 call: 'debug_getModifiedAccountsByNumber',373 params: 2,374 inputFormatter: [null, null],375 }),376 new web3._extend.Method({377 name: 'getModifiedAccountsByHash',378 call: 'debug_getModifiedAccountsByHash',379 params: 2,380 inputFormatter:[null, null],381 }),382 ],383 properties: []384});385`386const Eth_JS = `387web3._extend({388 property: 'eth',389 methods: [390 new web3._extend.Method({391 name: 'sign',392 call: 'eth_sign',393 params: 2,394 inputFormatter: [web3._extend.formatters.inputAddressFormatter, null]395 }),396 new web3._extend.Method({397 name: 'resend',398 call: 'eth_resend',399 params: 3,400 inputFormatter: [web3._extend.formatters.inputTransactionFormatter, web3._extend.utils.fromDecimal, web3._extend.utils.fromDecimal]401 }),402 new web3._extend.Method({403 name: 'signTransaction',404 call: 'eth_signTransaction',405 params: 1,406 inputFormatter: [web3._extend.formatters.inputTransactionFormatter]407 }),408 new web3._extend.Method({409 name: 'submitTransaction',410 call: 'eth_submitTransaction',411 params: 1,412 inputFormatter: [web3._extend.formatters.inputTransactionFormatter]413 }),414 new web3._extend.Method({415 name: 'getRawTransaction',416 call: 'eth_getRawTransactionByHash',417 params: 1418 }),419 new web3._extend.Method({420 name: 'getRawTransactionFromBlock',421 call: function(args) {422 return (web3._extend.utils.isString(args[0]) && args[0].indexOf('0x') === 0) ? 'eth_getRawTransactionByBlockHashAndIndex' : 'eth_getRawTransactionByBlockNumberAndIndex';423 },424 params: 2,425 inputFormatter: [web3._extend.formatters.inputBlockNumberFormatter, web3._extend.utils.toHex]426 }),427 ],428 properties: [429 new web3._extend.Property({430 name: 'pendingTransactions',431 getter: 'eth_pendingTransactions',432 outputFormatter: function(txs) {433 var formatted = [];434 for (var i = 0; i < txs.length; i++) {435 formatted.push(web3._extend.formatters.outputTransactionFormatter(txs[i]));436 formatted[i].blockHash = null;437 }438 return formatted;439 }440 }),441 ]442});443`444const Miner_JS = `445web3._extend({446 property: 'miner',447 methods: [448 new web3._extend.Method({449 name: 'start',450 call: 'miner_start',451 params: 1,452 inputFormatter: [null]453 }),454 new web3._extend.Method({455 name: 'stop',456 call: 'miner_stop'457 }),458 new web3._extend.Method({459 name: 'setEtherbase',460 call: 'miner_setEtherbase',461 params: 1,462 inputFormatter: [web3._extend.formatters.inputAddressFormatter]463 }),464 new web3._extend.Method({465 name: 'setExtra',466 call: 'miner_setExtra',467 params: 1468 }),469 new web3._extend.Method({470 name: 'setGasPrice',471 call: 'miner_setGasPrice',472 params: 1,473 inputFormatter: [web3._extend.utils.fromDecimal]474 }),475 new web3._extend.Method({476 name: 'getHashrate',477 call: 'miner_getHashrate'478 }),479 ],480 properties: []481});482`483const Net_JS = `484web3._extend({485 property: 'net',486 methods: [],487 properties: [488 new web3._extend.Property({489 name: 'version',490 getter: 'net_version'491 }),492 ]493});494`495const Personal_JS = `496web3._extend({497 property: 'personal',498 methods: [499 new web3._extend.Method({500 name: 'importRawKey',501 call: 'personal_importRawKey',502 params: 2503 }),504 new web3._extend.Method({505 name: 'sign',506 call: 'personal_sign',507 params: 3,508 inputFormatter: [null, web3._extend.formatters.inputAddressFormatter, null]509 }),510 new web3._extend.Method({511 name: 'ecRecover',512 call: 'personal_ecRecover',513 params: 2514 }),515 new web3._extend.Method({516 name: 'openWallet',517 call: 'personal_openWallet',518 params: 2519 }),520 new web3._extend.Method({521 name: 'deriveAccount',522 call: 'personal_deriveAccount',523 params: 3524 }),525 new web3._extend.Method({526 name: 'signTransaction',527 call: 'personal_signTransaction',528 params: 2,529 inputFormatter: [web3._extend.formatters.inputTransactionFormatter, null]530 }),531 ],532 properties: [533 new web3._extend.Property({534 name: 'listWallets',535 getter: 'personal_listWallets'536 }),537 ]538})539`540const RPC_JS = `541web3._extend({542 property: 'rpc',543 methods: [],544 properties: [545 new web3._extend.Property({546 name: 'modules',547 getter: 'rpc_modules'548 }),549 ]550});551`552const Shh_JS = `553web3._extend({554 property: 'shh',555 methods: [556 ],557 properties:558 [559 new web3._extend.Property({560 name: 'version',561 getter: 'shh_version',562 outputFormatter: web3._extend.utils.toDecimal563 }),564 new web3._extend.Property({565 name: 'info',566 getter: 'shh_info'567 }),568 ]569});570`571const SWARMFS_JS = `572web3._extend({573 property: 'swarmfs',574 methods:575 [576 new web3._extend.Method({577 name: 'mount',578 call: 'swarmfs_mount',579 params: 2580 }),581 new web3._extend.Method({582 name: 'unmount',583 call: 'swarmfs_unmount',584 params: 1585 }),586 new web3._extend.Method({587 name: 'listmounts',588 call: 'swarmfs_listmounts',589 params: 0590 }),591 ]592});593`594const TxPool_JS = `595web3._extend({596 property: 'txpool',597 methods: [],598 properties:599 [600 new web3._extend.Property({601 name: 'content',602 getter: 'txpool_content'603 }),604 new web3._extend.Property({605 name: 'inspect',606 getter: 'txpool_inspect'607 }),608 new web3._extend.Property({609 name: 'status',610 getter: 'txpool_status',611 outputFormatter: function(status) {612 status.pending = web3._extend.utils.toDecimal(status.pending);613 status.queued = web3._extend.utils.toDecimal(status.queued);614 return status;615 }616 }),617 ]618});619`...
simplejson_test.go
Source:simplejson_test.go
...6)7func TestSimplejson(t *testing.T) {8 var ok bool9 var err error10 js, err := NewJson([]byte(`{11 "test": {12 "string_array": ["asdf", "ghjk", "zxcv"],13 "string_array_null": ["abc", null, "efg"],14 "array": [1, "2", 3],15 "arraywithsubs": [{"subkeyone": 1},16 {"subkeytwo": 2, "subkeythree": 3}],17 "int": 10,18 "float": 5.150,19 "string": "simplejson",20 "bool": true,21 "sub_obj": {"a": 1}22 }23 }`))24 assert.NotEqual(t, nil, js)25 assert.Equal(t, nil, err)26 _, ok = js.CheckGet("test")27 assert.Equal(t, true, ok)28 _, ok = js.CheckGet("missing_key")29 assert.Equal(t, false, ok)30 aws := js.Get("test").Get("arraywithsubs")31 assert.NotEqual(t, nil, aws)32 var awsval int33 awsval, _ = aws.GetIndex(0).Get("subkeyone").Int()34 assert.Equal(t, 1, awsval)35 awsval, _ = aws.GetIndex(1).Get("subkeytwo").Int()36 assert.Equal(t, 2, awsval)37 awsval, _ = aws.GetIndex(1).Get("subkeythree").Int()38 assert.Equal(t, 3, awsval)39 i, _ := js.Get("test").Get("int").Int()40 assert.Equal(t, 10, i)41 f, _ := js.Get("test").Get("float").Float64()42 assert.Equal(t, 5.150, f)43 s, _ := js.Get("test").Get("string").String()44 assert.Equal(t, "simplejson", s)45 b, _ := js.Get("test").Get("bool").Bool()46 assert.Equal(t, true, b)47 mi := js.Get("test").Get("int").MustInt()48 assert.Equal(t, 10, mi)49 mi2 := js.Get("test").Get("missing_int").MustInt(5150)50 assert.Equal(t, 5150, mi2)51 ms := js.Get("test").Get("string").MustString()52 assert.Equal(t, "simplejson", ms)53 ms2 := js.Get("test").Get("missing_string").MustString("fyea")54 assert.Equal(t, "fyea", ms2)55 ma2 := js.Get("test").Get("missing_array").MustArray([]interface{}{"1", 2, "3"})56 assert.Equal(t, ma2, []interface{}{"1", 2, "3"})57 msa := js.Get("test").Get("string_array").MustStringArray()58 assert.Equal(t, msa[0], "asdf")59 assert.Equal(t, msa[1], "ghjk")60 assert.Equal(t, msa[2], "zxcv")61 msa2 := js.Get("test").Get("string_array").MustStringArray([]string{"1", "2", "3"})62 assert.Equal(t, msa2[0], "asdf")63 assert.Equal(t, msa2[1], "ghjk")64 assert.Equal(t, msa2[2], "zxcv")65 msa3 := js.Get("test").Get("missing_array").MustStringArray([]string{"1", "2", "3"})66 assert.Equal(t, msa3, []string{"1", "2", "3"})67 mm2 := js.Get("test").Get("missing_map").MustMap(map[string]interface{}{"found": false})68 assert.Equal(t, mm2, map[string]interface{}{"found": false})69 strs, err := js.Get("test").Get("string_array").StringArray()70 assert.Equal(t, err, nil)71 assert.Equal(t, strs[0], "asdf")72 assert.Equal(t, strs[1], "ghjk")73 assert.Equal(t, strs[2], "zxcv")74 strs2, err := js.Get("test").Get("string_array_null").StringArray()75 assert.Equal(t, err, nil)76 assert.Equal(t, strs2[0], "abc")77 assert.Equal(t, strs2[1], "")78 assert.Equal(t, strs2[2], "efg")79 gp, _ := js.GetPath("test", "string").String()80 assert.Equal(t, "simplejson", gp)81 gp2, _ := js.GetPath("test", "int").Int()82 assert.Equal(t, 10, gp2)83 assert.Equal(t, js.Get("test").Get("bool").MustBool(), true)84 js.Set("float2", 300.0)85 assert.Equal(t, js.Get("float2").MustFloat64(), 300.0)86 js.Set("test2", "setTest")87 assert.Equal(t, "setTest", js.Get("test2").MustString())88 js.Del("test2")89 assert.NotEqual(t, "setTest", js.Get("test2").MustString())90 js.Get("test").Get("sub_obj").Set("a", 2)91 assert.Equal(t, 2, js.Get("test").Get("sub_obj").Get("a").MustInt())92 js.GetPath("test", "sub_obj").Set("a", 3)93 assert.Equal(t, 3, js.GetPath("test", "sub_obj", "a").MustInt())94}95func TestStdlibInterfaces(t *testing.T) {96 val := new(struct {97 Name string `json:"name"`98 Params *Json `json:"params"`99 })100 val2 := new(struct {101 Name string `json:"name"`102 Params *Json `json:"params"`103 })104 raw := `{"name":"myobject","params":{"string":"simplejson"}}`105 assert.Equal(t, nil, json.Unmarshal([]byte(raw), val))106 assert.Equal(t, "myobject", val.Name)107 assert.NotEqual(t, nil, val.Params.data)108 s, _ := val.Params.Get("string").String()109 assert.Equal(t, "simplejson", s)110 p, err := json.Marshal(val)111 assert.Equal(t, nil, err)112 assert.Equal(t, nil, json.Unmarshal(p, val2))113 assert.Equal(t, val, val2) // stable114}115func TestSet(t *testing.T) {116 js, err := NewJson([]byte(`{}`))117 assert.Equal(t, nil, err)118 js.Set("baz", "bing")119 s, err := js.GetPath("baz").String()120 assert.Equal(t, nil, err)121 assert.Equal(t, "bing", s)122}123func TestReplace(t *testing.T) {124 js, err := NewJson([]byte(`{}`))125 assert.Equal(t, nil, err)126 err = js.UnmarshalJSON([]byte(`{"baz":"bing"}`))127 assert.Equal(t, nil, err)128 s, err := js.GetPath("baz").String()129 assert.Equal(t, nil, err)130 assert.Equal(t, "bing", s)131}132func TestSetPath(t *testing.T) {133 js, err := NewJson([]byte(`{}`))134 assert.Equal(t, nil, err)135 js.SetPath([]string{"foo", "bar"}, "baz")136 s, err := js.GetPath("foo", "bar").String()137 assert.Equal(t, nil, err)138 assert.Equal(t, "baz", s)139}140func TestSetPathNoPath(t *testing.T) {141 js, err := NewJson([]byte(`{"some":"data","some_number":1.0,"some_bool":false}`))142 assert.Equal(t, nil, err)143 f := js.GetPath("some_number").MustFloat64(99.0)144 assert.Equal(t, f, 1.0)145 js.SetPath([]string{}, map[string]interface{}{"foo": "bar"})146 s, err := js.GetPath("foo").String()147 assert.Equal(t, nil, err)148 assert.Equal(t, "bar", s)149 f = js.GetPath("some_number").MustFloat64(99.0)150 assert.Equal(t, f, 99.0)151}152func TestPathWillAugmentExisting(t *testing.T) {153 js, err := NewJson([]byte(`{"this":{"a":"aa","b":"bb","c":"cc"}}`))154 assert.Equal(t, nil, err)155 js.SetPath([]string{"this", "d"}, "dd")156 cases := []struct {157 path []string158 outcome string159 }{160 {161 path: []string{"this", "a"},162 outcome: "aa",163 },164 {165 path: []string{"this", "b"},166 outcome: "bb",167 },168 {169 path: []string{"this", "c"},170 outcome: "cc",171 },172 {173 path: []string{"this", "d"},174 outcome: "dd",175 },176 }177 for _, tc := range cases {178 s, err := js.GetPath(tc.path...).String()179 assert.Equal(t, nil, err)180 assert.Equal(t, tc.outcome, s)181 }182}183func TestPathWillOverwriteExisting(t *testing.T) {184 // notice how "a" is 0.1 - but then we'll try to set at path a, foo185 js, err := NewJson([]byte(`{"this":{"a":0.1,"b":"bb","c":"cc"}}`))186 assert.Equal(t, nil, err)187 js.SetPath([]string{"this", "a", "foo"}, "bar")188 s, err := js.GetPath("this", "a", "foo").String()189 assert.Equal(t, nil, err)190 assert.Equal(t, "bar", s)191}...
New
Using AI Code Generation
1import (2func main() {3 vm := otto.New()4 underscore.Enable(vm)5 vm.Run(`6 var a = _.range(10);7 console.log(a);8}9import (10func main() {11 vm := otto.New()12 underscore.Enable(vm)13 vm.Run(`14 var a = _.range(10);15 console.log(a);16}17import (18func main() {19 vm := otto.New()20 underscore.Enable(vm)21 vm.Run(`22 var a = _.range(10);23 console.log(a);24}25import (26func main() {27 vm := otto.New()28 underscore.Enable(vm)29 vm.Run(`30 var a = _.range(10);31 console.log(a);32}33import (34func main() {35 vm := otto.New()36 underscore.Enable(vm)37 vm.Run(`38 var a = _.range(10);39 console.log(a);40}41import (42func main() {43 vm := otto.New()44 underscore.Enable(vm)45 vm.Run(`46 var a = _.range(10);
New
Using AI Code Generation
1func main() {2 js.Global().Get("document").Call("addEventListener", "DOMContentLoaded", func() {3 })4}5func main() {6 js.Global().Get("document").Call("addEventListener", "DOMContentLoaded", func() {7 })8}9func main() {10 js.Global().Get("document").Call("addEventListener", "DOMContentLoaded", func() {11 })12}13func main() {14 js.Global().Get("document").Call("addEventListener", "DOMContentLoaded", func() {15 })16}17func main() {18 js.Global().Get("document").Call("addEventListener", "DOMContentLoaded", func() {19 })20}21func main() {22 js.Global().Get("document").Call("addEventListener", "DOMContentLoaded", func() {23 })24}25func main() {26 js.Global().Get("document").Call("addEventListener", "DOMContentLoaded", func() {27 })28}29func main() {30 js.Global().Get("document").Call("addEventListener", "DOMContentLoaded", func() {31 })32}33func main() {34 js.Global().Get("document").Call("addEventListener", "DOMContentLoaded", func() {35 })36}37func main() {38 js.Global().Get("document").Call("addEventListener", "DOMContentLoaded", func() {
New
Using AI Code Generation
1import (2func main() {3 jsObj := js.Global.Get("Object").New()4 jsObj.Set("name", "GopherJS")5 fmt.Println(jsObj.Get("name"))6}7import (8func main() {9 jsObj := js.Global.Get("Object").New()10 jsObj.Set("name", "GopherJS")11 fmt.Println(jsObj.Get("name"))12 jsObj.Call("toString")13}14import (15func main() {16 jsObj := js.Global.Get("Object").New()17 jsObj.Set("name", "GopherJS")18 fmt.Println(jsObj.Get("name"))19 fmt.Println(jsObj.Call("toString"))20}21import (22func main() {23 jsObj := js.Global.Get("Object").New()24 jsObj.Set("name", "GopherJS")25 fmt.Println(jsObj.Get("name"))26 fmt.Println(jsObj.Call("toString").String())27}28import (29func main() {30 jsObj := js.Global.Get("Object").New()31 jsObj.Set("name", "GopherJS")32 fmt.Println(jsObj.Get("name"))33 fmt.Println(jsObj.Call("toString").String())
New
Using AI Code Generation
1js.Global.Get("Path").Call("New", "1.go")2js.Global.Get("Path").Call("New", "2.go")3js.Global.Get("Path").Call("New", "3.go")4js.Global.Get("Path").Call("New", "4.go")5js.Global.Get("Path").Call("New", "5.go")6js.Global.Get("Path").Call("New", "6.go")7js.Global.Get("Path").Call("New", "7.go")8js.Global.Get("Path").Call("New", "8.go")9js.Global.Get("Path").Call("New", "9.go")10js.Global.Get("Path").Call("New", "10.go")11js.Global.Get("Path").Call("New", "11.go")12js.Global.Get("Path").Call("New", "12.go")13js.Global.Get("Path").Call("New", "13.go")14js.Global.Get("Path").Call("New", "14.go")15js.Global.Get("Path").Call("New", "15.go")16js.Global.Get("Path").Call("New", "16.go")17js.Global.Get("Path").Call("New", "17.go")18js.Global.Get("Path").Call("New", "18.go")
New
Using AI Code Generation
1p.Set("name", "John")2p.Set("age", 42)3p.Set("name", "John")4p.Set("age", 42)5import (6func main() {7 p.Set("name", "John")8 p.Set("age", 42)9 p.Set("name", "John")10 p.Set("age", 42)11}12import (13func main() {14 p.Set("name", "John")15 p.Set("age", 42)16 p.Set("name", "John")17 p.Set("age", 42)18}19import (20func main() {
New
Using AI Code Generation
1p := js.Global.Get("Promise").New(func(resolve, reject js.Value) {2 resolve.Invoke("success")3})4p.Call("then", func(v js.Value) {5 fmt.Println(v.String())6})7p := js.Global.Get("Promise").New(func(resolve, reject js.Value) {8 resolve.Invoke("success")9})10p.Call("then", func(v js.Value) {11 fmt.Println(v.String())12})13p := js.Global.Get("Promise").New(func(resolve, reject js.Value) {14 resolve.Invoke("success")15})16p.Call("then", func(v js.Value) {17 fmt.Println(v.String())18})19p := js.Global.Get("Promise").New(func(resolve, reject js.Value) {20 resolve.Invoke("success")21})22p.Call("then", func(v js.Value) {23 fmt.Println(v.String())24})25p := js.Global.Get("Promise").New(func(resolve, reject js.Value) {26 resolve.Invoke("success")27})28p.Call("then", func(v js.Value) {29 fmt.Println(v.String())30})31p := js.Global.Get("Promise").New(func(resolve, reject js.Value) {32 resolve.Invoke("success")33})34p.Call("then", func(v js.Value) {35 fmt.Println(v.String())36})37p := js.Global.Get("Promise").New(func(resolve, reject js.Value) {38 resolve.Invoke("success")39})40p.Call("then", func(v js.Value) {41 fmt.Println(v.String())42})43p := js.Global.Get("Promise").New(func(resolve, reject js.Value) {44 resolve.Invoke("success")45})46p.Call("then", func(v js.Value) {
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!!