add pre-commit and format files

This commit is contained in:
hemengyang
2022-02-09 21:05:14 +08:00
parent 51c31637d5
commit 547be7608f
43 changed files with 2242 additions and 1365 deletions
+15 -12
View File
@@ -1,33 +1,36 @@
import typing
import pytest
import nonebot
import typing
from nonebug.fixture import nonebug_init, nonebug_clear
if typing.TYPE_CHECKING:
import sys
sys.path.append('./src/plugins')
sys.path.append("./src/plugins")
import nonebot_bison
@pytest.fixture#(scope="module")
@pytest.fixture # (scope="module")
def plugin_module(tmpdir):
nonebot.init(bison_config_path=str(tmpdir))
nonebot.load_plugins('src/plugins')
nonebot.load_plugins("src/plugins")
plugins = nonebot.get_loaded_plugins()
plugin = list(filter(lambda x: x.name == 'nonebot_bison', plugins))[0]
plugin = list(filter(lambda x: x.name == "nonebot_bison", plugins))[0]
return plugin.module
@pytest.fixture
def dummy_user_subinfo(plugin_module: 'nonebot_bison'):
user = plugin_module.types.User('123', 'group')
def dummy_user_subinfo(plugin_module: "nonebot_bison"):
user = plugin_module.types.User("123", "group")
return plugin_module.types.UserSubInfo(
user=user,
category_getter=lambda _: [],
tag_getter=lambda _: []
)
user=user, category_getter=lambda _: [], tag_getter=lambda _: []
)
@pytest.fixture
def n_plugin_module(tmpdir):
nonebot.init(bison_config_path=str(tmpdir))
nonebot.load_plugins('src/plugins')
nonebot.load_plugins("src/plugins")
yield None
nonebug_clear()
+61 -32
View File
@@ -1,64 +1,93 @@
import pytest
import typing
import respx
import pytest
from httpx import Response
if typing.TYPE_CHECKING:
import sys
sys.path.append('./src/plugins')
sys.path.append("./src/plugins")
import nonebot_bison
from .utils import get_json, get_file
from .utils import get_file, get_json
@pytest.fixture
def arknights(plugin_module: 'nonebot_bison'):
return plugin_module.platform.platform_manager['arknights']
def arknights(plugin_module: "nonebot_bison"):
return plugin_module.platform.platform_manager["arknights"]
@pytest.fixture(scope='module')
@pytest.fixture(scope="module")
def arknights_list_0():
return get_json('arknights_list_0.json')
return get_json("arknights_list_0.json")
@pytest.fixture(scope='module')
@pytest.fixture(scope="module")
def arknights_list_1():
return get_json('arknights_list_1.json')
return get_json("arknights_list_1.json")
@pytest.fixture(scope='module')
@pytest.fixture(scope="module")
def monster_siren_list_0():
return get_json('monster-siren_list_0.json')
return get_json("monster-siren_list_0.json")
@pytest.fixture(scope='module')
@pytest.fixture(scope="module")
def monster_siren_list_1():
return get_json('monster-siren_list_1.json')
return get_json("monster-siren_list_1.json")
@pytest.mark.asyncio
@respx.mock
async def test_fetch_new(arknights, dummy_user_subinfo, arknights_list_0, arknights_list_1, monster_siren_list_0, monster_siren_list_1):
ak_list_router = respx.get("https://ak-conf.hypergryph.com/config/prod/announce_meta/IOS/announcement.meta.json")
detail_router = respx.get("https://ak.hycdn.cn/announce/IOS/announcement/805_1640074952.html")
version_router = respx.get('https://ak-conf.hypergryph.com/config/prod/official/IOS/version')
preannouncement_router = respx.get('https://ak-conf.hypergryph.com/config/prod/announce_meta/IOS/preannouncement.meta.json')
async def test_fetch_new(
arknights,
dummy_user_subinfo,
arknights_list_0,
arknights_list_1,
monster_siren_list_0,
monster_siren_list_1,
):
ak_list_router = respx.get(
"https://ak-conf.hypergryph.com/config/prod/announce_meta/IOS/announcement.meta.json"
)
detail_router = respx.get(
"https://ak.hycdn.cn/announce/IOS/announcement/805_1640074952.html"
)
version_router = respx.get(
"https://ak-conf.hypergryph.com/config/prod/official/IOS/version"
)
preannouncement_router = respx.get(
"https://ak-conf.hypergryph.com/config/prod/announce_meta/IOS/preannouncement.meta.json"
)
monster_siren_router = respx.get("https://monster-siren.hypergryph.com/api/news")
ak_list_router.mock(return_value=Response(200, json=arknights_list_0))
detail_router.mock(return_value=Response(200, text=get_file('arknights-detail-805')))
version_router.mock(return_value=Response(200, json=get_json('arknights-version-0.json')))
preannouncement_router.mock(return_value=Response(200, json=get_json('arknights-pre-0.json')))
detail_router.mock(
return_value=Response(200, text=get_file("arknights-detail-805"))
)
version_router.mock(
return_value=Response(200, json=get_json("arknights-version-0.json"))
)
preannouncement_router.mock(
return_value=Response(200, json=get_json("arknights-pre-0.json"))
)
monster_siren_router.mock(return_value=Response(200, json=monster_siren_list_0))
target = ''
target = ""
res = await arknights.fetch_new_post(target, [dummy_user_subinfo])
assert(ak_list_router.called)
assert(len(res) == 0)
assert(not detail_router.called)
assert ak_list_router.called
assert len(res) == 0
assert not detail_router.called
mock_data = arknights_list_1
ak_list_router.mock(return_value=Response(200, json=mock_data))
res3 = await arknights.fetch_new_post(target, [dummy_user_subinfo])
assert(len(res3[0][1]) == 1)
assert(detail_router.called)
assert len(res3[0][1]) == 1
assert detail_router.called
post = res3[0][1][0]
assert(post.target_type == 'arknights')
assert(post.text == '')
assert(post.url == '')
assert(post.target_name == '明日方舟游戏内公告')
assert(len(post.pics) == 1)
assert post.target_type == "arknights"
assert post.text == ""
assert post.url == ""
assert post.target_name == "明日方舟游戏内公告"
assert len(post.pics) == 1
# assert(post.pics == ['https://ak-fs.hypergryph.com/announce/images/20210623/e6f49aeb9547a2278678368a43b95b07.jpg'])
print(res3[0][1])
r = await post.generate_messages()
+31 -15
View File
@@ -1,37 +1,53 @@
import pytest
import typing
import pytest
from httpx import Response
if typing.TYPE_CHECKING:
import sys
sys.path.append('./src/plugins')
sys.path.append("./src/plugins")
import nonebot_bison
from .utils import get_json
@pytest.fixture(scope='module')
@pytest.fixture(scope="module")
def bing_dy_list():
return get_json('bilibili_bing_list.json')['data']['cards']
return get_json("bilibili_bing_list.json")["data"]["cards"]
@pytest.fixture
def bilibili(plugin_module: 'nonebot_bison'):
return plugin_module.platform.platform_manager['bilibili']
def bilibili(plugin_module: "nonebot_bison"):
return plugin_module.platform.platform_manager["bilibili"]
@pytest.mark.asyncio
async def test_video_forward(bilibili, bing_dy_list):
post = await bilibili.parse(bing_dy_list[1])
assert(post.text == '答案揭晓:宿舍!来看看投票结果\nhttps://t.bilibili.com/568093580488553786\n--------------\n#可露希尔的秘密档案# \n11:来宿舍休息一下吧 \n档案来源:lambda:\\罗德岛内务\\秘密档案 \n发布时间:9/12 1:00 P.M. \n档案类型:可见 \n档案描述:今天请了病假在宿舍休息。很舒适。 \n提供者:赫默')
post = await bilibili.parse(bing_dy_list[1])
assert (
post.text
== "答案揭晓:宿舍!来看看投票结果\nhttps://t.bilibili.com/568093580488553786\n--------------\n#可露希尔的秘密档案# \n11:来宿舍休息一下吧 \n档案来源:lambda:\\罗德岛内务\\秘密档案 \n发布时间:9/12 1:00 P.M. \n档案类型:可见 \n档案描述:今天请了病假在宿舍休息。很舒适。 \n提供者:赫默"
)
@pytest.mark.asyncio
async def test_article_forward(bilibili, bing_dy_list):
post = await bilibili.parse(bing_dy_list[4])
assert(post.text == '#明日方舟##饼学大厦#\n9.11专栏更新完毕,这还塌了实属没跟新运营对上\n后边除了周日发饼和PV没提及的中文语音,稳了\n别忘了来参加#可露希尔的秘密档案#的主题投票\nhttps://t.bilibili.com/568093580488553786?tab=2' +
'\n--------------\n' +
'明日方舟饼学大厦#12~14(风暴瞭望&玛莉娅·临光&红松林&感谢庆典)9.11更新 更新记录09.11更新:覆盖09.10更新;以及排期更新,猜测周一周五开活动09.10更新:以周五开活动为底,PV/公告调整位置,整体结构更新09.08更新:饼学大厦#12更新,新增一件六星商店服饰(周日发饼)09.06更新:饼学大厦整栋整栋翻新,改为9.16开主线(四日无饼!)09.05凌晨更新:10.13后的排期(两日无饼,鹰角背刺,心狠手辣)前言感谢楪筱祈ぺ的动态-哔哩哔哩 (bilibili.com) 对饼学的贡献!后续排期:9.17【风暴瞭望】、10.01【玛莉娅·临光】复刻、10.1')
post = await bilibili.parse(bing_dy_list[4])
assert (
post.text
== "#明日方舟##饼学大厦#\n9.11专栏更新完毕,这还塌了实属没跟新运营对上\n后边除了周日发饼和PV没提及的中文语音,稳了\n别忘了来参加#可露希尔的秘密档案#的主题投票\nhttps://t.bilibili.com/568093580488553786?tab=2"
+ "\n--------------\n"
+ "【明日方舟】饼学大厦#12~14(风暴瞭望&玛莉娅·临光&红松林&感谢庆典)9.11更新 更新记录09.11更新:覆盖09.10更新;以及排期更新,猜测周一周五开活动09.10更新:以周五开活动为底,PV/公告调整位置,整体结构更新09.08更新:饼学大厦#12更新,新增一件六星商店服饰(周日发饼)09.06更新:饼学大厦整栋整栋翻新,改为9.16开主线(四日无饼!)09.05凌晨更新:10.13后的排期(两日无饼,鹰角背刺,心狠手辣)前言感谢楪筱祈ぺ的动态-哔哩哔哩 (bilibili.com) 对饼学的贡献!后续排期:9.17【风暴瞭望】、10.01【玛莉娅·临光】复刻、10.1"
)
@pytest.mark.asyncio
async def test_dynamic_forward(bilibili, bing_dy_list):
post = await bilibili.parse(bing_dy_list[5])
assert(post.text == '饼组主线饼学预测——9.11版\n①今日结果\n9.11 殿堂上的游禽-星极(x,新运营实锤了)\n②后续预测\n9.12 #罗德岛相簿#+#可露希尔的秘密档案#11话\n9.13 六星先锋(执旗手)干员-琴柳\n9.14 宣传策略-空弦+家具\n9.15 轮换池(+中文语音前瞻)\n9.16 停机\n9.17 #罗德岛闲逛部#+新六星EP+EP09·风暴瞭望开启\n9.19 #罗德岛相簿#' +
'\n--------------\n' +
'#明日方舟#\n【新增服饰】\n//殿堂上的游禽 - 星极\n塞壬唱片偶像企划《闪耀阶梯》特供服饰/殿堂上的游禽。星极自费参加了这项企划,尝试着用大众能接受的方式演绎天空之上的故事。\n\n_____________\n谦逊留给观众,骄傲发自歌喉,此夜,唯我璀璨。 ')
assert (
post.text
== "饼组主线饼学预测——9.11版\n①今日结果\n9.11 殿堂上的游禽-星极(x,新运营实锤了)\n②后续预测\n9.12 #罗德岛相簿#+#可露希尔的秘密档案#11话\n9.13 六星先锋(执旗手)干员-琴柳\n9.14 宣传策略-空弦+家具\n9.15 轮换池(+中文语音前瞻)\n9.16 停机\n9.17 #罗德岛闲逛部#+新六星EP+EP09·风暴瞭望开启\n9.19 #罗德岛相簿#"
+ "\n--------------\n"
+ "#明日方舟#\n【新增服饰】\n//殿堂上的游禽 - 星极\n塞壬唱片偶像企划《闪耀阶梯》特供服饰/殿堂上的游禽。星极自费参加了这项企划,尝试着用大众能接受的方式演绎天空之上的故事。\n\n_____________\n谦逊留给观众,骄傲发自歌喉,此夜,唯我璀璨。 "
)
+30 -25
View File
@@ -1,49 +1,54 @@
from .utils import get_json
import pytest
import respx
import typing
import time
import typing
import respx
import pytest
from httpx import Response
from .utils import get_json
if typing.TYPE_CHECKING:
import sys
sys.path.append('./src/plugins')
sys.path.append("./src/plugins")
import nonebot_bison
@pytest.fixture
def ncm_artist(plugin_module: 'nonebot_bison'):
return plugin_module.platform.platform_manager['ncm-artist']
def ncm_artist(plugin_module: "nonebot_bison"):
return plugin_module.platform.platform_manager["ncm-artist"]
@pytest.fixture(scope='module')
@pytest.fixture(scope="module")
def ncm_artist_raw():
return get_json('ncm_siren.json')
return get_json("ncm_siren.json")
@pytest.fixture(scope='module')
@pytest.fixture(scope="module")
def ncm_artist_0(ncm_artist_raw):
return {
**ncm_artist_raw,
'hotAlbums': ncm_artist_raw['hotAlbums'][1:]
}
return {**ncm_artist_raw, "hotAlbums": ncm_artist_raw["hotAlbums"][1:]}
@pytest.fixture(scope='module')
@pytest.fixture(scope="module")
def ncm_artist_1(ncm_artist_raw: dict):
res = ncm_artist_raw.copy()
res['hotAlbums'] = ncm_artist_raw['hotAlbums'][:]
res['hotAlbums'][0]['publishTime'] = int(time.time() * 1000)
return res
res["hotAlbums"] = ncm_artist_raw["hotAlbums"][:]
res["hotAlbums"][0]["publishTime"] = int(time.time() * 1000)
return res
@pytest.mark.asyncio
@respx.mock
async def test_fetch_new(ncm_artist, ncm_artist_0, ncm_artist_1, dummy_user_subinfo):
ncm_router = respx.get("https://music.163.com/api/artist/albums/32540734")
ncm_router = respx.get("https://music.163.com/api/artist/albums/32540734")
ncm_router.mock(return_value=Response(200, json=ncm_artist_0))
target = '32540734'
target = "32540734"
res = await ncm_artist.fetch_new_post(target, [dummy_user_subinfo])
assert(ncm_router.called)
assert(len(res) == 0)
assert ncm_router.called
assert len(res) == 0
ncm_router.mock(return_value=Response(200, json=ncm_artist_1))
res2 = await ncm_artist.fetch_new_post(target, [dummy_user_subinfo])
post = res2[0][1][0]
assert(post.target_type == 'ncm-artist')
assert(post.text == '新专辑发布:Y1K')
assert(post.url == 'https://music.163.com/#/album?id=131074504')
assert post.target_type == "ncm-artist"
assert post.text == "新专辑发布:Y1K"
assert post.url == "https://music.163.com/#/album?id=131074504"
+34 -28
View File
@@ -1,53 +1,59 @@
import time
import typing
import respx
import pytest
from httpx import Response
from .utils import get_json
import pytest
import respx
import typing
import time
from httpx import Response
if typing.TYPE_CHECKING:
import sys
sys.path.append('./src/plugins')
sys.path.append("./src/plugins")
import nonebot_bison
@pytest.fixture
def ncm_radio(plugin_module: 'nonebot_bison'):
return plugin_module.platform.platform_manager['ncm-radio']
def ncm_radio(plugin_module: "nonebot_bison"):
return plugin_module.platform.platform_manager["ncm-radio"]
@pytest.fixture(scope='module')
@pytest.fixture(scope="module")
def ncm_radio_raw():
return get_json('ncm_radio_ark.json')
return get_json("ncm_radio_ark.json")
@pytest.fixture(scope='module')
@pytest.fixture(scope="module")
def ncm_radio_0(ncm_radio_raw):
return {
**ncm_radio_raw,
'programs': ncm_radio_raw['programs'][1:]
}
return {**ncm_radio_raw, "programs": ncm_radio_raw["programs"][1:]}
@pytest.fixture(scope='module')
@pytest.fixture(scope="module")
def ncm_radio_1(ncm_radio_raw: dict):
res = ncm_radio_raw.copy()
res['programs'] = ncm_radio_raw['programs'][:]
res['programs'][0]['createTime'] = int(time.time() * 1000)
return res
res["programs"] = ncm_radio_raw["programs"][:]
res["programs"][0]["createTime"] = int(time.time() * 1000)
return res
@pytest.mark.asyncio
@respx.mock
async def test_fetch_new(ncm_radio, ncm_radio_0, ncm_radio_1, dummy_user_subinfo):
ncm_router = respx.post("http://music.163.com/api/dj/program/byradio")
ncm_router = respx.post("http://music.163.com/api/dj/program/byradio")
ncm_router.mock(return_value=Response(200, json=ncm_radio_0))
target = '793745436'
target = "793745436"
res = await ncm_radio.fetch_new_post(target, [dummy_user_subinfo])
assert(ncm_router.called)
assert(len(res) == 0)
assert ncm_router.called
assert len(res) == 0
ncm_router.mock(return_value=Response(200, json=ncm_radio_1))
res2 = await ncm_radio.fetch_new_post(target, [dummy_user_subinfo])
post = res2[0][1][0]
print(post)
assert(post.target_type == 'ncm-radio')
assert(post.text == '网易云电台更新:「松烟行动」灰齐山麓')
assert(post.url == 'https://music.163.com/#/program/2494997688')
assert(post.pics == ['http://p1.music.126.net/H5em5xUNIYXcjJhOmeaSqQ==/109951166647436789.jpg'])
assert(post.target_name == '《明日方舟》游戏原声OST')
assert post.target_type == "ncm-radio"
assert post.text == "网易云电台更新:「松烟行动」灰齐山麓"
assert post.url == "https://music.163.com/#/program/2494997688"
assert post.pics == [
"http://p1.music.126.net/H5em5xUNIYXcjJhOmeaSqQ==/109951166647436789.jpg"
]
assert post.target_name == "《明日方舟》游戏原声OST"
+255 -182
View File
@@ -6,42 +6,48 @@ import pytest
if typing.TYPE_CHECKING:
import sys
sys.path.append('./src/plugins')
sys.path.append("./src/plugins")
import nonebot_bison
from nonebot_bison.types import *
from nonebot_bison.post import Post
from time import time
now = time()
passed = now - 3 * 60 * 60
raw_post_list_1 = [
{'id': 1, 'text': 'p1', 'date': now, 'tags': ['tag1'], 'category': 1}
]
{"id": 1, "text": "p1", "date": now, "tags": ["tag1"], "category": 1}
]
raw_post_list_2 = raw_post_list_1 + [
{'id': 2, 'text': 'p2', 'date': now, 'tags': ['tag1'], 'category': 1},
{'id': 3, 'text': 'p3', 'date': now, 'tags': ['tag2'], 'category': 2},
{'id': 4, 'text': 'p4', 'date': now, 'tags': ['tag2'], 'category': 3}
]
{"id": 2, "text": "p2", "date": now, "tags": ["tag1"], "category": 1},
{"id": 3, "text": "p3", "date": now, "tags": ["tag2"], "category": 2},
{"id": 4, "text": "p4", "date": now, "tags": ["tag2"], "category": 3},
]
@pytest.fixture
def dummy_user(plugin_module: 'nonebot_bison'):
user = plugin_module.types.User('123', 'group')
def dummy_user(plugin_module: "nonebot_bison"):
user = plugin_module.types.User("123", "group")
return user
@pytest.fixture
def user_info_factory(plugin_module: 'nonebot_bison', dummy_user):
def user_info_factory(plugin_module: "nonebot_bison", dummy_user):
def _user_info(category_getter, tag_getter):
return plugin_module.types.UserSubInfo(dummy_user, category_getter, tag_getter)
return _user_info
@pytest.fixture
def mock_platform_without_cats_tags(plugin_module: 'nonebot_bison'):
def mock_platform_without_cats_tags(plugin_module: "nonebot_bison"):
class MockPlatform(plugin_module.platform.platform.NewMessage):
platform_name = 'mock_platform'
name = 'Mock Platform'
platform_name = "mock_platform"
name = "Mock Platform"
enabled = True
is_common = True
schedule_interval = 10
@@ -52,21 +58,26 @@ def mock_platform_without_cats_tags(plugin_module: 'nonebot_bison'):
def __init__(self):
self.sub_index = 0
super().__init__()
@staticmethod
async def get_target_name(_: 'Target'):
return 'MockPlatform'
async def get_target_name(_: "Target"):
return "MockPlatform"
def get_id(self, post: 'RawPost') -> Any:
return post['id']
def get_id(self, post: "RawPost") -> Any:
return post["id"]
def get_date(self, raw_post: 'RawPost') -> float:
return raw_post['date']
def get_date(self, raw_post: "RawPost") -> float:
return raw_post["date"]
async def parse(self, raw_post: 'RawPost') -> 'Post':
return plugin_module.post.Post('mock_platform', raw_post['text'], 'http://t.tt/' + str(self.get_id(raw_post)), target_name='Mock')
async def parse(self, raw_post: "RawPost") -> "Post":
return plugin_module.post.Post(
"mock_platform",
raw_post["text"],
"http://t.tt/" + str(self.get_id(raw_post)),
target_name="Mock",
)
async def get_sub_list(self, _: 'Target'):
async def get_sub_list(self, _: "Target"):
if self.sub_index == 0:
self.sub_index += 1
return raw_post_list_1
@@ -75,45 +86,52 @@ def mock_platform_without_cats_tags(plugin_module: 'nonebot_bison'):
return MockPlatform()
@pytest.fixture
def mock_platform(plugin_module: 'nonebot_bison'):
def mock_platform(plugin_module: "nonebot_bison"):
class MockPlatform(plugin_module.platform.platform.NewMessage):
platform_name = 'mock_platform'
name = 'Mock Platform'
platform_name = "mock_platform"
name = "Mock Platform"
enabled = True
is_common = True
schedule_interval = 10
enable_tag = True
has_target = True
categories = {
1: '转发',
2: '视频',
}
1: "转发",
2: "视频",
}
def __init__(self):
self.sub_index = 0
super().__init__()
@staticmethod
async def get_target_name(_: 'Target'):
return 'MockPlatform'
async def get_target_name(_: "Target"):
return "MockPlatform"
def get_id(self, post: 'RawPost') -> Any:
return post['id']
def get_id(self, post: "RawPost") -> Any:
return post["id"]
def get_date(self, raw_post: 'RawPost') -> float:
return raw_post['date']
def get_date(self, raw_post: "RawPost") -> float:
return raw_post["date"]
def get_tags(self, raw_post: 'RawPost') -> list['Tag']:
return raw_post['tags']
def get_tags(self, raw_post: "RawPost") -> list["Tag"]:
return raw_post["tags"]
def get_category(self, raw_post: 'RawPost') -> 'Category':
return raw_post['category']
def get_category(self, raw_post: "RawPost") -> "Category":
return raw_post["category"]
async def parse(self, raw_post: 'RawPost') -> 'Post':
return plugin_module.post.Post('mock_platform', raw_post['text'], 'http://t.tt/' + str(self.get_id(raw_post)), target_name='Mock')
async def parse(self, raw_post: "RawPost") -> "Post":
return plugin_module.post.Post(
"mock_platform",
raw_post["text"],
"http://t.tt/" + str(self.get_id(raw_post)),
target_name="Mock",
)
async def get_sub_list(self, _: 'Target'):
async def get_sub_list(self, _: "Target"):
if self.sub_index == 0:
self.sub_index += 1
return raw_post_list_1
@@ -122,49 +140,52 @@ def mock_platform(plugin_module: 'nonebot_bison'):
return MockPlatform()
@pytest.fixture
def mock_platform_no_target(plugin_module: 'nonebot_bison'):
def mock_platform_no_target(plugin_module: "nonebot_bison"):
class MockPlatform(plugin_module.platform.platform.NewMessage):
platform_name = 'mock_platform'
name = 'Mock Platform'
platform_name = "mock_platform"
name = "Mock Platform"
enabled = True
is_common = True
schedule_type = 'interval'
schedule_kw = {'seconds': 30}
schedule_type = "interval"
schedule_kw = {"seconds": 30}
enable_tag = True
has_target = False
categories = {
1: '转发',
2: '视频',
3: '不支持'
}
categories = {1: "转发", 2: "视频", 3: "不支持"}
def __init__(self):
self.sub_index = 0
super().__init__()
@staticmethod
async def get_target_name(_: 'Target'):
return 'MockPlatform'
async def get_target_name(_: "Target"):
return "MockPlatform"
def get_id(self, post: 'RawPost') -> Any:
return post['id']
def get_id(self, post: "RawPost") -> Any:
return post["id"]
def get_date(self, raw_post: 'RawPost') -> float:
return raw_post['date']
def get_date(self, raw_post: "RawPost") -> float:
return raw_post["date"]
def get_tags(self, raw_post: 'RawPost') -> list['Tag']:
return raw_post['tags']
def get_tags(self, raw_post: "RawPost") -> list["Tag"]:
return raw_post["tags"]
def get_category(self, raw_post: 'RawPost') -> 'Category':
if raw_post['category'] == 3:
def get_category(self, raw_post: "RawPost") -> "Category":
if raw_post["category"] == 3:
raise plugin_module.platform.platform.CategoryNotSupport()
return raw_post['category']
return raw_post["category"]
async def parse(self, raw_post: 'RawPost') -> 'Post':
return plugin_module.post.Post('mock_platform', raw_post['text'], 'http://t.tt/' + str(self.get_id(raw_post)), target_name='Mock')
async def parse(self, raw_post: "RawPost") -> "Post":
return plugin_module.post.Post(
"mock_platform",
raw_post["text"],
"http://t.tt/" + str(self.get_id(raw_post)),
target_name="Mock",
)
async def get_sub_list(self, _: 'Target'):
async def get_sub_list(self, _: "Target"):
if self.sub_index == 0:
self.sub_index += 1
return raw_post_list_1
@@ -173,54 +194,61 @@ def mock_platform_no_target(plugin_module: 'nonebot_bison'):
return MockPlatform()
@pytest.fixture
def mock_platform_no_target_2(plugin_module: 'nonebot_bison'):
def mock_platform_no_target_2(plugin_module: "nonebot_bison"):
class MockPlatform(plugin_module.platform.platform.NewMessage):
platform_name = 'mock_platform'
name = 'Mock Platform'
platform_name = "mock_platform"
name = "Mock Platform"
enabled = True
schedule_type = 'interval'
schedule_kw = {'seconds': 30}
schedule_type = "interval"
schedule_kw = {"seconds": 30}
is_common = True
enable_tag = True
has_target = False
categories = {
4: 'leixing4',
5: 'leixing5',
}
4: "leixing4",
5: "leixing5",
}
def __init__(self):
self.sub_index = 0
super().__init__()
@staticmethod
async def get_target_name(_: 'Target'):
return 'MockPlatform'
async def get_target_name(_: "Target"):
return "MockPlatform"
def get_id(self, post: 'RawPost') -> Any:
return post['id']
def get_id(self, post: "RawPost") -> Any:
return post["id"]
def get_date(self, raw_post: 'RawPost') -> float:
return raw_post['date']
def get_date(self, raw_post: "RawPost") -> float:
return raw_post["date"]
def get_tags(self, raw_post: 'RawPost') -> list['Tag']:
return raw_post['tags']
def get_tags(self, raw_post: "RawPost") -> list["Tag"]:
return raw_post["tags"]
def get_category(self, raw_post: 'RawPost') -> 'Category':
return raw_post['category']
def get_category(self, raw_post: "RawPost") -> "Category":
return raw_post["category"]
async def parse(self, raw_post: 'RawPost') -> 'Post':
return plugin_module.post.Post('mock_platform_2', raw_post['text'], 'http://t.tt/' + str(self.get_id(raw_post)), target_name='Mock')
async def parse(self, raw_post: "RawPost") -> "Post":
return plugin_module.post.Post(
"mock_platform_2",
raw_post["text"],
"http://t.tt/" + str(self.get_id(raw_post)),
target_name="Mock",
)
async def get_sub_list(self, _: 'Target'):
async def get_sub_list(self, _: "Target"):
list_1 = [
{'id': 5, 'text': 'p5', 'date': now, 'tags': ['tag1'], 'category': 4}
]
{"id": 5, "text": "p5", "date": now, "tags": ["tag1"], "category": 4}
]
list_2 = list_1 + [
{'id': 6, 'text': 'p6', 'date': now, 'tags': ['tag1'], 'category': 4},
{'id': 7, 'text': 'p7', 'date': now, 'tags': ['tag2'], 'category': 5},
]
{"id": 6, "text": "p6", "date": now, "tags": ["tag1"], "category": 4},
{"id": 7, "text": "p7", "date": now, "tags": ["tag2"], "category": 5},
]
if self.sub_index == 0:
self.sub_index += 1
return list_1
@@ -229,145 +257,190 @@ def mock_platform_no_target_2(plugin_module: 'nonebot_bison'):
return MockPlatform()
@pytest.fixture
def mock_status_change(plugin_module: 'nonebot_bison'):
def mock_status_change(plugin_module: "nonebot_bison"):
class MockPlatform(plugin_module.platform.platform.StatusChange):
platform_name = 'mock_platform'
name = 'Mock Platform'
platform_name = "mock_platform"
name = "Mock Platform"
enabled = True
is_common = True
enable_tag = False
schedule_type = 'interval'
schedule_kw = {'seconds': 10}
schedule_type = "interval"
schedule_kw = {"seconds": 10}
has_target = False
categories = {
1: '转发',
2: '视频',
}
1: "转发",
2: "视频",
}
def __init__(self):
self.sub_index = 0
super().__init__()
async def get_status(self, _: 'Target'):
async def get_status(self, _: "Target"):
if self.sub_index == 0:
self.sub_index += 1
return {'s': False}
return {"s": False}
elif self.sub_index == 1:
self.sub_index += 1
return {'s': True}
return {"s": True}
else:
return {'s': False}
return {"s": False}
def compare_status(self, target, old_status, new_status) -> list['RawPost']:
if old_status['s'] == False and new_status['s'] == True:
return [{'text': 'on', 'cat': 1}]
elif old_status['s'] == True and new_status['s'] == False:
return [{'text': 'off', 'cat': 2}]
def compare_status(self, target, old_status, new_status) -> list["RawPost"]:
if old_status["s"] == False and new_status["s"] == True:
return [{"text": "on", "cat": 1}]
elif old_status["s"] == True and new_status["s"] == False:
return [{"text": "off", "cat": 2}]
return []
async def parse(self, raw_post) -> 'Post':
return plugin_module.post.Post('mock_status', raw_post['text'], '')
async def parse(self, raw_post) -> "Post":
return plugin_module.post.Post("mock_status", raw_post["text"], "")
def get_category(self, raw_post):
return raw_post['cat']
return raw_post["cat"]
return MockPlatform()
@pytest.mark.asyncio
async def test_new_message_target_without_cats_tags(mock_platform_without_cats_tags, user_info_factory):
res1 = await mock_platform_without_cats_tags.fetch_new_post('dummy', [user_info_factory(lambda _: [1,2], lambda _: [])])
assert(len(res1) == 0)
res2 = await mock_platform_without_cats_tags.fetch_new_post('dummy', [
user_info_factory(lambda _: [], lambda _: []),
])
assert(len(res2) == 1)
async def test_new_message_target_without_cats_tags(
mock_platform_without_cats_tags, user_info_factory
):
res1 = await mock_platform_without_cats_tags.fetch_new_post(
"dummy", [user_info_factory(lambda _: [1, 2], lambda _: [])]
)
assert len(res1) == 0
res2 = await mock_platform_without_cats_tags.fetch_new_post(
"dummy",
[
user_info_factory(lambda _: [], lambda _: []),
],
)
assert len(res2) == 1
posts_1 = res2[0][1]
assert(len(posts_1) == 3)
assert len(posts_1) == 3
id_set_1 = set(map(lambda x: x.text, posts_1))
assert('p2' in id_set_1 and 'p3' in id_set_1 and 'p4' in id_set_1)
assert "p2" in id_set_1 and "p3" in id_set_1 and "p4" in id_set_1
@pytest.mark.asyncio
async def test_new_message_target(mock_platform, user_info_factory):
res1 = await mock_platform.fetch_new_post('dummy', [user_info_factory(lambda _: [1,2], lambda _: [])])
assert(len(res1) == 0)
res2 = await mock_platform.fetch_new_post('dummy', [
user_info_factory(lambda _: [1,2], lambda _: []),
user_info_factory(lambda _: [1], lambda _: []),
user_info_factory(lambda _: [1,2], lambda _: ['tag1'])
])
assert(len(res2) == 3)
res1 = await mock_platform.fetch_new_post(
"dummy", [user_info_factory(lambda _: [1, 2], lambda _: [])]
)
assert len(res1) == 0
res2 = await mock_platform.fetch_new_post(
"dummy",
[
user_info_factory(lambda _: [1, 2], lambda _: []),
user_info_factory(lambda _: [1], lambda _: []),
user_info_factory(lambda _: [1, 2], lambda _: ["tag1"]),
],
)
assert len(res2) == 3
posts_1 = res2[0][1]
posts_2 = res2[1][1]
posts_3 = res2[2][1]
assert(len(posts_1) == 2)
assert(len(posts_2) == 1)
assert(len(posts_3) == 1)
assert len(posts_1) == 2
assert len(posts_2) == 1
assert len(posts_3) == 1
id_set_1 = set(map(lambda x: x.text, posts_1))
id_set_2 = set(map(lambda x: x.text, posts_2))
id_set_3 = set(map(lambda x: x.text, posts_3))
assert('p2' in id_set_1 and 'p3' in id_set_1)
assert('p2' in id_set_2)
assert('p2' in id_set_3)
assert "p2" in id_set_1 and "p3" in id_set_1
assert "p2" in id_set_2
assert "p2" in id_set_3
@pytest.mark.asyncio
async def test_new_message_no_target(mock_platform_no_target, user_info_factory):
res1 = await mock_platform_no_target.fetch_new_post('dummy', [user_info_factory(lambda _: [1,2], lambda _: [])])
assert(len(res1) == 0)
res2 = await mock_platform_no_target.fetch_new_post('dummy', [
user_info_factory(lambda _: [1,2], lambda _: []),
user_info_factory(lambda _: [1], lambda _: []),
user_info_factory(lambda _: [1,2], lambda _: ['tag1'])
])
assert(len(res2) == 3)
res1 = await mock_platform_no_target.fetch_new_post(
"dummy", [user_info_factory(lambda _: [1, 2], lambda _: [])]
)
assert len(res1) == 0
res2 = await mock_platform_no_target.fetch_new_post(
"dummy",
[
user_info_factory(lambda _: [1, 2], lambda _: []),
user_info_factory(lambda _: [1], lambda _: []),
user_info_factory(lambda _: [1, 2], lambda _: ["tag1"]),
],
)
assert len(res2) == 3
posts_1 = res2[0][1]
posts_2 = res2[1][1]
posts_3 = res2[2][1]
assert(len(posts_1) == 2)
assert(len(posts_2) == 1)
assert(len(posts_3) == 1)
assert len(posts_1) == 2
assert len(posts_2) == 1
assert len(posts_3) == 1
id_set_1 = set(map(lambda x: x.text, posts_1))
id_set_2 = set(map(lambda x: x.text, posts_2))
id_set_3 = set(map(lambda x: x.text, posts_3))
assert('p2' in id_set_1 and 'p3' in id_set_1)
assert('p2' in id_set_2)
assert('p2' in id_set_3)
res3 = await mock_platform_no_target.fetch_new_post('dummy', [user_info_factory(lambda _: [1,2], lambda _: [])])
assert(len(res3) == 0)
assert "p2" in id_set_1 and "p3" in id_set_1
assert "p2" in id_set_2
assert "p2" in id_set_3
res3 = await mock_platform_no_target.fetch_new_post(
"dummy", [user_info_factory(lambda _: [1, 2], lambda _: [])]
)
assert len(res3) == 0
@pytest.mark.asyncio
async def test_status_change(mock_status_change, user_info_factory):
res1 = await mock_status_change.fetch_new_post('dummy', [user_info_factory(lambda _: [1,2], lambda _: [])])
assert(len(res1) == 0)
res2 = await mock_status_change.fetch_new_post('dummy', [
user_info_factory(lambda _: [1,2], lambda _:[])
])
assert(len(res2) == 1)
res1 = await mock_status_change.fetch_new_post(
"dummy", [user_info_factory(lambda _: [1, 2], lambda _: [])]
)
assert len(res1) == 0
res2 = await mock_status_change.fetch_new_post(
"dummy", [user_info_factory(lambda _: [1, 2], lambda _: [])]
)
assert len(res2) == 1
posts = res2[0][1]
assert(len(posts) == 1)
assert(posts[0].text == 'on')
res3 = await mock_status_change.fetch_new_post('dummy', [
user_info_factory(lambda _: [1,2], lambda _: []),
user_info_factory(lambda _: [1], lambda _: []),
])
assert(len(res3) == 2)
assert(len(res3[0][1]) == 1)
assert(res3[0][1][0].text == 'off')
assert(len(res3[1][1]) == 0)
res4 = await mock_status_change.fetch_new_post('dummy', [user_info_factory(lambda _: [1,2], lambda _: [])])
assert(len(res4) == 0)
assert len(posts) == 1
assert posts[0].text == "on"
res3 = await mock_status_change.fetch_new_post(
"dummy",
[
user_info_factory(lambda _: [1, 2], lambda _: []),
user_info_factory(lambda _: [1], lambda _: []),
],
)
assert len(res3) == 2
assert len(res3[0][1]) == 1
assert res3[0][1][0].text == "off"
assert len(res3[1][1]) == 0
res4 = await mock_status_change.fetch_new_post(
"dummy", [user_info_factory(lambda _: [1, 2], lambda _: [])]
)
assert len(res4) == 0
@pytest.mark.asyncio
async def test_group(plugin_module: 'nonebot_bison', mock_platform_no_target, mock_platform_no_target_2, user_info_factory):
group_platform = plugin_module.platform.platform.NoTargetGroup([mock_platform_no_target, mock_platform_no_target_2])
res1 = await group_platform.fetch_new_post('dummy', [user_info_factory(lambda _: [1,4], lambda _: [])])
assert(len(res1) == 0)
res2 = await group_platform.fetch_new_post('dummy', [user_info_factory(lambda _: [1,4], lambda _: [])])
assert(len(res2) == 1)
async def test_group(
plugin_module: "nonebot_bison",
mock_platform_no_target,
mock_platform_no_target_2,
user_info_factory,
):
group_platform = plugin_module.platform.platform.NoTargetGroup(
[mock_platform_no_target, mock_platform_no_target_2]
)
res1 = await group_platform.fetch_new_post(
"dummy", [user_info_factory(lambda _: [1, 4], lambda _: [])]
)
assert len(res1) == 0
res2 = await group_platform.fetch_new_post(
"dummy", [user_info_factory(lambda _: [1, 4], lambda _: [])]
)
assert len(res2) == 1
posts = res2[0][1]
assert(len(posts) == 2)
assert len(posts) == 2
id_set_2 = set(map(lambda x: x.text, posts))
assert('p2' in id_set_2 and 'p6' in id_set_2)
res3 = await group_platform.fetch_new_post('dummy', [user_info_factory(lambda _: [1,4], lambda _: [])])
assert(len(res3) == 0)
assert "p2" in id_set_2 and "p6" in id_set_2
res3 = await group_platform.fetch_new_post(
"dummy", [user_info_factory(lambda _: [1, 4], lambda _: [])]
)
assert len(res3) == 0
+76 -55
View File
@@ -1,110 +1,131 @@
import pytest
import typing
import respx
from datetime import datetime
import respx
import pytest
import feedparser
from pytz import timezone
from httpx import Response
import feedparser
if typing.TYPE_CHECKING:
import sys
sys.path.append('./src/plugins')
sys.path.append("./src/plugins")
import nonebot_bison
from .utils import get_json, get_file
from .utils import get_file, get_json
@pytest.fixture
def weibo(plugin_module: 'nonebot_bison'):
return plugin_module.platform.platform_manager['weibo']
def weibo(plugin_module: "nonebot_bison"):
return plugin_module.platform.platform_manager["weibo"]
@pytest.fixture(scope='module')
@pytest.fixture(scope="module")
def weibo_ak_list_1():
return get_json('weibo_ak_list_1.json')
return get_json("weibo_ak_list_1.json")
@pytest.mark.asyncio
async def test_get_name(weibo):
name = await weibo.get_target_name('6279793937')
assert(name == "明日方舟Arknights")
name = await weibo.get_target_name("6279793937")
assert name == "明日方舟Arknights"
@pytest.mark.asyncio
@respx.mock
async def test_fetch_new(weibo, dummy_user_subinfo):
ak_list_router = respx.get("https://m.weibo.cn/api/container/getIndex?containerid=1076036279793937")
ak_list_router = respx.get(
"https://m.weibo.cn/api/container/getIndex?containerid=1076036279793937"
)
detail_router = respx.get("https://m.weibo.cn/detail/4649031014551911")
ak_list_router.mock(return_value=Response(200, json=get_json('weibo_ak_list_0.json')))
detail_router.mock(return_value=Response(200, text=get_file('weibo_detail_4649031014551911')))
target = '6279793937'
ak_list_router.mock(
return_value=Response(200, json=get_json("weibo_ak_list_0.json"))
)
detail_router.mock(
return_value=Response(200, text=get_file("weibo_detail_4649031014551911"))
)
target = "6279793937"
res = await weibo.fetch_new_post(target, [dummy_user_subinfo])
assert(ak_list_router.called)
assert(len(res) == 0)
assert(not detail_router.called)
mock_data = get_json('weibo_ak_list_1.json')
assert ak_list_router.called
assert len(res) == 0
assert not detail_router.called
mock_data = get_json("weibo_ak_list_1.json")
ak_list_router.mock(return_value=Response(200, json=mock_data))
# import ipdb; ipdb.set_trace()
res2 = await weibo.fetch_new_post(target, [dummy_user_subinfo])
assert(len(res2) == 0)
mock_data['data']['cards'][1]['mblog']['created_at'] = \
datetime.now(timezone('Asia/Shanghai')).strftime('%a %b %d %H:%M:%S %z %Y')
assert len(res2) == 0
mock_data["data"]["cards"][1]["mblog"]["created_at"] = datetime.now(
timezone("Asia/Shanghai")
).strftime("%a %b %d %H:%M:%S %z %Y")
ak_list_router.mock(return_value=Response(200, json=mock_data))
res3 = await weibo.fetch_new_post(target, [dummy_user_subinfo])
assert(len(res3[0][1]) == 1)
assert(not detail_router.called)
assert len(res3[0][1]) == 1
assert not detail_router.called
post = res3[0][1][0]
assert(post.target_type == 'weibo')
assert(post.text == '#明日方舟#\nSideStory「沃伦姆德的薄暮」复刻现已开启! ')
assert(post.url == 'https://weibo.com/6279793937/KkBtUx2dv')
assert(post.target_name == '明日方舟Arknights')
assert(len(post.pics) == 1)
assert post.target_type == "weibo"
assert post.text == "#明日方舟#\nSideStory「沃伦姆德的薄暮」复刻现已开启! "
assert post.url == "https://weibo.com/6279793937/KkBtUx2dv"
assert post.target_name == "明日方舟Arknights"
assert len(post.pics) == 1
@pytest.mark.asyncio
async def test_classification(weibo):
mock_data = get_json('weibo_ak_list_1.json')
tuwen = mock_data['data']['cards'][1]
retweet = mock_data['data']['cards'][3]
video = mock_data['data']['cards'][0]
mock_data_ys = get_json('weibo_ys_list_0.json')
text = mock_data_ys['data']['cards'][2]
assert(weibo.get_category(retweet) == 1)
assert(weibo.get_category(video) == 2)
assert(weibo.get_category(tuwen) == 3)
assert(weibo.get_category(text) == 4)
mock_data = get_json("weibo_ak_list_1.json")
tuwen = mock_data["data"]["cards"][1]
retweet = mock_data["data"]["cards"][3]
video = mock_data["data"]["cards"][0]
mock_data_ys = get_json("weibo_ys_list_0.json")
text = mock_data_ys["data"]["cards"][2]
assert weibo.get_category(retweet) == 1
assert weibo.get_category(video) == 2
assert weibo.get_category(tuwen) == 3
assert weibo.get_category(text) == 4
@pytest.mark.asyncio
@respx.mock
async def test_parse_long(weibo):
detail_router = respx.get("https://m.weibo.cn/detail/4645748019299849")
detail_router.mock(return_value=Response(200, text=get_file('weibo_detail_4645748019299849')))
raw_post = get_json('weibo_ak_list_1.json')['data']['cards'][0]
detail_router.mock(
return_value=Response(200, text=get_file("weibo_detail_4645748019299849"))
)
raw_post = get_json("weibo_ak_list_1.json")["data"]["cards"][0]
post = await weibo.parse(raw_post)
assert(not '全文' in post.text)
assert(detail_router.called)
assert not "全文" in post.text
assert detail_router.called
def test_tag(weibo, weibo_ak_list_1):
raw_post = weibo_ak_list_1['data']['cards'][0]
assert(weibo.get_tags(raw_post) == ['明日方舟', '音律联觉'])
raw_post = weibo_ak_list_1["data"]["cards"][0]
assert weibo.get_tags(raw_post) == ["明日方舟", "音律联觉"]
@pytest.mark.asyncio
@pytest.mark.compare
async def test_rsshub_compare(weibo):
target = '6279793937'
target = "6279793937"
raw_posts = filter(weibo.filter_platform_custom, await weibo.get_sub_list(target))
posts = []
for raw_post in raw_posts:
posts.append(await weibo.parse(raw_post))
url_set = set(map(lambda x: x.url, posts))
feedres = feedparser.parse('https://rsshub.app/weibo/user/6279793937')
feedres = feedparser.parse("https://rsshub.app/weibo/user/6279793937")
for entry in feedres.entries[:5]:
# print(entry)
assert(entry.link in url_set)
assert entry.link in url_set
test_post = {
"mblog": {
"text": "<a href=\"https://m.weibo.cn/search?containerid=231522type%3D1%26t%3D10%26q%3D%23%E5%88%9A%E5%87%BA%E7%94%9F%E7%9A%84%E5%B0%8F%E7%BE%8A%E9%A9%BC%E9%95%BF%E5%95%A5%E6%A0%B7%23&extparam=%23%E5%88%9A%E5%87%BA%E7%94%9F%E7%9A%84%E5%B0%8F%E7%BE%8A%E9%A9%BC%E9%95%BF%E5%95%A5%E6%A0%B7%23&luicode=10000011&lfid=1076036003966749\" data-hide=\"\"><span class=\"surl-text\">#刚出生的小羊驼长啥样#</span></a> <br />小羊驼三三来也<span class=\"url-icon\"><img alt=[好喜欢] src=\"https://h5.sinaimg.cn/m/emoticon/icon/lxh/lxh_haoxihuan-51860b62e6.png\" style=\"width:1em; height:1em;\" /></span><br /><a href=\"https://m.weibo.cn/p/index?extparam=%E5%B0%8F%E7%BE%8A%E9%A9%BC%E4%B8%89%E4%B8%89&containerid=1008085ae16d2046db677de1b8491d2b708597&luicode=10000011&lfid=1076036003966749\" data-hide=\"\"><span class='url-icon'><img style='width: 1rem;height: 1rem' src='https://n.sinaimg.cn/photo/5213b46e/20180926/timeline_card_small_super_default.png'></span><span class=\"surl-text\">小羊驼三三</span></a> ",
"bid": "KnssqeqKK"
}
"mblog": {
"text": '<a href="https://m.weibo.cn/search?containerid=231522type%3D1%26t%3D10%26q%3D%23%E5%88%9A%E5%87%BA%E7%94%9F%E7%9A%84%E5%B0%8F%E7%BE%8A%E9%A9%BC%E9%95%BF%E5%95%A5%E6%A0%B7%23&extparam=%23%E5%88%9A%E5%87%BA%E7%94%9F%E7%9A%84%E5%B0%8F%E7%BE%8A%E9%A9%BC%E9%95%BF%E5%95%A5%E6%A0%B7%23&luicode=10000011&lfid=1076036003966749" data-hide=""><span class="surl-text">#刚出生的小羊驼长啥样#</span></a> <br />小羊驼三三来也<span class="url-icon"><img alt=[好喜欢] src="https://h5.sinaimg.cn/m/emoticon/icon/lxh/lxh_haoxihuan-51860b62e6.png" style="width:1em; height:1em;" /></span><br /><a href="https://m.weibo.cn/p/index?extparam=%E5%B0%8F%E7%BE%8A%E9%A9%BC%E4%B8%89%E4%B8%89&containerid=1008085ae16d2046db677de1b8491d2b708597&luicode=10000011&lfid=1076036003966749" data-hide=""><span class=\'url-icon\'><img style=\'width: 1rem;height: 1rem\' src=\'https://n.sinaimg.cn/photo/5213b46e/20180926/timeline_card_small_super_default.png\'></span><span class="surl-text">小羊驼三三</span></a> ',
"bid": "KnssqeqKK",
}
}
def test_chaohua_tag(weibo):
tags = weibo.get_tags(test_post)
assert('刚出生的小羊驼长啥样' in tags)
assert('小羊驼三三超话' in tags)
assert "刚出生的小羊驼长啥样" in tags
assert "小羊驼三三超话" in tags
+10 -6
View File
@@ -1,12 +1,16 @@
from pathlib import Path
import json
from pathlib import Path
path = Path(__file__).parent
def get_json(file_name: str):
with open(path / file_name, 'r') as f:
file_text = f.read()
with open(path / file_name, "r") as f:
file_text = f.read()
return json.loads(file_text)
def get_file(file_name:str):
with open(path / file_name, 'r') as f:
file_text = f.read()
def get_file(file_name: str):
with open(path / file_name, "r") as f:
file_text = f.read()
return file_text
+34 -25
View File
@@ -1,38 +1,47 @@
import pytest
import typing
import pytest
if typing.TYPE_CHECKING:
import sys
sys.path.append('./src/plugins')
sys.path.append("./src/plugins")
import nonebot_bison
@pytest.fixture
def config(plugin_module):
plugin_module.config.start_up()
return plugin_module.config.Config()
def test_create_and_get(config: 'nonebot_bison.config.Config', plugin_module: 'nonebot_bison'):
def test_create_and_get(
config: "nonebot_bison.config.Config", plugin_module: "nonebot_bison"
):
config.add_subscribe(
user='123',
user_type='group',
target='weibo_id',
target_name='weibo_name',
target_type='weibo',
cats=[],
tags=[])
confs = config.list_subscribe('123', 'group')
assert(len(confs) == 1)
assert(config.target_user_cache['weibo']['weibo_id'] == \
[plugin_module.types.User('123', 'group')])
assert(confs[0]['cats'] == [])
user="123",
user_type="group",
target="weibo_id",
target_name="weibo_name",
target_type="weibo",
cats=[],
tags=[],
)
confs = config.list_subscribe("123", "group")
assert len(confs) == 1
assert config.target_user_cache["weibo"]["weibo_id"] == [
plugin_module.types.User("123", "group")
]
assert confs[0]["cats"] == []
config.update_subscribe(
user='123',
user_type='group',
target='weibo_id',
target_name='weibo_name',
target_type='weibo',
cats=['1'],
tags=[])
confs = config.list_subscribe('123', 'group')
assert(len(confs) == 1)
assert(confs[0]['cats'] == ['1'])
user="123",
user_type="group",
target="weibo_id",
target_name="weibo_name",
target_type="weibo",
cats=["1"],
tags=[],
)
confs = config.list_subscribe("123", "group")
assert len(confs) == 1
assert confs[0]["cats"] == ["1"]
+54 -42
View File
@@ -1,75 +1,87 @@
import pytest
import typing
import pytest
if typing.TYPE_CHECKING:
import sys
sys.path.append('./src/plugins')
sys.path.append("./src/plugins")
import nonebot_bison
merge_source_9 = [
'https://wx1.sinaimg.cn/large/0071VPLMgy1gq0vib7zooj30dx0dxmz5.jpg',
"https://wx4.sinaimg.cn/large/0071VPLMgy1gq0vib5oqjj30dw0dxjt2.jpg",
"https://wx2.sinaimg.cn/large/0071VPLMgy1gq0vib8bjmj30dv0dxgn7.jpg",
"https://wx1.sinaimg.cn/large/0071VPLMgy1gq0vib6pn1j30dx0dw75v.jpg",
"https://wx4.sinaimg.cn/large/0071VPLMgy1gq0vib925mj30dw0dwabb.jpg",
"https://wx2.sinaimg.cn/large/0071VPLMgy1gq0vib7ujuj30dv0dwtap.jpg",
"https://wx1.sinaimg.cn/large/0071VPLMgy1gq0vibaexnj30dx0dvq49.jpg",
"https://wx1.sinaimg.cn/large/0071VPLMgy1gq0vibehw4j30dw0dv74u.jpg",
"https://wx1.sinaimg.cn/large/0071VPLMgy1gq0vibfb5fj30dv0dvtac.jpg",
"https://wx3.sinaimg.cn/large/0071VPLMgy1gq0viexkjxj30rs3pcx6p.jpg",
"https://wx2.sinaimg.cn/large/0071VPLMgy1gq0vif6qrpj30rs4mou10.jpg",
"https://wx4.sinaimg.cn/large/0071VPLMgy1gq0vifc826j30rs4a64qs.jpg",
"https://wx1.sinaimg.cn/large/0071VPLMgy1gq0vify21lj30rsbj71ld.jpg",
]
"https://wx1.sinaimg.cn/large/0071VPLMgy1gq0vib7zooj30dx0dxmz5.jpg",
"https://wx4.sinaimg.cn/large/0071VPLMgy1gq0vib5oqjj30dw0dxjt2.jpg",
"https://wx2.sinaimg.cn/large/0071VPLMgy1gq0vib8bjmj30dv0dxgn7.jpg",
"https://wx1.sinaimg.cn/large/0071VPLMgy1gq0vib6pn1j30dx0dw75v.jpg",
"https://wx4.sinaimg.cn/large/0071VPLMgy1gq0vib925mj30dw0dwabb.jpg",
"https://wx2.sinaimg.cn/large/0071VPLMgy1gq0vib7ujuj30dv0dwtap.jpg",
"https://wx1.sinaimg.cn/large/0071VPLMgy1gq0vibaexnj30dx0dvq49.jpg",
"https://wx1.sinaimg.cn/large/0071VPLMgy1gq0vibehw4j30dw0dv74u.jpg",
"https://wx1.sinaimg.cn/large/0071VPLMgy1gq0vibfb5fj30dv0dvtac.jpg",
"https://wx3.sinaimg.cn/large/0071VPLMgy1gq0viexkjxj30rs3pcx6p.jpg",
"https://wx2.sinaimg.cn/large/0071VPLMgy1gq0vif6qrpj30rs4mou10.jpg",
"https://wx4.sinaimg.cn/large/0071VPLMgy1gq0vifc826j30rs4a64qs.jpg",
"https://wx1.sinaimg.cn/large/0071VPLMgy1gq0vify21lj30rsbj71ld.jpg",
]
merge_source_9_2 = [
'https://wx2.sinaimg.cn/large/0071VPLMgy1gxo0eyycd7j30dw0dd3zk.jpg',
'https://wx1.sinaimg.cn/large/0071VPLMgy1gxo0eyx6mhj30dw0ddjs8.jpg',
'https://wx4.sinaimg.cn/large/0071VPLMgy1gxo0eyxf2bj30dw0dddh4.jpg',
'https://wx3.sinaimg.cn/large/0071VPLMgy1gxo0ez1h5zj30dw0efwfs.jpg',
'https://wx3.sinaimg.cn/large/0071VPLMgy1gxo0eyyku4j30dw0ef3zm.jpg',
'https://wx1.sinaimg.cn/large/0071VPLMgy1gxo0ez0bjhj30dw0efabs.jpg',
'https://wx4.sinaimg.cn/large/0071VPLMgy1gxo0ezdcafj30dw0dwacb.jpg',
'https://wx1.sinaimg.cn/large/0071VPLMgy1gxo0ezg2g3j30dw0dwq51.jpg',
'https://wx3.sinaimg.cn/large/0071VPLMgy1gxo0ez5oloj30dw0dw0uf.jpg',
'https://wx4.sinaimg.cn/large/0071VPLMgy1gxo0fnk6stj30rs44ne81.jpg',
'https://wx2.sinaimg.cn/large/0071VPLMgy1gxo0fohgcoj30rs3wpe81.jpg',
'https://wx3.sinaimg.cn/large/0071VPLMgy1gxo0fpr6chj30rs3m1b29.jpg'
]
"https://wx2.sinaimg.cn/large/0071VPLMgy1gxo0eyycd7j30dw0dd3zk.jpg",
"https://wx1.sinaimg.cn/large/0071VPLMgy1gxo0eyx6mhj30dw0ddjs8.jpg",
"https://wx4.sinaimg.cn/large/0071VPLMgy1gxo0eyxf2bj30dw0dddh4.jpg",
"https://wx3.sinaimg.cn/large/0071VPLMgy1gxo0ez1h5zj30dw0efwfs.jpg",
"https://wx3.sinaimg.cn/large/0071VPLMgy1gxo0eyyku4j30dw0ef3zm.jpg",
"https://wx1.sinaimg.cn/large/0071VPLMgy1gxo0ez0bjhj30dw0efabs.jpg",
"https://wx4.sinaimg.cn/large/0071VPLMgy1gxo0ezdcafj30dw0dwacb.jpg",
"https://wx1.sinaimg.cn/large/0071VPLMgy1gxo0ezg2g3j30dw0dwq51.jpg",
"https://wx3.sinaimg.cn/large/0071VPLMgy1gxo0ez5oloj30dw0dw0uf.jpg",
"https://wx4.sinaimg.cn/large/0071VPLMgy1gxo0fnk6stj30rs44ne81.jpg",
"https://wx2.sinaimg.cn/large/0071VPLMgy1gxo0fohgcoj30rs3wpe81.jpg",
"https://wx3.sinaimg.cn/large/0071VPLMgy1gxo0fpr6chj30rs3m1b29.jpg",
]
@pytest.mark.asyncio
async def test_9_merge(plugin_module: 'nonebot_bison'):
post = plugin_module.post.Post('', '', '', pics=merge_source_9)
await post._pic_merge()
async def test_9_merge(plugin_module: "nonebot_bison"):
post = plugin_module.post.Post("", "", "", pics=merge_source_9)
await post._pic_merge()
assert len(post.pics) == 5
await post.generate_messages()
@pytest.mark.asyncio
async def test_9_merge_2(plugin_module: 'nonebot_bison'):
post = plugin_module.post.Post('', '', '', pics=merge_source_9_2)
async def test_9_merge_2(plugin_module: "nonebot_bison"):
post = plugin_module.post.Post("", "", "", pics=merge_source_9_2)
await post._pic_merge()
assert len(post.pics) == 4
await post.generate_messages()
@pytest.mark.asyncio
async def test_6_merge(plugin_module):
post = plugin_module.post.Post('', '', '', pics=merge_source_9[0:6]+merge_source_9[9:])
await post._pic_merge()
post = plugin_module.post.Post(
"", "", "", pics=merge_source_9[0:6] + merge_source_9[9:]
)
await post._pic_merge()
assert len(post.pics) == 5
@pytest.mark.asyncio
async def test_3_merge(plugin_module):
post = plugin_module.post.Post('', '', '', pics=merge_source_9[0:3]+merge_source_9[9:])
await post._pic_merge()
post = plugin_module.post.Post(
"", "", "", pics=merge_source_9[0:3] + merge_source_9[9:]
)
await post._pic_merge()
assert len(post.pics) == 5
@pytest.mark.asyncio
async def test_6_merge_only(plugin_module):
post = plugin_module.post.Post('', '', '', pics=merge_source_9[0:6])
await post._pic_merge()
post = plugin_module.post.Post("", "", "", pics=merge_source_9[0:6])
await post._pic_merge()
assert len(post.pics) == 1
@pytest.mark.asyncio
async def test_3_merge_only(plugin_module):
post = plugin_module.post.Post('', '', '', pics=merge_source_9[0:3])
await post._pic_merge()
post = plugin_module.post.Post("", "", "", pics=merge_source_9[0:3])
await post._pic_merge()
assert len(post.pics) == 1
+10 -5
View File
@@ -1,20 +1,25 @@
import pytest
import typing
import pytest
if typing.TYPE_CHECKING:
import sys
sys.path.append('./src/plugins')
sys.path.append("./src/plugins")
import nonebot_bison
@pytest.mark.asyncio
@pytest.mark.render
async def test_render(plugin_module: 'nonebot_bison'):
async def test_render(plugin_module: "nonebot_bison"):
render = plugin_module.utils.Render()
res = await render.text_to_pic('''a\nbbbbbbbbbbbbbbbbbbbbbb\ncd
res = await render.text_to_pic(
"""a\nbbbbbbbbbbbbbbbbbbbbbb\ncd
<h1>中文</h1>
VuePress 由两部分组成:第一部分是一个极简静态网站生成器
(opens new window),它包含由 Vue 驱动的主题系统和插件 API,另一个部分是为书写技术文档而优化的默认主题,它的诞生初衷是为了支持 Vue 及其子项目的文档需求。
每一个由 VuePress 生成的页面都带有预渲染好的 HTML,也因此具有非常好的加载性能和搜索引擎优化(SEO)。同时,一旦页面被加载,Vue 将接管这些静态内容,并将其转换成一个完整的单页应用(SPA),其他的页面则会只在用户浏览到的时候才按需加载。
''')
"""
)