Add tests

This commit is contained in:
xtaodada 2023-08-25 16:33:06 +08:00
parent 0608edaa0d
commit 3ceddde101
Signed by: xtaodada
GPG Key ID: 4CBB3F4FA8C85659
9 changed files with 113 additions and 86 deletions

2
requirements.dev.txt Normal file
View File

@ -0,0 +1,2 @@
pytest
pytest-asyncio

View File

@ -25,29 +25,6 @@ class Hoyolab:
"X-Rpc-Language": lang,
}
@staticmethod
def get_images_params(
resize: int = 600,
quality: int = 80,
auto_orient: int = 0,
interlace: int = 1,
images_format: str = "jpg",
) -> str:
"""
image/resize,s_600/quality,q_80/auto-orient,0/interlace,1/format,jpg
:param resize: 图片大小
:param quality: 图片质量
:param auto_orient: 自适应
:param interlace: 未知
:param images_format: 图片格式
:return:
"""
params = (
f"image/resize,s_{resize}/quality,q_{quality}/auto-orient,"
f"{auto_orient}/interlace,{interlace}/format,{images_format}"
)
return f"?x-oss-process={params}"
async def get_news_recommend(
self, gids: int, page_size: int = 3, type_: int = 1
) -> List[PostRecommend]:

View File

@ -1,7 +1,3 @@
from contextlib import AbstractAsyncContextManager
from types import TracebackType
from typing import Optional, Type
import httpx
__all__ = ("HTTPXRequest",)
@ -16,30 +12,10 @@ timeout = httpx.Timeout(
)
class HTTPXRequest(AbstractAsyncContextManager):
class HTTPXRequest:
def __init__(self, *args, headers=None, **kwargs):
self._client = httpx.AsyncClient(headers=headers, *args, **kwargs)
async def __aenter__(self):
try:
await self.initialize()
return self
except Exception as exc:
await self.shutdown()
raise exc
async def __aexit__(
self,
exc_type: Optional[Type[BaseException]],
exc_val: Optional[BaseException],
exc_tb: Optional[TracebackType],
) -> None:
await self.initialize()
async def initialize(self):
if self._client.is_closed:
self._client = httpx.AsyncClient(timeout=timeout)
async def shutdown(self):
if self._client.is_closed:
return

View File

@ -48,41 +48,3 @@ class HyperionRequest(HTTPXRequest):
if not re_json_data and data is not None:
return data
return json_data
async def post(
self,
url: str,
*args,
de_json: bool = True,
re_json_data: bool = False,
**kwargs,
) -> Union[POST_DATA, JSON_DATA, Response]:
try:
response = await self._client.post(url=url, *args, **kwargs)
except httpx.TimeoutException as err:
raise APIHelperTimedOut from err
except httpx.HTTPError as exc:
raise NetworkException(
f"Unknown error in HTTP implementation: {repr(exc)}"
) from exc
if response.is_error:
raise ResponseException(
message=f"response error in status code: {response.status_code}"
)
if not de_json:
return response
json_data = response.json()
return_code = json_data.get("retcode", None)
data = json_data.get("data", None)
message = json_data.get("message", None)
if return_code is None:
return json_data
if return_code != 0:
if message is None:
raise ResponseException(
message=f"response error in return code: {return_code}"
)
raise ResponseException(response=json_data)
if not re_json_data and data is not None:
return data
return json_data

View File

View File

10
tests/test_app.py Normal file
View File

@ -0,0 +1,10 @@
import pytest
from main import main
@pytest.mark.asyncio
class TestAPP:
@staticmethod
async def test_app():
assert main is not None

View File

@ -0,0 +1,46 @@
import pytest
from src.render.article_hoyolab import process_article, refresh_hoyo_recommend_posts
@pytest.mark.asyncio
class TestHoyolabArticle:
@staticmethod
async def test_refresh_recommend_posts():
await refresh_hoyo_recommend_posts()
@staticmethod
async def test_get_hoyo_article():
content = await process_article(21097937, lang="zh")
assert content is not None
assert "【有奖活动】枫丹冒险之旅,参与赢原石等奖励" in content
assert (
"2023/08/22/cabb57e3aab8e212c035ee5dcca79540_7635259955618222979" in content
)
assert "参与资格(仅针对现金奖励)" in content
@staticmethod
async def test_get_hoyo_lang_article():
content = await process_article(21124034, lang="en")
assert content is not None
assert (
'"A Journey of Art and Heritage" - Adeptal Tales: Longquan Celadon | Genshin Impact'
in content
)
assert "The people of Liyue love drinking tea." in content
@staticmethod
async def test_get_hoyo_video_article():
content = await process_article(21124034, "zh-cn")
assert content is not None
assert "《原神》「流光拾遗之旅」——仙闻篇·龙泉青瓷" in content
assert "7Tuq-ritxJE" in content
assert "璃月人爱喝茶,用青色茶盏盛一碗茶汤,茶香似乎都变得更悠长。" in content
@staticmethod
async def test_get_hoyo_big_video_article():
content = await process_article(17958970, "zh-cn")
assert content is not None
assert "Spiral-Abyss-3.6 甘雨暴风雪 & 融甘视频 面板置放2和3楼" in content
assert "0jVRnQHwQ_g" in content
assert "这次的都是用加HP%加充能和E技能伤害没和伤害直接挂钩的buff" in content

54
tests/test_mys_article.py Normal file
View File

@ -0,0 +1,54 @@
import pytest
from src.error import ArticleNotFoundError
from src.render.article import process_article, refresh_recommend_posts
@pytest.mark.asyncio
class TestMYSArticle:
@staticmethod
async def test_refresh_recommend_posts():
await refresh_recommend_posts()
@staticmethod
async def test_get_mys_empty_gids():
with pytest.raises(ArticleNotFoundError) as e:
await process_article("", 0)
assert e is not None
@staticmethod
async def test_get_mys_text_article():
content = await process_article("ys", 42017325)
assert content is not None
assert "原神文本整理(二十二)大赤沙海元能尖碑《依稀可以辨认的铭文》" in content
assert "总之有错可以随时提出,会改的。" in content
@staticmethod
async def test_get_mys_image_article():
content = await process_article("ys", 42776789)
assert content is not None
assert "「绘知万物」——原神×知乎 网页答题活动现已开启" in content
assert (
"2023/08/25/75276539/f3b7c0ba388fddc603b4a76ea40d189d_6483724820064288526"
in content
)
assert "本次活动资源较大" in content
@staticmethod
async def test_get_mys_big_image_article():
content = await process_article("ys", 42643916)
assert content is not None
assert "居民委托" in content
assert (
"2023/08/21/100413398/fb66b26e0143da46181d40acfee9a5aa_6628603726056742795"
in content
)
assert "是居民声望委托!!!不是日常任务,更没有成就。" in content
@staticmethod
async def test_get_mys_video_article():
content = await process_article("ys", 42711525)
assert content is not None
assert "《原神》枫丹实机画面展示片Gamescom 2023" in content
assert "o4zAkZfsgYrL5akr9FTELBfEpurIEDQPgkGCUA" in content
assert "《原神》枫丹实机画面展示,踏上新的旅途。" in content