How to use Unsubscribe method of event Package

Best Testkube code snippet using event.Unsubscribe

03unsubscribe_test.go

Source:03unsubscribe_test.go Github

copy

Full Screen

...5 "testing"6 "github.com/resgateio/resgate/server/reserr"7)8// Test that a client can unsubscribe to a model9func TestUnsubscribeModel(t *testing.T) {10 runTest(t, func(s *Session) {11 event := json.RawMessage(`{"foo":"bar"}`)12 c := s.Connect()13 subscribeToTestModel(t, s, c)14 // Call unsubscribe15 c.Request("unsubscribe.test.model", nil).GetResponse(t)16 // Send event on model and validate no event was sent to client17 s.ResourceEvent("test.model", "custom", event)18 c.AssertNoEvent(t, "test.model")19 })20}21// Test unsubscribing without subscription22func TestUnsubscribeWithoutSubscription(t *testing.T) {23 runTest(t, func(s *Session) {24 c := s.Connect()25 // Call unsubscribe26 c.Request("unsubscribe.test.model", nil).GetResponse(t).AssertError(t, reserr.ErrNoSubscription)27 })28}29// Test that a client can unsubscribe to linked models30func TestUnsubscribeLinkedModel(t *testing.T) {31 runTest(t, func(s *Session) {32 event := json.RawMessage(`{"foo":"bar"}`)33 c := s.Connect()34 subscribeToTestModelParent(t, s, c, false)35 // Call unsubscribe36 c.Request("unsubscribe.test.model.parent", nil).GetResponse(t)37 // Send event on model and validate no event was sent to client38 s.ResourceEvent("test.model", "custom", event)39 c.AssertNoEvent(t, "test.model")40 // Send event on model parent and validate no event was sent to client41 s.ResourceEvent("test.model.parent", "custom", event)42 c.AssertNoEvent(t, "test.model.parent")43 })44}45// Test that an overlapping indirectly subscribed model is still subscribed46// after one parent is unsubscribed47func TestUnsubscribeOnOverlappingLinkedModel(t *testing.T) {48 runTest(t, func(s *Session) {49 modelSecondParent := resourceData("test.model.secondparent")50 event := json.RawMessage(`{"foo":"bar"}`)51 c := s.Connect()52 subscribeToTestModelParent(t, s, c, false)53 // Get second parent model54 creq := c.Request("subscribe.test.model.secondparent", nil)55 // Handle parent get and access request56 mreqs := s.GetParallelRequests(t, 2)57 mreqs.GetRequest(t, "get.test.model.secondparent").RespondSuccess(json.RawMessage(`{"model":` + modelSecondParent + `}`))58 mreqs.GetRequest(t, "access.test.model.secondparent").RespondSuccess(json.RawMessage(`{"get":true}`))59 // Get client response60 creq.GetResponse(t)61 // Call unsubscribe62 c.Request("unsubscribe.test.model.parent", nil).GetResponse(t)63 // Send event on model and validate no event was sent to client64 s.ResourceEvent("test.model.parent", "custom", event)65 c.AssertNoEvent(t, "test.model.parent")66 // Send event on model parent and validate client event67 s.ResourceEvent("test.model.secondparent", "custom", event)68 c.GetEvent(t).Equals(t, "test.model.secondparent.custom", event)69 })70}71// Test that a client can unsubscribe to a collection72func TestUnsubscribeCollection(t *testing.T) {73 runTest(t, func(s *Session) {74 event := json.RawMessage(`{"foo":"bar"}`)75 c := s.Connect()76 subscribeToTestCollection(t, s, c)77 // Call unsubscribe78 c.Request("unsubscribe.test.collection", nil).GetResponse(t)79 // Send event on collection and validate no event was sent to client80 s.ResourceEvent("test.collection", "custom", event)81 c.AssertNoEvent(t, "test.collection")82 })83}84// Test that a client can unsubscribe to linked collections85func TestUnsubscribeLinkedCollection(t *testing.T) {86 runTest(t, func(s *Session) {87 event := json.RawMessage(`{"foo":"bar"}`)88 c := s.Connect()89 subscribeToTestCollectionParent(t, s, c, false)90 // Call unsubscribe91 c.Request("unsubscribe.test.collection.parent", nil).GetResponse(t)92 // Send event on collection and validate no event was sent to client93 s.ResourceEvent("test.collection", "custom", event)94 c.AssertNoEvent(t, "test.collection")95 // Send event on collection parent and validate no event was sent to client96 s.ResourceEvent("test.collection.parent", "custom", event)97 c.AssertNoEvent(t, "test.collection.parent")98 })99}100// Test that an overlapping indirectly subscribed collection is still subscribed101// after one parent is unsubscribed102func TestUnsubscribeOnOverlappingLinkedCollection(t *testing.T) {103 runTest(t, func(s *Session) {104 collectionSecondParent := resourceData("test.collection.secondparent")105 event := json.RawMessage(`{"foo":"bar"}`)106 c := s.Connect()107 subscribeToTestCollectionParent(t, s, c, false)108 // Get second parent collection109 creq := c.Request("subscribe.test.collection.secondparent", nil)110 // Handle parent get and access request111 mreqs := s.GetParallelRequests(t, 2)112 mreqs.GetRequest(t, "get.test.collection.secondparent").RespondSuccess(json.RawMessage(`{"collection":` + collectionSecondParent + `}`))113 mreqs.GetRequest(t, "access.test.collection.secondparent").RespondSuccess(json.RawMessage(`{"get":true}`))114 // Get client response115 creq.GetResponse(t)116 // Call unsubscribe117 c.Request("unsubscribe.test.collection.parent", nil).GetResponse(t)118 // Send event on collection and validate no event was sent to client119 s.ResourceEvent("test.collection.parent", "custom", event)120 c.AssertNoEvent(t, "test.collection.parent")121 // Send event on collection parent and validate client event122 s.ResourceEvent("test.collection.secondparent", "custom", event)123 c.GetEvent(t).Equals(t, "test.collection.secondparent.custom", event)124 })125}126func TestUnsubscribe_FollowedByResourceResponse_IncludesResource(t *testing.T) {127 for useCount := true; useCount; useCount = false {128 runNamedTest(t, fmt.Sprintf("with useCount set to %+v", useCount), func(s *Session) {129 c := s.Connect()130 model := resourceData("test.model")131 // Send subscribe request132 creq := c.Request("subscribe.test.model", nil)133 // Handle model get and access request134 mreqs := s.GetParallelRequests(t, 2)135 mreqs.GetRequest(t, "get.test.model").RespondSuccess(json.RawMessage(`{"model":` + model + `}`))136 req := mreqs.GetRequest(t, "access.test.model")137 req.RespondSuccess(json.RawMessage(`{"get":true}`))138 // Validate client response and validate139 creq.GetResponse(t).AssertResult(t, json.RawMessage(`{"models":{"test.model":`+model+`}}`))140 // Send client request141 creq = c.Request("call.test.getModel", nil)142 req = s.GetRequest(t)143 req.AssertSubject(t, "access.test")144 req.RespondSuccess(json.RawMessage(`{"get":true,"call":"*"}`))145 // Get call request146 req = s.GetRequest(t)147 req.AssertSubject(t, "call.test.getModel")148 req.RespondResource("test.model")149 // Validate client response150 cresp := creq.GetResponse(t)151 cresp.AssertResult(t, json.RawMessage(`{"rid":"test.model"}`))152 // Call unsubscribe153 if useCount {154 c.Request("unsubscribe.test.model", json.RawMessage(`{"count":2}`)).GetResponse(t)155 } else {156 c.Request("unsubscribe.test.model", json.RawMessage(`{}`)).GetResponse(t)157 c.Request("unsubscribe.test.model", nil).GetResponse(t)158 }159 // Send client request160 creq = c.Request("call.test.getModel", nil)161 req = s.GetRequest(t)162 req.AssertSubject(t, "access.test")163 req.RespondSuccess(json.RawMessage(`{"get":true,"call":"*"}`))164 // Get call request165 req = s.GetRequest(t)166 req.AssertSubject(t, "call.test.getModel")167 req.RespondResource("test.model")168 // Access request169 req = s.GetRequest(t)170 req.AssertSubject(t, "access.test.model")171 req.RespondSuccess(json.RawMessage(`{"get":true}`))172 // Validate client response173 cresp = creq.GetResponse(t)174 cresp.AssertResult(t, json.RawMessage(`{"rid":"test.model","models":{"test.model":`+model+`}}`))175 })176 }177}178func TestUnsubscribe_WithCount_UnsubscribesModel(t *testing.T) {179 runTest(t, func(s *Session) {180 event := json.RawMessage(`{"foo":"bar"}`)181 c := s.Connect()182 subscribeToTestModel(t, s, c)183 // Call unsubscribe184 c.Request("unsubscribe.test.model", json.RawMessage(`{"count":1}`)).GetResponse(t)185 // Send event on model and validate no event was sent to client186 s.ResourceEvent("test.model", "custom", event)187 c.AssertNoEvent(t, "test.model")188 })189}190func TestUnsubscribe_WithInvalidPayload_DoesNotUnsubscribesModel(t *testing.T) {191 tbl := []struct {192 Payload interface{}193 ErrorCode string194 }{195 {json.RawMessage(`[]`), "system.invalidParams"},196 {json.RawMessage(`{"count":"foo"}`), "system.invalidParams"},197 {json.RawMessage(`{"count":true}`), "system.invalidParams"},198 {json.RawMessage(`{"count":0}`), "system.invalidParams"},199 {json.RawMessage(`{"count":-1}`), "system.invalidParams"},200 {json.RawMessage(`{"count":2}`), "system.noSubscription"},201 }202 event := json.RawMessage(`{"foo":"bar"}`)203 for i, l := range tbl {204 runNamedTest(t, fmt.Sprintf("#%d", i+1), func(s *Session) {...

