Skip to content

Commit

Permalink
Merge pull request #12 from pomponchik/develop
Browse files Browse the repository at this point in the history
0.0.6
  • Loading branch information
pomponchik authored Oct 8, 2023
2 parents 86598f7 + c08e7d0 commit 1488db5
Show file tree
Hide file tree
Showing 10 changed files with 60 additions and 41 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/lint.yml
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ jobs:

- name: Run mypy
shell: bash
run: mypy cantok
run: mypy cantok --strict --implicit-reexport

- name: Run ruff
shell: bash
Expand Down
18 changes: 5 additions & 13 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
![logo](https://raw.githubusercontent.com/pomponchik/cantok/main/docs/assets/logo_2.png)
![logo](https://raw.githubusercontent.com/pomponchik/cantok/main/docs/assets/logo_5.png)

[![Downloads](https://static.pepy.tech/badge/cantok/month)](https://pepy.tech/project/cantok)
[![Downloads](https://static.pepy.tech/badge/cantok)](https://pepy.tech/project/cantok)
Expand Down Expand Up @@ -36,27 +36,19 @@ And use:

```python
from random import randint
from threading import Thread

from cantok import ConditionToken, CounterToken, TimeoutToken


token = ConditionToken(lambda: randint(1, 100_000) == 1984) + CounterToken(400_000, direct=False) + TimeoutToken(1)
counter = 0

def function(token):
global counter
while token:
counter += 1

token = ConditionToken(lambda: randint(1, 100_000) == 1984) + CounterToken(400_000, direct=False) + TimeoutToken(1)
thread = Thread(target=function, args=(token, ))
thread.start()
thread.join()
while token:
counter += 1

print(counter)
```

In this example, we pass a token to the function that describes several restrictions: on the [number of iterations](#counter-token) of the cycle, on [time](#timeout-token), as well as on the [occurrence](#condition-token) of a random unlikely event. When any of the indicated events occur, the cycle stops.
In this example, we use a token that describes several restrictions: on the [number of iterations](#counter-token) of the cycle, on [time](#timeout-token), as well as on the [occurrence](#condition-token) of a random unlikely event. When any of the indicated events occur, the cycle stops.

Read more about the [possibilities of tokens](#tokens), as well as about the [pattern in general](#the-pattern).

Expand Down
26 changes: 13 additions & 13 deletions cantok/tokens/abstract_token.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,12 +22,12 @@ class AbstractToken(ABC):
exception = CancellationError
rollback_if_nondirect_polling = False

def __init__(self, *tokens: 'AbstractToken', cancelled=False):
def __init__(self, *tokens: 'AbstractToken', cancelled: bool = False) -> None:
self.tokens = tokens
self._cancelled = cancelled
self.lock = RLock()

def __repr__(self):
def __repr__(self) -> str:
chunks = []
superpower = self.text_representation_of_superpower()
if superpower:
Expand All @@ -44,14 +44,14 @@ def __repr__(self):
else:
extra_kwargs = {}
extra_kwargs.update(**(self.get_extra_kwargs()))
extra_kwargs = self.text_representation_of_kwargs(**extra_kwargs)
if extra_kwargs:
chunks.append(extra_kwargs)
text_representation_of_extra_kwargs = self.text_representation_of_kwargs(**extra_kwargs)
if text_representation_of_extra_kwargs:
chunks.append(text_representation_of_extra_kwargs)

chunks = ', '.join(chunks)
return f'{type(self).__name__}({chunks})'
glued_chunks = ', '.join(chunks)
return f'{type(self).__name__}({glued_chunks})'

def __str__(self):
def __str__(self) -> str:
cancelled_flag = 'cancelled' if self.is_cancelled(direct=False) else 'not cancelled'
return f'<{type(self).__name__} ({cancelled_flag})>'

Expand All @@ -71,7 +71,7 @@ def cancelled(self) -> bool:
return self.is_cancelled()

@cancelled.setter
def cancelled(self, new_value) -> None:
def cancelled(self, new_value: bool) -> None:
if new_value == True:
self._cancelled = True
else:
Expand All @@ -81,10 +81,10 @@ def cancelled(self, new_value) -> None:
def keep_on(self) -> bool:
return not self.is_cancelled()

def is_cancelled(self, direct=True) -> bool:
def is_cancelled(self, direct: bool = True) -> bool:
return self.get_report(direct=direct).cause != CancelCause.NOT_CANCELLED

def get_report(self, direct=True) -> CancellationReport:
def get_report(self, direct: bool = True) -> CancellationReport:
if self._cancelled:
return CancellationReport(
cause=CancelCause.CANCELLED,
Expand Down Expand Up @@ -115,7 +115,7 @@ def cancel(self) -> 'AbstractToken':
def superpower(self) -> bool: # pragma: no cover
pass

def superpower_rollback(self, superpower_data: Dict[str, Any]) -> None:
def superpower_rollback(self, superpower_data: Dict[str, Any]) -> None: # pragma: no cover
pass

def check_superpower(self, direct: bool) -> bool:
Expand All @@ -130,7 +130,7 @@ def check_superpower_with_rollback(self) -> bool:
self.superpower_rollback(superpower_data)
return result

def get_superpower_data(self) -> Dict[str, Any]:
def get_superpower_data(self) -> Dict[str, Any]: # pragma: no cover
return {}

@abstractmethod
Expand Down
2 changes: 1 addition & 1 deletion cantok/tokens/simple_token.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,4 @@ def text_representation_of_superpower(self) -> str:
return ''

def get_superpower_exception_message(self) -> str:
return 'The token has been cancelled.'
return 'The token has been cancelled.' # pragma: no cover
Binary file added docs/assets/logo_3.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added docs/assets/logo_4.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added docs/assets/logo_5.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
12 changes: 11 additions & 1 deletion tests/readme_examples/test_examples.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

counter = 0

def test_cancel_simple_token():
def test_cancel_simple_token_with_function_and_thread():
def function(token):
global counter
while not token.cancelled:
Expand All @@ -18,3 +18,13 @@ def function(token):
thread.join()

assert counter


def test_cancel_simple_token_with_function_and_thread():
token = ConditionToken(lambda: randint(1, 100_000) == 1984) + CounterToken(400_000, direct=False) + TimeoutToken(1)
counter = 0

while token:
counter += 1

assert counter
39 changes: 28 additions & 11 deletions tests/units/tokens/test_abstract_token.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,21 +91,13 @@ def test_repr(token_fabric):
ALL_TOKENS_FABRICS,
)
def test_repr_with_another_token(token_fabric):
another_token = token_fabric()
token = token_fabric(another_token)
nested_token = token_fabric()
token = token_fabric(nested_token)

superpower_text = token.text_representation_of_superpower()
extra_kwargs_text = token.text_representation_of_extra_kwargs()

print(superpower_text)
print(repr(token))
print(repr(token))
print(repr(token))
print(repr(token))
print(repr(token))
print(repr(token))

assert repr(token) == type(token).__name__ + '(' + ('' if not superpower_text else f'{superpower_text}, ') + repr(another_token) + (', ' + extra_kwargs_text if extra_kwargs_text else '') + ')'
assert repr(token) == type(token).__name__ + '(' + ('' if not superpower_text else f'{superpower_text}, ') + repr(nested_token) + (', ' + extra_kwargs_text if extra_kwargs_text else '') + ')'


@pytest.mark.parametrize(
Expand Down Expand Up @@ -293,3 +285,28 @@ def test_type_conversion_cancelled(token_fabric):

assert not token
assert not bool(token)


@pytest.mark.parametrize(
'cancelled_flag_nested_token, cancelled_flag_token',
[
(True, True),
(True, False),
(False, True),
(False, False),
],
)
@pytest.mark.parametrize(
'token_fabric_1',
ALL_TOKENS_FABRICS,
)
@pytest.mark.parametrize(
'token_fabric_2',
ALL_TOKENS_FABRICS,
)
def test_repr_if_nested_token_is_cancelled(token_fabric_1, token_fabric_2, cancelled_flag_nested_token, cancelled_flag_token):
nested_token = token_fabric_1(cancelled=cancelled_flag_nested_token)
token = token_fabric_2(nested_token, cancelled=cancelled_flag_token)

assert ('cancelled' in repr(token).replace(repr(nested_token), '')) == cancelled_flag_token
assert ('cancelled' in repr(nested_token)) == cancelled_flag_nested_token
2 changes: 1 addition & 1 deletion version.txt
Original file line number Diff line number Diff line change
@@ -1 +1 @@
0.0.5
0.0.6

0 comments on commit 1488db5

Please sign in to comment.