|
2 | 2 | import unittest
|
3 | 3 |
|
4 | 4 | from tweepy.api import API
|
| 5 | +from tweepy.models import Status |
5 | 6 | from tweepy.streaming import Stream, StreamListener
|
6 | 7 |
|
7 | 8 | from config import create_auth
|
8 | 9 | from mock import mock_tweet
|
9 | 10 |
|
10 | 11 | class MockStreamListener(StreamListener):
|
11 |
| - def __init__(self): |
| 12 | + def __init__(self, test_case): |
12 | 13 | super(MockStreamListener, self).__init__()
|
| 14 | + self.test_case = test_case |
13 | 15 | self.status_count = 0
|
| 16 | + self.status_stop_count = 0 |
| 17 | + self.connect_cb = None |
| 18 | + |
| 19 | + def on_connect(self): |
| 20 | + if self.connect_cb: |
| 21 | + self.connect_cb() |
14 | 22 |
|
15 | 23 | def on_status(self, status):
|
16 | 24 | self.status_count += 1
|
17 |
| - return False |
| 25 | + self.test_case.assertIsInstance(status, Status) |
| 26 | + if self.status_stop_count == self.status_count: |
| 27 | + return False |
18 | 28 |
|
19 | 29 | class TweepyStreamTests(unittest.TestCase):
|
20 | 30 | def setUp(self):
|
21 | 31 | self.auth = create_auth()
|
22 |
| - self.listener = MockStreamListener() |
| 32 | + self.listener = MockStreamListener(self) |
23 | 33 | self.stream = Stream(self.auth, self.listener)
|
24 | 34 |
|
25 | 35 | def tearDown(self):
|
26 | 36 | self.stream.disconnect()
|
27 | 37 |
|
28 | 38 | def test_userstream(self):
|
29 |
| - self.stream.userstream(async=True) |
30 |
| - |
31 | 39 | # Generate random tweet which should show up in the stream.
|
32 |
| - # Wait a bit of time for it to arrive before asserting. |
33 |
| - API(self.auth).update_status(mock_tweet()) |
34 |
| - sleep(1) |
| 40 | + def on_connect(): |
| 41 | + API(self.auth).update_status(mock_tweet()) |
35 | 42 |
|
| 43 | + self.listener.connect_cb = on_connect |
| 44 | + self.listener.status_stop_count = 1 |
| 45 | + self.stream.userstream() |
36 | 46 | self.assertEqual(self.listener.status_count, 1)
|
37 | 47 |
|
| 48 | + def test_sample(self): |
| 49 | + self.listener.status_stop_count = 10 |
| 50 | + self.stream.sample() |
| 51 | + self.assertEquals(self.listener.status_count, |
| 52 | + self.listener.status_stop_count) |
| 53 | + |
0 commit comments