-
Notifications
You must be signed in to change notification settings - Fork 197
/
Copy pathtest_js.py
2176 lines (1713 loc) · 64.2 KB
/
test_js.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import asyncio
import datetime
import random
import time
import unittest
import uuid
import pytest
import nats
import nats.js.api
from nats.aio.msg import Msg
from nats.aio.client import Client as NATS, __version__
from nats.aio.errors import *
from nats.errors import *
from nats.js.errors import *
from tests.utils import *
class PublishTest(SingleJetStreamServerTestCase):
@async_test
async def test_publish(self):
nc = NATS()
await nc.connect()
js = nc.jetstream()
with pytest.raises(NoStreamResponseError):
await js.publish("foo", b'bar')
await js.add_stream(name="QUUX", subjects=["quux"])
ack = await js.publish("quux", b'bar:1', stream="QUUX")
assert ack.stream == "QUUX"
assert ack.seq == 1
ack = await js.publish("quux", b'bar:2')
assert ack.stream == "QUUX"
assert ack.seq == 2
with pytest.raises(BadRequestError) as err:
await js.publish("quux", b'bar', stream="BAR")
assert err.value.err_code == 10060
await nc.close()
@async_test
async def test_publish_verbose(self):
nc = NATS()
await nc.connect(verbose=False)
js = nc.jetstream()
with pytest.raises(NoStreamResponseError):
await js.publish("foo", b'bar')
await js.add_stream(name="QUUX", subjects=["quux"])
ack = await js.publish("quux", b'bar:1', stream="QUUX")
assert ack.stream == "QUUX"
assert ack.seq == 1
ack = await js.publish("quux", b'bar:2')
assert ack.stream == "QUUX"
assert ack.seq == 2
with pytest.raises(BadRequestError) as err:
await js.publish("quux", b'bar', stream="BAR")
assert err.value.err_code == 10060
await nc.close()
class PullSubscribeTest(SingleJetStreamServerTestCase):
@async_test
async def test_auto_create_consumer(self):
nc = NATS()
await nc.connect()
js = nc.jetstream()
await js.add_stream(name="TEST2", subjects=["a1", "a2", "a3", "a4"])
for i in range(1, 10):
await js.publish("a1", f'a1:{i}'.encode())
# Should use a2 as the filter subject and receive a subset.
sub = await js.pull_subscribe("a2", "auto")
await js.publish("a2", b'one')
for i in range(10, 20):
await js.publish("a3", f'a3:{i}'.encode())
msgs = await sub.fetch(1)
msg = msgs[0]
await msg.ack()
assert msg.data == b'one'
# Getting another message should timeout for the a2 subject.
with pytest.raises(TimeoutError):
await sub.fetch(1, timeout=1)
# Customize consumer config.
sub = await js.pull_subscribe(
"a2", "auto2", config=nats.js.api.ConsumerConfig(max_waiting=10)
)
msgs = await sub.fetch(1)
msg = msgs[0]
await msg.ack()
assert msg.data == b'one'
info = await js.consumer_info("TEST2", "auto2")
assert info.config.max_waiting == 10
sub = await js.pull_subscribe("a3", "auto3")
msgs = await sub.fetch(1)
msg = msgs[0]
await msg.ack()
assert msg.data == b'a3:10'
# Getting all messages from stream.
sub = await js.pull_subscribe("", "all")
msgs = await sub.fetch(1)
msg = msgs[0]
await msg.ack()
assert msg.data == b'a1:1'
for _ in range(2, 10):
msgs = await sub.fetch(1)
msg = msgs[0]
await msg.ack()
# subject a2
msgs = await sub.fetch(1)
msg = msgs[0]
await msg.ack()
assert msg.data == b'one'
# subject a3
msgs = await sub.fetch(1)
msg = msgs[0]
await msg.ack()
assert msg.data == b'a3:10'
await nc.close()
await asyncio.sleep(1)
@async_test
async def test_fetch_one(self):
nc = NATS()
await nc.connect()
js = nc.jetstream()
await js.add_stream(name="TEST1", subjects=["foo.1", "bar"])
ack = await js.publish("foo.1", f'Hello from NATS!'.encode())
assert ack.stream == "TEST1"
assert ack.seq == 1
# Bind to the consumer that is already present.
sub = await js.pull_subscribe("foo.1", "dur")
msgs = await sub.fetch(1)
for msg in msgs:
await msg.ack()
msg = msgs[0]
assert msg.metadata.sequence.stream == 1
assert msg.metadata.sequence.consumer == 1
assert datetime.datetime.now() > msg.metadata.timestamp
assert msg.metadata.num_pending == 0
assert msg.metadata.num_delivered == 1
with pytest.raises(asyncio.TimeoutError):
await sub.fetch(timeout=1)
for i in range(0, 10):
await js.publish(
"foo.1", f"i:{i}".encode(), headers={'hello': 'world'}
)
# nak
msgs = await sub.fetch()
msg = msgs[0]
info = await js.consumer_info("TEST1", "dur", timeout=1)
assert msg.header == {'hello': 'world'}
await msg.nak()
info = await js.consumer_info("TEST1", "dur", timeout=1)
assert info.stream_name == "TEST1"
assert info.num_ack_pending == 1
assert info.num_redelivered == 0
# in_progress
msgs = await sub.fetch()
for msg in msgs:
await msg.in_progress()
# term
msgs = await sub.fetch()
for msg in msgs:
await msg.term()
await asyncio.sleep(1)
info = await js.consumer_info("TEST1", "dur", timeout=1)
assert info.num_ack_pending == 1
assert info.num_redelivered == 1
await nc.close()
@async_test
async def test_fetch_one_wait_forever(self):
nc = NATS()
await nc.connect()
js = nc.jetstream()
await js.add_stream(name="TEST111", subjects=["foo.111"])
ack = await js.publish("foo.111", f'Hello from NATS!'.encode())
assert ack.stream == "TEST111"
assert ack.seq == 1
# Bind to the consumer that is already present.
sub = await js.pull_subscribe("foo.111", "dur")
msgs = await sub.fetch(1, None)
for msg in msgs:
await msg.ack()
msg = msgs[0]
assert msg.metadata.sequence.stream == 1
assert msg.metadata.sequence.consumer == 1
assert datetime.datetime.now() > msg.metadata.timestamp
assert msg.metadata.num_pending == 0
assert msg.metadata.num_delivered == 1
received = False
async def f():
nonlocal received
await sub.fetch(1, None)
received = True
task = asyncio.create_task(f())
assert received is False
await asyncio.sleep(1)
assert received is False
await asyncio.sleep(1)
await js.publish("foo.111", 'Hello from NATS!'.encode())
await task
assert received
@async_test
async def test_add_pull_consumer_via_jsm(self):
nc = NATS()
await nc.connect()
js = nc.jetstream()
await js.add_stream(name="events", subjects=["events.a"])
await js.add_consumer(
"events",
durable_name="a",
deliver_policy=nats.js.api.DeliverPolicy.ALL,
max_deliver=20,
max_waiting=512,
# ack_wait=30,
max_ack_pending=1024,
filter_subject="events.a"
)
await js.publish("events.a", b'hello world')
sub = await js.pull_subscribe_bind("a", stream="events")
msgs = await sub.fetch(1)
for msg in msgs:
await msg.ack()
info = await js.consumer_info("events", "a")
assert 0 == info.num_pending
@async_long_test
async def test_fetch_n(self):
nc = NATS()
await nc.connect()
server_version = nc.connected_server_version
if server_version.major == 2 and server_version.minor < 9:
pytest.skip('needs to run at least on v2.9.0')
js = nc.jetstream()
await js.add_stream(name="TESTN", subjects=["a", "b", "c"])
for i in range(0, 10):
await js.publish("a", f'i:{i}'.encode())
sub = await js.pull_subscribe(
"a",
"durable-1",
config=nats.js.api.ConsumerConfig(max_waiting=3),
)
info = await sub.consumer_info()
assert info.config.max_waiting == 3
# 10 messages
# -5 fetched
# -----------
# 5 pending
msgs = await sub.fetch(5)
assert len(msgs) == 5
i = 0
for msg in msgs:
assert msg.data == f'i:{i}'.encode()
await msg.ack()
i += 1
info = await sub.consumer_info()
assert info.num_pending == 5
# 5 messages
# -10 fetched
# -----------
# 5 pending
msgs = await sub.fetch(10, timeout=0.5)
assert len(msgs) == 5
i = 5
for msg in msgs:
assert msg.data == f'i:{i}'.encode()
await msg.ack()
i += 1
info = await sub.consumer_info()
assert info.num_ack_pending == 0
assert info.num_redelivered == 0
assert info.delivered.stream_seq == 10
assert info.delivered.consumer_seq == 10
assert info.ack_floor.stream_seq == 10
assert info.ack_floor.consumer_seq == 10
assert info.num_pending == 0
# 1 message
# -1 fetched
# ----------
# 0 pending
# 1 ack pending
await js.publish("a", b'i:11')
msgs = await sub.fetch(2, timeout=0.5)
# Leave this message unacked.
msg = msgs[0]
unacked_msg = msg
assert msg.data == b'i:11'
info = await sub.consumer_info()
assert info.num_waiting < 2
assert info.num_pending == 0
assert info.num_ack_pending == 1
inflight = []
inflight.append(msg)
# +1 message
# 1 extra from before but request has expired so does not count.
# +1 ack pending since previous message not acked.
# +1 pending to be consumed.
await js.publish("a", b'i:12')
# Inspect the internal buffer which should be a 408 at this point.
try:
msg = await sub._sub.next_msg(timeout=0.5)
assert msg.headers['Status'] == '408'
except (nats.errors.TimeoutError, TypeError):
pass
info = await sub.consumer_info()
assert info.num_waiting == 0
assert info.num_pending == 1
assert info.num_ack_pending == 1
# Start background task that gathers messages.
fut = asyncio.create_task(sub.fetch(3, timeout=2))
await asyncio.sleep(0.5)
await js.publish("a", b'i:13')
await js.publish("a", b'i:14')
# It should receive the first one that is available already only.
msgs = await fut
assert len(msgs) == 1
for msg in msgs:
await msg.ack_sync()
info = await sub.consumer_info()
assert info.num_ack_pending == 1
assert info.num_redelivered == 0
assert info.num_waiting == 0
assert info.num_pending == 2
assert info.delivered.stream_seq == 12
assert info.delivered.consumer_seq == 12
# Message 10 is the last message that got acked.
assert info.ack_floor.stream_seq == 10
assert info.ack_floor.consumer_seq == 10
# Unacked last message so that ack floor is updated.
await unacked_msg.ack_sync()
info = await sub.consumer_info()
assert info.num_pending == 2
assert info.ack_floor.stream_seq == 12
assert info.ack_floor.consumer_seq == 12
# No messages at this point.
msgs = await sub.fetch(1, timeout=0.5)
self.assertEqual(msgs[0].data, b'i:13')
msgs = await sub.fetch(1, timeout=0.5)
self.assertEqual(msgs[0].data, b'i:14')
with pytest.raises(TimeoutError):
await sub.fetch(1, timeout=0.5)
with pytest.raises(nats.errors.Error):
await sub.fetch(1, timeout=0.5)
# Max waiting is 3 so it should be stuck at 2 but consumer_info resets this.
info = await sub.consumer_info()
assert info.num_waiting <= 1
await nc.close()
@async_test
async def test_fetch_max_waiting_fetch_one(self):
nc = NATS()
await nc.connect()
js = nc.jetstream()
await js.add_stream(name="TEST3", subjects=["max"])
sub = await js.pull_subscribe(
"max",
"example",
config=nats.js.api.ConsumerConfig(max_waiting=3),
)
results = await asyncio.gather(
sub.fetch(1, timeout=1),
sub.fetch(1, timeout=1),
sub.fetch(1, timeout=1),
sub.fetch(1, timeout=1),
sub.fetch(1, timeout=1),
return_exceptions=True,
)
for e in results:
if isinstance(e, asyncio.TimeoutError):
continue
else:
assert isinstance(e, APIError)
break
# info = await js.consumer_info("TEST3", "example")
# assert info.num_waiting == 0
for i in range(0, 10):
await js.publish("max", b'foo')
async def pub():
while True:
await js.publish("max", b'foo')
await asyncio.sleep(0)
producer = asyncio.create_task(pub())
async def cb():
future = await asyncio.gather(
sub.fetch(1, timeout=1),
sub.fetch(512, timeout=1),
sub.fetch(512, timeout=1),
sub.fetch(1, timeout=1),
sub.fetch(1, timeout=1),
sub.fetch(1, timeout=1),
sub.fetch(1, timeout=1),
return_exceptions=True,
)
for e in future:
if isinstance(e, (asyncio.TimeoutError, APIError)):
continue
tasks = []
for _ in range(0, 100):
task = asyncio.create_task(cb())
tasks.append(task)
await asyncio.sleep(0)
for task in tasks:
await task
producer.cancel()
await nc.close()
@async_test
async def test_fetch_max_waiting_fetch_n(self):
nc = NATS()
await nc.connect()
js = nc.jetstream()
await js.add_stream(name="TEST31", subjects=["max"])
sub = await js.pull_subscribe(
"max",
"example",
config=nats.js.api.ConsumerConfig(max_waiting=3),
)
results = await asyncio.gather(
sub.fetch(2, timeout=1),
sub.fetch(2, timeout=1),
sub.fetch(2, timeout=1),
sub.fetch(2, timeout=1),
sub.fetch(2, timeout=1),
return_exceptions=True,
)
for e in results:
if isinstance(e, asyncio.TimeoutError):
continue
elif isinstance(e, APIError):
raise e
# info = await js.consumer_info("TEST31", "example")
# assert info.num_waiting == 0
await nc.close()
@async_long_test
async def test_fetch_concurrent(self):
nc = await nats.connect()
js = nc.jetstream()
await js.add_stream(name="TESTN10", subjects=["a", "b", "c"])
async def go_publish():
i = 0
while True:
payload = f'{i}'.encode()
await js.publish("a", payload)
i += 1
await asyncio.sleep(0.01)
task = asyncio.create_task(go_publish())
sub = await js.pull_subscribe(
"a",
"durable-1",
config=nats.js.api.ConsumerConfig(max_waiting=3),
)
info = await sub.consumer_info()
assert info.config.max_waiting == 3
start_time = time.monotonic()
errors = []
m = {}
while True:
a = time.monotonic() - start_time
if a > 2: # seconds
break
try:
results = await asyncio.gather(
sub.fetch(2, timeout=1),
sub.fetch(2, timeout=1),
sub.fetch(2, timeout=1),
sub.fetch(2, timeout=1),
sub.fetch(2, timeout=1),
sub.fetch(2, timeout=1),
# return_exceptions=True,
)
for batch in results:
for msg in batch:
m[int(msg.data.decode())] = msg
assert msg.header is None
except Exception as e:
errors.append(e)
for e in errors:
if isinstance(e, asyncio.TimeoutError):
continue
else:
# There should be no API level errors on fetch,
# only timeouts or messages.
raise e
task.cancel()
await nc.close()
@async_long_test
async def test_fetch_headers(self):
nc = NATS()
await nc.connect()
js = nc.jetstream()
await js.add_stream(name="test-nats", subjects=["test.nats.1"])
await js.publish("test.nats.1", b'first_msg', headers={'': ''})
sub = await js.pull_subscribe("test.nats.1", "durable")
msgs = await sub.fetch(1)
assert msgs[0].header == None
msg = await js.get_msg("test-nats", 1)
assert msgs[0].header == None
# NOTE: Headers with empty spaces are ignored.
await js.publish(
"test.nats.1",
b'second_msg',
headers={
' AAA AAA AAA ': ' ',
' B B B ': ' '
}
)
msgs = await sub.fetch(1)
assert msgs[0].header == None
msg = await js.get_msg("test-nats", 2)
assert msgs[0].header == None
# NOTE: As soon as there is a message with empty spaces are ignored.
await js.publish(
"test.nats.1",
b'third_msg',
headers={
' AAA-AAA-AAA ': ' a ',
' AAA-BBB-AAA ': ' ',
' B B B ': ' a '
}
)
msgs = await sub.fetch(1)
assert msgs[0].header['AAA-AAA-AAA'] == 'a'
assert msgs[0].header['AAA-BBB-AAA'] == ''
msg = await js.get_msg("test-nats", 3)
assert msg.header['AAA-AAA-AAA'] == 'a'
assert msg.header['AAA-BBB-AAA'] == ''
# FIXME: An unprocessable key makes the rest of the header be invalid.
await js.publish(
"test.nats.1",
b'third_msg',
headers={
' AAA AAA AAA ': ' a ',
' AAA-BBB-AAA ': ' b ',
' B B B ': ' a '
}
)
msgs = await sub.fetch(1)
assert msgs[0].header == None
msg = await js.get_msg("test-nats", 4)
assert msg.header == None
await nc.close()
@async_test
async def test_pull_subscribe_limits(self):
nc = NATS()
errors = []
async def error_cb(err):
errors.append(err)
await nc.connect(error_cb=error_cb)
js = nc.jetstream()
await js.add_stream(name="TEST2", subjects=["a1", "a2", "a3", "a4"])
for i in range(1, 10):
await js.publish("a1", f'a1:{i}'.encode())
# Shorter msgs limit, and disable bytes limit to not get slow consumers.
sub = await js.pull_subscribe(
"a3",
"auto",
pending_msgs_limit=50,
pending_bytes_limit=-1,
)
for i in range(0, 100):
await js.publish("a3", b'test')
# Internal buffer will drop some of the messages due to reaching limit.
msgs = await sub.fetch(100, timeout=1)
i = 0
for msg in msgs:
i += 1
await asyncio.sleep(0)
await msg.ack()
assert 50 <= len(msgs) <= 51
assert sub.pending_msgs == 0
assert sub.pending_bytes == 0
# Infinite queue and pending bytes.
sub = await js.pull_subscribe(
"a3",
"two",
pending_msgs_limit=-1,
pending_bytes_limit=-1,
)
msgs = await sub.fetch(100, timeout=1)
for msg in msgs:
await msg.ack()
assert len(msgs) <= 100
assert sub.pending_msgs == 0
assert sub.pending_bytes == 0
# Consumer has a single message pending but none in buffer.
await js.publish("a3", b'last message')
info = await sub.consumer_info()
assert info.num_pending == 1
assert sub.pending_msgs == 0
# Remove interest
await sub.unsubscribe()
with pytest.raises(TimeoutError):
await sub.fetch(1, timeout=1)
# The pending message is still there, but not possible to consume.
info = await sub.consumer_info()
assert info.num_pending == 1
await nc.close()
class JSMTest(SingleJetStreamServerTestCase):
@async_test
async def test_stream_management(self):
nc = NATS()
await nc.connect()
jsm = nc.jsm()
acc = await jsm.account_info()
assert isinstance(acc, nats.js.api.AccountInfo)
# Create stream
stream = await jsm.add_stream(
name="hello", subjects=["hello", "world", "hello.>"]
)
assert isinstance(stream, nats.js.api.StreamInfo)
assert isinstance(stream.config, nats.js.api.StreamConfig)
assert stream.config.name == "hello"
assert isinstance(stream.state, nats.js.api.StreamState)
# Create without name
with pytest.raises(ValueError):
await jsm.add_stream(subjects=["hello", "world", "hello.>"])
# Create with config, but without name
with pytest.raises(ValueError):
await jsm.add_stream(nats.js.api.StreamConfig())
# Create with config, name is provided as kwargs
stream_with_name = await jsm.add_stream(
nats.js.api.StreamConfig(), name="hi"
)
assert stream_with_name.config.name == "hi"
# Get info
current = await jsm.stream_info("hello")
stream.did_create = None
assert stream == current
assert isinstance(current, nats.js.api.StreamInfo)
assert isinstance(current.config, nats.js.api.StreamConfig)
assert current.config.name == "hello"
assert isinstance(current.state, nats.js.api.StreamState)
# Send messages
producer = nc.jetstream()
ack = await producer.publish('world', b'Hello world!')
assert ack.stream == "hello"
assert ack.seq == 1
current = await jsm.stream_info("hello")
assert current.state.messages == 1
assert current.state.bytes == 47
stream_config = current.config
stream_config.subjects.append("extra")
updated_stream = await jsm.update_stream(stream_config)
assert updated_stream.config.subjects == [
'hello', 'world', 'hello.>', 'extra'
]
# Purge Stream
is_purged = await jsm.purge_stream("hello")
assert is_purged
current = await jsm.stream_info("hello")
assert current.state.messages == 0
assert current.state.bytes == 0
# Delete stream
is_deleted = await jsm.delete_stream("hello")
assert is_deleted
# Not foundError since there is none
with pytest.raises(NotFoundError):
await jsm.stream_info("hello")
await nc.close()
@async_test
async def test_consumer_management(self):
nc = NATS()
await nc.connect()
jsm = nc.jsm()
acc = await jsm.account_info()
assert isinstance(acc, nats.js.api.AccountInfo)
# Create stream.
await jsm.add_stream(name="ctests", subjects=["a", "b", "c.>"])
# Create durable consumer.
cinfo = await jsm.add_consumer(
"ctests",
durable_name="dur",
ack_policy="explicit",
)
# Fail with missing stream.
with pytest.raises(NotFoundError) as err:
await jsm.consumer_info("missing", "c")
assert err.value.err_code == 10059
# Get consumer, there should be no changes.
current = await jsm.consumer_info("ctests", "dur")
assert cinfo == current
# Delete consumer.
ok = await jsm.delete_consumer("ctests", "dur")
assert ok
# Consumer lookup should not be 404 now.
with pytest.raises(NotFoundError) as err:
await jsm.consumer_info("ctests", "dur")
assert err.value.err_code == 10014
# Create ephemeral consumer.
cinfo = await jsm.add_consumer(
"ctests",
ack_policy="explicit",
deliver_subject="asdf",
)
# Should not be empty.
assert len(cinfo.name) > 0
ok = await jsm.delete_consumer("ctests", cinfo.name)
assert ok
# Ephemeral no longer found after delete.
with pytest.raises(NotFoundError):
await jsm.delete_consumer("ctests", cinfo.name)
await nc.close()
@async_test
async def test_jsm_get_delete_msg(self):
nc = NATS()
await nc.connect()
js = nc.jetstream()
jsm = nc.jsm()
# Create stream
stream = await jsm.add_stream(name="foo", subjects=["foo.>"])
await js.publish("foo.a.1", b'Hello', headers={'foo': 'bar'})
await js.publish("foo.b.1", b'World')
await js.publish("foo.c.1", b'!!!')
# GetMsg
msg = await jsm.get_msg("foo", 2)
assert msg.subject == 'foo.b.1'
assert msg.data == b'World'
msg = await jsm.get_msg("foo", 3)
assert msg.subject == 'foo.c.1'
assert msg.data == b'!!!'
msg = await jsm.get_msg("foo", 1)
assert msg.subject == 'foo.a.1'
assert msg.data == b'Hello'
assert msg.headers["foo"] == "bar"
assert msg.hdrs == 'TkFUUy8xLjANCmZvbzogYmFyDQoNCg=='
with pytest.raises(BadRequestError):
await jsm.get_msg("foo", 0)
# DeleteMsg
stream_info = await jsm.stream_info("foo")
assert stream_info.state.messages == 3
ok = await jsm.delete_msg("foo", 2)
assert ok
stream_info = await jsm.stream_info("foo")
assert stream_info.state.messages == 2
msg = await jsm.get_msg("foo", 1)
assert msg.data == b"Hello"
# Deleted message should be gone now.
with pytest.raises(NotFoundError):
await jsm.get_msg("foo", 2)
msg = await jsm.get_msg("foo", 3)
assert msg.data == b"!!!"
await nc.close()
@async_test
async def test_jsm_stream_management(self):
nc = NATS()
await nc.connect()
js = nc.jetstream()
jsm = nc.jsm()
await jsm.add_stream(name="foo")
await jsm.add_stream(name="bar")
await jsm.add_stream(name="quux")
streams = await jsm.streams_info()
expected = ["foo", "bar", "quux"]
responses = []
for stream in streams:
responses.append(stream.config.name)
for name in expected:
assert name in responses
await nc.close()
@async_test
async def test_jsm_consumer_management(self):
nc = NATS()
await nc.connect()
js = nc.jetstream()
jsm = nc.jsm()
await jsm.add_stream(name="hello", subjects=["hello"])
durables = ["a", "b", "c"]
subs = []
for durable in durables:
sub = await js.pull_subscribe("hello", durable)
subs.append(sub)
consumers = await jsm.consumers_info("hello")
assert len(consumers) == 3
expected = ["a", "b", "c"]
responses = []
for consumer in consumers:
responses.append(consumer.config.durable_name)
for name in expected:
assert name in responses
await nc.close()
@async_test
async def test_number_of_consumer_replicas(self):
nc = await nats.connect()
js = nc.jetstream()
await js.add_stream(name="TESTREPLICAS", subjects=["test.replicas"])
for i in range(0, 10):
await js.publish("test.replicas", f'{i}'.encode())
# Create consumer
config = nats.js.api.ConsumerConfig(
num_replicas=1, durable_name="mycons"
)
cons = await js.add_consumer(stream="TESTREPLICAS", config=config)
if cons.config.num_replicas:
assert cons.config.num_replicas == 1
await nc.close()
class SubscribeTest(SingleJetStreamServerTestCase):
@async_test
async def test_queue_subscribe_deliver_group(self):
nc = await nats.connect()
js = nc.jetstream()
await js.add_stream(name="qsub", subjects=["quux"])
a, b, c = ([], [], [])
async def cb1(msg):
a.append(msg)
async def cb2(msg):
b.append(msg)
async def cb3(msg):