import time import pytest from ytownership import config from ytownership.errors import RetryCountExceededError from ytownership.utils.misc import DotDict from ytownership.utils.misc import rate_limited from ytownership.utils.misc import retry TEST_VALUE = 'test_value' def test_dot_dict_get_set(): """Test DotDict get and set value """ context = DotDict() context.test_value = TEST_VALUE assert context.test_value == TEST_VALUE def test_dot_dict_no_value(): """Test DotDict get value that does not exist returns None """ context = DotDict() assert context.test_value is None def test_dot_set_dict_get(): """Test DotDict set value with dot notation get it with dict notation """ context = DotDict() context.test_value = TEST_VALUE assert context['test_value'] == TEST_VALUE def test_dict_set_dot_get(): """Test DotDict set value with dict notation get it with dot notation """ context = DotDict() context['test_value'] = TEST_VALUE assert context.test_value == TEST_VALUE def test_retry_succeded(): """Test retry decorator successfull retry """ counter = {'count': 0} @retry(error_condition=lambda err: type(err) is ValueError) def func_to_decorate(counter): counter['count'] += 1 if counter['count'] == 1: raise ValueError else: return True result = func_to_decorate(counter) assert result assert counter['count'] == 2 def test_retry_count_exceeded(): """Test retry decorator raises RetryCountExceededError if retry limit exceeded """ @retry(error_condition=lambda err: type(err) is ValueError, retry_count=3) def func_to_decorate(): raise ValueError with pytest.raises(RetryCountExceededError): func_to_decorate() def test_rate_limited(): """Test rate_limited decorator. """ seconds = 2 test_count = 0 rate_limit = config.API_RATE_LIMIT @rate_limited(max_per_second=rate_limit) def test_func(): nonlocal test_count test_count += 1 timeout = time.time() + seconds while time.time() <= timeout: test_func() assert test_count <= seconds * rate_limit