290 lines
11 KiB
Python
290 lines
11 KiB
Python
import json
|
|
import os
|
|
import subprocess
|
|
import sys
|
|
import wave
|
|
import zipfile
|
|
|
|
import numpy as np
|
|
import pytest
|
|
|
|
HERE = os.path.dirname(os.path.abspath(__file__))
|
|
sys.path.insert(0, os.path.join(HERE, ".."))
|
|
|
|
from chart import Note # noqa: E402
|
|
from pack import (SongPack, default_config, open_pack, save_pack, # noqa: E402
|
|
validate_pack, import_image, extract_audio)
|
|
|
|
|
|
# ---------- 測試素材 ----------
|
|
|
|
def write_wav(path, seconds=1.0):
|
|
sr = 44100
|
|
t = np.arange(int(sr * seconds)) / sr
|
|
data = (np.sin(2 * np.pi * 440 * t) * 8000).astype(np.int16)
|
|
with wave.open(str(path), "wb") as w:
|
|
w.setnchannels(1)
|
|
w.setsampwidth(2)
|
|
w.setframerate(sr)
|
|
w.writeframes(data.tobytes())
|
|
return str(path)
|
|
|
|
|
|
def write_image(path, size=(800, 600)):
|
|
from PIL import Image
|
|
Image.new("RGB", size, (200, 80, 120)).save(path)
|
|
return str(path)
|
|
|
|
|
|
def make_pack(tmp_path):
|
|
p = SongPack(default_config(id="test-song", name="Test", artist="Someone", charter="Me",
|
|
bpm=120.0, beat_offset=100, easy_num=3, hard_num=12))
|
|
p.set_music(write_wav(tmp_path / "a.wav"))
|
|
p.set_image(write_image(tmp_path / "cover.jpg"))
|
|
e = p.chart("easy", create=True)
|
|
e.notes = [Note(100, "L", "tap", pos=(0, 1)), Note(600, "R", "hold", 900, pos=(4, 2), locked=True)]
|
|
h = p.chart("hard", create=True)
|
|
h.notes = [Note(100, "M", "tap", pos=(2, 0)),
|
|
Note(400, "L", "slide", 800, path=[(0, 0), (1, 1), (2, 2)])]
|
|
return p
|
|
|
|
|
|
# ---------- 往返 ----------
|
|
|
|
def test_save_open_roundtrip(tmp_path):
|
|
p = make_pack(tmp_path)
|
|
z = str(tmp_path / "test-song.zip")
|
|
save_pack(p, z)
|
|
|
|
names = set(zipfile.ZipFile(z).namelist())
|
|
assert names == {"config.json", "easy.json", "hard.json", "music.wav", "image.png"} # 沒有 normal
|
|
|
|
q = open_pack(z)
|
|
assert q.config["id"] == "test-song" and q.config["easy_num"] == 3
|
|
assert set(q.charts) == {"easy", "hard"}
|
|
|
|
def dump(pack, d):
|
|
return [(n.t, n.lane, n.type, n.end, n.pos, n.path, n.locked) for n in pack.charts[d].notes]
|
|
for d in ("easy", "hard"):
|
|
assert dump(q, d) == dump(p, d)
|
|
# 曲目層級的 BPM / 第一拍來自 config
|
|
assert q.charts["easy"].bpm == 120.0 and q.charts["easy"].offset == 100
|
|
|
|
|
|
def test_chart_file_is_unified_format(tmp_path):
|
|
p = make_pack(tmp_path)
|
|
z = str(tmp_path / "x.zip")
|
|
save_pack(p, z)
|
|
d = json.loads(zipfile.ZipFile(z).read("easy.json"))
|
|
assert d["format"] == 1 and d["divisor"] == 4
|
|
assert d["notes"][1] == {"t": 600, "lane": "R", "type": "hold", "end": 900,
|
|
"pos": {"x": 4, "y": 2}, "locked": True}
|
|
assert "bpm" not in d
|
|
|
|
|
|
def test_save_failure_keeps_old_zip(tmp_path):
|
|
p = make_pack(tmp_path)
|
|
z = str(tmp_path / "x.zip")
|
|
save_pack(p, z)
|
|
before = open(z, "rb").read()
|
|
p.config["name"] = ""
|
|
with pytest.raises(ValueError):
|
|
save_pack(p, z)
|
|
assert open(z, "rb").read() == before
|
|
|
|
|
|
def test_open_ignores_unexpected_paths(tmp_path):
|
|
z = tmp_path / "evil.zip"
|
|
with zipfile.ZipFile(z, "w") as f:
|
|
f.writestr("config.json", json.dumps(default_config(id="x1", name="n", artist="a")))
|
|
f.writestr("../escape.txt", "nope")
|
|
f.writestr("sub/easy.json", "{}")
|
|
q = open_pack(str(z))
|
|
assert not os.path.exists(os.path.join(os.path.dirname(q.workdir), "escape.txt"))
|
|
assert q.charts == {}
|
|
|
|
|
|
# ---------- 驗證 ----------
|
|
|
|
def test_validate_reports_each_problem(tmp_path):
|
|
p = make_pack(tmp_path)
|
|
assert validate_pack(p) == []
|
|
|
|
p.config["id"] = "Bad ID"
|
|
p.config.pop("hard_num")
|
|
p.config["bpm"] = "fast"
|
|
errs = " ".join(validate_pack(p))
|
|
assert "id 只能用" in errs and "hard_num" in errs and "bpm" in errs
|
|
|
|
q = SongPack(default_config(id="empty", name="n", artist="a"))
|
|
errs = " ".join(validate_pack(q))
|
|
assert "至少需要啟用一個難度" in errs and "music 或 video" in errs and "image.png" in errs
|
|
|
|
|
|
def test_validate_rejects_non_square_image(tmp_path):
|
|
p = make_pack(tmp_path)
|
|
from PIL import Image
|
|
Image.new("RGB", (300, 200)).save(p.file("image.png"))
|
|
assert any("正方形" in e for e in validate_pack(p))
|
|
|
|
|
|
def test_import_image_center_crop(tmp_path):
|
|
from PIL import Image
|
|
src = tmp_path / "wide.png"
|
|
im = Image.new("RGB", (900, 300), (0, 0, 255))
|
|
for x in range(300, 600): # 中間 300x300 為紅色
|
|
for y in range(300):
|
|
im.putpixel((x, y), (255, 0, 0))
|
|
im.save(src)
|
|
dst = tmp_path / "out.png"
|
|
import_image(str(src), str(dst))
|
|
out = Image.open(dst).convert("RGB")
|
|
assert out.size == (512, 512)
|
|
assert out.getpixel((10, 256)) == (255, 0, 0) and out.getpixel((500, 256)) == (255, 0, 0)
|
|
|
|
|
|
# ---------- 只有影片 ----------
|
|
|
|
def test_video_only_extracts_audio(tmp_path):
|
|
import imageio_ffmpeg
|
|
ff = imageio_ffmpeg.get_ffmpeg_exe()
|
|
video = str(tmp_path / "clip.mp4")
|
|
subprocess.run([ff, "-y", "-loglevel", "error", "-f", "lavfi", "-i", "color=c=black:s=64x64:d=2",
|
|
"-f", "lavfi", "-i", "sine=frequency=440:duration=2", "-shortest",
|
|
"-c:v", "libx264", "-c:a", "aac", video], check=True)
|
|
|
|
p = SongPack(default_config(id="video-song", name="v", artist="a", normal_num=5))
|
|
p.set_video(video)
|
|
assert p.video and p.music and p.music.endswith("music.wav")
|
|
with wave.open(p.music) as w:
|
|
assert w.getframerate() == 44100 and w.getnchannels() == 2
|
|
assert abs(w.getnframes() / 44100 - 2.0) < 0.1
|
|
|
|
p.set_image(write_image(tmp_path / "c.png", (256, 256)))
|
|
p.chart("normal", create=True).notes = [Note(500, "M", "tap", pos=(2, 2))]
|
|
z = str(tmp_path / "v.zip")
|
|
save_pack(p, z)
|
|
assert {"video.mp4", "music.wav"} <= set(zipfile.ZipFile(z).namelist())
|
|
|
|
|
|
# ---------- Maker:難度切換 ----------
|
|
|
|
def test_maker_switch_difficulty_keeps_edits_and_undo(tmp_path):
|
|
os.environ["SDL_VIDEODRIVER"] = "dummy"
|
|
import pygame
|
|
from maker import Editor
|
|
p = make_pack(tmp_path)
|
|
ed = Editor(audio_enabled=False)
|
|
try:
|
|
ed.set_pack(p, "easy")
|
|
ed.push_undo()
|
|
ed.chart.add(Note(1500, "L", "tap"))
|
|
ed.switch_diff("normal") # 不存在 → 建立空譜面
|
|
assert ed.chart.notes == [] and "normal" in p.charts
|
|
assert ed.undo_stack == [] # undo 各難度獨立
|
|
ed.switch_diff("easy")
|
|
assert len(ed.chart.notes) == 3 # 剛剛的編輯還在
|
|
ed.undo()
|
|
assert len(ed.chart.notes) == 2
|
|
finally:
|
|
pygame.quit()
|
|
|
|
|
|
# ---------- 啟用 / 停用難度、空曲包 ----------
|
|
|
|
def test_empty_pack_can_be_saved_and_opened(tmp_path):
|
|
from pack import create_pack
|
|
z = str(tmp_path / "new.zip")
|
|
p = create_pack(z, {"id": "new-song", "name": "N", "artist": "A", "bpm": 150.0, "beat_offset": 0},
|
|
write_wav(tmp_path / "m.wav"), write_image(tmp_path / "c.png"), {"normal": 5, "hard": 11})
|
|
assert p.path == z
|
|
names = set(zipfile.ZipFile(z).namelist())
|
|
assert {"normal.json", "hard.json"} <= names and "easy.json" not in names
|
|
q = open_pack(z)
|
|
assert q.enabled() == ["normal", "hard"]
|
|
assert q.charts["normal"].notes == [] and q.config["hard_num"] == 11
|
|
|
|
|
|
def test_disable_removes_difficulty_on_save(tmp_path):
|
|
p = make_pack(tmp_path)
|
|
z = str(tmp_path / "x.zip")
|
|
save_pack(p, z)
|
|
p.disable("easy")
|
|
save_pack(p, z) # 同一路徑直接覆蓋
|
|
q = open_pack(z)
|
|
assert q.enabled() == ["hard"]
|
|
assert "easy.json" not in zipfile.ZipFile(z).namelist() and "easy_num" not in q.config
|
|
|
|
|
|
def test_at_least_one_difficulty_required(tmp_path):
|
|
p = make_pack(tmp_path)
|
|
p.disable("easy")
|
|
p.disable("hard")
|
|
assert any("至少需要啟用一個難度" in e for e in validate_pack(p))
|
|
|
|
|
|
def test_enabled_difficulty_needs_number(tmp_path):
|
|
p = make_pack(tmp_path)
|
|
p.enable("normal") # 沒給難度數字
|
|
assert any("normal_num" in e for e in validate_pack(p))
|
|
p.enable("normal", 7)
|
|
assert validate_pack(p) == []
|
|
|
|
|
|
def test_convert_audio_to_ogg_keeps_length(tmp_path):
|
|
from pack import convert_audio
|
|
from audio import load_audio
|
|
src = write_wav(tmp_path / "a.wav", seconds=3.0)
|
|
dst = str(tmp_path / "a.ogg")
|
|
convert_audio(src, dst)
|
|
assert os.path.getsize(dst) < os.path.getsize(src)
|
|
assert abs(len(load_audio(dst)) / 44100 - 3.0) < 0.05
|
|
|
|
|
|
# ---------- 啟動視窗的檢查 ----------
|
|
|
|
def test_launcher_checks(tmp_path):
|
|
from launcher import check_open_path, new_pack_errors
|
|
assert check_open_path(str(tmp_path / "nope.zip")) == "找不到這個檔案"
|
|
assert check_open_path("song.txt") == "請選擇 .zip 曲包"
|
|
bad = tmp_path / "bad.zip"
|
|
bad.write_text("not a zip")
|
|
assert check_open_path(str(bad)) == "這不是有效的 zip 檔"
|
|
|
|
ok = {"save_path": str(tmp_path / "s.zip"), "id": "my-song", "name": "N", "artist": "A", "charter": "",
|
|
"bpm": "120", "beat_offset": "0", "media": write_wav(tmp_path / "m.wav"),
|
|
"image": write_image(tmp_path / "c.png"), "use_easy": False, "use_normal": True, "use_hard": False,
|
|
"easy_num": "", "normal_num": "6", "hard_num": ""}
|
|
assert new_pack_errors(ok) == []
|
|
errs = new_pack_errors(dict(ok, id="My Song", bpm="x", use_normal=False))
|
|
assert any("ID" in e for e in errs) and any("BPM" in e for e in errs) and any("至少勾選" in e for e in errs)
|
|
assert any("normal 的難度數字" in e for e in new_pack_errors(dict(ok, normal_num="0")))
|
|
|
|
|
|
# ---------- Maker:難度勾選列 ----------
|
|
|
|
def test_maker_diff_toggle(tmp_path, monkeypatch):
|
|
os.environ["SDL_VIDEODRIVER"] = "dummy"
|
|
import pygame
|
|
from maker import Editor
|
|
p = make_pack(tmp_path)
|
|
ed = Editor(audio_enabled=False)
|
|
try:
|
|
ed.set_pack(p, "hard")
|
|
monkeypatch.setattr(ed, "dialog_number", lambda *a: 8)
|
|
monkeypatch.setattr(ed, "confirm", lambda *a: True)
|
|
ed.toggle_diff("normal") # 啟用 normal → 切過去
|
|
assert ed.diff == "normal" and p.config["normal_num"] == 8
|
|
ed.toggle_diff("hard") # 停用目前以外的難度
|
|
assert "hard" not in p.charts
|
|
ed.toggle_diff("normal") # 停用目前難度 → 自動切到 easy
|
|
assert ed.diff == "easy" and p.enabled() == ["easy"]
|
|
ed.toggle_diff("easy") # 最後一個不能停用
|
|
assert p.enabled() == ["easy"]
|
|
# 點擊勾選列也能操作
|
|
d, box, lv = ed.diff_bar_rects()[2]
|
|
ed.handle(pygame.event.Event(pygame.MOUSEBUTTONDOWN, pos=box.center, button=1))
|
|
assert "hard" in p.charts
|
|
finally:
|
|
pygame.quit()
|