Full Screen

Full Screen

event_stream.go

Source:event_stream.go Github

copy

Full Screen

...7type SubscribeMessage struct {8 subscriber ActorRef9 channel string10}11type UnsubscribeMessage struct {12 subscriber ActorRef13 channel string14}15type UnsubscribeAllMessage struct {16 subscriber ActorRef17}18// Receiver19type EventStream struct {20 channels map[string][]ActorRef21}22func NewEventStream() *EventStream {23 return &EventStream{24 channels: make(map[string][]ActorRef),25 }26}27func add(refs []ActorRef, newRef ActorRef) []ActorRef {28 for _, ref := range refs {29 if ref.Equals(newRef) {30 return refs // Already exists31 }32 }33 return append(refs, newRef)34}35func remove(refs []ActorRef, oldRef ActorRef) []ActorRef {36 for i, ref := range refs {37 if ref.Equals(oldRef) {38 copy(refs[i:], refs[i+1:]) // Shift left by 139 return refs[:len(refs)-1] // Shrink by 140 }41 }42 return refs43}44func (e *EventStream) Publish(event Event, self ActorRef) {45 if refs, ok := e.channels[event.channel]; ok {46 for _, ref := range refs {47 ref.Tell(event.message, self)48 }49 }50}51func (e *EventStream) Subscribe(subscriber ActorRef, channel string) {52 if refs, ok := e.channels[channel]; ok {53 e.channels[channel] = add(refs, subscriber)54 } else {55 // First ref for channel, make the slice56 e.channels[channel] = []ActorRef{subscriber}57 }58}59func (e *EventStream) Unsubscribe(subscriber ActorRef, channel string) {60 if refs, ok := e.channels[channel]; ok {61 e.channels[channel] = remove(refs, subscriber)62 }63}64func (e *EventStream) UnsubscribeAll(subscriber ActorRef) {65 for channel, refs := range e.channels {66 e.channels[channel] = remove(refs, subscriber)67 }68}69func (e *EventStream) Receive(message interface{}, sender ActorRef, context *Actor) {70 switch message := message.(type) {71 case Event:72 e.Publish(message, context.Self)73 case SubscribeMessage:74 e.Subscribe(message.subscriber, message.channel)75 case UnsubscribeMessage:76 e.Unsubscribe(message.subscriber, message.channel)77 case UnsubscribeAllMessage:78 e.UnsubscribeAll(message.subscriber)79 }80}81// ActorRef82type EventStreamActorRef struct {83 ActorRef84}85func (e *EventStreamActorRef) Publish(channel string, message interface{}) {86 e.Tell(Event{87 message: message,88 channel: channel,89 }, nil)90}91func (e *EventStreamActorRef) Subscribe(subscriber ActorRef, channel string) {92 e.Tell(SubscribeMessage{93 subscriber: subscriber,94 channel: channel,95 }, nil)96}97func (e *EventStreamActorRef) Unsubscribe(subscriber ActorRef, channel string) {98 e.Tell(UnsubscribeMessage{99 subscriber: subscriber,100 channel: channel,101 }, nil)102}103func (e *EventStreamActorRef) UnsubscribeAll(subscriber ActorRef) {104 e.Tell(UnsubscribeAllMessage{105 subscriber: subscriber,106 }, nil)107}...

