feat: add init unit test
All checks were successful
Test CI / test speed (push) Successful in 17s

This commit is contained in:
sangge 2024-01-06 13:28:39 +08:00
parent 42765f9b8d
commit 99a39a0777
2 changed files with 41 additions and 10 deletions

View File

@ -20,7 +20,9 @@ app = FastAPI(lifespan=lifespan)
def init(): def init():
asyncio.create_task(receive_heartbeat_internal()) asyncio.create_task(receive_heartbeat_internal())
init_db()
def init_db():
conn = sqlite3.connect("server.db") conn = sqlite3.connect("server.db")
cursor = conn.cursor() cursor = conn.cursor()
# init table: id: int; ip: TEXT # init table: id: int; ip: TEXT
@ -66,11 +68,11 @@ def validate_ip(ip: str) -> bool:
@app.get("/server/get_node") @app.get("/server/get_node")
async def get_node(ip: str) -> int: async def get_node(ip: str) -> int:
""" """
中心服务器与节点交互, 节点发送ip, 中心服务器接收ip存入数据库并将ip转换为int作为节点id返回给节点 中心服务器与节点交互, 节点发送ip, 中心服务器接收ip存入数据库并将ip转换为int作为节点id返回给节点
params: params:
ip: node ip ip: node ip
return: return:
id: ip按点分割成四部分, 每部分转二进制后拼接再转十进制作为节点id id: ip按点分割成四部分, 每部分转二进制后拼接再转十进制作为节点id
""" """
if not validate_ip(ip): if not validate_ip(ip):
content = {"message": "invalid ip "} content = {"message": "invalid ip "}
@ -100,12 +102,12 @@ async def get_node(ip: str) -> int:
@app.get("/server/delete_node") @app.get("/server/delete_node")
async def delete_node(ip: str) -> None: async def delete_node(ip: str) -> None:
""" """
param: param:
ip: 待删除节点的ip地址 ip: 待删除节点的ip地址
return: return:
None None
""" """
with sqlite3.connect("server.db") as db: with sqlite3.connect("server.db") as db:
# 查询要删除的节点 # 查询要删除的节点
cursor = db.execute("SELECT * FROM nodes WHERE ip=?", (ip,)) cursor = db.execute("SELECT * FROM nodes WHERE ip=?", (ip,))

View File

@ -0,0 +1,29 @@
import unittest
import sqlite3
import os
from server import *
class TestServer(unittest.TestCase):
def test_init_creates_table(self):
# 执行初始化函数
init_db()
conn = sqlite3.connect("server.db")
cursor = conn.cursor()
# 检查表是否被正确创建
cursor.execute(
"SELECT name FROM sqlite_master WHERE type='table' AND name='nodes'"
)
tables = cursor.fetchall()
self.assertTrue(any("nodes" in table for table in tables))
# 关闭数据库连接
conn.close()
os.remove("server.db")
if __name__ == "__main__":
unittest.main()