aboutsummaryrefslogtreecommitdiff
blob: 9b96ab88d1542fb4dff8cbb2ecd126d4d2f98625 (plain) (blame)
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
import six
import pytest
import itertools
from mastodon.streaming import StreamListener, CallbackStreamListener
from mastodon.Mastodon import MastodonMalformedEventError
from mastodon import Mastodon

import threading
import time

import select

# For monkeypatching so we can make vcrpy better
import vcr.stubs

streaming_is_patched = False
real_connections = []
close_connections = False

def patch_streaming():
    global streaming_is_patched
    global close_connections
    if streaming_is_patched is True:
        return
    streaming_is_patched = True
    
    real_get_response = vcr.stubs.VCRConnection.getresponse
    def fake_get_response(*args, **kwargs):
        global close_connections
        close_connections = False
        if args[0]._vcr_request.path.startswith("/api/v1/streaming/"):
            real_connections.append(args[0].real_connection)
            real_connection_real_get_response = args[0].real_connection.getresponse
            def fakeRealConnectionGetresponse(*args, **kwargs):
                response = real_connection_real_get_response(*args, **kwargs)
                real_body = b""
                try:
                    while close_connections is False:
                        if len(select.select([response], [], [], 0.01)[0]) > 0:
                            chunk = response.read(1)
                            real_body += chunk
                except AttributeError: 
                    pass # Connection closed
                print(real_body)
                response.read = (lambda: real_body)
                return response
            args[0].real_connection.getresponse = fakeRealConnectionGetresponse
        return real_get_response(*args, **kwargs)
    vcr.stubs.VCRConnection.getresponse = fake_get_response

def streaming_close():
    global real_connections
    for connection in real_connections:
        connection.close()
    real_connections = []
    close_connections = True
    
class Listener(StreamListener):
    def __init__(self):
        self.updates = []
        self.notifications = []
        self.deletes = []
        self.heartbeats = 0
        self.bla_called = False
        self.do_something_called = False

    def on_update(self, status):
        self.updates.append(status)

    def on_notification(self, notification):
        self.notifications.append(notification)

    def on_delete(self, status_id):
        self.deletes.append(status_id)

    def on_blahblah(self, data):
        self.bla_called = True
        pass

    def on_do_something(self, data):
        self.do_something_called = True
        pass

    def handle_heartbeat(self):
        self.heartbeats += 1

    def handle_stream_(self, lines):
        """Test helper to avoid littering all tests with six.b()."""
        class MockResponse():
            def __init__(self, data):
                self.data = data
                
            def iter_content(self, chunk_size):
                for line in self.data:
                    for byte in line:
                        bytearr = bytearray()
                        bytearr.append(byte)
                        yield(bytearr)
                    yield(b'\n')
        return self.handle_stream(MockResponse(map(six.b, lines)))


def test_heartbeat():
    listener = Listener()
    listener.handle_stream_([':one', ':two'])
    assert listener.heartbeats == 2


def test_status():
    listener = Listener()
    listener.handle_stream_([
        'event: update',
        'data: {"foo": "bar"}',
        '',
    ])
    assert listener.updates == [{"foo": "bar"}]


def test_notification():
    listener = Listener()
    listener.handle_stream_([
        'event: notification',
        'data: {"foo": "bar"}',
        '',
    ])
    assert listener.notifications == [{"foo": "bar"}]


def test_delete():
    listener = Listener()
    listener.handle_stream_([
        'event: delete',
        'data: 123',
        '',
    ])
    assert listener.deletes == [123]


@pytest.mark.parametrize('events', itertools.permutations([
    ['event: update', 'data: {"foo": "bar"}', ''],
    ['event: notification', 'data: {"foo": "bar"}', ''],
    ['event: delete', 'data: 123', ''],
    [':toot toot'],
    [':beep beep'],
]))
def test_many(events):
    listener = Listener()
    stream = [
        line
        for event in events
        for line in event
    ]
    listener.handle_stream_(stream)
    assert listener.updates == [{"foo": "bar"}]
    assert listener.notifications == [{"foo": "bar"}]
    assert listener.deletes == [123]
    assert listener.heartbeats == 2


