Skip to content

Commit e21180e

Browse files
authored
Merge pull request #10 from zenproducts/improve/remove-old-function
古い内部用クラスの削除
2 parents 5576c42 + a0d83cf commit e21180e

File tree

10 files changed

+163
-92
lines changed

10 files changed

+163
-92
lines changed

setup.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,8 +25,11 @@
2525
"aiohttp",
2626
],
2727
"dev": [
28+
"aioresponses",
2829
"pytest",
30+
"pytest-asyncio",
2931
"pytest-mock",
32+
"pytest-responses",
3033
"mypy",
3134
"types-requests",
3235
],

shodo/aio/lint.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,16 +4,16 @@
44
import aiohttp
55

66
from shodo.aio.api import lint_create, lint_result
7-
from shodo.lint import Lint, LintFailed, LintResult, Message
7+
from shodo.lint import LintFailed, LintResult, LintStatus, Message
88

99

10-
async def lint(body: str, is_html: bool = False, profile: Optional[str] = None) -> LintResult:
10+
async def lint(body: str, is_html: bool = False, profile: Optional[str] = None, _initial_pause: float = 0.25) -> LintResult:
1111
async with aiohttp.ClientSession() as session:
1212
create_res = await lint_create(body, is_html, profile, session)
1313

14-
status = Lint.STATUS_PROCESSING
15-
pause = 0.25
16-
while status == Lint.STATUS_PROCESSING:
14+
status = LintStatus.PROCESSING.value
15+
pause = _initial_pause
16+
while status == LintStatus.PROCESSING.value:
1717
await asyncio.sleep(pause)
1818
result_res = await lint_result(create_res.lint_id, profile, session)
1919
status = result_res.status
@@ -23,7 +23,7 @@ async def lint(body: str, is_html: bool = False, profile: Optional[str] = None)
2323
if pause < 16:
2424
pause *= 2
2525

26-
if status == Lint.STATUS_FAILED:
26+
if status == LintStatus.FAILED.value:
2727
raise LintFailed
2828

2929
return LintResult(status=status, messages=messages, updated=result_res.updated)

shodo/api.py

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,20 @@
11
import time
22
from dataclasses import dataclass
3-
from datetime import datetime
3+
from datetime import datetime, timezone
44
from pathlib import Path
55
from typing import Any, Dict, Generator, List, Optional
66

77
import requests
88

99
from shodo.conf import conf
1010

11+
try:
12+
from zoneinfo import ZoneInfo
13+
JST = ZoneInfo("Asia/Tokyo")
14+
except ImportError:
15+
from datetime import timedelta, timezone
16+
JST = timezone(timedelta(hours=+9), "JST")
17+
1118

1219
def api_path(path, profile) -> str:
1320
return conf(profile).api_root.rstrip("/") + "/" + path.strip("/") + "/"
@@ -37,7 +44,7 @@ class LintResultResponse:
3744

3845
def __post_init__(self) -> None:
3946
if isinstance(self.updated, int):
40-
self.updated = datetime.fromtimestamp(self.updated)
47+
self.updated = datetime.fromtimestamp(self.updated, JST)
4148

4249

