Skip to content

Commit 8ab1af2

Browse files
authored
Merge pull request #1 from Pavkazzz/add-mypy
Mypy support
2 parents f5bf0cb + baea13c commit 8ab1af2

File tree

16 files changed

+111
-25
lines changed

16 files changed

+111
-25
lines changed
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
# This workflow will install Python dependencies, run tests and lint with a variety of Python versions
2+
# For more information see: https://help.github.com/actions/language-and-framework-guides/using-python-with-github-actions
3+
4+
name: Python package
5+
6+
on:
7+
push:
8+
branches: [ master ]
9+
pull_request:
10+
branches: [ master ]
11+
12+
jobs:
13+
build:
14+
15+
runs-on: ubuntu-latest
16+
strategy:
17+
matrix:
18+
python-version: [3.5, 3.6, 3.7, 3.8]
19+
20+
steps:
21+
- uses: actions/checkout@v2
22+
- name: Set up Python ${{ matrix.python-version }}
23+
uses: actions/setup-python@v1
24+
with:
25+
python-version: ${{ matrix.python-version }}
26+
- name: Install dependencies
27+
run: |
28+
python -m pip install --upgrade pip
29+
pip install -r requirements.txt
30+
pip install -r requirements.dev.txt
31+
- name: Test with pytest
32+
run: |
33+
pytest

.gitignore

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -138,3 +138,5 @@ fabric.properties
138138
.DS_Store
139139

140140
/*/version.py
141+
142+
.mypy_cache/*

.travis.yml

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,12 @@ matrix:
44
include:
55
- python: 3.5
66
env: TOXENV=py35
7-
87
- python: 3.6
98
env: TOXENV=py36
9+
- python: 3.7
10+
env: TOXENV=py36
11+
- python: 3.8
12+
env: TOXENV=py36
1013
install:
1114
- pip install tox coveralls codecov
1215
script:

Makefile

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,3 +36,6 @@ develop: purge bump
3636
env/bin/pip install -Ue '.[develop]'
3737

3838
release: test upload
39+
40+
mypy:
41+
mypy jwt_rsa

jwt_rsa/__init__.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@
44
version_info = (0, 0, 0, 'x')
55
__version__ = '{}.{}.{}+{}'.format(*version_info)
66

7-
87
authors = (
98
('Dmitry Orlov', '[email protected]'),
109
)

jwt_rsa/issue.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
type=float, default=...)
1515

1616

17-
def main():
17+
def main() -> None:
1818
arguments = parser.parse_args()
1919
jwt = JWT(private_key=arguments.private_key)
2020
print(

jwt_rsa/keygen.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
from cryptography.hazmat.primitives import serialization
77

88

9-
def main():
9+
def main() -> None:
1010
parser = argparse.ArgumentParser()
1111
parser.add_argument('-b', '--bits', dest="bits", type=int, default=2048)
1212
parser.add_argument('-P', '--pem', dest="pem", action='store_true')

jwt_rsa/rsa.py

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,18 @@
11
import base64
22
from collections import namedtuple
3-
from typing import Tuple
43

54
from cryptography.hazmat.backends import default_backend
6-
from cryptography.hazmat.primitives.asymmetric import rsa
75
from cryptography.hazmat.primitives import serialization
8-
6+
from cryptography.hazmat.primitives.asymmetric import rsa
97
from cryptography.hazmat.primitives.asymmetric.rsa import (
108
RSAPrivateKeyWithSerialization as RSAPrivateKey,
119
RSAPublicKeyWithSerialization as RSAPublicKey,
1210
)
1311

14-
1512
KeyPair = namedtuple('KeyPair', ('private', 'public'))
1613

1714

18-
def generate_rsa(bits=2048) -> Tuple[RSAPrivateKey, RSAPublicKey]:
15+
def generate_rsa(bits: int = 2048) -> KeyPair:
1916
'''
2017
Generate an RSA keypair with an exponent of 65537 in PEM format
2118
param: bits The key length in bits

jwt_rsa/token.py

Lines changed: 34 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,20 @@
11
import time
2-
from datetime import timedelta, datetime
3-
from operator import sub, add
4-
from typing import Union
2+
from datetime import datetime, timedelta
3+
from operator import add, sub
4+
from typing import Any, Callable, Dict, Optional, TYPE_CHECKING, TypeVar, \
5+
Union
56

67
from jwt import PyJWT
8+
79
from jwt_rsa.rsa import RSAPrivateKey, RSAPublicKey
810

11+
if TYPE_CHECKING:
12+
# pylama:ignore=E0602
13+
DateType = Union[timedelta, datetime, float, int, ellipsis]
14+
else:
15+
DateType = Union[timedelta, datetime, float, int, type(Ellipsis)]
916

10-
DateType = Union[timedelta, datetime, float, int, type(Ellipsis)]
17+
R = TypeVar('R')
1118

1219

1320
class JWT:
@@ -21,9 +28,14 @@ class JWT:
2128
'ES521', 'ES512', 'PS256', 'PS384', 'PS512'
2229
})
2330

24-
def __init__(self, private_key: RSAPrivateKey=None,
25-
public_key: RSAPublicKey=None, expires=None,
26-
nbf_delta=None, algorithm="RS512"):
31+
def __init__(
32+
self,
33+
private_key: Optional[RSAPrivateKey] = None,
34+
public_key: Optional[RSAPublicKey] = None,
35+
expires: Optional[int] = None,
36+
nbf_delta: Optional[int] = None,
37+
algorithm: str = "RS512"
38+
):
2739

2840
self.__private_key = private_key
2941
self.__public_key = public_key
@@ -32,7 +44,12 @@ def __init__(self, private_key: RSAPrivateKey=None,
3244
self.__nbf_delta = nbf_delta or self.NBF_DELTA
3345
self.__algorithm = algorithm
3446

35-
def _date_to_timestamp(self, value, default, timedelta_func=add):
47+
def _date_to_timestamp(
48+
self,
49+
value: DateType,
50+
default: Callable[[], R],
51+
timedelta_func: Callable[[float, float], int] = add
52+
) -> Union[int, float, R]:
3653
if isinstance(value, timedelta):
3754
return timedelta_func(time.time(), value.total_seconds())
3855
elif isinstance(value, datetime):
@@ -44,7 +61,12 @@ def _date_to_timestamp(self, value, default, timedelta_func=add):
4461

4562
raise ValueError(type(value))
4663

47-
def encode(self, expired: DateType=..., nbf: DateType=..., **claims) -> str:
64+
def encode(
65+
self,
66+
expired: DateType = ...,
67+
nbf: DateType = ...,
68+
**claims: int
69+
) -> str:
4870
if not self.__private_key:
4971
raise RuntimeError("Can't encode without private key")
5072

@@ -72,7 +94,9 @@ def encode(self, expired: DateType=..., nbf: DateType=..., **claims) -> str:
7294
algorithm=self.__algorithm,
7395
).decode()
7496

75-
def decode(self, token: str, verify=True, **kwargs) -> dict:
97+
def decode(
98+
self, token: str, verify: bool = True, **kwargs: Any
99+
) -> Dict[str, Any]:
76100
if not self.__public_key:
77101
raise RuntimeError("Can't decode without public key")
78102

jwt_rsa/verify.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
from jwt_rsa.rsa import load_private_key, load_public_key
99

1010

11-
def main():
11+
def main() -> None:
1212
logging.basicConfig(level=logging.INFO)
1313

1414
logging.info("Awaiting JSON on stdin...")

0 commit comments

Comments
 (0)