def test_unknown_event():
    """Be tolerant of new event types"""
    listener = Listener()
    listener.handle_stream_([
        'event: blahblah',
        'data: {}',
        '',
    ])
    assert listener.bla_called is True
    assert listener.updates == []
    assert listener.notifications == []
    assert listener.deletes == []
    assert listener.heartbeats == 0

def test_unknown_handled_event():
    """Be tolerant of new unknown event types, if on_unknown_event is available"""
    listener = Listener()
    listener.on_unknown_event = lambda name, payload: None

    listener.handle_stream_([
        'event: complete.new.event',
        'data: {"k": "v"}',
        '',
    ])

    assert listener.updates == []
    assert listener.notifications == []
    assert listener.deletes == []
    assert listener.heartbeats == 0

def test_dotted_unknown_event():
    """Be tolerant of new event types with dots in the event-name"""
    listener = Listener()
    listener.handle_stream_([
        'event: do.something',
        'data: {}',
        '',
    ])
    assert listener.do_something_called is True
    assert listener.updates == []
    assert listener.notifications == []
    assert listener.deletes == []
    assert listener.heartbeats == 0

def test_invalid_json():
    """But not too tolerant"""
    listener = Listener()
    with pytest.raises(MastodonMalformedEventError):
        listener.handle_stream_([
            'event: blahblah',
            'data: {kjaslkdjalskdjasd asdkjhak ajdasldasd}',
            '',
        ])

def test_missing_event_name():
    listener = Listener()
    with pytest.raises(MastodonMalformedEventError):
        listener.handle_stream_([
            'data: {}',
            '',
        ])

    assert listener.updates == []
    assert listener.notifications == []
    assert listener.deletes == []
    assert listener.heartbeats == 0


def test_missing_data():
    listener = Listener()
    with pytest.raises(MastodonMalformedEventError):
        listener.handle_stream_([
            'event: update',
            '',
        ])

    assert listener.updates == []
    assert listener.notifications == []
    assert listener.deletes == []
    assert listener.heartbeats == 0


def test_sse_order_doesnt_matter():
    listener = Listener()
    listener.handle_stream_([
        'data: {"foo": "bar"}',
        'event: update',
        '',
    ])
    assert listener.updates == [{"foo": "bar"}]


def test_extra_keys_ignored():
    """
    https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format
    defines 'id' and 'retry' keys which the Mastodon streaming API doesn't use,
    and alleges that "All other field names are ignored".
    """
    listener = Listener()
    listener.handle_stream_([
        'event: update',
        'data: {"foo": "bar"}',
        'id: 123',
        'retry: 456',
        'ignoreme: blah blah blah',
        '',
    ])
    assert listener.updates == [{"foo": "bar"}]


def test_valid_utf8():
    """Snowman Cat Face With Tears Of Joy"""
    listener = Listener()
    listener.handle_stream_([
        'event: update',
        'data: {"foo": "\xE2\x98\x83\xF0\x9F\x98\xB9"}',
        '',
    ])
    assert listener.updates == [{"foo": u"\u2603\U0001F639"}]


def test_invalid_utf8():
    """Cat Face With Tears O"""
    listener = Listener()
    with pytest.raises(MastodonMalformedEventError):
        listener.handle_stream_([
            'event: update',
            'data: {"foo": "\xF0\x9F\x98"}',
            '',
        ])


def test_multiline_payload():
    """
    https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Data-only_messages
    says that newlines in the 'data' field can be encoded by sending the field
    twice! This would be really pathological for Mastodon because the payload
    is JSON, but technically literal newlines are permissible (outside strings)
    so let's handle this case.
    """
    listener = Listener()
    listener.handle_stream_([
        'event: update',
        'data: {"foo":',
        'data: "bar"',
        'data: }',
        '',
    ])
    assert listener.updates == [{"foo": "bar"}]