4350
def lint_create(

shodo/lint.py

Lines changed: 10 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import time
22
from dataclasses import asdict, dataclass
33
from datetime import datetime
4+
from enum import Enum
45
from typing import Any, Dict, List, Optional
56

67
from shodo.api import lint_create, lint_result
@@ -64,46 +65,18 @@ class LintFailed(Exception):
6465
pass
6566

6667

67-
class Lint:
68-
STATUS_PROCESSING = "processing"
69-
STATUS_FAILED = "failed"
68+
class LintStatus(Enum):
69+
PROCESSING = "processing"
70+
FAILED = "failed"
71+
DONE = "done"
7072

71-
def __init__(self, body, lint_id, profile):
72-
self.body = body
73-
self.lint_id = lint_id
74-
self.body = None
75-
self.status = self.STATUS_PROCESSING
76-
self.messages = []
77-
self.profile = profile
7873

79-
def results(self):
80-
while self.status == self.STATUS_PROCESSING:
81-
time.sleep(0.5)
82-
res = lint_result(self.lint_id, self.profile)
83-
self.status = res.status
84-
msgs = [Message.load(m) for m in res.messages]
85-
self.messages = sorted(msgs, key=lambda m: (m.from_.line, m.from_.ch))
86-
87-
if self.status == self.STATUS_FAILED:
88-
raise LintFailed
89-
90-
return self.messages
91-
92-
def __repr__(self):
93-
return f"Lint({self.lint_id})"
94-
95-
@classmethod
96-
def start(cls, body: str, is_html: bool = False, profile: Optional[str] = None):
97-
res = lint_create(body, is_html, profile)
98-
return cls(body, res.lint_id, profile)
99-
100-
101-
def lint(body: str, is_html: bool = False, profile: Optional[str] = None) -> LintResult:
74+
def lint(body: str, is_html: bool = False, profile: Optional[str] = None, _initial_pause: float=0.25) -> LintResult:
10275
create_res = lint_create(body, is_html, profile)
10376

104-
status = Lint.STATUS_PROCESSING
105-
pause = 0.25
106-
while status == Lint.STATUS_PROCESSING:
77+
status = LintStatus.PROCESSING.value
78+
pause = _initial_pause
79+
while status == LintStatus.PROCESSING.value:
10780
time.sleep(pause)
10881
result_res = lint_result(create_res.lint_id, profile)
10982
status = result_res.status
@@ -113,7 +86,7 @@ def lint(body: str, is_html: bool = False, profile: Optional[str] = None) -> Lin
11386
if pause < 16:
11487
pause *= 2
11588

116-
if status == Lint.STATUS_FAILED:
89+
if status == LintStatus.FAILED.value:
11790
raise LintFailed
11891

11992
return LintResult(status=status, messages=messages, updated=result_res.updated)

shodo/main.py

Lines changed: 6 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010

1111
from shodo.api import download_image, list_post_files
1212
from shodo.conf import UnableLocateCredentialsError, save_credentials
13-
from shodo.lint import Lint
13+
from shodo.lint import lint as shodo_lint
1414

1515

1616
class ClickCatchExceptions(click.Group):
@@ -72,32 +72,28 @@ def lint(filename, html, output, profile):
7272
if not body:
7373
return
7474

75-
linting = Lint.start(body, is_html=html, profile=profile)
7675
click.echo("Linting...", err=True)
76+
result = shodo_lint(body, is_html=html, profile=profile)
7777

7878
if output == "json":
7979
click.echo(
8080
json.dumps(
81-
[msg.asdict() for msg in linting.results()],
81+
[msg.asdict() for msg in result.messages],
8282
ensure_ascii=False,
8383
indent=2,
8484
)
8585
)
8686
return
8787

88-
for message in linting.results():
88+
for message in result.messages:
8989
if message.score < 0.5:
9090
continue
9191
color = "red" if message.severity == message.ERROR else "yellow"
9292
body_highlight = (
9393
body[message.index - 10 : message.index]
9494
+ click.style(
9595
body[message.index : message.index_to]
96-
+ (
97-
f"(→ {message.after or 'トル'})"
98-
if message.after is not None
99-
else ""
100-
),
96+
+ (f"(→ {message.after or 'トル'})" if message.after is not None else ""),
10197
color,
10298
)
10399
+ body[message.index_to : message.index_to + 10]
@@ -109,7 +105,7 @@ def lint(filename, html, output, profile):
109105
click.echo(" ", nl=False)
110106
click.echo(body_highlight)
111107

112-
if linting.messages:
108+
if result.messages:
113109
sys.exit(1)
114110

115111

tests/conftest.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
import pytest
2+
3+
4+
@pytest.fixture
5+
def credential(monkeypatch):
6+
monkeypatch.setenv("SHODO_API_ROOT", "https://api.shodo.ink/@shodo/shodo/")
7+
monkeypatch.setenv("SHODO_API_TOKEN", "test-token")

tests/test_aio/__init__.py

Whitespace-only changes.

tests/test_aio/test_lint.py

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
from datetime import datetime, timezone
2+
from aioresponses import aioresponses
3+
4+
import pytest
5+
from shodo.aio.lint import lint
6+
7+
8+
@pytest.mark.asyncio
9+
async def test_lint(credential):
10+
with aioresponses() as m:
11+
m.post(
12+
"https://api.shodo.ink/@shodo/shodo/lint/",
13+
payload={
14+
"lint_id": "spam-spam-spam",
15+
"monthly_amount": 100,
16+
"current_usage": 10,
17+
"len_body": 10,
18+
"len_used": 10,
19+
},
20+
)
21+
m.get(
22+
"https://api.shodo.ink/@shodo/shodo/lint/spam-spam-spam/",
23+
payload={"status": "done", "updated": 1_700_000_000, "messages": []},
24+
)
25+
actual = await lint("body", is_html=False)
26+
27+
assert actual.status == "done"
28+
assert actual.messages == []
29+
assert actual.updated.timetuple()[:6] == (2023, 11, 15, 7, 13, 20)
30+
m.assert_called_with(
31+
"https://api.shodo.ink/@shodo/shodo/lint/",
32+
"post",
33+
json={
34+
"body": "body",
35+
"type": "text",
36+
},
37+
headers={"Authorization": "Bearer test-token"},
38+
)
39+
m.assert_called_with(
40+
"https://api.shodo.ink/@shodo/shodo/lint/spam-spam-spam/",
41+
"get",
42+
headers={"Authorization": "Bearer test-token"},
43+
)

tests/test_lint.py

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
import json
2+
from datetime import datetime, timezone
3+
4+
from shodo.lint import lint
5+
6+
7+
class TestLint:
8+
def test_lint(self, credential, responses):
9+
responses.add(
10+
"POST",
11+
"https://api.shodo.ink/@shodo/shodo/lint/",
12+
json={
13+
"lint_id": "spam-spam-spam",
14+
"monthly_amount": 100,
15+
"current_usage": 10,
16+
"len_body": 10,
17+
"len_used": 10,
18+
},
19+
)
20+
responses.add(
21+
"GET",
22+
"https://api.shodo.ink/@shodo/shodo/lint/spam-spam-spam/",
23+
json={
24+
"status": "done",
25+
"messages": [],
26+
"updated": 1_700_000_000,
27+
},
28+
)
29+
30+
actual = lint("これはテストです", is_html=False, profile=None, _initial_pause=0)
31+
32+
assert actual.status == "done"
33+
assert actual.messages == []
34+
assert actual.updated.timetuple()[:6] == (2023, 11, 15, 7, 13, 20)
35+
36+
assert len(responses.calls) == 2
37+
assert json.loads(responses.calls[0].request.body.decode("utf-8")) == {
38+
"body": "これはテストです",
39+
"type": "text",
40+
}

0 commit comments

Comments
 (0)