57 lines
2.1 KiB
Python
57 lines
2.1 KiB
Python
|
|
"""数据导出/导入测试"""
|
||
|
|
|
||
|
|
from datetime import date
|
||
|
|
import json
|
||
|
|
|
||
|
|
from src.vitals.core import database as db
|
||
|
|
from src.vitals.core.export import export_all_data_json, export_to_csv, import_from_json
|
||
|
|
from src.vitals.core.models import Exercise, Meal, Sleep, Weight, UserConfig
|
||
|
|
|
||
|
|
|
||
|
|
def test_export_all_data_json(tmp_path):
|
||
|
|
db.save_config(UserConfig(age=28, gender="male", height=175.0, weight=72.0))
|
||
|
|
db.add_exercise(Exercise(date=date(2026, 1, 18), type="跑步", duration=30, calories=240))
|
||
|
|
db.add_meal(Meal(date=date(2026, 1, 18), meal_type="午餐", description="米饭+鸡蛋", calories=400))
|
||
|
|
db.add_sleep(Sleep(date=date(2026, 1, 18), duration=7.5, quality=4))
|
||
|
|
db.add_weight(Weight(date=date(2026, 1, 18), weight_kg=72.5))
|
||
|
|
|
||
|
|
out = tmp_path / "export.json"
|
||
|
|
export_all_data_json(out)
|
||
|
|
|
||
|
|
assert out.exists()
|
||
|
|
data = json.loads(out.read_text(encoding="utf-8"))
|
||
|
|
assert data["version"] == "1.0"
|
||
|
|
assert "exercises" in data and len(data["exercises"]) == 1
|
||
|
|
assert "meals" in data and len(data["meals"]) == 1
|
||
|
|
assert "sleep" in data and len(data["sleep"]) == 1
|
||
|
|
assert "weight" in data and len(data["weight"]) == 1
|
||
|
|
assert data["config"]["age"] == 28
|
||
|
|
|
||
|
|
|
||
|
|
def test_export_to_csv_exercise(tmp_path):
|
||
|
|
db.add_exercise(Exercise(date=date(2026, 1, 18), type="跑步", duration=30, calories=240))
|
||
|
|
|
||
|
|
out = tmp_path / "exercise.csv"
|
||
|
|
export_to_csv("exercise", out)
|
||
|
|
|
||
|
|
assert out.exists()
|
||
|
|
content = out.read_text(encoding="utf-8")
|
||
|
|
assert "date,type,duration,calories" in content
|
||
|
|
assert "2026-01-18" in content
|
||
|
|
|
||
|
|
|
||
|
|
def test_import_from_json_roundtrip(tmp_path):
|
||
|
|
# 先写入数据并导出
|
||
|
|
db.save_config(UserConfig(age=28, gender="male", height=175.0, weight=72.0))
|
||
|
|
db.add_exercise(Exercise(date=date(2026, 1, 18), type="跑步", duration=30, calories=240))
|
||
|
|
db.add_weight(Weight(date=date(2026, 1, 18), weight_kg=72.5))
|
||
|
|
|
||
|
|
out = tmp_path / "export.json"
|
||
|
|
export_all_data_json(out)
|
||
|
|
|
||
|
|
# 新的临时 DB 会在 conftest.py 中自动创建,这里直接导入并验证统计
|
||
|
|
stats = import_from_json(out)
|
||
|
|
assert stats["exercise"] >= 1
|
||
|
|
assert stats["weight"] >= 1
|
||
|
|
|