Skip to content

Commit

Permalink
Merge pull request #19 from luizalabs/ro-do_not_open_circuit_duplicated
Browse files Browse the repository at this point in the history
Check if circuit breaker is open in __exit__ method
  • Loading branch information
RomuloOliveira committed Nov 16, 2016
2 parents e3a1228 + 3ce9992 commit 580972b
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 3 deletions.
1 change: 1 addition & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -34,3 +34,4 @@ deploy:
tags: true
distributions: "sdist bdist_wheel"
repo: luizalabs/django-toolkit
skip_cleanup: true
8 changes: 6 additions & 2 deletions django_toolkit/fallbacks/circuit_breaker.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,21 +34,25 @@ def total_failures(self):
return self.cache.get(self.failure_cache_key) or 0

def open_circuit(self):
self.cache.set(self.circuit_cache_key, True, self.circuit_timeout)

logger.critical(
'Open circuit for {failure_cache_key} {cicuit_cache_key}'.format(
failure_cache_key=self.failure_cache_key,
cicuit_cache_key=self.circuit_cache_key
)
)

self.cache.set(self.circuit_cache_key, True, self.circuit_timeout)

def __enter__(self):
if self.is_circuit_open:
raise self.max_failure_exception

return self

def __exit__(self, exc_type, exc_value, traceback):
if exc_type in self.catch_exceptions:
if self.is_circuit_open:
raise self.max_failure_exception

self._increase_failure_count()

Expand Down
24 changes: 23 additions & 1 deletion tests/fallbacks/test_circuit_breaker.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,6 @@ def test_should_open_circuit_when_max_failures_exceeds(self):
assert cache.get(failure_cache_key, 2)

def test_should_raise_exception_when_circuit_is_open(self):

cache.set('circuit_circuit_open', True)

with pytest.raises(MyException):
Expand All @@ -92,3 +91,26 @@ def test_should_raise_exception_when_circuit_is_open(self):
success_function()

assert circuit_breaker.is_circuit_open

def test_should_not_increment_fail_when_circuit_is_open(self):
"""
It should not increment fail count over the max failures limit, when
circuit breaker is open after a successful enter.
"""
failure_cache_key = 'fail_count'
max_failures = 10

with pytest.raises(MyException):
with CircuitBreaker(
cache=cache,
failure_cache_key=failure_cache_key,
max_failures=max_failures,
max_failure_exception=MyException,
catch_exceptions=(ValueError,),
) as circuit_breaker:
cache.set(failure_cache_key, max_failures)
circuit_breaker.open_circuit()

fail_function()

assert cache.get(failure_cache_key) == max_failures

0 comments on commit 580972b

Please sign in to comment.