|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | +""" |
| 3 | + proxy.py |
| 4 | + ~~~~~~~~ |
| 5 | + ⚡⚡⚡ Fast, Lightweight, Pluggable, TLS interception capable proxy server focused on |
| 6 | + Network monitoring, controls & Application development, testing, debugging. |
| 7 | +
|
| 8 | + :copyright: (c) 2013-present by Abhinav Singh and contributors. |
| 9 | + :license: BSD, see LICENSE for more details. |
| 10 | +""" |
| 11 | +import time |
| 12 | + |
| 13 | +import unittest |
| 14 | + |
| 15 | +from proxy.common.leakage import Leakage |
| 16 | + |
| 17 | + |
| 18 | +class TestLeakage(unittest.TestCase): |
| 19 | + |
| 20 | + def test_initial_consume_no_tokens(self) -> None: |
| 21 | + # Test consuming with no tokens available initially |
| 22 | + rate = 100 # bytes per second |
| 23 | + bucket = Leakage(rate) |
| 24 | + self.assertEqual( |
| 25 | + bucket.consume(150), |
| 26 | + 100, |
| 27 | + ) # No tokens yet, so expect 0 bytes to be sent |
| 28 | + |
| 29 | + def test_consume_with_refill(self) -> None: |
| 30 | + # Test consuming with refill after waiting |
| 31 | + rate = 100 # bytes per second |
| 32 | + bucket = Leakage(rate) |
| 33 | + time.sleep(1) # Wait for a second to allow refill |
| 34 | + self.assertEqual(bucket.consume(50), 50) # 50 bytes should be available |
| 35 | + |
| 36 | + def test_consume_above_leak_rate(self) -> None: |
| 37 | + # Test attempting to consume more than the leak rate after a refill |
| 38 | + rate = 100 # bytes per second |
| 39 | + bucket = Leakage(rate) |
| 40 | + time.sleep(1) # Wait for a second to allow refill |
| 41 | + self.assertEqual(bucket.consume(150), 100) # Only 100 bytes should be allowed |
| 42 | + |
| 43 | + def test_repeated_consume_with_partial_refill(self) -> None: |
| 44 | + # Test repeated consumption with partial refill |
| 45 | + rate = 100 # bytes per second |
| 46 | + bucket = Leakage(rate) |
| 47 | + |
| 48 | + time.sleep(1) # Allow tokens to accumulate |
| 49 | + bucket.consume(80) # Consume 80 bytes, should leave 20 |
| 50 | + time.sleep(0.5) # Wait half a second to refill by 50 bytes |
| 51 | + |
| 52 | + self.assertEqual(bucket.consume(50), 50) # 50 bytes should be available now |
| 53 | + |
| 54 | + def test_negative_token_guard(self) -> None: |
| 55 | + # Ensure tokens do not go negative |
| 56 | + rate = 100 # bytes per second |
| 57 | + bucket = Leakage(rate) |
| 58 | + time.sleep(1) # Allow tokens to accumulate |
| 59 | + bucket.consume(150) # Consume all available tokens |
| 60 | + self.assertEqual(bucket.consume(10), 0) # Should return 0 as no tokens are left |
| 61 | + self.assertEqual(bucket.tokens, 0) # Tokens should not be negative |
0 commit comments