新增原生 gRPC 画面与数据接收器
This commit is contained in:
@@ -0,0 +1,206 @@
|
||||
import os
|
||||
os.environ.setdefault('QT_QPA_PLATFORM', 'offscreen')
|
||||
import json
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import socket
|
||||
import time
|
||||
import unittest
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
import grpc
|
||||
from PySide6.QtCore import QBuffer, QIODevice, Qt
|
||||
from PySide6.QtGui import QImage, QColor
|
||||
from PySide6.QtWidgets import QApplication
|
||||
import fusion_input_pb2 as pb
|
||||
import fusion_input_pb2_grpc as rpc
|
||||
from receiver import Store, Receiver, Decoder
|
||||
from window import MainWindow
|
||||
|
||||
|
||||
APP = QApplication.instance() or QApplication([])
|
||||
|
||||
|
||||
def jpeg(width=320, height=180):
|
||||
image = QImage(width, height, QImage.Format.Format_RGB32)
|
||||
image.fill(QColor('#218c79'))
|
||||
buf = QBuffer()
|
||||
buf.open(QIODevice.OpenModeFlag.WriteOnly)
|
||||
assert image.save(buf, 'JPEG', 85)
|
||||
return bytes(buf.data())
|
||||
|
||||
|
||||
def message(number=1, kind='DATA', equipment='EQ-01', source='source-01', frame=True, image=None):
|
||||
frame_id = f'{number:016x}' if frame else None
|
||||
meta = dict(schemaVersion=1, kind=kind, messageId=f'{kind}/{equipment}/{source}/{number}',
|
||||
equipmentId=equipment, equipmentCode=equipment, sourceEndpointId=source,
|
||||
trialId=None, trialIds=['试验甲', '试验乙'], frameId=frame_id,
|
||||
pairingAvailable=frame, sourceTime=1794190000000,
|
||||
receivedTime=1794190000010,
|
||||
upload=dict(frameId=frame_id, reused=True, time=1794190000020))
|
||||
if kind == 'DATA':
|
||||
meta['data'] = {'values': {'经度': 116.3, '状态': '运行', 'zero': 0, 'false': False},
|
||||
'raw': {'原始': '保持原样'}}
|
||||
else:
|
||||
image = image if image is not None else jpeg()
|
||||
meta.update(imageContentType='image/jpeg', imageBytes=len(image))
|
||||
return pb.FusionInput(json=json.dumps(meta, ensure_ascii=False), image=image or b'')
|
||||
|
||||
|
||||
class ReceiverTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.store = Store()
|
||||
self.receiver = Receiver(self.store)
|
||||
self.port = self.receiver.start(0)
|
||||
self.channel = grpc.insecure_channel(f'127.0.0.1:{self.port}')
|
||||
grpc.channel_ready_future(self.channel).result(timeout=5)
|
||||
self.stub = rpc.FusionInputServiceStub(self.channel)
|
||||
|
||||
def tearDown(self):
|
||||
self.channel.close()
|
||||
self.receiver.stop()
|
||||
|
||||
def test_real_grpc_contract_and_binary(self):
|
||||
data, image = message(), message(kind='IMAGE')
|
||||
response = self.stub.Push(iter([data, image]), timeout=3)
|
||||
self.assertEqual(response.SerializeToString(), b'')
|
||||
source = self.store.sources[('EQ-01', 'source-01')]
|
||||
self.assertEqual(source.latest_image.jpeg, image.image)
|
||||
self.assertEqual(source.latest_data.meta, json.loads(data.json))
|
||||
latest, paired = self.store.data_for(source.latest_image)
|
||||
self.assertIs(latest, paired)
|
||||
self.assertEqual(self.store.snapshot()['batches'], 1)
|
||||
|
||||
def test_retry_deduplicates_partial_stream(self):
|
||||
good = message()
|
||||
with self.assertRaises(grpc.RpcError) as err:
|
||||
self.stub.Push(iter([good, pb.FusionInput(json='{bad')]), timeout=3)
|
||||
self.assertEqual(err.exception.code(), grpc.StatusCode.INVALID_ARGUMENT)
|
||||
self.stub.Push(iter([good, message(2)]), timeout=3)
|
||||
self.assertEqual(self.store.snapshot()['data'], 2)
|
||||
self.assertEqual(self.store.snapshot()['duplicates'], 1)
|
||||
|
||||
def test_legacy_data_without_frame(self):
|
||||
self.stub.Push(iter([message(frame=False)]), timeout=3)
|
||||
self.assertEqual(self.store.snapshot()['data'], 1)
|
||||
self.assertEqual(len(self.store.pairs), 0)
|
||||
|
||||
def test_pair_does_not_cross_equipment_or_source(self):
|
||||
self.stub.Push(iter([message(), message(kind='IMAGE', source='another'),
|
||||
message(kind='IMAGE', equipment='another')]), timeout=3)
|
||||
self.store.select(('EQ-01', 'another'))
|
||||
image = self.store.sources[self.store.selected].latest_image
|
||||
self.assertEqual(self.store.data_for(image), (None, None))
|
||||
self.stub.Push(iter([message(source='another')]), timeout=3)
|
||||
self.assertIsNotNone(self.store.data_for(image)[1])
|
||||
|
||||
def test_concurrent_duplicates(self):
|
||||
with ThreadPoolExecutor(max_workers=8) as pool:
|
||||
list(pool.map(lambda _: self.stub.Push(iter([message()]), timeout=4), range(20)))
|
||||
stats = self.store.snapshot()
|
||||
self.assertEqual(stats['data'], 1)
|
||||
self.assertEqual(stats['duplicates'], 19)
|
||||
|
||||
def test_latest_frame_and_bounded_storage(self):
|
||||
image = jpeg()
|
||||
self.stub.Push((message(i, 'IMAGE', image=image) for i in range(150)), timeout=5)
|
||||
source = self.store.sources[('EQ-01', 'source-01')]
|
||||
self.assertEqual(source.latest_image.meta['frameId'], f'{149:016x}')
|
||||
self.assertEqual(self.store.snapshot()['cached_jpeg_bytes'], len(image))
|
||||
self.assertEqual(self.store.snapshot()['superseded'], 149)
|
||||
self.store.MAX_PAIRS = 5
|
||||
self.store.MAX_IDS = 10
|
||||
self.stub.Push((message(i) for i in range(1000, 1020)), timeout=4)
|
||||
self.assertLessEqual(len(self.store.pairs), 5)
|
||||
self.assertLessEqual(len(self.store.ids), 10)
|
||||
|
||||
def test_pair_memory_budget_and_source_limit(self):
|
||||
self.store.MAX_PAIR_BYTES = 600
|
||||
self.store.MAX_SOURCES = 3
|
||||
self.stub.Push((message(i, equipment=f'EQ-{i}') for i in range(8)), timeout=3)
|
||||
self.assertEqual(len(self.store.sources), 3)
|
||||
self.assertLessEqual(self.store.pair_bytes, 600)
|
||||
self.assertIn(('EQ-0', 'source-01'), self.store.sources)
|
||||
|
||||
def test_decoder_produces_native_image(self):
|
||||
decoder = Decoder(self.store)
|
||||
decoder.start()
|
||||
try:
|
||||
self.stub.Push(iter([message(kind='IMAGE', image=jpeg(1920, 1080))]), timeout=3)
|
||||
ready = None
|
||||
end = time.monotonic()+3
|
||||
while time.monotonic()<end and ready is None:
|
||||
ready = decoder.take()
|
||||
time.sleep(.005)
|
||||
self.assertIsNotNone(ready)
|
||||
self.assertEqual((ready[2].width(), ready[2].height()), (1920, 1080))
|
||||
self.assertGreater(ready[3], 0)
|
||||
finally:
|
||||
decoder.close()
|
||||
|
||||
def test_corrupt_jpeg_reports_decode_failure(self):
|
||||
decoder = Decoder(self.store)
|
||||
decoder.start()
|
||||
try:
|
||||
self.stub.Push(iter([message(kind='IMAGE', image=b'\xff\xd8broken\xff\xd9')]), timeout=3)
|
||||
end = time.monotonic()+2
|
||||
while time.monotonic()<end and not self.store.snapshot()['decode_errors']:
|
||||
time.sleep(.01)
|
||||
self.assertEqual(self.store.snapshot()['decode_errors'], 1)
|
||||
self.assertIsNone(decoder.take())
|
||||
finally:
|
||||
decoder.close()
|
||||
|
||||
def test_listener_restart_recovers(self):
|
||||
self.stub.Push(iter([message()]), timeout=3)
|
||||
self.receiver.stop()
|
||||
self.receiver.start(self.port)
|
||||
self.stub.Push(iter([message(), message(2)]), timeout=5, wait_for_ready=True)
|
||||
self.assertEqual(self.store.snapshot()['data'], 2)
|
||||
self.assertEqual(self.store.snapshot()['duplicates'], 1)
|
||||
|
||||
def test_invalid_input_status(self):
|
||||
for raw in ['[]', '{"schemaVersion":2}', '{"schemaVersion":1,"kind":"DATA"}']:
|
||||
with self.assertRaises(grpc.RpcError) as err:
|
||||
self.stub.Push(iter([pb.FusionInput(json=raw)]), timeout=2)
|
||||
self.assertEqual(err.exception.code(), grpc.StatusCode.INVALID_ARGUMENT)
|
||||
|
||||
def test_native_pause_resume_and_source_switch(self):
|
||||
with socket.socket() as reserve:
|
||||
reserve.bind(('127.0.0.1', 0))
|
||||
port = reserve.getsockname()[1]
|
||||
window = MainWindow(port)
|
||||
window.show()
|
||||
def until(predicate):
|
||||
end = time.monotonic()+3
|
||||
while time.monotonic()<end:
|
||||
APP.processEvents()
|
||||
if predicate(): return
|
||||
time.sleep(.005)
|
||||
self.fail('Native UI condition timed out')
|
||||
try:
|
||||
with grpc.insecure_channel(f'127.0.0.1:{port}') as channel:
|
||||
stub = rpc.FusionInputServiceStub(channel)
|
||||
stub.Push(iter([message(1, 'IMAGE'), message(1)]), timeout=3)
|
||||
until(lambda: window.canvas.message is not None)
|
||||
original = window.canvas.message
|
||||
window.pause_button.setChecked(True)
|
||||
stub.Push(iter([message(2, 'IMAGE'), message(3, 'IMAGE')]), timeout=3)
|
||||
until(lambda: window.store.snapshot()['decoded'] >= 2)
|
||||
self.assertIs(window.canvas.message, original)
|
||||
window.pause_button.setChecked(False)
|
||||
until(lambda: window.canvas.message.meta['frameId'] == f'{3:016x}')
|
||||
stub.Push(iter([message(4, 'IMAGE', source='other')]), timeout=3)
|
||||
window.refresh_info()
|
||||
item = next(window.sources.item(i) for i in range(window.sources.count())
|
||||
if window.sources.item(i).data(Qt.ItemDataRole.UserRole)[1] == 'other')
|
||||
window.sources.setCurrentItem(item)
|
||||
until(lambda: window.canvas.message and window.canvas.message.key == ('EQ-01','other'))
|
||||
self.assertEqual(window.store.selected, ('EQ-01','other'))
|
||||
finally:
|
||||
window.close()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main(verbosity=2)
|
||||
Reference in New Issue
Block a user