@pytest.mark.vcr(match_on=['path'])
def test_stream_user_direct(api, api2, api3):
    patch_streaming()
    
    # Make sure we are in the right state to not receive updates from api2
    user = api2.account_verify_credentials()
    api.account_unfollow(user)
    time.sleep(2)

    updates = []
    local_updates = []
    notifications = []
    deletes = []
    conversations = []
    edits = []
    listener = CallbackStreamListener(
        update_handler = lambda x: updates.append(x),
        local_update_handler = lambda x: local_updates.append(x),
        notification_handler = lambda x: notifications.append(x),
        delete_handler = lambda x: deletes.append(x),
        conversation_handler = lambda x: conversations.append(x),
        status_update_handler = lambda x: edits.append(x),
        filters_changed_handler = lambda x: 0,
        announcement_handler = lambda x: 0,
        announcement_reaction_handler = lambda x: 0,
        announcement_delete_handler = lambda x: 0,
        encryted_message_handler = lambda x: 0,
    )
    
    posted = []
    def do_activities():
        time.sleep(5)
        posted.append(api.status_post("only real cars respond."))
        posted.append(api2.status_post("@mastodonpy_test beep beep I'm a jeep"))
        posted.append(api2.status_post("on the internet, nobody knows you're a plane"))
        posted.append(api.status_post("@mastodonpy_test_2 pssssst", visibility="direct"))
        time.sleep(1)
        posted.append(api3.status_post("@mastodonpy_test pssssst!", visibility="direct", in_reply_to_id=posted[-1]))
        time.sleep(2)
        api.status_update(posted[0], "only real animals respond.")
        time.sleep(1)
        api.status_delete(posted[0])
        time.sleep(7)
        streaming_close()
        
    t = threading.Thread(args=(), target=do_activities)
    t.start()
    
    stream = api.stream_user(listener, run_async=True)
    stream2 = api.stream_direct(listener, run_async=True)
    time.sleep(25)
    stream.close()
    stream2.close()
        
    assert len(updates) == 2
    assert len(local_updates) == 2
    assert len(notifications) == 2
    assert len(deletes) == 1
    assert len(conversations) == 2
    assert len(edits) == 1

    assert updates[0].id == posted[0].id
    assert deletes[0] == posted[0].id
    assert notifications[0].status.id == posted[1].id
    
    t.join()
    
@pytest.mark.vcr(match_on=['path'])
def test_stream_user_local(api, api2):
    patch_streaming()
    
    # Make sure we are in the right state to not receive updates from api2
    user = api2.account_verify_credentials()
    api.account_unfollow(user)
    
    updates = []
    listener = CallbackStreamListener(
        local_update_handler = lambda x: updates.append(x),
    )
    
    posted = []
    def do_activities():
        time.sleep(5)
        posted.append(api.status_post("it's cool guy"))
        time.sleep(10)
        streaming_close()
        
    t = threading.Thread(args=(), target=do_activities)
    t.start()
    
    stream = api.stream_user(listener, run_async=True)
    time.sleep(20)
    stream.close()
        
    assert len(updates) == 1
    assert updates[0].id == posted[0].id
    
    t.join()

@pytest.mark.vcr(match_on=['path'])
def test_stream_direct(api, api2):
    patch_streaming()
    
    conversations = []
    listener = CallbackStreamListener(
        conversation_handler = lambda x: conversations.append(x),
    )
    
    def do_activities():
        time.sleep(5)
        api2.status_post("@mastodonpy_test todo funny text here", visibility = "direct")
        time.sleep(10)
        streaming_close()
        
    t = threading.Thread(args=(), target=do_activities)
    t.start()
    
    stream = api.stream_direct(listener, run_async=True)
    time.sleep(20)
    stream.close()
        
    assert len(conversations) == 1

@pytest.mark.vcr()
def test_stream_healthy(api_anonymous):
    assert api_anonymous.stream_healthy()
Powered by cgit v1.2.3 (git 2.41.0)