Debian Codegraph @

test/enc_test.go

raw
1 // Copyright 2012-2026 The NATS Authors
2 // Licensed under the Apache License, Version 2.0 (the "License");
3 // you may not use this file except in compliance with the License.
4 // You may obtain a copy of the License at
5 //
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 package test
15
16 import (
17 "bytes"
18 "context"
19 "strings"
20 "testing"
21 "time"
22
23 "github.com/nats-io/nats.go"
24 "github.com/nats-io/nats.go/encoders/builtin"
25 "github.com/nats-io/nats.go/encoders/protobuf"
26 "github.com/nats-io/nats.go/encoders/protobuf/testdata"
27 testservice "github.com/synadia-io/orbit.go/ntf-client"
28 )
29
30 //lint:file-ignore SA1019 Ignore deprecation warnings for EncodedConn
31
32 // newDefaultEncodedConn wraps an existing *nats.Conn as a DEFAULT_ENCODER conn.
33 func newDefaultEncodedConn(t *testing.T, nc *nats.Conn) *nats.EncodedConn {
34 t.Helper()
35 ec, err := nats.NewEncodedConn(nc, nats.DEFAULT_ENCODER)
36 if err != nil {
37 t.Fatalf("Failed to create an encoded connection: %v\n", err)
38 }
39 return ec
40 }
41
42 // encOpts returns a nats.Options pre-populated with the testservice URL of the
43 // first server in inst. Matches the shape of the historical `options` var in
44 // enc_test.go.
45 func encOpts(inst *testservice.Instance) nats.Options {
46 return nats.Options{
47 Url: inst.Servers[0].URL,
48 AllowReconnect: true,
49 MaxReconnect: 10,
50 ReconnectWait: 100 * time.Millisecond,
51 Timeout: nats.DefaultTimeout,
52 }
53 }
54
55 func TestEncBuiltinConstructorErrs(t *testing.T) {
56 withServer(t, func(t *testing.T, nc *nats.Conn) {
57 if _, err := nats.NewEncodedConn(nil, "default"); err == nil {
58 t.Fatal("Expected err for nil connection")
59 }
60 if _, err := nats.NewEncodedConn(nc, "foo22"); err == nil {
61 t.Fatal("Expected err for bad encoder")
62 }
63 nc.Close()
64 if _, err := nats.NewEncodedConn(nc, "default"); err == nil {
65 t.Fatal("Expected err for closed connection")
66 }
67 })
68 }
69
70 func TestEncBuiltinMarshalString(t *testing.T) {
71 withServer(t, func(t *testing.T, nc *nats.Conn) {
72 ec := newDefaultEncodedConn(t, nc)
73 ch := make(chan bool)
74
75 testString := "Hello World!"
76 ec.Subscribe("enc_string", func(s string) {
77 if s != testString {
78 t.Fatalf("Received test string of '%s', wanted '%s'", s, testString)
79 }
80 ch <- true
81 })
82 ec.Publish("enc_string", testString)
83 if e := Wait(ch); e != nil {
84 if ec.LastError() != nil {
85 e = ec.LastError()
86 }
87 t.Fatalf("Did not receive the message: %s", e)
88 }
89 })
90 }
91
92 func TestEncBuiltinMarshalBytes(t *testing.T) {
93 withServer(t, func(t *testing.T, nc *nats.Conn) {
94 ec := newDefaultEncodedConn(t, nc)
95 ch := make(chan bool)
96
97 testBytes := []byte("Hello World!")
98 ec.Subscribe("enc_bytes", func(b []byte) {
99 if !bytes.Equal(b, testBytes) {
100 t.Fatalf("Received test bytes of '%s', wanted '%s'", b, testBytes)
101 }
102 ch <- true
103 })
104 ec.Publish("enc_bytes", testBytes)
105 if e := Wait(ch); e != nil {
106 if ec.LastError() != nil {
107 e = ec.LastError()
108 }
109 t.Fatalf("Did not receive the message: %s", e)
110 }
111 })
112 }
113
114 func TestEncBuiltinMarshalInt(t *testing.T) {
115 withServer(t, func(t *testing.T, nc *nats.Conn) {
116 ec := newDefaultEncodedConn(t, nc)
117 ch := make(chan bool)
118
119 testN := 22
120 ec.Subscribe("enc_int", func(n int) {
121 if n != testN {
122 t.Fatalf("Received test number of %d, wanted %d", n, testN)
123 }
124 ch <- true
125 })
126 ec.Publish("enc_int", testN)
127 if e := Wait(ch); e != nil {
128 if ec.LastError() != nil {
129 e = ec.LastError()
130 }
131 t.Fatalf("Did not receive the message: %s", e)
132 }
133 })
134 }
135
136 func TestEncBuiltinMarshalInt32(t *testing.T) {
137 withServer(t, func(t *testing.T, nc *nats.Conn) {
138 ec := newDefaultEncodedConn(t, nc)
139 ch := make(chan bool)
140
141 testN := 22
142 ec.Subscribe("enc_int", func(n int32) {
143 if n != int32(testN) {
144 t.Fatalf("Received test number of %d, wanted %d", n, testN)
145 }
146 ch <- true
147 })
148 ec.Publish("enc_int", testN)
149 if e := Wait(ch); e != nil {
150 if ec.LastError() != nil {
151 e = ec.LastError()
152 }
153 t.Fatalf("Did not receive the message: %s", e)
154 }
155 })
156 }
157
158 func TestEncBuiltinMarshalInt64(t *testing.T) {
159 withServer(t, func(t *testing.T, nc *nats.Conn) {
160 ec := newDefaultEncodedConn(t, nc)
161 ch := make(chan bool)
162
163 testN := 22
164 ec.Subscribe("enc_int", func(n int64) {
165 if n != int64(testN) {
166 t.Fatalf("Received test number of %d, wanted %d", n, testN)
167 }
168 ch <- true
169 })
170 ec.Publish("enc_int", testN)
171 if e := Wait(ch); e != nil {
172 if ec.LastError() != nil {
173 e = ec.LastError()
174 }
175 t.Fatalf("Did not receive the message: %s", e)
176 }
177 })
178 }
179
180 func TestEncBuiltinMarshalFloat32(t *testing.T) {
181 withServer(t, func(t *testing.T, nc *nats.Conn) {
182 ec := newDefaultEncodedConn(t, nc)
183 ch := make(chan bool)
184
185 testN := float32(22)
186 ec.Subscribe("enc_float", func(n float32) {
187 if n != testN {
188 t.Fatalf("Received test number of %f, wanted %f", n, testN)
189 }
190 ch <- true
191 })
192 ec.Publish("enc_float", testN)
193 if e := Wait(ch); e != nil {
194 if ec.LastError() != nil {
195 e = ec.LastError()
196 }
197 t.Fatalf("Did not receive the message: %s", e)
198 }
199 })
200 }
201
202 func TestEncBuiltinMarshalFloat64(t *testing.T) {
203 withServer(t, func(t *testing.T, nc *nats.Conn) {
204 ec := newDefaultEncodedConn(t, nc)
205 ch := make(chan bool)
206
207 testN := float64(22.22)
208 ec.Subscribe("enc_float", func(n float64) {
209 if n != testN {
210 t.Fatalf("Received test number of %f, wanted %f", n, testN)
211 }
212 ch <- true
213 })
214 ec.Publish("enc_float", testN)
215 if e := Wait(ch); e != nil {
216 if ec.LastError() != nil {
217 e = ec.LastError()
218 }
219 t.Fatalf("Did not receive the message: %s", e)
220 }
221 })
222 }
223
224 func TestEncBuiltinMarshalBool(t *testing.T) {
225 withServer(t, func(t *testing.T, nc *nats.Conn) {
226 ec := newDefaultEncodedConn(t, nc)
227 ch := make(chan bool)
228 expected := make(chan bool, 1)
229
230 ec.Subscribe("enc_bool", func(b bool) {
231 val := <-expected
232 if b != val {
233 t.Fatal("Boolean values did not match")
234 }
235 ch <- true
236 })
237
238 expected <- false
239 ec.Publish("enc_bool", false)
240 if e := Wait(ch); e != nil {
241 if ec.LastError() != nil {
242 e = ec.LastError()
243 }
244 t.Fatalf("Did not receive the message: %s", e)
245 }
246
247 expected <- true
248 ec.Publish("enc_bool", true)
249 if e := Wait(ch); e != nil {
250 if ec.LastError() != nil {
251 e = ec.LastError()
252 }
253 t.Fatalf("Did not receive the message: %s", e)
254 }
255 })
256 }
257
258 func TestEncBuiltinExtendedSubscribeCB(t *testing.T) {
259 withServer(t, func(t *testing.T, nc *nats.Conn) {
260 ec := newDefaultEncodedConn(t, nc)
261 ch := make(chan bool)
262
263 testString := "Hello World!"
264 subject := "cb_args"
265
266 ec.Subscribe(subject, func(subj, s string) {
267 if s != testString {
268 t.Fatalf("Received test string of '%s', wanted '%s'", s, testString)
269 }
270 if subj != subject {
271 t.Fatalf("Received subject of '%s', wanted '%s'", subj, subject)
272 }
273 ch <- true
274 })
275 ec.Publish(subject, testString)
276 if e := Wait(ch); e != nil {
277 if ec.LastError() != nil {
278 e = ec.LastError()
279 }
280 t.Fatalf("Did not receive the message: %s", e)
281 }
282 })
283 }
284
285 func TestEncBuiltinExtendedSubscribeCB2(t *testing.T) {
286 withServer(t, func(t *testing.T, nc *nats.Conn) {
287 ec := newDefaultEncodedConn(t, nc)
288 ch := make(chan bool)
289
290 testString := "Hello World!"
291 oSubj := "cb_args"
292 oReply := "foobar"
293
294 ec.Subscribe(oSubj, func(subj, reply, s string) {
295 if s != testString {
296 t.Fatalf("Received test string of '%s', wanted '%s'", s, testString)
297 }
298 if subj != oSubj {
299 t.Fatalf("Received subject of '%s', wanted '%s'", subj, oSubj)
300 }
301 if reply != oReply {
302 t.Fatalf("Received reply of '%s', wanted '%s'", reply, oReply)
303 }
304 ch <- true
305 })
306 ec.PublishRequest(oSubj, oReply, testString)
307 if e := Wait(ch); e != nil {
308 if ec.LastError() != nil {
309 e = ec.LastError()
310 }
311 t.Fatalf("Did not receive the message: %s", e)
312 }
313 })
314 }
315
316 func TestEncBuiltinRawMsgSubscribeCB(t *testing.T) {
317 withServer(t, func(t *testing.T, nc *nats.Conn) {
318 ec := newDefaultEncodedConn(t, nc)
319 ch := make(chan bool)
320
321 testString := "Hello World!"
322 oSubj := "cb_args"
323 oReply := "foobar"
324
325 ec.Subscribe(oSubj, func(m *nats.Msg) {
326 s := string(m.Data)
327 if s != testString {
328 t.Fatalf("Received test string of '%s', wanted '%s'", s, testString)
329 }
330 if m.Subject != oSubj {
331 t.Fatalf("Received subject of '%s', wanted '%s'", m.Subject, oSubj)
332 }
333 if m.Reply != oReply {
334 t.Fatalf("Received reply of '%s', wanted '%s'", m.Reply, oReply)
335 }
336 ch <- true
337 })
338 ec.PublishRequest(oSubj, oReply, testString)
339 if e := Wait(ch); e != nil {
340 if ec.LastError() != nil {
341 e = ec.LastError()
342 }
343 t.Fatalf("Did not receive the message: %s", e)
344 }
345 })
346 }
347
348 func TestEncBuiltinRequest(t *testing.T) {
349 withServer(t, func(t *testing.T, nc *nats.Conn) {
350 ec := newDefaultEncodedConn(t, nc)
351 expectedResp := "I can help!"
352
353 ec.Subscribe("help", func(subj, reply, req string) {
354 ec.Publish(reply, expectedResp)
355 })
356
357 var resp string
358 if err := ec.Request("help", "help me", &resp, 1*time.Second); err != nil {
359 t.Fatalf("Failed at receiving proper response: %v", err)
360 }
361 if resp != expectedResp {
362 t.Fatalf("Received reply '%s', wanted '%s'", resp, expectedResp)
363 }
364 })
365 }
366
367 func TestEncBuiltinRequestReceivesMsg(t *testing.T) {
368 withServer(t, func(t *testing.T, nc *nats.Conn) {
369 ec := newDefaultEncodedConn(t, nc)
370 expectedResp := "I can help!"
371
372 ec.Subscribe("help", func(subj, reply, req string) {
373 ec.Publish(reply, expectedResp)
374 })
375
376 var resp nats.Msg
377 if err := ec.Request("help", "help me", &resp, 1*time.Second); err != nil {
378 t.Fatalf("Failed at receiving proper response: %v", err)
379 }
380 if string(resp.Data) != expectedResp {
381 t.Fatalf("Received reply '%s', wanted '%s'", string(resp.Data), expectedResp)
382 }
383 })
384 }
385
386 func TestEncBuiltinAsyncMarshalErr(t *testing.T) {
387 withServer(t, func(t *testing.T, nc *nats.Conn) {
388 ec := newDefaultEncodedConn(t, nc)
389 ch := make(chan bool)
390
391 testString := "Hello World!"
392 subject := "err_marshall"
393
394 ec.Subscribe(subject, func(subj, num int) {
395 // This will never get called.
396 })
397
398 ec.Conn.Opts.AsyncErrorCB = func(c *nats.Conn, s *nats.Subscription, err error) {
399 ch <- true
400 }
401
402 ec.Publish(subject, testString)
403 if e := Wait(ch); e != nil {
404 t.Fatalf("Did not receive the message: %s", e)
405 }
406 })
407 }
408
409 func TestEncBuiltinEncodeNil(t *testing.T) {
410 de := &builtin.DefaultEncoder{}
411 if _, err := de.Encode("foo", nil); err != nil {
412 t.Fatalf("Expected no error encoding nil: %v", err)
413 }
414 }
415
416 func TestEncBuiltinDecodeDefault(t *testing.T) {
417 de := &builtin.DefaultEncoder{}
418 b, err := de.Encode("foo", 22)
419 if err != nil {
420 t.Fatalf("Expected no error encoding number: %v", err)
421 }
422 var c chan bool
423 if err := de.Decode("foo", b, &c); err == nil {
424 t.Fatalf("Expected an error decoding")
425 }
426 }
427
428 func TestEncDrainSupported(t *testing.T) {
429 withServer(t, func(t *testing.T, nc *nats.Conn) {
430 ec := newDefaultEncodedConn(t, nc)
431 if err := ec.Drain(); err != nil {
432 t.Fatalf("Expected no error calling Drain(), got %v", err)
433 }
434 })
435 }
436
437 func TestPublishErrorAfterSubscribeDecodeError(t *testing.T) {
438 withServerInstance(t, func(t *testing.T, _ *nats.Conn, inst *testservice.Instance) {
439 opts := encOpts(inst)
440 nc, _ := opts.Connect()
441 defer nc.Close()
442
443 nc.SetErrorHandler(func(_ *nats.Conn, _ *nats.Subscription, _ error) {})
444
445 c, _ := nats.NewEncodedConn(nc, nats.JSON_ENCODER)
446
447 type Message struct {
448 Message string
449 }
450 const testSubj = "test"
451
452 c.Subscribe(testSubj, func(msg *Message) {})
453
454 // Publish invalid json to catch decode error in subscription callback
455 c.Publish(testSubj, `foo`)
456 c.Flush()
457
458 // Next publish should be successful
459 if err := c.Publish(testSubj, Message{"2"}); err != nil {
460 t.Error("Fail to send correct json message after decode error in subscription")
461 }
462 })
463 }
464
465 func TestPublishErrorAfterInvalidPublishMessage(t *testing.T) {
466 withServerInstance(t, func(t *testing.T, _ *nats.Conn, inst *testservice.Instance) {
467 opts := encOpts(inst)
468 nc, _ := opts.Connect()
469 defer nc.Close()
470 c, _ := nats.NewEncodedConn(nc, protobuf.PROTOBUF_ENCODER)
471 const testSubj = "test"
472
473 c.Publish(testSubj, &testdata.Person{Name: "Anatolii"})
474
475 // Publish invalid protobuf message to catch decode error
476 c.Publish(testSubj, "foo")
477
478 // Next publish with valid protobuf message should be successful
479 if err := c.Publish(testSubj, &testdata.Person{Name: "Anatolii"}); err != nil {
480 t.Error("Fail to send correct protobuf message after invalid message publishing", err)
481 }
482 })
483 }
484
485 func TestVariousFailureConditions(t *testing.T) {
486 withServerInstance(t, func(t *testing.T, _ *nats.Conn, inst *testservice.Instance) {
487 dch := make(chan bool)
488
489 opts := encOpts(inst)
490 opts.AsyncErrorCB = func(_ *nats.Conn, _ *nats.Subscription, e error) {
491 dch <- true
492 }
493 nc, _ := opts.Connect()
494 nc.Close()
495
496 if _, err := nats.NewEncodedConn(nil, protobuf.PROTOBUF_ENCODER); err == nil {
497 t.Fatal("Expected an error")
498 }
499
500 if _, err := nats.NewEncodedConn(nc, protobuf.PROTOBUF_ENCODER); err == nil || err != nats.ErrConnectionClosed {
501 t.Fatalf("Wrong error: %v instead of %v", err, nats.ErrConnectionClosed)
502 }
503
504 nc, _ = opts.Connect()
505 defer nc.Close()
506
507 if _, err := nats.NewEncodedConn(nc, "foo"); err == nil {
508 t.Fatal("Expected an error")
509 }
510
511 c, err := nats.NewEncodedConn(nc, protobuf.PROTOBUF_ENCODER)
512 if err != nil {
513 t.Fatalf("Unable to create encoded connection: %v", err)
514 }
515 defer c.Close()
516
517 if _, err := c.Subscribe("bar", func(subj, obj string) {}); err != nil {
518 t.Fatalf("Unable to create subscription: %v", err)
519 }
520
521 if err := c.Publish("bar", &testdata.Person{Name: "Ivan"}); err != nil {
522 t.Fatalf("Unable to publish: %v", err)
523 }
524
525 if err := Wait(dch); err != nil {
526 t.Fatal("Did not get the async error callback")
527 }
528
529 if err := c.PublishRequest("foo", "bar", "foo"); err == nil {
530 t.Fatal("Expected an error")
531 }
532
533 if err := c.Request("foo", "foo", nil, 2*time.Second); err == nil {
534 t.Fatal("Expected an error")
535 }
536
537 nc.Close()
538
539 if err := c.PublishRequest("foo", "bar", &testdata.Person{Name: "Ivan"}); err == nil {
540 t.Fatal("Expected an error")
541 }
542
543 resp := &testdata.Person{}
544 if err := c.Request("foo", &testdata.Person{Name: "Ivan"}, resp, 2*time.Second); err == nil {
545 t.Fatal("Expected an error")
546 }
547
548 if _, err := c.Subscribe("foo", nil); err == nil {
549 t.Fatal("Expected an error")
550 }
551
552 if _, err := c.Subscribe("foo", func() {}); err == nil {
553 t.Fatal("Expected an error")
554 }
555
556 func() {
557 defer func() {
558 if r := recover(); r == nil {
559 t.Fatal("Expected an error")
560 }
561 }()
562 if _, err := c.Subscribe("foo", "bar"); err == nil {
563 t.Fatal("Expected an error")
564 }
565 }()
566 })
567 }
568
569 func TestEncodedConnRequest(t *testing.T) {
570 withServerInstance(t, func(t *testing.T, _ *nats.Conn, inst *testservice.Instance) {
571 dch := make(chan bool)
572
573 opts := encOpts(inst)
574 nc, _ := opts.Connect()
575 defer nc.Close()
576
577 c, err := nats.NewEncodedConn(nc, protobuf.PROTOBUF_ENCODER)
578 if err != nil {
579 t.Fatalf("Unable to create encoded connection: %v", err)
580 }
581 defer c.Close()
582
583 sentName := "Ivan"
584 recvName := "Kozlovic"
585
586 if _, err := c.Subscribe("foo", func(_, reply string, p *testdata.Person) {
587 if p.Name != sentName {
588 t.Fatalf("Got wrong name: %v instead of %v", p.Name, sentName)
589 }
590 c.Publish(reply, &testdata.Person{Name: recvName})
591 dch <- true
592 }); err != nil {
593 t.Fatalf("Unable to create subscription: %v", err)
594 }
595 if _, err := c.Subscribe("foo", func(_ string, p *testdata.Person) {
596 if p.Name != sentName {
597 t.Fatalf("Got wrong name: %v instead of %v", p.Name, sentName)
598 }
599 dch <- true
600 }); err != nil {
601 t.Fatalf("Unable to create subscription: %v", err)
602 }
603
604 if err := c.Publish("foo", &testdata.Person{Name: sentName}); err != nil {
605 t.Fatalf("Unable to publish: %v", err)
606 }
607
608 if err := Wait(dch); err != nil {
609 t.Fatal("Did not get message")
610 }
611 if err := Wait(dch); err != nil {
612 t.Fatal("Did not get message")
613 }
614
615 response := &testdata.Person{}
616 if err := c.Request("foo", &testdata.Person{Name: sentName}, response, 2*time.Second); err != nil {
617 t.Fatalf("Unable to publish: %v", err)
618 }
619 if response.Name != recvName {
620 t.Fatalf("Wrong response: %v instead of %v", response.Name, recvName)
621 }
622
623 if err := Wait(dch); err != nil {
624 t.Fatal("Did not get message")
625 }
626 if err := Wait(dch); err != nil {
627 t.Fatal("Did not get message")
628 }
629
630 c2, err := nats.NewEncodedConn(nc, nats.GOB_ENCODER)
631 if err != nil {
632 t.Fatalf("Unable to create encoded connection: %v", err)
633 }
634 defer c2.Close()
635
636 if _, err := c2.QueueSubscribe("bar", "baz", func(m *nats.Msg) {
637 response := &nats.Msg{Subject: m.Reply, Data: []byte(recvName)}
638 c2.Conn.PublishMsg(response)
639 dch <- true
640 }); err != nil {
641 t.Fatalf("Unable to create subscription: %v", err)
642 }
643
644 mReply := nats.Msg{}
645 if err := c2.Request("bar", &nats.Msg{Data: []byte(sentName)}, &mReply, 2*time.Second); err != nil {
646 t.Fatalf("Unable to send request: %v", err)
647 }
648 if string(mReply.Data) != recvName {
649 t.Fatalf("Wrong reply: %v instead of %v", string(mReply.Data), recvName)
650 }
651
652 if err := Wait(dch); err != nil {
653 t.Fatal("Did not get message")
654 }
655
656 if c.LastError() != nil {
657 t.Fatalf("Unexpected connection error: %v", c.LastError())
658 }
659 if c2.LastError() != nil {
660 t.Fatalf("Unexpected connection error: %v", c2.LastError())
661 }
662 })
663 }
664
665 func TestRequestGOB(t *testing.T) {
666 withServerInstance(t, func(t *testing.T, _ *nats.Conn, inst *testservice.Instance) {
667 type Request struct {
668 Name string
669 }
670
671 type Person struct {
672 Name string
673 Age int
674 }
675
676 nc, err := nats.Connect(inst.Servers[0].URL)
677 if err != nil {
678 t.Fatalf("Could not connect: %v", err)
679 }
680 defer nc.Close()
681
682 ec, err := nats.NewEncodedConn(nc, nats.GOB_ENCODER)
683 if err != nil {
684 t.Fatalf("Unable to create encoded connection: %v", err)
685 }
686 defer ec.Close()
687
688 ec.QueueSubscribe("foo.request", "g", func(subject, reply string, r *Request) {
689 if r.Name != "meg" {
690 t.Fatalf("Expected request to be 'meg', got %q", r)
691 }
692 response := &Person{Name: "meg", Age: 21}
693 ec.Publish(reply, response)
694 })
695
696 reply := Person{}
697 if err := ec.Request("foo.request", &Request{Name: "meg"}, &reply, time.Second); err != nil {
698 t.Fatalf("Failed to receive response: %v", err)
699 }
700 if reply.Name != "meg" || reply.Age != 21 {
701 t.Fatalf("Did not receive proper response, %+v", reply)
702 }
703 })
704 }
705
706 func TestContextEncodedRequestWithTimeout(t *testing.T) {
707 withServer(t, func(t *testing.T, nc *nats.Conn) {
708 c, err := nats.NewEncodedConn(nc, nats.JSON_ENCODER)
709 if err != nil {
710 t.Fatalf("Unable to create encoded connection: %v", err)
711 }
712 defer c.Close()
713
714 deadline := time.Now().Add(100 * time.Millisecond)
715 ctx, cancelCB := context.WithDeadline(context.Background(), deadline)
716 defer cancelCB()
717
718 type request struct {
719 Message string `json:"message"`
720 }
721 type response struct {
722 Code int `json:"code"`
723 }
724 c.Subscribe("slow", func(_, reply string, req *request) {
725 if req.Message != "Hello" {
726 t.Errorf("Expected to receive request with %q, got %q", "Hello", req.Message)
727 }
728 time.Sleep(40 * time.Millisecond)
729 c.Publish(reply, &response{Code: 200})
730 })
731
732 for i := 0; i < 2; i++ {
733 req := &request{Message: "Hello"}
734 resp := &response{}
735 if err := c.RequestWithContext(ctx, "slow", req, resp); err != nil {
736 t.Fatalf("Expected encoded request with context to not fail: %s", err)
737 }
738 if resp.Code != 200 {
739 t.Errorf("Expected to receive %v, got: %v", 200, resp.Code)
740 }
741 }
742
743 req := &request{Message: "Hello"}
744 resp := &response{}
745 err = c.RequestWithContext(ctx, "slow", req, resp)
746 if err == nil {
747 t.Fatal("Expected request with context to reach deadline")
748 }
749
750 type timeoutError interface {
751 Timeout() bool
752 }
753 timeoutErr, ok := err.(timeoutError)
754 if !ok || !timeoutErr.Timeout() {
755 t.Errorf("Expected to have a timeout error")
756 }
757 expected := `context deadline exceeded`
758 if !strings.Contains(err.Error(), expected) {
759 t.Errorf("Expected %q error, got: %q", expected, err.Error())
760 }
761 })
762 }
763
764 func TestContextEncodedRequestWithTimeoutCanceled(t *testing.T) {
765 withServer(t, func(t *testing.T, nc *nats.Conn) {
766 c, err := nats.NewEncodedConn(nc, nats.JSON_ENCODER)
767 if err != nil {
768 t.Fatalf("Unable to create encoded connection: %v", err)
769 }
770 defer c.Close()
771
772 ctx, cancelCB := context.WithTimeout(context.Background(), 100*time.Millisecond)
773 defer cancelCB()
774
775 type request struct {
776 Message string `json:"message"`
777 }
778 type response struct {
779 Code int `json:"code"`
780 }
781
782 c.Subscribe("fast", func(_, reply string, req *request) {
783 if req.Message != "Hello" {
784 t.Errorf("Expected to receive request with %q, got %q", "Hello", req.Message)
785 }
786 time.Sleep(40 * time.Millisecond)
787 c.Publish(reply, &response{Code: 200})
788 })
789
790 req := &request{Message: "Hello"}
791 resp := &response{}
792 c.RequestWithContext(ctx, "fast", req, resp)
793 if resp.Code != 200 {
794 t.Errorf("Expected to receive %d, got: %d", 200, resp.Code)
795 }
796
797 cancelCB()
798
799 err = c.RequestWithContext(ctx, "fast", req, resp)
800 if err == nil {
801 t.Fatal("Expected request with timeout context to fail")
802 }
803
804 type timeoutError interface {
805 Timeout() bool
806 }
807 if _, ok := err.(timeoutError); ok {
808 t.Errorf("Expected to not have a timeout error")
809 }
810 expected := `context canceled`
811 if !strings.Contains(err.Error(), expected) {
812 t.Errorf("Expected %q error, got: %q", expected, err.Error())
813 }
814
815 err = c.RequestWithContext(ctx, "fast", req, resp)
816 if err == nil {
817 t.Fatal("Expected request with timeout context to fail")
818 }
819 })
820 }
821
822 func TestContextEncodedRequestWithCancel(t *testing.T) {
823 withServer(t, func(t *testing.T, nc *nats.Conn) {
824 c, err := nats.NewEncodedConn(nc, nats.JSON_ENCODER)
825 if err != nil {
826 t.Fatalf("Unable to create encoded connection: %v", err)
827 }
828 defer c.Close()
829
830 ctx, cancelCB := context.WithCancel(context.Background())
831 defer cancelCB()
832
833 expirationTimer := time.AfterFunc(100*time.Millisecond, func() {
834 cancelCB()
835 })
836
837 type request struct {
838 Message string `json:"message"`
839 }
840 type response struct {
841 Code int `json:"code"`
842 }
843 c.Subscribe("slow", func(_, reply string, req *request) {
844 if req.Message != "Hello" {
845 t.Errorf("Expected to receive request with %q, got %q", "Hello", req.Message)
846 }
847 time.Sleep(40 * time.Millisecond)
848 c.Publish(reply, &response{Code: 200})
849 })
850 c.Subscribe("slower", func(_, reply string, req *request) {
851 if req.Message != "World" {
852 t.Errorf("Expected to receive request with %q, got %q", "World", req.Message)
853 }
854 expirationTimer.Reset(100 * time.Millisecond)
855 time.Sleep(90 * time.Millisecond)
856 c.Publish(reply, &response{Code: 200})
857 })
858
859 for i := 0; i < 2; i++ {
860 req := &request{Message: "Hello"}
861 resp := &response{}
862 if err := c.RequestWithContext(ctx, "slow", req, resp); err != nil {
863 t.Fatalf("Expected encoded request with context to not fail: %s", err)
864 }
865 if resp.Code != 200 {
866 t.Errorf("Expected to receive %v, got: %v", 200, resp.Code)
867 }
868 }
869
870 for i := 0; i < 10; i++ {
871 req := &request{Message: "World"}
872 resp := &response{}
873 if err := c.RequestWithContext(ctx, "slower", req, resp); err != nil {
874 t.Fatalf("Expected request with context to not fail: %s", err)
875 }
876 if resp.Code != 200 {
877 t.Errorf("Expected to receive %d, got: %d", 200, resp.Code)
878 }
879 }
880
881 req := &request{Message: "Hello"}
882 resp := &response{}
883 err = c.RequestWithContext(ctx, "slow", req, resp)
884 if err == nil {
885 t.Fatal("Expected request with cancellation context to fail")
886 }
887
888 type timeoutError interface {
889 Timeout() bool
890 }
891 if _, ok := err.(timeoutError); ok {
892 t.Errorf("Expected to not have a timeout error")
893 }
894 expected := `context canceled`
895 if !strings.Contains(err.Error(), expected) {
896 t.Errorf("Expected %q error, got: %q", expected, err.Error())
897 }
898 })
899 }
900
901 func TestContextEncodedRequestWithDeadline(t *testing.T) {
902 withServer(t, func(t *testing.T, nc *nats.Conn) {
903 c, err := nats.NewEncodedConn(nc, nats.JSON_ENCODER)
904 if err != nil {
905 t.Fatalf("Unable to create encoded connection: %v", err)
906 }
907 defer c.Close()
908
909 deadline := time.Now().Add(100 * time.Millisecond)
910 ctx, cancelCB := context.WithDeadline(context.Background(), deadline)
911 defer cancelCB()
912
913 type request struct {
914 Message string `json:"message"`
915 }
916 type response struct {
917 Code int `json:"code"`
918 }
919 c.Subscribe("slow", func(_, reply string, req *request) {
920 if req.Message != "Hello" {
921 t.Errorf("Expected to receive request with %q, got %q", "Hello", req.Message)
922 }
923 time.Sleep(40 * time.Millisecond)
924 c.Publish(reply, &response{Code: 200})
925 })
926
927 for i := 0; i < 2; i++ {
928 req := &request{Message: "Hello"}
929 resp := &response{}
930 if err := c.RequestWithContext(ctx, "slow", req, resp); err != nil {
931 t.Fatalf("Expected encoded request with context to not fail: %s", err)
932 }
933 if resp.Code != 200 {
934 t.Errorf("Expected to receive %v, got: %v", 200, resp.Code)
935 }
936 }
937
938 req := &request{Message: "Hello"}
939 resp := &response{}
940 err = c.RequestWithContext(ctx, "slow", req, resp)
941 if err == nil {
942 t.Fatal("Expected request with context to reach deadline")
943 }
944
945 type timeoutError interface {
946 Timeout() bool
947 }
948 timeoutErr, ok := err.(timeoutError)
949 if !ok || !timeoutErr.Timeout() {
950 t.Errorf("Expected to have a timeout error")
951 }
952 expected := `context deadline exceeded`
953 if !strings.Contains(err.Error(), expected) {
954 t.Errorf("Expected %q error, got: %q", expected, err.Error())
955 }
956 })
957 }
958
959 func TestEncodedContextInvalid(t *testing.T) {
960 withServer(t, func(t *testing.T, nc *nats.Conn) {
961 c, err := nats.NewEncodedConn(nc, nats.JSON_ENCODER)
962 if err != nil {
963 t.Fatalf("Unable to create encoded connection: %v", err)
964 }
965 defer c.Close()
966
967 type request struct {
968 Message string `json:"message"`
969 }
970 type response struct {
971 Code int `json:"code"`
972 }
973 req := &request{Message: "Hello"}
974 resp := &response{}
975 //lint:ignore SA1012 testing that passing nil fails
976 err = c.RequestWithContext(nil, "slow", req, resp)
977 if err == nil {
978 t.Fatal("Expected request to fail with error")
979 }
980 if err != nats.ErrInvalidContext {
981 t.Errorf("Expected request to fail with invalid context: %s", err)
982 }
983 })
984 }