import subprocess import json import tempfile import unittest from pathlib import Path from unittest.mock import patch import imageio_ffmpeg from PIL import Image, ImageOps from core import Cancelled, Options, FrameConfig, export_frames, geometry, inspect_media, sample_indices, preview_samples class ExtractionTests(unittest.TestCase): def setUp(self): self.temp = tempfile.TemporaryDirectory() self.root = Path(self.temp.name) self.gif = self.root / '中文 动画.gif' images = [] for i in range(7): image = Image.new('RGBA', (40, 20), (0, 0, 0, 0)) for x in range(10, 30): for y in range(5, 15): image.putpixel((x, y), (i * 35, 240 - i * 30, 50, 255)) images.append(image) image.putpixel((10, 5), (255, 255, 255, 255)) images[0].save(self.gif, save_all=True, append_images=images[1:], duration=100, disposal=2, loop=0) def tearDown(self): self.temp.cleanup() def test_sampling_and_gif_transparency(self): info = inspect_media(self.gif) self.assertEqual(info.count, 7) self.assertEqual(sample_indices(7, 4), [0, 2, 4, 6]) self.assertEqual(sample_indices(7, 1), [0]) for total in range(1, 40): for count in range(1, total + 1): indices = sample_indices(total, count) self.assertEqual(len(set(indices)), count) self.assertEqual(indices, sorted(indices)) files = export_frames(self.gif, self.root / '输出', info, Options(count=4, prefix='角色')) self.assertEqual([f.name for f in files], [f'角色_{i}.png' for i in range(4)]) for path, source_idx in zip(files, [0, 2, 4, 6]): with Image.open(path) as result: self.assertEqual(result.getpixel((20, 10)), (source_idx * 35, 240 - source_idx * 30, 50, 255)) self.assertEqual(result.getpixel((0, 0))[3], 0) def test_crop_resize_and_no_overwrite(self): info = inspect_media(self.gif) options = Options(count=3, left=25, right=75, top=25, bottom=75, scale_axis='width', target=80) files = export_frames(self.gif, self.root / 'sized', info, options) with Image.open(files[0]) as result: self.assertEqual(result.size, (80, 40)) self.assertEqual(result.getpixel((40, 20)), (0, 240, 50, 255)) before = files[0].read_bytes() with self.assertRaises(ValueError): export_frames(self.gif, files[0].parent, info, options) self.assertEqual(before, files[0].read_bytes()) self.assertEqual(geometry(info.size, Options(scale_axis='height', target=33))[1], (66, 33)) def test_invalid_settings_and_cancel_rollback(self): for options in [Options(left=80, right=20), Options(top=float('nan')), Options(prefix='../bad'), Options(count=0)]: with self.assertRaises(ValueError): options.validate() info = inspect_media(self.gif) with self.assertRaises(ValueError): export_frames(self.gif, self.root / 'bad', info, Options(count=8)) stopped = [False] with self.assertRaises(Cancelled): export_frames(self.gif, self.root / 'cancel', info, Options(count=7), lambda *_: stopped.__setitem__(0, True), lambda: stopped[0]) self.assertEqual(list((self.root / 'cancel').iterdir()), []) def test_real_webm(self): video = self.root / '视频.webm' pixels = b''.join(Image.new('RGB', (40, 20), (i * 30, 100, 150)).tobytes() for i in range(6)) subprocess.run([imageio_ffmpeg.get_ffmpeg_exe(), '-v', 'error', '-f', 'rawvideo', '-pix_fmt', 'rgb24', '-s', '40x20', '-r', '10', '-i', 'pipe:0', '-c:v', 'libvpx-vp9', '-lossless', '1', str(video)], input=pixels, check=True) info = inspect_media(video) self.assertEqual((info.count, info.size), (6, (40, 20))) files = export_frames(video, self.root / 'webm', info, Options(count=3, scale_axis='height', target=10)) for path, source_idx in zip(files, [0, 3, 5]): with Image.open(path) as result: self.assertEqual(result.size, (20, 10)) self.assertLessEqual(abs(result.getpixel((10, 5))[0] - source_idx * 30), 4) def test_frame_config_and_mirrored_images(self): info = inspect_media(self.gif) options = Options(count=3, prefix='角色', left=25, right=75, top=25, bottom=75, scale_axis='width', target=160) config = FrameConfig('RogueTest', -51, -85, source_direction=1) output = self.root / 'config' files = export_frames(self.gif, output, info, options, config=config) self.assertEqual(len(files), 6) data = json.loads((output / '角色.json').read_text(encoding='utf-8')) template = json.loads((Path(__file__).parent.parent / 'game/frame/character/Rogue59.json').read_text(encoding='utf-8')) self.assertEqual(list(data), list(template)) self.assertEqual(data['HEAD_POS'], [-65, -5]) self.assertEqual(data['NAME'], 'RogueTest') self.assertEqual(data['INTERVAL'], 200) for action in ('STAND_R', 'STAND_U', 'STAND_L', 'STAND_D', 'R', 'U', 'L', 'D'): item = data[action] direction = 0 if action.endswith(('R', 'D')) else 1 self.assertEqual((item['Len'], item['Cx'], item['Cy']), (3, -51 if direction == 1 else -109, -85)) self.assertEqual(item['Cloth']['CX'], [0] * 3) self.assertEqual(item['Cloth']['CY'], [0] * 3) self.assertEqual(item['Cloth']['IMG'], [f'角色_{direction}_{i}.png' for i in range(3)]) self.assertTrue(all((output / name).is_file() for name in item['Cloth']['IMG'])) from core import transform with Image.open(output / '角色_1_0.png') as left, Image.open(output / '角色_0_0.png') as right: expected = transform(info.first, options) self.assertEqual(left.tobytes(), expected.tobytes()) self.assertEqual(right.tobytes(), ImageOps.mirror(expected).tobytes()) def test_mirrored_offset_preserves_world_anchor(self): info = inspect_media(self.gif) for direction in (0, 1): for width, cx in ((160, -51), (161, 13), (160, -80)): with self.subTest(direction=direction, width=width, cx=cx): options = Options(count=1, scale_axis='width', target=width) folder = self.root / f'anchor_{direction}_{width}_{cx}' export_frames(self.gif, folder, info, options, config=FrameConfig('Anchor', cx, -85, direction)) data = json.loads((folder / 'frame.json').read_text()) original_key, mirror_key = ('R', 'L') if direction == 0 else ('L', 'R') original, mirrored = data[original_key], data[mirror_key] self.assertEqual(original['Cx'], cx) self.assertEqual(mirrored['Cx'], -cx - width) self.assertEqual(original['Cy'], mirrored['Cy']) scenes = [] for item in (original, mirrored): scene = Image.new('RGBA', (600, 300)) with Image.open(folder / item['Cloth']['IMG'][0]) as sprite: scene.alpha_composite(sprite, (300 + item['Cx'], 150 + item['Cy'])) scenes.append(scene) # Check actual rendered pixels about the same world anchor, # including positive offsets and odd output widths. self.assertEqual(ImageOps.mirror(scenes[0]).tobytes(), scenes[1].tobytes()) def test_config_collision_and_failure_rollback(self): info = inspect_media(self.gif) options = Options(count=2) config = FrameConfig('Test') output = self.root / 'collision' output.mkdir() (output / 'frame.json').write_text('existing', encoding='utf-8') with self.assertRaises(ValueError): export_frames(self.gif, output, info, options, config=config) self.assertEqual(list(output.iterdir()), [output / 'frame.json']) self.assertEqual((output / 'frame.json').read_text(), 'existing') with patch('core.json.dump', side_effect=OSError('disk full')): with self.assertRaises(OSError): export_frames(self.gif, self.root / 'rollback', info, options, config=config) self.assertEqual(list((self.root / 'rollback').iterdir()), []) def test_single_direction_config_without_mirror(self): info = inspect_media(self.gif) for direction in (0, 1): with self.subTest(source_direction=direction): folder = self.root / f'single_{direction}' options = Options(count=3, prefix='static', scale_axis='width', target=100) config = FrameConfig('StaticMonster', -31, -63, direction, mirror=False) files = export_frames(self.gif, folder, info, options, config=config) self.assertEqual([p.name for p in files], [f'static_0_{i}.png' for i in range(3)]) self.assertEqual(len(list(folder.glob('*.png'))), 3) data = json.loads((folder / 'static.json').read_text()) self.assertEqual(data['HEAD_POS'], [-35, 0]) for key in ('STAND_R', 'STAND_U', 'STAND_L', 'STAND_D', 'R', 'U', 'L', 'D'): self.assertEqual((data[key]['Len'], data[key]['Cx'], data[key]['Cy']), (3, -31, -63)) self.assertEqual(data[key]['Cloth']['IMG'], [p.name for p in files]) self.assertEqual(data[key]['Cloth']['CX'], [0] * 3) self.assertEqual(data[key]['Cloth']['CY'], [0] * 3) from core import transform with Image.open(files[0]) as image: self.assertEqual(image.tobytes(), transform(info.first, options).tobytes()) def test_gui_config_export_snapshot(self): import time from main import App app = App() try: app.update() app.events.put(('loaded', self.gif, inspect_media(self.gif))) app.poll() app.output.set(str(self.root / 'gui_config')) app.count.set('2') app.prefix.set('test') app.preview_offset = [-24, -72] app.config_toggle.invoke() with patch('main.messagebox.showinfo'), patch('main.messagebox.showerror') as error: app.start_button.invoke() app.preview_offset = [999, 999] deadline = time.monotonic() + 5 while app.busy and time.monotonic() < deadline: app.update() time.sleep(0.01) self.assertFalse(app.busy) error.assert_not_called() data = json.loads((self.root / 'gui_config/test.json').read_text(encoding='utf-8')) self.assertEqual(data['NAME'], 'test') self.assertEqual((data['R']['Cx'], data['R']['Cy']), (-24, -72)) self.assertEqual(data['HEAD_POS'], [-5, 0]) self.assertEqual(len(list((self.root / 'gui_config').glob('*.png'))), 4) self.assertTrue(app.mirror_directions.get()) app.mirror_toggle.invoke() self.assertEqual(str(app.direction_select.cget('state')), 'disabled') app.output.set(str(self.root / 'gui_single')) app.preview_offset = [-24, -72] with patch('main.messagebox.showinfo'), patch('main.messagebox.showerror') as error: app.start_button.invoke() deadline = time.monotonic() + 5 while app.busy and time.monotonic() < deadline: app.update() time.sleep(0.01) self.assertFalse(app.busy) error.assert_not_called() single = json.loads((self.root / 'gui_single/test.json').read_text()) self.assertEqual(single['R'], single['L']) self.assertEqual(single['L']['Cloth']['IMG'], ['test_0_0.png', 'test_0_1.png']) self.assertEqual(len(list((self.root / 'gui_single').glob('*.png'))), 2) app.mirror_toggle.invoke() self.assertEqual(str(app.direction_select.cget('state')), 'readonly') finally: app.destroy() def test_gui_preview_and_export_button(self): import time from main import App app = App() try: app.update() self.assertTrue(app.start_button.winfo_ismapped()) self.assertLess(app.start_button.winfo_rooty() - app.winfo_rooty(), app.winfo_height()) app.events.put(('loaded', self.gif, inspect_media(self.gif))) app.poll() app.output.set(str(self.root / 'gui')) app.prefix.set('界面') app.count.set('3') app.crop['左'].set('25') app.crop['右'].set('75') app.axis.set('指定宽度') app.target.set('60') app.update() self.assertIn('60 × 60', app.dimensions.get()) app.grid_toggle.invoke() self.assertEqual((app.photo.width(), app.photo.height()), (60, 60)) self.assertIn('1.5 × 1.5 格', app.dimensions.get()) def check_grid_spacing(): lines = [app.canvas.coords(item) for item in app.canvas.find_withtag('game_grid')] vertical = [line[0] for line in lines if line[0] == line[2]] self.assertGreater(len(vertical), 1) self.assertTrue(all(b - a == 40 for a, b in zip(vertical, vertical[1:]))) check_grid_spacing() app.target.set('800') app.update() self.assertEqual((app.photo.width(), app.photo.height()), (800, 800)) check_grid_spacing() self.assertLess(app.canvas.xview()[1], 1) app.scroll_preview('x', 'moveto', 1) check_grid_spacing() app.target.set('60') app.update() def drag_world(start, end): left, top = app.canvas.canvasx(0), app.canvas.canvasy(0) sx, sy = round(start[0] - left), round(start[1] - top) ex, ey = round(end[0] - left), round(end[1] - top) app.canvas.event_generate('', x=sx, y=sy) app.canvas.event_generate('', x=ex, y=ey) app.canvas.event_generate('', x=ex, y=ey) app.center_view_button.invoke() reference = app.canvas.coords(app.canvas.find_withtag('reference_cell')[0]) self.assertEqual(reference, [80, 80, 120, 120]) bounds = app.canvas.coords(app.canvas.find_withtag('sprite_bounds')[0]) self.assertEqual(bounds[:2], [100, 100]) drag_world((110, 110), (73, 180)) self.assertEqual(app.preview_offset, [-37, 70]) self.assertIn('X: -37 px', app.offset_status.get()) self.assertIn('Y: +70 px', app.offset_status.get()) self.assertEqual(app.canvas.coords(app.canvas.find_withtag('reference_cell')[0]), reference) self.assertEqual(app.canvas.coords(app.canvas.find_withtag('sprite_bounds')[0])[:2], [63, 170]) # A redraw or a settings change must not move the reference or reset placement. app.draw_current() app.target.set('80') app.update() self.assertEqual(app.preview_offset, [-37, 70]) app.reset_position_button.invoke() self.assertEqual(app.preview_offset, [0, 0]) app.target.set('60') app.update() # Leave a nonzero placement active while exporting. drag_world((110, 110), (140, 150)) self.assertEqual(app.preview_offset, [30, 40]) with patch('main.messagebox.showinfo'), patch('main.messagebox.showerror') as error: app.start_button.invoke() deadline = time.monotonic() + 15 while app.busy and time.monotonic() < deadline: app.update() time.sleep(0.02) self.assertFalse(app.busy) error.assert_not_called() self.assertEqual(len(list((self.root / 'gui').glob('界面_*.png'))), 3) with Image.open(self.root / 'gui' / '界面_0.png') as result: self.assertEqual(result.size, (60, 60)) self.assertEqual(result.getpixel((0, 0))[3], 0) # Grid enabled in the UI must not change any exported pixel. from core import transform expected = transform(app.info.first, app.options()) self.assertEqual(result.tobytes(), expected.tobytes()) finally: app.destroy() def test_center_and_pan_view_without_moving_sprite(self): from main import App app = App() try: app.update() app.events.put(('loaded', self.gif, inspect_media(self.gif))) app.poll() app.axis.set('指定宽度') app.target.set('144') app.preview_offset = [-61, -117] app.grid_toggle.invoke() app.update() width, height = app.canvas.winfo_width(), app.canvas.winfo_height() left, top = app.canvas.canvasx(0), app.canvas.canvasy(0) # Center both the sprite and reference cell, including negative placement. self.assertAlmostEqual(left + width / 2, (39 + 183) / 2, delta=1) self.assertAlmostEqual(top + height / 2, (-17 + 120) / 2, delta=1) before_sprite = app.canvas.coords(app.canvas.find_withtag('sprite_bounds')[0]) before_offset = app.preview_offset.copy() before_label = app.offset_status.get() for button, dx, dy in [(3, 140, 70), (2, -90, -45)]: old_left, old_top = app.canvas.canvasx(0), app.canvas.canvasy(0) app.canvas.event_generate(f'', x=150, y=100) app.canvas.event_generate(f'', x=150 + dx, y=100 + dy) app.canvas.event_generate(f'', x=150 + dx, y=100 + dy) self.assertAlmostEqual(app.canvas.canvasx(0), old_left - dx, delta=1) self.assertAlmostEqual(app.canvas.canvasy(0), old_top - dy, delta=1) self.assertEqual(app.preview_offset, before_offset) self.assertEqual(app.offset_status.get(), before_label) self.assertEqual(app.canvas.coords(app.canvas.find_withtag('sprite_bounds')[0]), before_sprite) held_view = (app.canvas.canvasx(0), app.canvas.canvasy(0)) for _ in range(4): app.draw_current() self.assertEqual(held_view, (app.canvas.canvasx(0), app.canvas.canvasy(0))) app.scroll_preview('x', 'scroll', -1, 'pages') self.assertLess(app.canvas.canvasx(0), held_view[0]) self.assertEqual(app.preview_offset, before_offset) app.center_view_button.invoke() self.assertAlmostEqual(app.canvas.canvasx(0), left, delta=1) self.assertAlmostEqual(app.canvas.canvasy(0), top, delta=1) self.assertEqual(app.preview_offset, before_offset) finally: app.destroy() def test_scrollable_settings_and_animation(self): import time from main import App app = App() def pump_until(predicate, timeout=5): deadline = time.monotonic() + timeout while not predicate() and time.monotonic() < deadline: app.update() time.sleep(0.005) self.assertTrue(predicate()) try: # Reproduce a shorter window with larger system text. app.tk.call('tk', 'scaling', 1.75) app.geometry('1000x600') app.update() app.settings_canvas.yview_moveto(1) app.update() canvas = app.settings_canvas entry = app.target_entry # Scaling is no longer the final section; scroll it into view explicitly. region = [float(value) for value in canvas.cget('scrollregion').split()] canvas.yview_moveto((canvas.canvasy(entry.winfo_rooty() - canvas.winfo_rooty()) - 20) / region[3]) app.update() self.assertGreaterEqual(entry.winfo_rooty(), canvas.winfo_rooty()) self.assertLessEqual(entry.winfo_rooty() + entry.winfo_height(), canvas.winfo_rooty() + canvas.winfo_height()) self.assertLessEqual(entry.winfo_rootx() + entry.winfo_width(), canvas.winfo_rootx() + canvas.winfo_width()) self.assertTrue(app.start_button.winfo_ismapped()) app.events.put(('loaded', self.gif, inspect_media(self.gif))) app.poll() app.count.set('3') pump_until(lambda: len(app.samples) == 3) self.assertEqual(app.sample_sources, [0, 3, 6]) # Confirm scheduled playback advances and wraps at the requested cadence. positions = [] last = app.sample_position started = time.monotonic() while len(positions) < 4 and time.monotonic() - started < 2: app.update() if last != app.sample_position: positions.append((app.sample_position, time.monotonic())) last = app.sample_position time.sleep(0.003) self.assertEqual([p[0] for p in positions], [1, 2, 0, 1]) for before, after in zip(positions, positions[1:]): self.assertGreaterEqual(after[1] - before[1], 0.09) self.assertLess(after[1] - before[1], 0.25) app.play_button.invoke() paused = app.sample_position until = time.monotonic() + 0.25 while time.monotonic() < until: app.update() time.sleep(0.005) self.assertEqual(app.sample_position, paused) app.count.set('2') app.crop['左'].set('25') app.crop['右'].set('75') app.axis.set('指定宽度') app.target.set('60') pump_until(lambda: len(app.samples) == 2) self.assertEqual(app.sample_sources, [0, 6]) self.assertEqual(app.samples[0].size, (60, 60)) self.assertFalse(app.want_play) app.play_button.invoke() pump_until(lambda: app.sample_position == 1) finally: app.destroy() if __name__ == '__main__': unittest.main()