Files
minecraft-bot/tests/test_web_inventory_api.py
T
2026-11-14 22:02:08 +00:00

282 lines
9.8 KiB
Python

import base64
import importlib.util
from pathlib import Path
import threading
import unittest
from munch import Munch
from mosfet.info import blocks
from mosfet.protocol.types import Slot
ENTRY = Path(__file__).resolve().parents[1] / 'mosfet.py'
SPEC = importlib.util.spec_from_file_location('mosfet_web_entry', ENTRY)
mosfet_web = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(mosfet_web)
class FakeGame:
def __init__(self):
self.drop_calls = []
self.dump_item = None
self.dump_result = 2
def drop_inventory_slot(self, slot, whole_stack=True):
self.drop_calls.append((slot, whole_stack))
return True
def start_dump(self, item_id):
self.dump_item = item_id
return self.dump_result
class TestWebInventoryAPI(unittest.TestCase):
def test_connection_loop_retries_socket_disconnects_without_crashing(self):
state = Munch(running=True)
attempts = []
delays = []
def connector(global_state):
attempts.append(True)
if len(attempts) == 1:
raise BrokenPipeError(32, 'Broken pipe')
if len(attempts) == 2:
raise ValueError('I/O operation on closed file')
global_state.running = False
mosfet_web._run_connection_loop(
state, connector, sleep=lambda delay: delays.append(delay))
self.assertEqual(len(attempts), 3)
self.assertEqual(delays, [1.0, 2.0])
self.assertFalse(state.connected)
self.assertIs(state.connection, False)
self.assertEqual(state.connection_status, 'reconnecting')
def test_web_port_uses_bot_name_suffix(self):
for suffix in range(1, 10):
with self.subTest(suffix=suffix):
self.assertEqual(
mosfet_web.web_port_for_player('mosfet{}'.format(suffix)),
3300 + suffix)
for name in ('mosfet0', 'mosfet', 'bot10', None, ''):
with self.subTest(name=name):
self.assertEqual(mosfet_web.web_port_for_player(name), 3300)
def setUp(self):
self.g = mosfet_web.g
self.original = {
key: self.g.get(key) for key in
('connected', 'game', 'inv', 'chest_viewers', 'time', 'time_base',
'weather', 'rain_level', 'thunder_level', 'chunks', 'pos', 'yaw',
'path', 'chat_log')
}
self.game = FakeGame()
self.g.connected = True
self.g.game = self.game
self.g.inv = {
9: Slot(True, 1145, 3,
components={'custom_name': {'text': 'Test Paper'}})
}
self.g.reload_lock = threading.RLock()
self.client = mosfet_web.app.test_client()
def tearDown(self):
for key, value in self.original.items():
self.g[key] = value
def test_inventory_api_exposes_slot_components(self):
response = self.client.get('/api/global')
self.assertEqual(response.status_code, 200)
item = response.get_json()['inv']['9']
self.assertEqual(item['components']['custom_name']['text'], 'Test Paper')
def test_minimap_api_returns_surface_blocks_centered_on_bot(self):
grass = blocks.MCD_BLOCKS['grass_block']['minStateId']
class FakeChunk:
sections = {
0: {'non_empty_blocks': 1},
1: {'non_empty_blocks': 0},
}
@staticmethod
def get_block_at(x, y, z):
return grass if (x, y, z) == (1, 5, 1) else blocks.AIR
class FakeChunks:
min_y = 0
chunks = {(0, 0): FakeChunk()}
self.g.connected = True
self.g.chunks = FakeChunks()
self.g.pos = Munch(x=1.5, y=6.0, z=1.5)
self.g.yaw = 90
self.g.path = [(-1, 5, 1), Munch(x=1, y=5, z=1)]
response = self.client.get(
'/api/minimap?radius=4&radius_x=6&radius_z=4')
self.assertEqual(response.status_code, 200)
data = response.get_json()
self.assertTrue(data['ready'])
self.assertEqual(data['center'], {'x': 1, 'y': 6, 'z': 1})
self.assertEqual(data['yaw'], 90)
self.assertEqual(data['path'], [
{'x': -1.0, 'z': 1.0}, {'x': 1.0, 'z': 1.0},
])
self.assertEqual(data['radius_x'], 6)
self.assertEqual(data['radius_z'], 4)
self.assertEqual(data['palette'], ['grass_block'])
indices = base64.b64decode(data['cells_b64'])
self.assertEqual(len(indices), 9 * 13)
self.assertEqual(indices[4 * 13 + 6], 1)
self.assertNotIn('cells', data)
def test_minimap_returns_palette_encoded_surface_grid(self):
grass = blocks.MCD_BLOCKS['grass_block']['minStateId']
target_index = ((5 * 16 + 1) * 16 + 1)
class FakePalette:
def get(self, index):
return grass if index == target_index else blocks.AIR
class FakeChunk:
sections = {0: {
'non_empty_blocks': 1,
'blocks': FakePalette(),
}}
def get_block_at(self, *_args):
raise AssertionError('palette lookup should avoid per-block API')
class FakeChunks:
min_y = 0
chunks = {(0, 0): FakeChunk()}
self.g.connected = True
self.g.chunks = FakeChunks()
self.g.pos = Munch(x=1.5, y=6.0, z=1.5)
response = self.client.get(
'/api/minimap?radius=4&radius_x=4&radius_z=4')
self.assertEqual(response.status_code, 200)
data = response.get_json()
self.assertTrue(data['ready'])
self.assertEqual(data['palette'], ['grass_block'])
self.assertNotIn('cells', data)
indices = base64.b64decode(data['cells_b64'])
self.assertEqual(len(indices), 9 * 9)
self.assertEqual(indices[4 * 9 + 4], 1)
def test_minimap_api_allows_three_additional_zoom_out_levels(self):
class EmptyChunks:
chunks = {}
self.g.connected = True
self.g.chunks = EmptyChunks()
self.g.pos = Munch(x=0.0, y=64.0, z=0.0)
response = self.client.get(
'/api/minimap?radius=36&radius_x=48&radius_z=36')
self.assertEqual(response.status_code, 200)
data = response.get_json()
self.assertEqual(data['radius'], 36)
self.assertEqual(data['radius_x'], 48)
self.assertEqual(data['radius_z'], 36)
def test_global_api_exposes_chat_log_events(self):
self.g.chat_log = [{
'id': '123', 'timestamp': 123.0, 'type': 'join',
'sender': 'tanner', 'message': 'tanner joined the game',
}]
response = self.client.get('/api/global')
self.assertEqual(response.status_code, 200)
self.assertEqual(response.get_json()['chat_log'][0], {
'id': '123', 'timestamp': 123.0, 'type': 'join',
'sender': 'tanner', 'message': 'tanner joined the game',
})
def test_global_api_exposes_world_time_ticks(self):
self.g.time = 12345.5
self.g.time_base = 12345.5
response = self.client.get('/api/global')
self.assertEqual(response.status_code, 200)
self.assertEqual(response.get_json()['time'], 12345.5)
self.assertEqual(response.get_json()['time_base'], 12345.5)
def test_global_api_exposes_weather_state(self):
self.g.weather = 'thunderstorm'
self.g.rain_level = 1.0
self.g.thunder_level = 0.8
response = self.client.get('/api/global')
self.assertEqual(response.status_code, 200)
payload = response.get_json()
self.assertEqual(payload['weather'], 'thunderstorm')
self.assertEqual(payload['rain_level'], 1.0)
self.assertEqual(payload['thunder_level'], 0.8)
def test_global_api_stringifies_tuple_keys(self):
self.g.chest_viewers = {(12, 64, -7): 1}
response = self.client.get('/api/global')
self.assertEqual(response.status_code, 200)
self.assertEqual(response.get_json()['chest_viewers'], {
'(12, 64, -7)': 1,
})
def test_global_api_retries_if_live_dictionary_changes_during_snapshot(self):
class ChangingDict(dict):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.first_read = True
def items(self):
if self.first_read:
self.first_read = False
raise RuntimeError('dictionary changed size during iteration')
return super().items()
self.g.chest_viewers = ChangingDict({(12, 64, -7): 1})
response = self.client.get('/api/global')
self.assertEqual(response.status_code, 200)
self.assertEqual(response.get_json()['chest_viewers'], {
'(12, 64, -7)': 1,
})
def test_drop_endpoint_supports_one_stack_and_matching_actions(self):
one = self.client.post('/api/inventory/drop', json={
'slot': 9, 'action': 'one'})
stack = self.client.post('/api/inventory/drop', json={
'slot': 9, 'action': 'stack'})
matching = self.client.post('/api/inventory/drop', json={
'slot': 9, 'action': 'matching'})
self.assertEqual(one.status_code, 200)
self.assertEqual(stack.status_code, 200)
self.assertEqual(matching.status_code, 200)
self.assertEqual(self.game.drop_calls, [(9, False), (9, True)])
self.assertEqual(self.game.dump_item, 1145)
self.assertEqual(matching.get_json()['stacks'], 2)
def test_drop_endpoint_rejects_cross_origin_actions(self):
response = self.client.post('/api/inventory/drop', json={
'slot': 9, 'action': 'stack'},
headers={'Origin': 'https://elsewhere.example'})
self.assertEqual(response.status_code, 403)
if __name__ == '__main__':
unittest.main()