Merge main into t3/7a98935a: keep both sides' appended checks
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> # Conflicts: # tools/lan_e2e.py
This commit is contained in:
@@ -22,19 +22,40 @@ def prohibited(path):
|
||||
return bool(parsed.parts and parsed.parts[0] in PRIVATE_ROOTS) or parsed.suffix.lower() in PRIVATE_EXTENSIONS
|
||||
|
||||
|
||||
def paths_in_repository(history=False):
|
||||
def paths_in_repository(history=False, revisions=None):
|
||||
if not history:
|
||||
result = subprocess.check_output(["git", "ls-files", "-z"])
|
||||
return result.decode("utf-8").split("\0")
|
||||
result = subprocess.check_output(["git", "log", "--all", "--format=", "--name-only", "-z"])
|
||||
# An empty push (including deletions only) must not fall back to HEAD or --all.
|
||||
if revisions is not None and not revisions:
|
||||
return []
|
||||
roots = ["--all"] if revisions is None else revisions
|
||||
# Include diffs against merge parents so merge-resolution-only artifacts are caught.
|
||||
# Git pushes the stored objects, not the history presented by local replace refs.
|
||||
result = subprocess.check_output(["git", "--no-replace-objects", "log", "--format=", "--name-only",
|
||||
"-z", "-m", *roots, "--"])
|
||||
return [path.lstrip("\n") for path in result.decode("utf-8").split("\0")]
|
||||
|
||||
|
||||
def pushed_revisions(stream):
|
||||
"""Read Git's pre-push ref updates and retain the non-deleted local object IDs."""
|
||||
revisions = []
|
||||
for line in stream:
|
||||
_local_ref, local_oid, _remote_ref, _remote_oid = line.split()
|
||||
if local_oid.strip("0"):
|
||||
revisions.append(local_oid)
|
||||
return revisions
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--history", action="store_true", help="Also inspect paths in all local Git history")
|
||||
mode = parser.add_mutually_exclusive_group()
|
||||
mode.add_argument("--history", action="store_true", help="Inspect paths in all local Git history")
|
||||
mode.add_argument("--pre-push", action="store_true", help="Inspect history reachable from Git's ref updates on stdin")
|
||||
args = parser.parse_args()
|
||||
rejected = sorted({path for path in paths_in_repository(args.history) if path and prohibited(path)})
|
||||
revisions = pushed_revisions(sys.stdin) if args.pre_push else None
|
||||
rejected = sorted({path for path in paths_in_repository(args.history or args.pre_push, revisions)
|
||||
if path and prohibited(path)})
|
||||
if rejected:
|
||||
print("Private game/profiling artifacts must stay outside Git:", file=sys.stderr)
|
||||
for path in rejected:
|
||||
|
||||
@@ -36,6 +36,11 @@ def group_setup():
|
||||
*setup('/kill @e[type=!player]'),
|
||||
{'op': 'tick', 'n': 25},
|
||||
*setup('/fill 0 200 0 15 228 15 air', '/time set 1000', '/weather clear', '/difficulty normal', '/clear @s'),
|
||||
# Before the gamerules above, while the oracle waits for its entities to load (a number of ticks that
|
||||
# depends on the machine), mobs spawn and some die with their drops on: a bat's death rolled
|
||||
# minecraft:entities/bat on 1 vanilla run in 24, one more sequence for the ticking group's
|
||||
# /random reset * to count. Every run starts the script without them.
|
||||
*setup('/random reset *'),
|
||||
]
|
||||
|
||||
|
||||
|
||||
+381
-1
@@ -104,6 +104,9 @@ address. The script then checks, from both sides, what a guest's game used to ge
|
||||
pushes it, as in vanilla), not ever faster across the ground.
|
||||
- eat: holding right click with bread, the guest's own screen plays the eating (the item in use
|
||||
counts up) and the server eats one loaf and feeds the guest.
|
||||
- consume-release: the host and the guest each cancel eating a golden apple and drinking milk from
|
||||
either hand: use ends on client and server, the item and effects stay, and holding
|
||||
use to completion still consumes the item (#1293).
|
||||
- eating: each side sees the other player eat: the item in use (LivingEntity's flags) on the
|
||||
player it draws, and no longer once the bread is eaten (#803);
|
||||
- xp: experience orbs 4 blocks away fly to the guest, show on the guest's screen and give the
|
||||
@@ -111,7 +114,9 @@ address. The script then checks, from both sides, what a guest's game used to ge
|
||||
- objects: boats, minecarts, armor stands, item frames and paintings the host summons reach the
|
||||
guest as the host has them (kind, place, rotation, what they hold or wear, the variant).
|
||||
- projectiles: primed TNT (one falling), an end crystal and an arrow that lands reach the guest where
|
||||
the host has them; a falling block lands on both sides.
|
||||
the host has them; a falling block lands on both sides.
|
||||
- shulker_bullets: every shot a shulker fires has its own id and flies on both sides, following
|
||||
the same trajectory; the bullets disappear on both sides when they hit blocks (#1494).
|
||||
- thrown: a splash potion and an eye of ender the host and the guest each throw fly on both
|
||||
sides (#1363, #1391);
|
||||
- sparks: level events' particles on both sides: the host's and the guest's bone meal on wheat
|
||||
@@ -138,6 +143,8 @@ address. The script then checks, from both sides, what a guest's game used to ge
|
||||
server's game time after the guest's game stalls for a few seconds (#848).
|
||||
- growth: far from the host, the chunks around the guest tick (#890): water placed there flows
|
||||
and wheat on farmland grows (random ticks), however the host runs its world.
|
||||
- farmland: the host and guest each trample planted farmland: the wheat breaks and drops its items,
|
||||
and both clients see dirt/air (#1492).
|
||||
- ladder: the guest climbs down ten blocks of ladder and lands unhurt: the server resets its fall
|
||||
distance on a ladder every tick, as LivingEntity.handleOnClimbable does (#1255).
|
||||
- boats: the host (single player, on its server thread or not) and the guest each right-click a
|
||||
@@ -4899,6 +4906,82 @@ CHECKS += ['helduse']
|
||||
CHECK_FNS.update(helduse=check_held_use)
|
||||
|
||||
|
||||
def check_consume_release(host, guest, out):
|
||||
"""#1293: releasing a consumable in either hand cancels it on client and server, while
|
||||
holding it to completion applies its effects and remainder (Consumable.onConsume)."""
|
||||
apart(host, guest)
|
||||
seen = {}
|
||||
try:
|
||||
for game in (host, guest):
|
||||
game('command', command='gamemode survival')
|
||||
x, y, z = pos_of(game)
|
||||
game.raw('look-at', x, y + 1.6, z + 2)
|
||||
for hand in ('mainhand', 'offhand'):
|
||||
for item in ('golden_apple', 'milk_bucket'):
|
||||
case = f'{game.name}-{hand}-{item}'
|
||||
game('command', command='clear @s')
|
||||
game('command', command='item replace entity @s weapon.offhand with minecraft:air')
|
||||
game('command', command='effect clear @s')
|
||||
if item == 'milk_bucket':
|
||||
game('command', command='effect give @s minecraft:speed 60')
|
||||
game('command', command=f'item replace entity @s weapon.{hand} with minecraft:{item}')
|
||||
game.wait(10)
|
||||
assert game('looking_at')['kind'] == 'none', f'{case} is not aimed into the air'
|
||||
before = set(effect_ids(game))
|
||||
assert before == ({'speed'} if item == 'milk_bucket' else set()), f'{case}: {before}'
|
||||
game.raw('mouse', 'right', 'down')
|
||||
game.wait(5)
|
||||
during = {'client': game('state').get('using'), 'server': server_using(host, game)}
|
||||
game.raw('mouse', 'right', 'up')
|
||||
game.wait(10)
|
||||
released = {'client': game('state').get('using'), 'server': server_using(host, game)}
|
||||
# Wait past the full use duration: the server must not finish eating after release.
|
||||
game.wait(60)
|
||||
effects = set(effect_ids(game))
|
||||
inventory = game('inventory')
|
||||
stack = inventory['offhand'] if hand == 'offhand' else inventory['held']
|
||||
cancelled = {'during': during, 'released': released,
|
||||
'stack': stack, 'effects': sorted(effects)}
|
||||
seen[case] = {'cancelled': cancelled}
|
||||
assert during['client'] and during['server'], f'{case} did not start on both sides: {cancelled}'
|
||||
assert released == {'client': None, 'server': None}, f'{case} did not cancel: {cancelled}'
|
||||
assert stack and stack['item'] == f'minecraft:{item}' and stack['count'] == 1, \
|
||||
f'{case} consumed the released item: {cancelled}'
|
||||
assert effects == before, f'{case} applied consumption effects after release: {cancelled}'
|
||||
game.shot(out, f'consume-release-{hand}-{item}')
|
||||
# A sustained press must still consume normally, including the milk's empty bucket.
|
||||
game.raw('mouse', 'right', 'down')
|
||||
game.wait(40)
|
||||
game.raw('mouse', 'right', 'up')
|
||||
game.wait(10)
|
||||
inventory = game('inventory')
|
||||
stack = inventory['offhand'] if hand == 'offhand' else inventory['held']
|
||||
completed = {'stack': stack, 'effects': sorted(effect_ids(game)),
|
||||
'using': (game('state').get('using'), server_using(host, game))}
|
||||
seen[case]['completed'] = completed
|
||||
assert completed['using'] == (None, None), \
|
||||
f'{case} did not finish normally: {completed}'
|
||||
if item == 'golden_apple':
|
||||
assert inventory['counts'].get('minecraft:golden_apple', 0) == 0, \
|
||||
f'{case} kept the eaten apple: {completed}'
|
||||
assert set(completed['effects']) == {'regeneration', 'absorption'}, f'{case}: {completed}'
|
||||
else:
|
||||
assert not completed['effects'] and stack and stack['item'] == 'minecraft:bucket' \
|
||||
and stack['count'] == 1, f'{case}: {completed}'
|
||||
finally:
|
||||
for game in (host, guest):
|
||||
game.raw('mouse', 'right', 'up')
|
||||
game('command', command='clear @s')
|
||||
game('command', command='item replace entity @s weapon.offhand with minecraft:air')
|
||||
game('command', command='effect clear @s')
|
||||
face_each_other(host, guest)
|
||||
return seen
|
||||
|
||||
|
||||
CHECKS += ['consume-release']
|
||||
CHECK_FNS.update({'consume-release': check_consume_release})
|
||||
|
||||
|
||||
def check_wind(host, guest, out):
|
||||
"""A wind charge each player throws at its own feet (ServerExplosion with TRIGGER_BLOCK): the
|
||||
server's burst pushes the thrower through its ClientboundExplodePacket (hitPlayers), which
|
||||
@@ -5441,6 +5524,57 @@ CHECKS += ['knockback']
|
||||
CHECK_FNS.update(knockback=check_knockback)
|
||||
|
||||
|
||||
def check_spectator_travel(host, guest, out):
|
||||
"""Player.tick's spectator noPhysics survives a replacement body after dimension travel (#1299)."""
|
||||
players = (host, guest) if SERVER_THREAD else (host,)
|
||||
seen = {}
|
||||
for game in players:
|
||||
home = pos_of(game)
|
||||
game('command', command='gamemode spectator')
|
||||
game.wait(10)
|
||||
try:
|
||||
for dimension in (NETHER, OVERWORLD):
|
||||
game('command', command=f'execute in {dimension} run tp @s .5 102 .5 0 0')
|
||||
there = wait_dimension(game, dimension, 600)
|
||||
assert there.get('dimension') == dimension, f'{game.name} stayed in {there.get("dimension")}'
|
||||
# A replacement body arrives before its chunks; fill needs the whole corridor loaded.
|
||||
for _ in range(30):
|
||||
if all(game.raw('block', *pos).get('loaded') for pos in ((-2, 101, -1), (2, 105, 16))):
|
||||
break
|
||||
game.wait(20)
|
||||
game('command', command='fill -2 101 -1 2 105 16 minecraft:air')
|
||||
game('command', command='fill -2 101 3 2 105 3 minecraft:stone')
|
||||
game.wait(10)
|
||||
wall = game.raw('block', 0, 102, 3)
|
||||
assert wall.get('loaded') and wall.get('block') == 'minecraft:stone', f'wall: {wall}'
|
||||
label = f'spectator-{dimension.removeprefix("minecraft:")}'
|
||||
game.shot(out, f'{label}-before')
|
||||
game.raw('key', 'w', 'down')
|
||||
game.wait(20)
|
||||
game.raw('key', 'w', 'up')
|
||||
game.wait(10)
|
||||
state = game('state')
|
||||
client = state['player']
|
||||
server = server_player(host, game)
|
||||
seen[f'{game.name}-{dimension}'] = {'client': client['position'], 'server': server['position']}
|
||||
game.shot(out, f'{label}-after')
|
||||
assert state.get('gamemode') == 'spectator' and client['flying'], f'{game.name} lost spectator flight'
|
||||
assert client['position'][2] > 4 and server['position'][2] > 4, \
|
||||
f'{game.name} collides after travel to {dimension}: {seen}'
|
||||
game('command', command='fill -2 101 3 2 105 3 minecraft:air')
|
||||
finally:
|
||||
game.raw('key', 'w', 'up')
|
||||
game('command', command=f'execute in {OVERWORLD} run tp @s {home[0]:.2f} {home[1]:.2f} {home[2]:.2f}')
|
||||
wait_dimension(game, OVERWORLD, 600)
|
||||
game('command', command='gamemode survival')
|
||||
game.wait(20)
|
||||
return seen
|
||||
|
||||
|
||||
CHECKS += ['spectator-travel']
|
||||
CHECK_FNS.update({'spectator-travel': check_spectator_travel})
|
||||
|
||||
|
||||
def check_villagers(host, guest, out):
|
||||
"""Villager.DATA_VILLAGER_DATA and ZombieVillager's reach the guest: summoned villagers show
|
||||
their type, profession and level, and an unemployed villager that takes a composter placed
|
||||
@@ -5565,6 +5699,252 @@ CHECKS += ['recipe_removal']
|
||||
CHECK_FNS.update(recipe_removal=check_recipe_removal)
|
||||
|
||||
|
||||
def check_shulker_bullets(host, guest, out):
|
||||
"""ShulkerAttackGoal's bullets reach ClientPacketListener.handleAddEntity, then the existing
|
||||
projectile renderer and interpolation, with distinct ids from the server's entity counter."""
|
||||
x, y, z = (int(v // 1) for v in pos_of(host))
|
||||
tag = 'lan_shulker_bullets'
|
||||
selector = f'@e[type=minecraft:shulker,tag={tag},limit=1]'
|
||||
sound = 'minecraft:entity.shulker.shoot'
|
||||
paths = {g.name: {} for g in (host, guest)}
|
||||
before = {g.name: heard(g, sound) for g in (host, guest)}
|
||||
shots = dict.fromkeys(before, 0)
|
||||
first_shot = stopped = None
|
||||
photographed = False
|
||||
|
||||
def bullets(status):
|
||||
return [p for p in status['projectiles'] if p['kind'] == 'ShulkerBullet']
|
||||
|
||||
try:
|
||||
host('command', command='difficulty normal')
|
||||
host('command', command='gamemode creative')
|
||||
guest('command', command='gamemode survival')
|
||||
guest('command', command='effect give @s minecraft:resistance 120 4 true')
|
||||
host('command', command=f'fill {x - 10} {y - 1} {z - 10} {x + 10} {y - 1} {z + 18} minecraft:stone')
|
||||
host('command', command=f'fill {x - 10} {y} {z - 10} {x + 10} {y + 12} {z + 18} minecraft:air')
|
||||
# A west wall supports the shulker above the floor, leaving room for a short flight.
|
||||
host('command', command=f'fill {x - 1} {y} {z + 7} {x - 1} {y + 4} {z + 7} minecraft:stone')
|
||||
host('command', command=f'tp @s {x + 4.5} {y} {z - 0.5}')
|
||||
guest('command', command=f'tp @s {x + 0.5} {y} {z + 0.5}')
|
||||
host('command', command=f'summon minecraft:shulker {x + 0.5} {y + 3} {z + 7.5} '
|
||||
f'{{NoAI:1b,PersistenceRequired:1b,Tags:["{tag}"]}}')
|
||||
for game in (host, guest):
|
||||
game.raw('look-at', x + 0.5, y + 3.5, z + 7.5)
|
||||
guest.wait(20)
|
||||
host('command', command=f'data merge entity {selector} {{NoAI:0b}}')
|
||||
for waited in range(2, 402, 2):
|
||||
guest.wait(2)
|
||||
for game in (host, guest):
|
||||
status = game('status')
|
||||
live = bullets(status)
|
||||
ids = [p['id'] for p in live]
|
||||
assert all(ids) and len(set(ids)) == len(ids), f'{game.name}: invalid bullet ids {ids}'
|
||||
for p in live:
|
||||
paths[game.name].setdefault(p['id'], []).append(p['position'])
|
||||
shots[game.name] = status['heard'].get(sound, 0) - before[game.name]
|
||||
if shots['host'] and first_shot is None:
|
||||
first_shot = waited
|
||||
if first_shot is not None and waited - first_shot >= 8 and not photographed:
|
||||
host('command', command='tick freeze')
|
||||
try:
|
||||
for game in (host, guest):
|
||||
game.raw('look-at', x + 0.5, y + 3.5, z + 7.5)
|
||||
game.raw('key', 'f1', 'tap')
|
||||
try:
|
||||
game.shot(out, 'shulker-bullets')
|
||||
finally:
|
||||
game.raw('key', 'f1', 'tap')
|
||||
finally:
|
||||
host('command', command='tick unfreeze')
|
||||
photographed = True
|
||||
if shots['host'] >= 2 and stopped is None:
|
||||
host('command', command=f'data merge entity {selector} {{NoAI:1b}}')
|
||||
stopped = waited
|
||||
if stopped is not None and waited - stopped >= 20:
|
||||
break
|
||||
# Keep the survival target in range after a hit applies levitation.
|
||||
if waited % 20 == 0:
|
||||
guest('command', command='effect clear @s minecraft:levitation')
|
||||
guest('command', command=f'tp @s {x + 0.5} {y} {z + 0.5}')
|
||||
lab.write_json(out / 'shulker-bullets.json', {'shots': shots, 'paths': paths})
|
||||
assert shots['host'] >= 2, f'the shulker did not attack twice: {shots}'
|
||||
for name, by_id in paths.items():
|
||||
assert len(by_id) == shots[name], f'{name}: {shots[name]} shots but bullet ids {list(by_id)}'
|
||||
for id, positions in by_id.items():
|
||||
assert any(math.dist(positions[0], p) > 0.5 for p in positions), \
|
||||
f'{name}: bullet {id} did not move: {positions}'
|
||||
assert paths['host'].keys() == paths['guest'].keys(), f'different bullets: {paths}'
|
||||
for id, positions in paths['guest'].items():
|
||||
# The clients interpolate three ticks behind, and reads are not simultaneous.
|
||||
assert all(min(math.dist(p, q) for q in paths['host'][id]) < 1.5 for p in positions), \
|
||||
f'bullet {id} diverged from the host: {paths}'
|
||||
|
||||
# Put blocks in the flight volume to exercise server removal without depending on homing.
|
||||
for game in (host, guest):
|
||||
game('command', command='gamemode creative')
|
||||
game('command', command=f'tp @s {x + 0.5} {y + 16} {z + 0.5}')
|
||||
host('command', command=f'fill {x - 10} {y} {z - 10} {x + 10} {y + 12} {z + 18} minecraft:stone')
|
||||
for _ in range(20):
|
||||
guest.wait(2)
|
||||
remaining = {g.name: bullets(g('status')) for g in (host, guest)}
|
||||
if not any(remaining.values()):
|
||||
break
|
||||
assert not any(remaining.values()), f'bullets survived block hits: {remaining}'
|
||||
finally:
|
||||
host('command', command='tick unfreeze')
|
||||
host('command', command=f'kill @e[tag={tag}]')
|
||||
host('command', command=f'fill {x - 10} {y} {z - 10} {x + 10} {y + 12} {z + 18} minecraft:air')
|
||||
for game in (host, guest):
|
||||
game('command', command='effect clear @s')
|
||||
game('command', command=f'tp @s {x + 0.5} {y} {z + 0.5}')
|
||||
game('command', command='gamemode survival')
|
||||
face_each_other(host, guest)
|
||||
return {'shots': shots, 'ids': sorted(paths['host']), 'removed': True}
|
||||
|
||||
|
||||
CHECKS += ['shulker_bullets']
|
||||
CHECK_FNS.update(shulker_bullets=check_shulker_bullets)
|
||||
|
||||
|
||||
def check_farmland(host, guest, out):
|
||||
"""FarmlandBlock.fallOn's base-block change breaks the unsupported crop (#1492):
|
||||
the host and guest each land on mature wheat, get its drops, and both clients see dirt/air."""
|
||||
hx, hy, hz = (int(v // 1) for v in pos_of(host))
|
||||
y = max(hy + 12, 100)
|
||||
starts = {g.name: pos_of(g) for g in (host, guest)}
|
||||
seen = {}
|
||||
host('command', command='gamerule random_tick_speed 0')
|
||||
try:
|
||||
for game, other, dz in ((host, guest, -3), (guest, host, 3)):
|
||||
x, z = hx + 2, hz + dz
|
||||
soil, crop, marker = (x, y, z), (x, y + 1, z), (x + 4, y + 1, z)
|
||||
for g in (game, other):
|
||||
g('command', command='gamemode creative')
|
||||
host('command', command=f'fill {x - 4} {y} {z - 2} {x + 4} {y} {z + 2} minecraft:stone')
|
||||
host('command', command=f'fill {x - 4} {y + 1} {z - 2} {x + 4} {y + 7} {z + 2} minecraft:air')
|
||||
host('command', command=f'setblock {x} {y} {z} minecraft:farmland[moisture=7]')
|
||||
host('command', command=f'setblock {x} {y + 1} {z} minecraft:wheat[age=7]')
|
||||
other('command', command=f'tp @s {x + 3.5} {y + 1} {z + 0.5}')
|
||||
game('command', command=f'tp @s {x + 2.5} {y + 1} {z + 0.5}')
|
||||
game('command', command='clear @s')
|
||||
game('command', command='gamemode survival')
|
||||
game.wait(20)
|
||||
before = {g.name: [g.raw('block', *p).get('block') for p in (soil, crop)]
|
||||
for g in (host, guest)}
|
||||
assert all(v == ['minecraft:farmland', 'minecraft:wheat'] for v in before.values()), \
|
||||
f'{game.name}: planted wheat missing before landing: {before}'
|
||||
other.raw('look-at', x + 0.5, y + 1, z + 0.5)
|
||||
other.shot(out, f'farmland-{game.name}-before')
|
||||
# More than 1.5 blocks of fall distance guarantees the trampling random check.
|
||||
game('command', command=f'tp @s {x + 0.5} {y + 6} {z + 0.5}')
|
||||
game.wait(80)
|
||||
after = {g.name: [g.raw('block', *p).get('block') for p in (soil, crop)]
|
||||
for g in (host, guest)}
|
||||
# Test the authoritative blocks too, rather than only each client's view.
|
||||
game('command', command=f'execute if block {x} {y} {z} minecraft:dirt '
|
||||
f'if block {x} {y + 1} {z} minecraft:air run '
|
||||
f'setblock {marker[0]} {marker[1]} {marker[2]} minecraft:gold_block')
|
||||
game.wait(10)
|
||||
counts = {item: server_count(game, item) for item in ('wheat', 'wheat_seeds')}
|
||||
client_counts = game('inventory')['counts']
|
||||
seen[game.name] = {'blocks': after, 'server': game.raw('block', *marker).get('block'),
|
||||
'drops': counts,
|
||||
'client_drops': {item: client_counts.get('minecraft:' + item, 0)
|
||||
for item in counts}}
|
||||
other.shot(out, f'farmland-{game.name}-after')
|
||||
finally:
|
||||
host('command', command='gamerule random_tick_speed 3')
|
||||
host('command', command='kill @e[type=minecraft:item]')
|
||||
for g in (host, guest):
|
||||
x0, y0, z0 = starts[g.name]
|
||||
g('command', command=f'tp @s {x0} {y0} {z0}')
|
||||
g('command', command='gamemode survival')
|
||||
for name, s in seen.items():
|
||||
assert all(v == ['minecraft:dirt', 'minecraft:air'] for v in s['blocks'].values()), \
|
||||
f'{name}: unsupported wheat after landing: {seen}'
|
||||
assert s['server'] == 'minecraft:gold_block', f'{name}: server kept the unsupported wheat: {seen}'
|
||||
assert s['drops']['wheat'] == 1 and 1 <= s['drops']['wheat_seeds'] <= 4, \
|
||||
f'{name}: mature wheat drops missing: {seen}'
|
||||
assert s['client_drops'] == s['drops'], f'{name}: crop drops did not synchronize: {seen}'
|
||||
return seen
|
||||
|
||||
|
||||
CHECKS += ['farmland']
|
||||
CHECK_FNS.update(farmland=check_farmland)
|
||||
|
||||
|
||||
def check_large_chest(host, guest, out):
|
||||
"""Every player slot can be picked up or shift-clicked into a double chest (#1505, #1589).
|
||||
Reopening checks the authoritative contents, with a single chest as the control."""
|
||||
seen = {}
|
||||
for game in (host, guest):
|
||||
game('command', command='gamemode survival')
|
||||
x, y, z = (int(v // 1) for v in pos_of(game))
|
||||
chest, other = (x, y, z + 2), (x + 1, y, z + 2)
|
||||
try:
|
||||
for double in (False, True):
|
||||
size = 54 if double else 27
|
||||
# Double chest indices 54..89 include the old cutoff at 63/64 and every hotbar slot.
|
||||
sources = list(range(9, 36)) + list(range(9)) if double else [19, 0, 8]
|
||||
for shift in (False, True):
|
||||
back_to_game(game)
|
||||
for at in (chest, other):
|
||||
game('command', command=f'setblock {at[0]} {at[1]} {at[2]} minecraft:air')
|
||||
game('command', command='kill @e[type=minecraft:item,distance=..8]')
|
||||
game('command', command='clear @s')
|
||||
block = 'minecraft:chest[facing=north,type=left]' if double else 'minecraft:chest'
|
||||
game('command', command=f'setblock {x} {y} {z + 2} {block}')
|
||||
if double:
|
||||
game('command', command=f'setblock {x + 1} {y} {z + 2} minecraft:chest[facing=north,type=right]')
|
||||
for slot in sources:
|
||||
name = f'hotbar.{slot}' if slot < 9 else f'inventory.{slot - 9}'
|
||||
game('command', command=f'item replace entity @s {name} with minecraft:diamond')
|
||||
game.wait(10)
|
||||
game.raw('interact', *chest)
|
||||
game.raw('wait-for', 'screen', 'container', '--timeout', 10)
|
||||
game.wait(10)
|
||||
assert container_items(game)[1] == size, f'{game.name}: expected {size} chest slots'
|
||||
label = f'{"double" if double else "single"}-chest-{"shift" if shift else "pickup"}'
|
||||
for target, slot in enumerate(sources):
|
||||
if shift:
|
||||
game.raw('key', 'shift', 'down')
|
||||
try:
|
||||
mouse(game, slot)
|
||||
finally:
|
||||
if shift:
|
||||
game.raw('key', 'shift', 'up')
|
||||
if not shift:
|
||||
held = game('inventory').get('carried') or {}
|
||||
if held.get('item') != 'minecraft:diamond' or held.get('count') != 1:
|
||||
game.shot(out, f'{label}-slot-{slot}-failed')
|
||||
raise AssertionError(f'{game.name} {label}: slot {slot} picked up {held}')
|
||||
mouse(game, 300 + target)
|
||||
game.raw('key', 'esc', 'tap')
|
||||
game.wait(10)
|
||||
game.raw('interact', *chest)
|
||||
game.raw('wait-for', 'screen', 'container', '--timeout', 10)
|
||||
game.wait(10)
|
||||
contents = [s for s in game('screen')['slots'] if 300 <= s['slot'] < 300 + size and s.get('item')]
|
||||
inv = game('inventory')
|
||||
stored = sum(s['count'] for s in contents if s['item'] == 'minecraft:diamond')
|
||||
assert stored == len(sources) and not inv['counts'].get('minecraft:diamond') and not inv.get('carried'), \
|
||||
f'{game.name} {label}: chest {contents}, inventory {inv}'
|
||||
game.shot(out, label)
|
||||
seen[f'{game.name}-{label}'] = stored
|
||||
game.raw('key', 'esc', 'tap')
|
||||
finally:
|
||||
back_to_game(game)
|
||||
for at in (chest, other):
|
||||
game('command', command=f'setblock {at[0]} {at[1]} {at[2]} minecraft:air')
|
||||
game('command', command='kill @e[type=minecraft:item,distance=..8]')
|
||||
game('command', command='clear @s')
|
||||
return seen
|
||||
|
||||
|
||||
CHECKS += ['large_chest']
|
||||
CHECK_FNS.update(large_chest=check_large_chest)
|
||||
|
||||
|
||||
def check_falling(host, guest, out):
|
||||
"""ItemEntity and FallingBlockEntity tick on a client too (gravity, collisions, drag), and their
|
||||
position packets snap them (Entity's NO_OP InterpolationHandler). The server sends an item's
|
||||
|
||||
@@ -181,20 +181,25 @@ def settle(server, ticks=600, timeout=600):
|
||||
break
|
||||
time.sleep(2)
|
||||
|
||||
def game_time():
|
||||
start = len(server.lines)
|
||||
server.console('time query gametime')
|
||||
while time.time() < deadline:
|
||||
for line in server.lines[start:]:
|
||||
if m := re.search(r'The (?:game )?time is (\d+)', line):
|
||||
return int(m.group(1))
|
||||
time.sleep(0.2)
|
||||
raise AssertionError(f'{server.log_path.name}: no game time in {timeout} s')
|
||||
until = game_time() + ticks
|
||||
while game_time() < until:
|
||||
until = game_time(server, deadline - time.time()) + ticks
|
||||
while game_time(server, deadline - time.time()) < until:
|
||||
time.sleep(2)
|
||||
|
||||
|
||||
def game_time(server, timeout=300):
|
||||
"""The server's game time, asked from its console: the console runs its queue in order, so every console
|
||||
command sent before has run."""
|
||||
deadline = time.time() + timeout
|
||||
start = len(server.lines)
|
||||
server.console('time query gametime')
|
||||
while time.time() < deadline:
|
||||
for line in server.lines[start:]:
|
||||
if m := re.search(r'The (?:game )?time is (\d+)', line):
|
||||
return int(m.group(1))
|
||||
time.sleep(0.05)
|
||||
raise AssertionError(f'{server.log_path.name}: no game time in {timeout:.0f} s')
|
||||
|
||||
|
||||
def legacy_ping(port):
|
||||
"""The reply to a 1.6 client's 0xFE 0x01 0xFA MC|PingHost query (LegacyQueryHandler)."""
|
||||
host = 'localhost'
|
||||
|
||||
Executable
+177
@@ -0,0 +1,177 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Item stacks on the wire: every data component, as vanilla 26.3 encodes it.
|
||||
|
||||
VanillaItemWireOracle encodes stacks with ItemStack.OPTIONAL_STREAM_CODEC
|
||||
(what a server sends in inventories, recipe books and advancements): each
|
||||
default component value of every vanilla item, the SNBT fixtures below
|
||||
(direct holders, tags and lists, optional fields, every consume effect,
|
||||
block predicates with component matchers, the mob variants) and patches
|
||||
built in Java (components without a persistent codec, removals). The Rust
|
||||
probe decodes each with horizon_protocol::item::Slot and must consume every
|
||||
byte and find the same component ids in the same order; a stack whose
|
||||
components Horizon only reads past must also encode back to the same bytes.
|
||||
Every id in DataComponents must be covered."""
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import platform
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
try:
|
||||
from . import lab, test_rust_parity as base
|
||||
except ImportError:
|
||||
import lab
|
||||
import test_rust_parity as base
|
||||
|
||||
COMPONENT_TYPES = 122
|
||||
|
||||
FIXTURES = [
|
||||
('custom_data', '{custom_data:{a:1,b:"x",c:[1,2]}}'),
|
||||
('unbreakable', '{unbreakable:{}}'),
|
||||
('custom_name', '{custom_name:{text:"Hi",color:"red",bold:1b}}'),
|
||||
('lore', '{lore:["a",{text:"b",italic:0b}]}'),
|
||||
('enchantments', '{enchantments:{"minecraft:sharpness":5,"minecraft:unbreaking":3}}'),
|
||||
('can_break tag', '{can_break:{blocks:"#minecraft:logs"}}'),
|
||||
('can_break list state nbt', '{can_break:[{blocks:["minecraft:stone","minecraft:dirt"],state:{snowy:"true",age:{min:"1",max:"3"},level:{min:"2"}},nbt:"{a:1b}"}]}'),
|
||||
('can_place_on components', '{can_place_on:{blocks:"minecraft:chest",components:{"minecraft:custom_name":"x","minecraft:damage":3},predicates:{"minecraft:custom_data":{a:1},"minecraft:damage":{durability:{min:1}}}}}'),
|
||||
('can_place_on empty', '{can_place_on:[{}]}'),
|
||||
('custom_model_data', '{custom_model_data:{floats:[1.0f,2.5f],flags:[1b,0b],strings:["a"],colors:[16711680]}}'),
|
||||
('tooltip_display', '{tooltip_display:{hide_tooltip:1b,hidden_components:["minecraft:enchantments","minecraft:damage"]}}'),
|
||||
('repair_cost', '{repair_cost:7}'),
|
||||
('intangible_projectile', '{intangible_projectile:{}}'),
|
||||
('tooltip_style', '{tooltip_style:"minecraft:fancy"}'),
|
||||
('interact_animation', '{interact_animation:{type:"stab",duration:9}}'),
|
||||
('dyed_color', '{dyed_color:16711935}'),
|
||||
('map_id', '{map_id:42}'),
|
||||
('written_book_content', '{written_book_content:{title:{raw:"T",filtered:"F"},author:"me",generation:1,pages:[{raw:"p1",filtered:"q1"},"p2"],resolved:1b}}'),
|
||||
('trim registry', '{trim:{material:"minecraft:gold",pattern:"minecraft:coast"}}'),
|
||||
('trim direct', '{trim:{material:{palette_id:"minecraft:x",description:"X"},pattern:{asset_id:"minecraft:y",description:"Y",decal:1b}}}'),
|
||||
('block_entity_data', '{block_entity_data:{id:"minecraft:chest",Items:[]}}'),
|
||||
('lodestone_tracker target', '{lodestone_tracker:{target:{dimension:"minecraft:the_nether",pos:[1,-64,3]},tracked:0b}}'),
|
||||
('lodestone_tracker empty', '{lodestone_tracker:{}}'),
|
||||
('firework_explosion', '{firework_explosion:{shape:"star",colors:[1,2],fade_colors:[3],has_trail:1b,has_twinkle:0b}}'),
|
||||
('profile name', '{profile:{name:"Notch"}}'),
|
||||
('profile full', '{profile:{name:"jeb_",id:[I;1,2,3,4],properties:[{name:"textures",value:"abc",signature:"sig"}]}}'),
|
||||
('note_block_sound', '{note_block_sound:"minecraft:block.note_block.bell"}'),
|
||||
('base_color', '{base_color:"lime"}'),
|
||||
('sulfur_cube_content', '{sulfur_cube_content:{id:"minecraft:stone",count:1}}'),
|
||||
('lock', '{lock:{items:"minecraft:diamond"}}'),
|
||||
('container_loot', '{container_loot:{loot_table:"minecraft:chests/simple_dungeon",seed:5L}}'),
|
||||
('waxed', '{waxed:{}}'),
|
||||
('banner_patterns', '{banner_patterns:[{pattern:"minecraft:stripe_bottom",color:"red"},{pattern:{asset_id:"minecraft:x",translation_key:"y"},color:"blue"}]}'),
|
||||
('pot_decorations', '{pot_decorations:{back:{id:"minecraft:brick"},left:{id:"minecraft:angler_pottery_sherd"},front:{id:"minecraft:skull_pottery_sherd",count:1}}}'),
|
||||
('suspicious_stew_effects', '{suspicious_stew_effects:[{id:"minecraft:night_vision",duration:100},{id:"minecraft:poison"}]}'),
|
||||
('potion_contents full', '{potion_contents:{potion:"minecraft:swiftness",custom_color:123,custom_effects:[{id:"minecraft:speed",amplifier:1b,duration:200,ambient:1b,show_particles:0b,show_icon:1b,hidden_effect:{id:"minecraft:speed",duration:100,hidden_effect:{id:"minecraft:speed",duration:50}}}],custom_name:"x"}}'),
|
||||
('potion_contents bare', '{potion_contents:{}}'),
|
||||
('container', '{container:[{slot:0,item:{id:"minecraft:stone",count:3}},{slot:5,item:{id:"minecraft:diamond_sword",components:{"minecraft:damage":5,"minecraft:trim":{material:"minecraft:gold",pattern:"minecraft:coast"}}}}]}'),
|
||||
('bundle_contents', '{bundle_contents:[{id:"minecraft:stone",count:2},{id:"minecraft:potion",components:{"minecraft:potion_contents":{potion:"minecraft:water"}}}]}'),
|
||||
('charged_projectiles', '{charged_projectiles:[{id:"minecraft:arrow"},{id:"minecraft:firework_rocket",components:{"minecraft:fireworks":{flight_duration:2b,explosions:[{shape:"burst",colors:[5]}]}}}]}'),
|
||||
('block_state', '{block_state:{facing:"north",half:"top"}}'),
|
||||
('bees', '{bees:[{entity_data:{id:"minecraft:bee",Health:5f},ticks_in_hive:5,min_ticks_in_hive:10}]}'),
|
||||
('entity_data', '{entity_data:{id:"minecraft:pig",NoAI:1b}}'),
|
||||
('bucket_entity_data', '{bucket_entity_data:{Health:5f}}'),
|
||||
('instrument direct', '{instrument:{sound_event:{sound_id:"minecraft:x",range:8f},use_duration:3f,range:64f,description:"Horn"}}'),
|
||||
('painting variant', '{"minecraft:painting/variant":"minecraft:kebab"}'),
|
||||
('sign_text_front', '{sign_text_front:{messages:["a","b","c","d"],filtered_messages:["e","f","g","h"],color:"red",has_glowing_text:1b}}'),
|
||||
('sign_text_back', '{sign_text_back:{messages:["a","","",""]}}'),
|
||||
('map_decorations', '{map_decorations:{a:{type:"minecraft:player",x:1.0d,z:2.0d,rotation:0f}}}'),
|
||||
('debug_stick_state', '{debug_stick_state:{"minecraft:oak_stairs":"facing"}}'),
|
||||
('recipes', '{recipes:["minecraft:stone_bricks"]}'),
|
||||
('attribute_modifiers', '{attribute_modifiers:[{type:"minecraft:attack_damage",id:"minecraft:x",amount:1.5d,operation:"add_value",slot:"mainhand",display:{type:"override",value:"hi"}},{type:"minecraft:armor",id:"minecraft:y",amount:2d,operation:"add_multiplied_total",display:{type:"hidden"}}]}'),
|
||||
('consumable all effects', '{consumable:{consume_seconds:2f,animation:"drink",sound:{sound_id:"minecraft:x",range:4f},has_consume_particles:0b,on_consume_effects:[{type:"apply_effects",effects:[{id:"minecraft:speed",duration:20}],probability:0.5f},{type:"remove_effects",effects:"minecraft:poison"},{type:"remove_effects",effects:["minecraft:poison","minecraft:wither"]},{type:"clear_all_effects"},{type:"teleport_randomly",diameter:8f},{type:"play_sound",sound:"minecraft:entity.generic.eat"}]}}'),
|
||||
('death_protection', '{death_protection:{death_effects:[{type:"clear_all_effects"}]}}'),
|
||||
('equippable full', '{equippable:{slot:"head",equip_sound:"minecraft:item.armor.equip_gold",asset_id:"minecraft:gold",camera_overlay:"minecraft:misc/pumpkinblur",allowed_entities:"#minecraft:skeletons",dispensable:0b,swappable:0b,damage_on_hurt:0b,equip_on_interact:1b,can_be_sheared:1b,shearing_sound:{sound_id:"minecraft:y"}}}'),
|
||||
('equippable bare', '{equippable:{slot:"chest"}}'),
|
||||
('tool rules', '{tool:{rules:[{blocks:"#minecraft:mineable/pickaxe",speed:4f,correct_for_drops:1b},{blocks:["minecraft:stone"]}],default_mining_speed:2f,damage_per_block:2,can_destroy_blocks_in_creative:0b}}'),
|
||||
('blocks_attacks full', '{blocks_attacks:{block_delay_seconds:0.5f,disable_cooldown_scale:2f,damage_reductions:[{horizontal_blocking_angle:45f,type:"#minecraft:is_fire",base:1f,factor:0.5f},{base:0f,factor:1f}],item_damage:{threshold:3f,base:1f,factor:2f},bypassed_by:"#minecraft:bypasses_shield",block_sound:"minecraft:item.shield.block",disable_sound:{sound_id:"minecraft:z"}}}'),
|
||||
('damage_resistant', '{damage_resistant:{types:"#minecraft:is_fire"}}'),
|
||||
('repairable list', '{repairable:{items:["minecraft:diamond","minecraft:emerald"]}}'),
|
||||
('use_cooldown group', '{use_cooldown:{seconds:1.5f,cooldown_group:"minecraft:x"}}'),
|
||||
('use_remainder', '{use_remainder:{id:"minecraft:bowl",count:2}}'),
|
||||
('fireworks', '{fireworks:{flight_duration:3b,explosions:[{shape:"creeper",colors:[1],fade_colors:[2,3],has_trail:1b},{shape:"small_ball"}]}}'),
|
||||
('provides_banner_patterns', '{provides_banner_patterns:"#minecraft:pattern_item/globe"}'),
|
||||
('wolf variant', '{"minecraft:wolf/variant":"minecraft:ashen","minecraft:wolf/sound_variant":"minecraft:angry","minecraft:wolf/collar":"red"}'),
|
||||
('fox salmon parrot', '{"minecraft:fox/variant":"snow","minecraft:salmon/size":"large","minecraft:parrot/variant":"blue"}'),
|
||||
('tropical fish', '{"minecraft:tropical_fish/pattern":"flopper","minecraft:tropical_fish/base_color":"white","minecraft:tropical_fish/pattern_color":"black"}'),
|
||||
('mooshroom rabbit', '{"minecraft:mooshroom/variant":"brown","minecraft:rabbit/variant":"gold"}'),
|
||||
('pig cow chicken', '{"minecraft:pig/variant":"minecraft:cold","minecraft:pig/sound_variant":"minecraft:big","minecraft:cow/variant":"minecraft:warm","minecraft:cow/sound_variant":"minecraft:classic","minecraft:chicken/variant":"minecraft:cold","minecraft:chicken/sound_variant":"minecraft:classic"}'),
|
||||
('nautilus frog horse', '{"minecraft:zombie_nautilus/variant":"minecraft:warm","minecraft:frog/variant":"minecraft:cold","minecraft:horse/variant":"chestnut"}'),
|
||||
('llama axolotl cat', '{"minecraft:llama/variant":"brown","minecraft:axolotl/variant":"blue","minecraft:cat/variant":"minecraft:tabby","minecraft:cat/sound_variant":"minecraft:classic","minecraft:cat/collar":"blue"}'),
|
||||
('sheep shulker villager', '{"minecraft:sheep/color":"pink","minecraft:shulker/color":"purple","minecraft:villager/variant":"minecraft:taiga"}'),
|
||||
('trim material direct provider', '{provides_trim_material:{palette_id:"minecraft:x",description:"X"}}'),
|
||||
('everything at once', '{damage:3,unbreakable:{},custom_name:"n",enchantments:{"minecraft:mending":1},trim:{material:"minecraft:gold",pattern:"minecraft:coast"},banner_patterns:[{pattern:"minecraft:globe",color:"red"}],pot_decorations:{right:{id:"minecraft:brick"}},lore:["x"],rarity:"epic"}'),
|
||||
]
|
||||
# Fixtures on another item than a stick (the components need it, or read better there).
|
||||
ITEMS = {'profile name': 'player_head', 'profile full': 'player_head', 'trim registry': 'diamond_chestplate',
|
||||
'trim direct': 'diamond_chestplate', 'banner_patterns': 'white_banner', 'pot_decorations': 'decorated_pot',
|
||||
'everything at once': 'diamond_chestplate'}
|
||||
|
||||
|
||||
def compare(vanilla, rust):
|
||||
"""Failures, stacks checked, and the component ids covered."""
|
||||
results = {r['label']: r for r in rust}
|
||||
failures, covered = [], set()
|
||||
for v in vanilla:
|
||||
if 'error' in v:
|
||||
failures.append(f"oracle {v['label']}: {v['error']}")
|
||||
continue
|
||||
covered.update(v['added'] + v['removed'])
|
||||
r = results.get(v['label'])
|
||||
if r is None or 'error' in r:
|
||||
failures.append(f"{v['label']}: {r and r['error']}")
|
||||
elif r['left'] or r['added'] != v['added'] or r['removed'] != v['removed']:
|
||||
failures.append(f"{v['label']}: {r['left']} bytes left, ids {r['added']}/{r['removed']}, vanilla {v['added']}/{v['removed']}")
|
||||
elif not r['same_bytes'] and not r['typed']:
|
||||
failures.append(f"{v['label']}: read past, but encoded back differently")
|
||||
missing = sorted(set(range(COMPONENT_TYPES)) - covered)
|
||||
if missing:
|
||||
failures.append(f'component ids no stack covers: {missing}')
|
||||
return failures, len(vanilla), covered
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--prepare', action='store_true')
|
||||
args = parser.parse_args()
|
||||
build = lab.LOCAL / 'item-wire-parity'
|
||||
build.mkdir(parents=True, exist_ok=True)
|
||||
report_path = build / 'report.json'
|
||||
report_path.unlink(missing_ok=True)
|
||||
if args.prepare:
|
||||
lab.prepare()
|
||||
lock, jars, libraries = base.verify_artifacts()
|
||||
oracle = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaItemWireOracle.java'
|
||||
classes = build / 'classes'
|
||||
classes.mkdir(exist_ok=True)
|
||||
|
||||
def run(command, name):
|
||||
with (build / (name + '.log')).open('w', encoding='utf-8') as log:
|
||||
base.run(list(map(str, command)), stdout=log, stderr=subprocess.STDOUT)
|
||||
dependency_path = os.pathsep.join(map(str, libraries))
|
||||
run(['javac', '--release', lock['minecraft']['java_major'], '-proc:none', '-sourcepath',
|
||||
lab.ROOT / 'mods/horizon/src/test/java', '-cp', str(jars['server']) + os.pathsep + dependency_path,
|
||||
'-d', classes, oracle], 'compile-java')
|
||||
fixtures = build / 'fixtures.tsv'
|
||||
fixtures.write_text(''.join(f'{label}\t{{id:"minecraft:{ITEMS.get(label, "stick")}",count:1,components:{snbt}}}\n'
|
||||
for label, snbt in FIXTURES), encoding='utf-8')
|
||||
vanilla_path, rust_path = build / 'vanilla.jsonl', build / 'rust.jsonl'
|
||||
run(['java', '-Xmx1G', '-cp', os.pathsep.join([str(classes), str(jars['server']), dependency_path]),
|
||||
'dev.horizonlab.parity.VanillaItemWireOracle', fixtures, vanilla_path], 'oracle')
|
||||
run(['cargo', 'build', '--release', '-p', 'horizon-protocol', '--example', 'item_wire_probe'], 'compile-rust')
|
||||
binary = lab.cargo_target() / 'release/examples' / ('item_wire_probe.exe' if os.name == 'nt' else 'item_wire_probe')
|
||||
run([binary, vanilla_path, rust_path], 'rust')
|
||||
read = lambda path: [json.loads(line) for line in path.read_text(encoding='utf-8').splitlines() if line.strip()]
|
||||
failures, stacks, covered = compare(read(vanilla_path), read(rust_path))
|
||||
for failure in failures[:40]:
|
||||
print(failure)
|
||||
if failures:
|
||||
raise SystemExit(f'{len(failures)} item wire mismatches (of {stacks} stacks)')
|
||||
lab.write_json(report_path, {
|
||||
'schema': 1, 'minecraft': lock['minecraft']['version'], 'platform': platform.platform(),
|
||||
'stacks': stacks, 'component_types_covered': len(covered),
|
||||
'oracle_sha256': lab.digest(vanilla_path, 'sha256'), 'rust_sha256': lab.digest(rust_path, 'sha256')})
|
||||
print(f'Item wire parity passed: {stacks} stacks, all {len(covered)} component types: {report_path}')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -10,7 +10,11 @@ A vanilla dedicated server and Horizon's (`horizon-client --dedicated --nogui`)
|
||||
vanilla generated first, with Alice and Bob as operators in creative. LocatorBarClient joins them both (players made
|
||||
of vanilla's protocol code) and records, step by step, the system chat each receives and what the server changes
|
||||
about it: game mode events, teleports, inventory slots, effects, its death (with the death message), the other
|
||||
players it is sent or loses and the levels it respawns into. Each player's lines in each step are compared exactly,
|
||||
players it is sent or loses and the levels it respawns into. A step ends by the server's clock, not the wall's: its
|
||||
console commands have run (the console's `time query gametime` comes back), each player's commands have run (a
|
||||
`sync` round trip), the server has ticked STEP_TICKS more times, and each client holds what was sent until then (a
|
||||
last `sync`), so a server that stalls under load still has each packet recorded in its own step (a fixed 2.5 s
|
||||
filed a stalled vanilla's teleports under the next step). Each player's lines in each step are compared exactly,
|
||||
in sorted order (the packets of one step may leave in another order within the tick), with the locator bar's
|
||||
waypoints as each step leaves them (one manager per level: a player in another level is untracked). What a death does besides its messages
|
||||
is left to its own harness.
|
||||
@@ -25,12 +29,12 @@ import time
|
||||
|
||||
try:
|
||||
from . import lab, test_rust_parity as base
|
||||
from .test_dedicated_server_parity import Server
|
||||
from .test_dedicated_server_parity import Server, game_time
|
||||
from .test_locator_bar_parity import generate_world, server_dir
|
||||
except ImportError:
|
||||
import lab
|
||||
import test_rust_parity as base
|
||||
from test_dedicated_server_parity import Server
|
||||
from test_dedicated_server_parity import Server, game_time
|
||||
from test_locator_bar_parity import generate_world, server_dir
|
||||
|
||||
NAME = 'server-player-targets-parity'
|
||||
@@ -70,7 +74,8 @@ SCRIPT = [
|
||||
# What the players' locator bars show has its own harness (test_locator_bar_parity), and what a death does
|
||||
# besides its messages (drops, the body leaving) the player combat ones: here only the messages of `kill`.
|
||||
DEATH_STEP = 'step=console-kill'
|
||||
STEP_SECONDS = 2.5
|
||||
STEP_TICKS = 40
|
||||
PLAYERS = ('Alice', 'Bob')
|
||||
|
||||
|
||||
def run_side(label, server_command, client_command, build, world):
|
||||
@@ -83,32 +88,49 @@ def run_side(label, server_command, client_command, build, world):
|
||||
server.wait_for(r'Done \(')
|
||||
with (build / f'{label}-client.log').open('w') as log:
|
||||
client = subprocess.Popen([*map(str, client_command), '127.0.0.1', str(port), str(out)],
|
||||
cwd=lab.ROOT, stdin=subprocess.PIPE, stdout=log, stderr=subprocess.STDOUT,
|
||||
text=True)
|
||||
cwd=lab.ROOT, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
|
||||
stderr=subprocess.STDOUT, text=True)
|
||||
|
||||
def tell(line):
|
||||
client.stdin.write(line + '\n')
|
||||
client.stdin.flush()
|
||||
|
||||
def sync():
|
||||
for name in PLAYERS:
|
||||
tell(f'sync {name}')
|
||||
for name in PLAYERS:
|
||||
while (line := client.stdout.readline()) != f'synced {name}\n':
|
||||
if not line:
|
||||
raise AssertionError(f'{label}: the client exited (see {build}/{label}-client.log)')
|
||||
log.write(line)
|
||||
|
||||
def finish_step():
|
||||
sync()
|
||||
until = game_time(server) + STEP_TICKS
|
||||
while game_time(server) < until:
|
||||
time.sleep(0.2)
|
||||
for name in PLAYERS:
|
||||
tell(f'still {name}')
|
||||
sync()
|
||||
try:
|
||||
for name, x in (('Alice', 0.5), ('Bob', 4.5)):
|
||||
for name, x in zip(PLAYERS, (0.5, 4.5)):
|
||||
tell(f'join {name}')
|
||||
server.wait_for(rf'{name} joined the game', timeout=120)
|
||||
tell(f'fly {name} on')
|
||||
tell(f'cmd {name} tp @s {x} -60 0.5 0 0')
|
||||
time.sleep(STEP_SECONDS)
|
||||
finish_step()
|
||||
for flag in ('chat', 'state', 'players'):
|
||||
tell(f'{flag} on')
|
||||
for step, console, actions in SCRIPT:
|
||||
tell(f'step {step}')
|
||||
for command in console:
|
||||
server.console(command)
|
||||
game_time(server) # the console runs its queue in order: these commands have run
|
||||
for action in actions:
|
||||
tell(action)
|
||||
time.sleep(STEP_SECONDS)
|
||||
for name in ('Alice', 'Bob'):
|
||||
tell(f'still {name}')
|
||||
finish_step()
|
||||
tell('end')
|
||||
client.wait(timeout=60)
|
||||
log.write(client.communicate(timeout=60)[0])
|
||||
finally:
|
||||
if client.poll() is None:
|
||||
client.kill()
|
||||
|
||||
Reference in New Issue
Block a user