Full Screen

Full Screen

pubsub.go

Source:pubsub.go Github

copy

Full Screen

...14 Subscriber[V]15}16type Subscription[V any] interface {17 Chan() <-chan V18 Unsubscribe()19}20type subject[V any] struct {21 subscribers []chan V22 mtx sync.RWMutex23}24type subscription[V any] struct {25 ch <-chan V26 unsubscribed bool27 unsubscribeEventHandler eventhandler.EventHandler[*subscription[V], struct{}]28}29func (s *subscription[V]) Chan() <-chan V {30 return s.ch31}32func (s *subscription[V]) Unsubscribe() {33 if s.unsubscribed {34 return35 }36 s.unsubscribed = true37 s.unsubscribeEventHandler.Invoke(s, struct{}{})38}39func NewSubject[V any]() Subject[V] {40 return &subject[V]{41 subscribers: make([]chan V, 0),42 mtx: sync.RWMutex{},43 }44}45func (s *subject[V]) Publish(value V) {46 s.mtx.RLock()...

Full Screen

Full Screen

Unsubscribe

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 if err != nil {4 fmt.Println(err)5 }6 query := ethereum.FilterQuery{7 Addresses: []common.Address{8 common.HexToAddress("0x8d12A197cB00D4747a1fe03395095ce2A5CC6819"),9 },10 }11 logs := make(chan types.Log)12 sub, err := client.SubscribeFilterLogs(context.Background(), query, logs)13 if err != nil {14 fmt.Println(err)15 }16 for {17 select {18 case err := <-sub.Err():19 fmt.Println(err)20 fmt.Println(vLog)21 }22 }23}24{0x8d12A197cB00D4747a1fe03395095ce2A5CC6819 {0xc6b4d6b2a6f4c6f8b6a0c6b4d6b2a

Full Screen

Full Screen

Unsubscribe

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 if err != nil {4 log.Fatal(err)5 }6 if err != nil {7 log.Fatal(err)8 }9 contractAddress := common.HexToAddress("0x2B0dDcA75fD7CfBbC1b7A9A1d1A7C3BbAaE7F8F0")10 query := ethereum.FilterQuery{11 Addresses: []common.Address{contractAddress},12 }13 logs := make(chan types.Log)14 sub, err := conn.SubscribeFilterLogs(context.Background(), query, logs)15 if err != nil {16 log.Fatal(err)17 }18 for {19 select {20 case err := <-sub.Err():21 log.Fatal(err)22 fmt.Println("Block Number:", blockNumber)23 txHash := vLog.TxHash.Hex()24 fmt.Println("Tx Hash:", txHash)25 fmt.Println("Tx Index:", txIndex)26 blockHash := vLog.BlockHash.Hex()27 fmt.Println("Block Hash:", blockHash)28 address := vLog.Address.Hex()29 fmt.Println("Address:", address)30 fmt.Println("Data:", data)31 fmt.Println("Topics:", topics)32 }33 }34}

Full Screen

Full Screen

Unsubscribe

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 consumer, err := sarama.NewConsumer([]string{"localhost:9092"}, nil)4 if err != nil {5 panic(err)6 }7 defer consumer.Close()8 partitionConsumer, err := consumer.ConsumePartition("my_topic", 0, sarama.OffsetNewest)9 if err != nil {10 panic(err)11 }12 defer partitionConsumer.Close()13 for msg := range partitionConsumer.Messages() {14 fmt.Println(string(msg.Key), string(msg.Value))15 }16}17import (18func main() {19 consumer, err := sarama.NewConsumer([]string{"localhost:9092"}, nil)20 if err != nil {21 panic(err)22 }23 defer consumer.Close()24 partitionConsumer, err := consumer.ConsumePartition("my_topic", 0, sarama.OffsetNewest)25 if err != nil {26 panic(err)27 }28 defer partitionConsumer.Close()29 for msg := range partitionConsumer.Messages() {30 fmt.Println(string(msg.Key), string(msg.Value))31 }32}33import (34func main() {35 consumer, err := sarama.NewConsumer([]string{"localhost:9092"}, nil)36 if err != nil {37 panic(err)38 }39 defer consumer.Close()40 partitionConsumer, err := consumer.ConsumePartition("my_topic", 0, sarama.OffsetNewest)41 if err != nil {42 panic(err)43 }44 defer partitionConsumer.Close()45 for msg := range partitionConsumer.Messages() {46 fmt.Println(string(msg.Key), string(msg.Value))47 }48}49import (50func main() {51 consumer, err := sarama.NewConsumer([]string{"localhost:9092"}, nil)52 if err != nil {53 panic(err)

Full Screen

Full Screen

Unsubscribe

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 config := sarama.NewConfig()4 brokers := []string{"localhost:9092"}5 consumer, err := sarama.NewConsumer(brokers, config)6 if err != nil {7 panic(err)8 }9 partitionConsumer, err := consumer.ConsumePartition("my_topic", 0, sarama.OffsetNewest)10 if err != nil {11 panic(err)12 }13 for {14 select {15 case msg := <-partitionConsumer.Messages():16 fmt.Printf("Message claimed: value = %s, offset = %d17", string(msg.Value), msg.Offset)18 case err := <-partitionConsumer.Errors():19 fmt.Printf("Error: %s20", err.Error())21 }22 }23 if err := partitionConsumer.Unsubscribe(); err != nil {24 panic(err)25 }26 if err := consumer.Close(); err != nil {27 panic(err)28 }29}

Full Screen

Full Screen

Unsubscribe

Using AI Code Generation

copy

Full Screen

1import (2type Eventer struct {3}4func (e *Eventer) Subscribe(ch chan<- int) event.Subscription {5 return e.Feed.Subscribe(ch)6}7func main() {8 e := &Eventer{}9 ch := make(chan int)10 sub := e.Subscribe(ch)11 go func() {12 for i := 0; i < 10; i++ {13 e.Feed.Send(i)14 }15 }()16 for i := 0; i < 10; i++ {17 fmt.Println(<-ch)18 }19 sub.Unsubscribe()20}21import (22type Eventer struct {23}24func (e *Eventer) Subscribe(ch chan<- int) event.Subscription {25 return e.Feed.Subscribe(ch)26}27func main() {28 e := &Eventer{}29 ch := make(chan int)30 sub := e.Subscribe(ch)31 go func() {32 for i := 0; i < 10; i++ {33 e.Feed.Send(i)34 }35 }()36 for i := 0; i < 10; i++ {37 fmt.Println(<-ch)38 }39 sub.Unsubscribe()40}

Full Screen

Full Screen

Unsubscribe

Using AI Code Generation

copy

Full Screen

1import (2type Event struct {3}4type Subscriber struct {5}6func (e *Event) Subscribe(sub Subscriber) {7 e.Subscribers = append(e.Subscribers, sub)8}9func (e *Event) Unsubscribe(sub Subscriber) {10 for i, s := range e.Subscribers {11 if reflect.DeepEqual(s, sub) {12 e.Subscribers = append(e.Subscribers[:i], e.Subscribers[i+1:]...)13 }14 }15}16func main() {17 fmt.Println("Hello World")18}

Full Screen

Full Screen

Unsubscribe

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 e := event.New()4 e.Subscribe("test", func() {5 fmt.Println("test")6 })7 e.Subscribe("test", func() {8 fmt.Println("test2")9 })10 e.Unsubscribe("test", 0)11 e.Emit("test")12}13import (14func main() {15 e := event.New()16 e.Subscribe("test", func() {17 fmt.Println("test")18 })19 e.Subscribe("test", func() {20 fmt.Println("test2")21 })22 e.UnsubscribeAll("test")23 e.Emit("test")24}25import (26func main() {27 e := event.New()28 e.Subscribe("test", func() {29 fmt.Println("test")30 })31 e.Subscribe("test", func() {32 fmt.Println("test2")33 })34 e.Clear()35 e.Emit("test")36}37import (38func main() {39 e := event.New()40 e.Subscribe("test", func() {41 fmt.Println("test")42 })43 e.Subscribe("test", func() {44 fmt.Println("test2")45 })46 fmt.Println(e.Has("test"))47 fmt.Println(e.Has("test2"))48}49import (50func main() {51 e := event.New()52 e.Subscribe("test", func() {53 fmt.Println("test")54 })55 e.Subscribe("test", func() {56 fmt.Println("test2")57 })58 fmt.Println(e.Listeners("test"))59}60import (

Full Screen

Full Screen

Unsubscribe

Using AI Code Generation

copy

Full Screen

1import (2type Event struct {3}4func main() {5 feed := new(event.Feed)6 channel := make(chan Event)7 sub := feed.Subscribe(channel)8 feed.Send(Event{Name: "Hello World"})9 fmt.Println(<-channel)10 sub.Unsubscribe()11 feed.Send(Event{Name: "Hello World"})12 fmt.Println(<-channel)13}14{Hello World}15{Hello World}

Full Screen

Full Screen

Unsubscribe

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 sdl.Init(sdl.INIT_EVERYTHING)4 window, _ = sdl.CreateWindow("Event Window", sdl.WINDOWPOS_UNDEFINED, sdl.WINDOWPOS_UNDEFINED, 800, 600, sdl.WINDOW_SHOWN)5 for {6 e = sdl.PollEvent()7 eventType = e.GetType()8 if eventType == sdl.QUIT {9 sdl.UnsubscribeEvent(sdl.QUIT, sdl.GetWindowID(window))10 window.Destroy()11 sdl.Quit()12 }13 fmt.Println("E

Full Screen

Full Screen

Unsubscribe

Using AI Code Generation

copy

Full Screen

1import (2var (3 event = giu.NewEvent()4func loop() {5 giu.SingleWindow("Hello").Layout(6 giu.Button("Click Me", func() {7 event.Publish()8 }),9 giu.Label(fmt.Sprintf("Count: %d", counter)),10 event.Subscribe(func() {11 fmt.Println("Count: ", counter)12 }),13}14func main() {15 wnd := giu.NewMasterWindow("Hello", 400, 200, 0)16 wnd.Run(loop)17}18func (e *Event) Unsubscribe(id int) {19 e.Lock()20 defer e.Unlock()21 delete(e.subscribers, id)22}23import (24var (25 event = giu.NewEvent()26func loop() {27 giu.SingleWindow("Hello").Layout(28 giu.Button("Click Me", func() {

Full Screen

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful