Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Speed up unit tests from 21s to 8ms by mocking call to time(). #1

Merged
merged 1 commit into from
Nov 15, 2016
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 10 additions & 6 deletions tests/ratelimitingfilter_test.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,16 @@
import os
import time
from unittest.case import TestCase
from unittest.mock import Mock
from unittest.mock import Mock, patch

from ratelimitingfilter import RateLimitingFilter


class RateLimitingFilterTest(TestCase):
def setUp(self):
patcher = patch('ratelimitingfilter.ratelimitingfilter.time')
self.mock_time = patcher.start()
self.addCleanup(patcher.stop)
self.mock_time.return_value = 0

def test_limit_to_one_record_per_second(self):
f = RateLimitingFilter(rate=1, per=1, burst=1)
Expand Down Expand Up @@ -65,7 +69,7 @@ def _filter_twenty_records_over_two_seconds(self, f):

for _ in range(20):
result.append(f.filter(mock_record))
time.sleep(0.1)
self.mock_time.return_value += 0.1

return result

Expand All @@ -78,7 +82,7 @@ def test_append_num_limited_records_to_message(self):
mock_record.msg = 'test message'
if f.filter(mock_record):
filtered.append(mock_record)
time.sleep(0.1)
self.mock_time.return_value += 0.1

self.assertEqual(len(filtered), 6)
self.assertTrue(filtered[4].msg.endswith(os.linesep + '... 6 additional messages suppressed'))
Expand All @@ -101,7 +105,7 @@ def test_rate_limit_messages_matching_substring(self):
result.append(mock_matching_record.msg) # Only 2 of these get logged as they match the substring
if f.filter(mock_non_matching_record):
result.append(mock_non_matching_record.msg) # 20 of these get logged as they don't match
time.sleep(0.1)
self.mock_time.return_value += 0.1

self.assertEqual(len([m for m in result if 'a rate limited test message' in m]), 2)
self.assertEqual(result.count('a different test message'), 20)
Expand All @@ -126,7 +130,7 @@ def test_rate_limit_messages_automatically(self):
if f.filter(mock_rate_limited_record):
# Only 2 of these get logged as they are the all identical
result.append(mock_rate_limited_record.msg)
time.sleep(0.1)
self.mock_time.return_value += 0.1

self.assertEqual(len([m for m in result if 'a rate limited varying message' in m]), 2)
self.assertEqual(len([m for m in result if 'a completely different message' in m]), 2)