Files
worklog/tests/test_timetable_occupancy.py
T

100 lines
5.3 KiB
Python

import io
import unittest
from unittest.mock import patch
from PIL import Image, ImageDraw
from server import timetable_ocr as ocr
def line(x, y, text, score=.99):
return {'box': [[x-12,y-8],[x+12,y-8],[x+12,y+8],[x-12,y+8]], 'text':text, 'score':score}
def headers():
return ([line(120+80*i,100,word) for i,word in enumerate('一二三四五六日')]
+ [line(35,160+40*i,str(i+1)) for i in range(10)])
def sample_image():
image=Image.new('RGB',(680,600),'white');draw=ImageDraw.Draw(image)
draw.rectangle((165,142,235,298),fill='#89a66d') # 周二一至四节
draw.rectangle((85,382,155,458),fill='#8ba3fc') # 周一七八节
draw.rectangle((165,302,235,378),fill='#8ed7ed')
draw.rectangle((245,302,315,378),fill='#f66f6f') # 紧贴区域按颜色分割
draw.rectangle((165,382,315,458),fill='#f66f6f') # 同色两列,分别计入
draw.rectangle((405,462,475,538),fill='#82be54') # 周五晚课,不计入七八节
raw=io.BytesIO();image.save(raw,'PNG');return raw.getvalue()
class TimetableOccupancyTests(unittest.TestCase):
def setUp(self):
with ocr._cache_lock:ocr._cache.clear()
def test_colored_blocks_include_cross_periods_split_adjacent_days_and_skip_evening(self):
raw=sample_image();blocks=ocr.course_blocks(raw)
result=ocr.occupancy_from_blocks(headers(),blocks,(680,600))
self.assertIsNotNone(result)
cells={(c['day'],c['slot']):c for c in result['cells']}
expected={(2,'1-2'),(2,'3-4'),(2,'5-6'),(3,'5-6'),(1,'7-8'),(2,'7-8'),(3,'7-8')}
self.assertEqual({key for key,c in cells.items() if c['status']=='busy'},expected)
self.assertTrue(all(c['status'] in ('busy','free') for c in cells.values()))
def test_one_missing_weekday_and_spurious_header_fragment_do_not_shift_columns(self):
raw=sample_image();blocks=ocr.course_blocks(raw)
complete=ocr.occupancy_from_blocks(headers(),blocks,(680,600))
missing=[l for l in headers() if l['text']!='一']
self.assertEqual(ocr.occupancy_from_blocks(missing,blocks,(680,600))['cells'],complete['cells'])
fragmented=headers()+[line(200,110,'一',.7)]
self.assertEqual(ocr.occupancy_from_blocks(fragmented,blocks,(680,600))['cells'],complete['cells'])
def test_partial_cropped_or_unlocated_table_never_invents_free_slots(self):
blocks=ocr.course_blocks(sample_image())
self.assertIsNone(ocr.occupancy_from_blocks([],blocks,(680,600)))
self.assertIsNone(ocr.occupancy_from_blocks(headers(),blocks,(680,400)))
incomplete=[l for l in headers() if l['text'] not in ('7','8')]
self.assertIsNone(ocr.occupancy_from_blocks(incomplete,blocks,(680,600)))
def test_evening_number_misread_as_six_does_not_shift_afternoon_rows(self):
blocks=ocr.course_blocks(sample_image())
normal=ocr.occupancy_from_blocks(headers(),blocks,(680,600))
mistaken=[l for l in headers() if l['text']!='9']+[line(35,480,'6')]
result=ocr.occupancy_from_blocks(mistaken,blocks,(680,600))
self.assertEqual(result['cells'],normal['cells'])
def test_grid_handles_month_label_merged_into_monday_header(self):
raw=sample_image()
complete=ocr.occupancy_from_grid(headers(),raw,(680,600))
compact = [line(55,100,'11月16一')] + [
line(200+80*i,100,f'{17+i}{weekday}') for i,weekday in enumerate('二三四五六日')
] + [line(35,160+40*i,str(i+1)) for i in range(10)]
result=ocr.occupancy_from_grid(compact,raw,(680,600))
self.assertIsNotNone(result)
self.assertEqual(result['method'],'color_grid')
self.assertEqual(result['cells'],complete['cells'])
def test_layout_extraction_still_runs_when_monday_and_morning_are_empty(self):
image=Image.new('RGB',(680,900),'white');draw=ImageDraw.Draw(image)
draw.rectangle((325,500,395,650),fill='#8ba3fc')
raw=io.BytesIO();image.save(raw,'PNG');raw=raw.getvalue()
with patch.object(ocr,'read_image',return_value=[]) as reader:
ocr.layout_lines(raw,ocr.course_blocks(raw))
reader.assert_called_once()
def test_fast_path_skips_course_text_and_cache_returns_independent_results(self):
raw=sample_image()
with patch.object(ocr,'layout_lines',return_value=headers()) as layout,patch.object(ocr,'read_image') as full_ocr:
first=ocr.recognize(raw)
self.assertEqual(first['method'],'color_grid');self.assertFalse(first['cache_hit'])
self.assertEqual(first['raw_text'],'');self.assertTrue(all(c['courses']=='' for c in first['cells']))
first['cells'][0]['status']='changed'
second=ocr.recognize(raw)
self.assertTrue(second['cache_hit']);self.assertNotEqual(second['cells'][0]['status'],'changed')
layout.assert_called_once();full_ocr.assert_not_called()
def test_missing_layout_falls_back_without_retaining_course_names(self):
with patch.object(ocr,'layout_lines',return_value=[]),patch.object(ocr,'read_image',return_value=[line(120,200,'测试课程')]):
result=ocr.recognize(sample_image())
self.assertEqual(result['method'],'text_fallback')
self.assertTrue(all(c['status']=='unknown' and c['courses']=='' for c in result['cells']))
self.assertEqual(result['raw_text'],'')