init commit

This commit is contained in:
cantyonion committed 2026-11-24 12:43:25 +08:00
commit 1497f114e6
47 files changed
+8358

No files matched your search

+231
View File
@@ -0,0 +1,231 @@
#include "ActionExecutor.h"
#include "ActionFile.h"
#include "BilicraftClient.h"
#include <climits>
#include <stdexcept>
#include <string>
#include <gtest/gtest.h>
#include "protocolCraft/Packets/Game/Serverbound/ServerboundContainerClickPacket.hpp"
#include "botcraft/Game/Inventory/Window.hpp"
namespace
{
using namespace Bilicraft;
using Botcraft::InventoryType;
TEST(ActionExecutor, MapsEveryGenericContainerSize)
{
const InventoryType types[] = {InventoryType::Generic9x1, InventoryType::Generic9x2, InventoryType::Generic9x3,
InventoryType::Generic9x4, InventoryType::Generic9x5, InventoryType::Generic9x6};
for (int rows = 1; rows <= 6; ++rows)
{
EXPECT_EQ(ActionGuiSlot(types[rows - 1], 1, 1), 0);
EXPECT_EQ(ActionGuiSlot(types[rows - 1], rows, 9), rows * 9 - 1);
EXPECT_THROW(ActionGuiSlot(types[rows - 1], rows + 1, 1), std::runtime_error);
}
EXPECT_EQ(ActionGuiSlot(InventoryType::ShulkerBox, 3, 9), 26);
EXPECT_THROW(ActionGuiSlot(InventoryType::ShulkerBox, 4, 1), std::runtime_error);
}
TEST(ActionExecutor, RejectsNonNineColumnGuiRatherThanGuessing)
{
for (const auto type : {InventoryType::PlayerInventory, InventoryType::Default, InventoryType::Generic3x3,
InventoryType::Furnace, InventoryType::Hopper, InventoryType::Crafting,
InventoryType::Merchant, InventoryType::Anvil})
EXPECT_THROW(ActionGuiSlot(type, 1, 1), std::runtime_error);
}
TEST(ActionExecutor, RejectsGuiBoundsBeforeArithmetic)
{
for (int bad : {INT_MIN, -1, 0, 10, INT_MAX})
EXPECT_THROW(ActionGuiSlot(InventoryType::Generic9x6, 1, bad), std::runtime_error);
for (int bad : {INT_MIN, -1, 0, 7, INT_MAX})
EXPECT_THROW(ActionGuiSlot(InventoryType::Generic9x6, bad, 1), std::runtime_error);
}
TEST(ActionExecutor, MapsAllBackpackAndHotbarPositions)
{
for (int row = 1; row <= 3; ++row)
for (int col = 1; col <= 9; ++col)
EXPECT_EQ(ActionBackpackSlot(row, col), 9 + (row - 1) * 9 + col - 1);
for (int slot = 1; slot <= 9; ++slot)
EXPECT_EQ(ActionHotbarIndex(slot), slot - 1);
}
TEST(ActionExecutor, RejectsBackpackAndHotbarBounds)
{
for (int bad : {INT_MIN, -1, 0, 4, INT_MAX})
EXPECT_THROW(ActionBackpackSlot(bad, 1), std::runtime_error);
for (int bad : {INT_MIN, -1, 0, 10, INT_MAX})
{
EXPECT_THROW(ActionBackpackSlot(1, bad), std::runtime_error);
EXPECT_THROW(ActionHotbarIndex(bad), std::runtime_error);
}
}
TEST(ActionExecutor, BuildsRealNumberKeySwapWithoutCursorPrediction)
{
const auto packet = MakeBackpackSwapPacket(3, 9, 9);
EXPECT_EQ(packet->GetContainerId(), 0);
EXPECT_EQ(packet->GetStateId(), -1);
EXPECT_EQ(packet->GetSlotNum(), 35);
EXPECT_EQ(packet->GetButtonNum(), 8);
EXPECT_EQ(packet->GetClickType(), 2);
EXPECT_TRUE(packet->GetChangedSlots().empty());
EXPECT_FALSE(packet->GetCarriedItem().GetActualItem().has_value());
ProtocolCraft::WriteContainer bytes;
packet->Write(bytes);
EXPECT_FALSE(bytes.empty());
}
TEST(ActionExecutor, SwapPacketRejectsInvalidPositions)
{
EXPECT_THROW(MakeBackpackSwapPacket(0, 1, 1), std::runtime_error);
EXPECT_THROW(MakeBackpackSwapPacket(1, 10, 1), std::runtime_error);
EXPECT_THROW(MakeBackpackSwapPacket(1, 1, 10), std::runtime_error);
}
TEST(ActionExecutor, ResolvesDropTargetWithoutChangingTheSelection)
{
for (int selected = 0; selected < 9; ++selected)
{
EXPECT_EQ(ActionDropSlot(0, selected), selected + 1);
for (int requested = 1; requested <= 9; ++requested)
EXPECT_EQ(ActionDropSlot(requested, selected), requested);
}
for (int invalid : {INT_MIN, -1, 9, INT_MAX})
EXPECT_THROW(ActionDropSlot(0, invalid), std::runtime_error);
for (int invalid : {INT_MIN, -1, 10, INT_MAX})
EXPECT_THROW(ActionDropSlot(invalid, 0), std::runtime_error);
}
TEST(ActionExecutor, BuildsSingleAndWholeStackDropPacketsForEveryHotbarSlot)
{
for (int slot = 1; slot <= 9; ++slot)
for (bool all : {false, true})
{
const auto packet = MakeHotbarDropPacket(slot, all);
EXPECT_EQ(packet->GetContainerId(), 0);
EXPECT_EQ(packet->GetStateId(), -1);
EXPECT_EQ(packet->GetSlotNum(), 35 + slot);
EXPECT_EQ(packet->GetClickType(), 4);
EXPECT_EQ(packet->GetButtonNum(), all ? 1 : 0);
EXPECT_TRUE(packet->GetChangedSlots().empty());
EXPECT_FALSE(packet->GetCarriedItem().GetActualItem().has_value());
ProtocolCraft::WriteContainer bytes;
packet->Write(bytes);
EXPECT_FALSE(bytes.empty());
}
for (int invalid : {INT_MIN, -1, 0, 10, INT_MAX})
EXPECT_THROW(MakeHotbarDropPacket(invalid, false), std::runtime_error);
}
TEST(ActionExecutor, DropRemainderHandlesEmptySingleAndFullStacksWithoutMutatingInput)
{
const ProtocolCraft::Slot empty;
EXPECT_TRUE(RemainingAfterDrop(empty, false).IsEmptySlot());
EXPECT_TRUE(RemainingAfterDrop(empty, true).IsEmptySlot());
ProtocolCraft::Slot original;
original.SetItemId(1);
for (int count : {1, 2, 64})
{
original.SetItemCount(count);
const auto remaining = RemainingAfterDrop(original, false);
EXPECT_EQ(remaining.GetItemCount(), count - 1);
EXPECT_EQ(remaining.IsEmptySlot(), count == 1);
if (count > 1)
{
auto expected = original;
expected.SetItemCount(count - 1);
ProtocolCraft::WriteContainer actualBytes, expectedBytes;
remaining.Write(actualBytes);
expected.Write(expectedBytes);
EXPECT_EQ(actualBytes, expectedBytes);
}
EXPECT_TRUE(RemainingAfterDrop(original, true).IsEmptySlot());
EXPECT_EQ(original.GetItemCount(), count);
}
}
TEST(ActionExecutor, DropDistinguishesKnownEmptySlotsFromInventoryReset)
{
Botcraft::Window window(InventoryType::PlayerInventory);
EXPECT_THROW(ReadDropSlot(window, 36), std::runtime_error);
window.SetSlot(36, ProtocolCraft::Slot());
EXPECT_TRUE(ReadDropSlot(window, 36).IsEmptySlot());
ProtocolCraft::Slot stack;
stack.SetItemId(1);
stack.SetItemCount(4);
window.SetSlot(36, stack);
EXPECT_EQ(ReadDropSlot(window, 36).GetItemCount(), 4);
window.Init(); // Clears the contents but preserves window identity.
EXPECT_THROW(ReadDropSlot(window, 36), std::runtime_error);
}
TEST(ActionExecutor, OfflineFailureIncludesSourceAndLine)
{
BilicraftClient client;
ActionCommand command{};
command.kind = ActionKind::SendCommand;
command.text = "/help";
command.source = "offline.act";
command.line = 42;
try
{
ExecuteAction(client, command);
FAIL() << "Offline execution should fail before sending a packet";
}
catch (const std::runtime_error &error)
{
EXPECT_NE(std::string(error.what()).find("offline.act:42:"), std::string::npos);
}
}
TEST(ActionExecutor, ValidatesWorldAndPackedCoordinateBounds)
{
EXPECT_NO_THROW(ValidateActionPosition(-29999984, -2048, 29999984));
EXPECT_NO_THROW(ValidateActionPosition(29999984, 2047, -29999984));
EXPECT_THROW(ValidateActionPosition(29999985, 0, 0), std::runtime_error);
EXPECT_THROW(ValidateActionPosition(0, -2049, 0), std::runtime_error);
EXPECT_THROW(ValidateActionPosition(0, 2048, 0), std::runtime_error);
EXPECT_THROW(ValidateActionPosition(0, 0, INT_MIN), std::runtime_error);
EXPECT_THROW(ValidateActionPosition(INT_MAX, 0, 0), std::runtime_error);
}
TEST(ActionExecutor, MaintainingInputsWithoutShiftDoesNotRequirePlayer)
{
BilicraftClient client;
EXPECT_NO_THROW(MaintainActionInputs(client));
}
TEST(ActionExecutor, ItemOnlyClicksNeverAttackKnownEmptyFrames)
{
EXPECT_EQ(PlanFrameAttack(false, false, false), FrameAttackIntent::None);
EXPECT_EQ(PlanFrameAttack(false, false, true), FrameAttackIntent::None);
EXPECT_EQ(PlanFrameAttack(false, true, false), FrameAttackIntent::TakeItem);
EXPECT_THROW(PlanFrameAttack(false, true, true), std::runtime_error);
}
TEST(ActionExecutor, ExplicitFrameRemovalPlansOnlyTheNecessaryPhases)
{
for (bool creative : {false, true})
{
EXPECT_EQ(PlanFrameAttack(true, false, creative), FrameAttackIntent::RemoveFrame);
EXPECT_EQ(PlanFrameAttack(true, true, creative), FrameAttackIntent::TakeItem);
}
}
TEST(ActionExecutor, ChangedFrameContentsCannotTurnTakeItemIntoAnExtraRemovalAttack)
{
EXPECT_NO_THROW(ValidateFrameAttack(FrameAttackIntent::TakeItem, true, true, false));
EXPECT_THROW(ValidateFrameAttack(FrameAttackIntent::TakeItem, true, false, false), std::runtime_error);
EXPECT_THROW(ValidateFrameAttack(FrameAttackIntent::TakeItem, false, false, false), std::runtime_error);
EXPECT_THROW(ValidateFrameAttack(FrameAttackIntent::TakeItem, false, true, true), std::runtime_error);
EXPECT_NO_THROW(ValidateFrameAttack(FrameAttackIntent::RemoveFrame, true, false, false));
EXPECT_THROW(ValidateFrameAttack(FrameAttackIntent::RemoveFrame, true, true, false), std::runtime_error);
EXPECT_THROW(ValidateFrameAttack(FrameAttackIntent::None, false, false, false), std::runtime_error);
}
} // namespace
+849
View File
@@ -0,0 +1,849 @@
#include "ActionFile.h"
#include <atomic>
#include <chrono>
#include <filesystem>
#include <fstream>
#include <iterator>
#include <limits>
#include <stdexcept>
#include <string>
#include <string_view>
#include <gtest/gtest.h>
namespace
{
namespace fs = std::filesystem;
using Bilicraft::ActionKind;
using Bilicraft::EntityFace;
using Bilicraft::LoadActionFile;
using Bilicraft::ParseInteractiveCommand;
void RejectInteractive(std::string_view text, std::string_view reason = {})
{
try
{
(void)ParseInteractiveCommand(text);
FAIL() << "Expected console rejection for: " << text;
}
catch (const std::runtime_error &error)
{
const std::string message = error.what();
EXPECT_TRUE(message.starts_with("<console>:1:")) << message;
EXPECT_NE(message.find(reason), std::string::npos) << message;
}
}
class ActionFileTest : public ::testing::Test
{
protected:
fs::path base;
fs::path directory;
void SetUp() override
{
// CMake compiles this source with an absolute path. Standalone builds
// should likewise pass its absolute path, or run from the source root.
const auto source = fs::absolute(fs::path(__FILE__)).lexically_normal();
ASSERT_TRUE(fs::is_regular_file(source));
const auto build = source.parent_path().parent_path() / "build";
fs::create_directories(build);
base = fs::canonical(build);
ASSERT_EQ(base.parent_path(), fs::canonical(source.parent_path().parent_path()));
static std::atomic<unsigned long> sequence{0};
const auto stamp = std::chrono::steady_clock::now().time_since_epoch().count();
for (unsigned attempt = 0; attempt < 100; ++attempt)
{
const auto candidate =
base / ("action-file-tests-" + std::to_string(stamp) + "-" + std::to_string(sequence++));
if (fs::create_directory(candidate))
{
directory = fs::canonical(candidate);
return;
}
}
FAIL() << "Unable to allocate unique test directory under " << base;
}
void TearDown() override
{
if (directory.empty())
return;
std::error_code ec;
const auto resolved = fs::canonical(directory, ec);
// Verify the exact absolute deletion target remains our own directory.
ASSERT_FALSE(ec);
ASSERT_EQ(resolved, directory);
ASSERT_EQ(resolved.parent_path(), base);
ASSERT_TRUE(resolved.filename().string().starts_with("action-file-tests-"));
fs::remove_all(resolved, ec);
EXPECT_FALSE(ec);
}
fs::path Write(std::string_view filename, std::string_view contents)
{
const auto path = directory / std::string(filename);
std::ofstream out(path, std::ios::binary);
if (!out || !out.write(contents.data(), static_cast<std::streamsize>(contents.size())))
throw std::runtime_error("Unable to write test file: " + path.string());
return path;
}
Bilicraft::ActionProgram Parse(std::string_view contents)
{
return LoadActionFile(Write("test.act", contents));
}
void Reject(std::string_view contents, std::string_view reason = {}, std::size_t line = 2)
{
const auto path = Write("test.act", contents);
try
{
(void)LoadActionFile(path);
FAIL() << "Expected rejection for: " << contents;
}
catch (const std::runtime_error &error)
{
const std::string message = error.what();
EXPECT_NE(message.find(path.string() + ":" + std::to_string(line) + ":"), std::string::npos) << message;
EXPECT_NE(message.find(reason), std::string::npos) << message;
}
}
};
TEST_F(ActionFileTest, ParsesEveryInstructionAndStoresSourceLocations)
{
const auto program = Parse("# action: farming\n"
"goto -1 +2 3\nrclick 4 5 6 shift\nlclick 7 8 9 shift destory\n"
"grclick 2 9\nglclick 4 1\nsw 9\nswb 3 8 2\n"
"sendcmd /say hello world\nsendmsg hello everyone\nsendmsg @Farmer hello friend\n");
EXPECT_EQ(program.name, "farming");
ASSERT_EQ(program.commands.size(), 10U);
const auto &c = program.commands;
EXPECT_EQ(c[0].kind, ActionKind::Goto);
EXPECT_EQ(c[0].x, -1);
EXPECT_EQ(c[0].y, 2);
EXPECT_EQ(c[0].z, 3);
EXPECT_EQ(c[1].kind, ActionKind::RightClick);
EXPECT_TRUE(c[1].shift);
EXPECT_FALSE(c[1].destroy);
EXPECT_EQ(c[2].kind, ActionKind::LeftClick);
EXPECT_TRUE(c[2].shift);
EXPECT_TRUE(c[2].destroy);
EXPECT_EQ(c[3].kind, ActionKind::GuiRightClick);
EXPECT_EQ(c[3].row, 2);
EXPECT_EQ(c[3].col, 9);
EXPECT_EQ(c[4].kind, ActionKind::GuiLeftClick);
EXPECT_EQ(c[4].row, 4);
EXPECT_EQ(c[4].col, 1);
EXPECT_EQ(c[5].kind, ActionKind::SelectHotbar);
EXPECT_EQ(c[5].slot, 9);
EXPECT_EQ(c[6].kind, ActionKind::SwapBackpack);
EXPECT_EQ(c[6].row, 3);
EXPECT_EQ(c[6].col, 8);
EXPECT_EQ(c[6].slot, 2);
EXPECT_EQ(c[7].kind, ActionKind::SendCommand);
EXPECT_EQ(c[7].text, "/say hello world");
EXPECT_EQ(c[8].kind, ActionKind::SendMessage);
EXPECT_EQ(c[8].text, "hello everyone");
EXPECT_TRUE(c[8].recipient.empty());
EXPECT_EQ(c[9].text, "hello friend");
EXPECT_EQ(c[9].recipient, "Farmer");
for (std::size_t i = 0; i < c.size(); ++i)
{
EXPECT_FALSE(c[i].entity);
EXPECT_EQ(c[i].entityFace, EntityFace::Any);
EXPECT_EQ(c[i].source, directory / "test.act");
EXPECT_EQ(c[i].line, i + 2);
}
}
TEST_F(ActionFileTest, ParsesDropCurrentOrExplicitSlotAndOptionalAll)
{
const auto program = Parse("# action: dropping\ndrop\ndrop 1\ndrop 9\ndrop all\n"
"drop 3 all # entire stack\ndrop all 5\n");
ASSERT_EQ(program.commands.size(), 6U);
const int slots[] = {0, 1, 9, 0, 3, 5};
for (std::size_t i = 0; i < program.commands.size(); ++i)
{
EXPECT_EQ(program.commands[i].kind, ActionKind::Drop);
EXPECT_EQ(program.commands[i].slot, slots[i]);
EXPECT_EQ(program.commands[i].all, i >= 3);
EXPECT_EQ(program.commands[i].line, i + 2);
}
}
TEST_F(ActionFileTest, RejectsInvalidDropSlotsFlagsAndExtraArguments)
{
for (const auto command :
{"drop 0", "drop -1", "drop 10", "drop 2147483648", "drop 1.5", "drop ALL", "drop shift", "drop ?all",
"drop all all", "drop 1 2", "drop 1 all all", "drop all 0", "drop all 1 2", "drop 1 unknown"})
{
SCOPED_TRACE(command);
Reject("# action: test\n" + std::string(command));
}
}
TEST_F(ActionFileTest, DropKeepsCurrentSlotUnresolvedAcrossImports)
{
Write("child.act", "# action: child\ndrop all\n");
const auto program = Parse("# action: parent\nsw 9\nimport child\ndrop 2\n");
ASSERT_EQ(program.commands.size(), 3U);
EXPECT_EQ(program.commands[1].kind, ActionKind::Drop);
EXPECT_EQ(program.commands[1].slot, 0); // Resolve at execution, after sw 9.
EXPECT_TRUE(program.commands[1].all);
EXPECT_EQ(program.commands[1].source, directory / "child.act");
EXPECT_EQ(program.commands[2].slot, 2);
EXPECT_FALSE(program.commands[2].all);
}
TEST_F(ActionFileTest, HandlesBomCrLfWhitespaceAndInlineComments)
{
const auto program = Parse("\xEF\xBB\xBF # ordinary comment\r\n\r\n # action: example # note\r\n"
"\t goto\t1 2 3 # comment\r\n sendmsg hello # removed\r\n# trailing\r\n");
EXPECT_EQ(program.name, "example");
ASSERT_EQ(program.commands.size(), 2U);
EXPECT_EQ(program.commands[0].line, 4U);
EXPECT_EQ(program.commands[1].text, "hello");
}
TEST_F(ActionFileTest, AllowsHeaderOnlyAndNoFinalNewline)
{
EXPECT_TRUE(Parse("# action: empty").commands.empty());
EXPECT_EQ(Parse("# action: test\nsw 1").commands.size(), 1U);
}
TEST_F(ActionFileTest, SupportsDestroyAliasAndEitherFlagOrder)
{
const auto program = Parse("# action: test\nlclick 1 2 3 destroy shift\nlclick 1 2 3 destory\n"
"lclick 1 2 3 shift\nlclick 1 2 3\nrclick 1 2 3\n");
ASSERT_EQ(program.commands.size(), 5U);
EXPECT_TRUE(program.commands[0].shift);
EXPECT_TRUE(program.commands[0].destroy);
EXPECT_TRUE(program.commands[1].destroy);
EXPECT_FALSE(program.commands[1].shift);
EXPECT_TRUE(program.commands[2].shift);
EXPECT_FALSE(program.commands[2].destroy);
EXPECT_FALSE(program.commands[3].shift);
EXPECT_FALSE(program.commands[3].destroy);
EXPECT_FALSE(program.commands[4].shift);
for (const auto &command : program.commands)
{
EXPECT_FALSE(command.entity);
EXPECT_EQ(command.entityFace, EntityFace::Any);
}
}
TEST_F(ActionFileTest, ParsesAllEntryFacesWithShortAndFullNamesInFilesAndConsole)
{
const struct
{
const char *shortName;
const char *fullName;
EntityFace face;
} faces[] = {{"t", "top", EntityFace::Top}, {"b", "bottom", EntityFace::Bottom},
{"s", "south", EntityFace::South}, {"n", "north", EntityFace::North},
{"w", "west", EntityFace::West}, {"e", "east", EntityFace::East}};
for (const auto verb : {"rclick", "lclick"})
{
for (const auto &face : faces)
{
for (const auto token : {face.shortName, face.fullName})
{
const auto text = std::string(verb) + " -1 +2 3 entry " + token + " # frame";
SCOPED_TRACE(text);
const auto program = Parse("# action: test\n" + text);
ASSERT_EQ(program.commands.size(), 1U);
const auto interactive = ParseInteractiveCommand(text);
ASSERT_TRUE(interactive.has_value());
const auto &file = program.commands[0];
for (const auto *command : {&file, &*interactive})
{
EXPECT_EQ(command->kind,
std::string_view(verb) == "rclick" ? ActionKind::RightClick : ActionKind::LeftClick);
EXPECT_EQ(command->x, -1);
EXPECT_EQ(command->y, 2);
EXPECT_EQ(command->z, 3);
EXPECT_TRUE(command->entity);
EXPECT_EQ(command->entityFace, face.face);
EXPECT_FALSE(command->shift);
EXPECT_FALSE(command->destroy);
}
EXPECT_EQ(file.source, directory / "test.act");
EXPECT_EQ(file.line, 2U);
EXPECT_EQ(interactive->source, fs::path("<console>"));
EXPECT_EQ(interactive->line, 1U);
}
}
}
}
TEST_F(ActionFileTest, EntryAllowsOmittedFaceAndEveryLegacyFlagOrder)
{
// Treat entry [face] as one flag group: it may precede, follow or sit
// between the legacy flags, but the face itself cannot move independently.
for (const auto entry : {"entry", "entry n", "entry north"})
{
for (const auto verb : {"rclick", "lclick"})
{
for (const auto suffix : {std::string(entry), std::string(entry) + " shift", "shift " + std::string(entry)})
{
const auto text = std::string(verb) + " 1 2 3 " + suffix;
SCOPED_TRACE(text);
const auto program = Parse("# action: test\n" + text);
ASSERT_EQ(program.commands.size(), 1U);
const auto interactive = ParseInteractiveCommand(text);
ASSERT_TRUE(interactive.has_value());
for (const auto *command : {&program.commands[0], &*interactive})
{
EXPECT_TRUE(command->entity);
EXPECT_EQ(command->entityFace,
std::string_view(entry) == "entry" ? EntityFace::Any : EntityFace::North);
EXPECT_EQ(command->shift, suffix.find("shift") != std::string::npos);
EXPECT_FALSE(command->destroy);
}
}
}
for (const auto destroy : {"destory", "destroy"})
{
const std::string e = entry, d = destroy;
for (const auto &suffix :
{e + " " + d, d + " " + e, e + " shift " + d, e + " " + d + " shift", "shift " + e + " " + d,
"shift " + d + " " + e, d + " " + e + " shift", d + " shift " + e})
{
const auto text = "lclick 1 2 3 " + suffix;
SCOPED_TRACE(text);
const auto program = Parse("# action: test\n" + text);
ASSERT_EQ(program.commands.size(), 1U);
const auto interactive = ParseInteractiveCommand(text);
ASSERT_TRUE(interactive.has_value());
for (const auto *command : {&program.commands[0], &*interactive})
{
EXPECT_TRUE(command->entity);
EXPECT_EQ(command->entityFace, e == "entry" ? EntityFace::Any : EntityFace::North);
EXPECT_EQ(command->shift, suffix.find("shift") != std::string::npos);
EXPECT_TRUE(command->destroy);
}
}
}
}
}
TEST_F(ActionFileTest, RejectsInvalidEntryFacesFlagsAndOrderingInFilesAndConsole)
{
for (const auto text : {"rclick 1 2 3 entry entry",
"lclick 1 2 3 entry n entry",
"lclick 1 2 3 entry entry n",
"rclick 1 2 3 entry n n",
"lclick 1 2 3 entry n north",
"lclick 1 2 3 entry n s",
"rclick 1 2 3 n entry",
"lclick 1 2 3 north entry",
"rclick 1 2 3 entry shift n",
"lclick 1 2 3 entry destroy n",
"lclick 1 2 3 entry destory north",
"lclick 1 2 3 entry n shift e",
"rclick 1 2 3 n",
"lclick 1 2 3 top",
"rclick 1 2 3 shift n",
"rclick 1 2 3 entry any",
"lclick 1 2 3 entry unknown",
"rclick 1 2 3 ENTRY",
"rclick 1 2 3 entry N",
"lclick 1 2 3 entry North",
"rclick 1 2 3 entry shift shift",
"lclick 1 2 3 entry n shift shift",
"lclick 1 2 3 entry destroy destroy",
"lclick 1 2 3 entry destory destroy",
"lclick 1 2 3 entry destroy destory",
"lclick 1 2 3 entry destory destory",
"rclick 1 2 3 entry destroy",
"rclick 1 2 3 entry n destory",
"rclick 1 2 3 destroy entry",
"rclick 1 2 3 destory entry n",
"goto 1 2 3 entry",
"goto 1 2 3 entry n",
"goto 1 2 3 n",
"grclick 1 2 entry",
"glclick 1 2 entry",
"sw 1 entry",
"swb 1 2 3 entry",
"drop entry",
"rclick entry 1 2 3",
"lclick 1 2 entry",
"lclick 1 2 3 entry n shift destroy extra"})
{
SCOPED_TRACE(text);
Reject("# action: test\n" + std::string(text));
RejectInteractive(text);
}
}
TEST_F(ActionFileTest, AcceptsIntegerAndSlotBoundaries)
{
const auto program = Parse("# action: bounds\ngoto -2147483648 2147483647 -0\n"
"grclick 2147483647 9\nglclick 1 1\nsw 1\nsw 9\nswb 1 1 1\nswb 3 9 9\n");
ASSERT_EQ(program.commands.size(), 7U);
EXPECT_EQ(program.commands[0].x, std::numeric_limits<int>::min());
EXPECT_EQ(program.commands[0].y, std::numeric_limits<int>::max());
EXPECT_EQ(program.commands[1].row, std::numeric_limits<int>::max());
}
TEST_F(ActionFileTest, PreservesUtf8NamesAndMessageText)
{
const auto program = Parse("# action: 种田\nsendmsg @玩家 你好 世界\n");
EXPECT_EQ(program.name, "种田");
ASSERT_EQ(program.commands.size(), 1U);
EXPECT_EQ(program.commands[0].recipient, "玩家");
EXPECT_EQ(program.commands[0].text, "你好 世界");
}
TEST_F(ActionFileTest, RejectsMissingHeader)
{
Reject("", "missing action header", 1);
Reject("# ordinary comment", "missing action header", 1);
Reject("goto 1 2 3\n# action: late\n", "before first instruction", 1);
Reject("import child\n# action: late\n", "before first instruction", 1);
}
TEST_F(ActionFileTest, RejectsDuplicateHeaders)
{
Reject("# action: test\n# action: test\n", "duplicate");
Reject("# action: test\nsw 1\n# action: other\n", "duplicate", 3);
}
TEST_F(ActionFileTest, RejectsEmptyAndUnsafeHeaderNames)
{
for (const auto name :
{"", " ", ".", "..", "../evil", "dir/name", "dir\\name", "C:evil", "a b", "a.", "a*", "name.act"})
{
SCOPED_TRACE(name);
Reject("# action: " + std::string(name), "simple filename", 1);
}
}
TEST_F(ActionFileTest, RejectsInvalidIntegers)
{
for (const auto value : {"1.0", "1x", "0x10", "2147483648", "-2147483649", "+", "-", "+-1", "--1", "++1", "1e2"})
{
SCOPED_TRACE(value);
Reject("# action: test\ngoto " + std::string(value) + " 2 3\n", "integer");
}
}
TEST_F(ActionFileTest, RejectsIncorrectArgumentCounts)
{
for (const auto command : {"goto", "goto 1 2", "goto 1 2 3 4", "rclick 1 2", "rclick 1 2 3 shift shift",
"lclick 1 2", "lclick 1 2 3 shift destory extra", "grclick 1", "grclick 1 2 3",
"glclick 1", "glclick 1 2 3", "sw", "sw 1 2", "swb 1 2", "swb 1 2 3 4"})
{
SCOPED_TRACE(command);
Reject("# action: test\n" + std::string(command));
}
}
TEST_F(ActionFileTest, RejectsUnknownAndDuplicateFlags)
{
for (const auto command : {"rclick 1 2 3 destory", "rclick 1 2 3 SHIFT", "rclick 1 2 3 unknown",
"lclick 1 2 3 shift shift", "lclick 1 2 3 destroy destory",
"lclick 1 2 3 destory destory", "lclick 1 2 3 nope", "lclick 1 2 3 destory nope"})
{
SCOPED_TRACE(command);
Reject("# action: test\n" + std::string(command), "unknown or duplicate flag");
}
}
TEST_F(ActionFileTest, RejectsInvalidGuiBackpackAndHotbarRanges)
{
for (const auto command :
{"grclick 0 1", "grclick -1 1", "grclick 1 0", "grclick 1 10", "glclick 0 1", "glclick 1 10", "sw 0", "sw 10",
"sw -1", "swb 0 1 1", "swb 4 1 1", "swb 1 0 1", "swb 1 10 1", "swb 1 1 0", "swb 1 1 10"})
{
SCOPED_TRACE(command);
Reject("# action: test\n" + std::string(command));
}
}
TEST_F(ActionFileTest, RejectsEmptyTextAndMissingRecipientMessages)
{
for (const auto command : {"sendcmd", "sendcmd # comment", "sendcmd /", "sendcmd / ", "sendcmd / # comment",
"sendmsg", "sendmsg @Player", "sendmsg @Player # comment", "sendmsg @ hello"})
{
SCOPED_TRACE(command);
Reject("# action: test\n" + std::string(command));
}
}
TEST_F(ActionFileTest, RejectsUnknownInstructionsAndEmbeddedNul)
{
Reject("# action: test\nunknown 1 2 3", "unknown instruction");
const std::string input = std::string("# action: test\nsendmsg hi") + '\0' + "hidden";
Reject(input, "NUL");
}
TEST_F(ActionFileTest, ExpandsNestedAndRepeatedImportsInExactOrder)
{
Write("leaf.act", "# action: leaf\nsendmsg leaf\n");
Write("child.act", "# action: child\nsendmsg child-before\nimport leaf\nsendmsg child-after\n");
const auto program =
Parse("# action: root\nsendmsg before\nimport child\nsendmsg middle\nimport child\nsendmsg after\n");
EXPECT_EQ(program.name, "root");
ASSERT_EQ(program.commands.size(), 9U);
const std::string expected[] = {"before", "child-before", "leaf", "child-after", "middle",
"child-before", "leaf", "child-after", "after"};
for (std::size_t i = 0; i < 9; ++i)
EXPECT_EQ(program.commands[i].text, expected[i]);
EXPECT_EQ(program.commands[2].source, directory / "leaf.act");
EXPECT_EQ(program.commands[2].line, 2U);
EXPECT_EQ(program.commands[3].source, directory / "child.act");
EXPECT_EQ(program.commands[3].line, 4U);
EXPECT_EQ(program.commands[8].source, directory / "test.act");
EXPECT_EQ(program.commands[8].line, 6U);
}
TEST_F(ActionFileTest, AllowsEmptyImports)
{
Write("empty.act", "# action: empty\n");
EXPECT_TRUE(Parse("# action: root\nimport empty\nimport empty\n").commands.empty());
}
TEST_F(ActionFileTest, RejectsMissingImportWithImportSite)
{
Reject("# action: root\nimport missing\n", "cannot import 'missing'");
}
TEST_F(ActionFileTest, RejectsImportHeaderMismatchWithBothLocations)
{
const auto child = Write("child.act", "# action: different\n");
Reject("# action: root\nimport child\n", child.string() + ":1:");
Reject("# action: root\nimport child\n", "does not match imported name");
}
TEST_F(ActionFileTest, ReportsImportedSyntaxErrorWithBothLocations)
{
const auto child = Write("child.act", "# action: child\nsw 99\n");
Reject("# action: root\nimport child\n", child.string() + ":2:");
}
TEST_F(ActionFileTest, RejectsDirectAndIndirectCycles)
{
Reject("# action: test\nimport test\n", "cyclic import");
Write("child.act", "# action: child\nimport test\n");
Reject("# action: test\nimport child\n", "cyclic import");
}
TEST_F(ActionFileTest, RejectsUnsafeImportPathsAndArity)
{
for (const auto name : {"", "../child", "./child", "/child", "folder/child", "folder\\child", "C:child", ".", "..",
"child extra", "child.act"})
{
SCOPED_TRACE(name);
Reject("# action: test\nimport " + std::string(name), "one simple action name");
}
}
TEST_F(ActionFileTest, RejectsSymlinkImportEscapingDirectory)
{
fs::create_directory(directory / "outside");
const auto outside = Write("outside/child.act", "# action: child\nsw 1\n");
std::error_code ec;
fs::create_symlink(outside, directory / "child.act", ec);
if (ec)
GTEST_SKIP() << "Symlinks unavailable: " << ec.message();
Reject("# action: test\nimport child\n", "escapes");
}
TEST_F(ActionFileTest, RejectsMissingAndNonregularRootFiles)
{
EXPECT_THROW(LoadActionFile(directory / "missing.act"), std::runtime_error);
fs::create_directory(directory / "folder.act");
EXPECT_THROW(LoadActionFile(directory / "folder.act"), std::runtime_error);
}
TEST_F(ActionFileTest, RejectsEntryFilesWithoutActExtension)
{
for (const auto name : {"plain", "test.txt", "test.ACT", "test.act.bak"})
{
const auto path = Write(name, "# action: test\n");
try
{
(void)LoadActionFile(path);
FAIL() << "Accepted unsupported extension: " << name;
}
catch (const std::runtime_error &error)
{
const std::string message = error.what();
EXPECT_NE(message.find(path.string() + ":1:"), std::string::npos);
EXPECT_NE(message.find(".act extension"), std::string::npos);
}
}
}
TEST_F(ActionFileTest, PreservesCommandsWithOrWithoutLeadingSlash)
{
const auto program = Parse("# action: test\nsendcmd /say hi there\nsendcmd say hi there\n");
ASSERT_EQ(program.commands.size(), 2U);
EXPECT_EQ(program.commands[0].text, "/say hi there");
EXPECT_EQ(program.commands[1].text, "say hi there");
}
TEST_F(ActionFileTest, ParsesWaitDefaultUnitEveryUnitAndZero)
{
const auto program = Parse("# action: waits\nwait 2\nwait 2 s\nwait 2 ms\nwait 2 min\nwait 2 h\nwait 2 d\n"
"wait 0\nwait 0 s\nwait 0 ms\nwait 0 min\nwait 0 h\nwait 0 d\n");
const std::chrono::milliseconds::rep expected[] = {2000, 2000, 2, 120000, 7200000, 172800000, 0, 0, 0, 0, 0, 0};
ASSERT_EQ(program.commands.size(), std::size(expected));
for (std::size_t i = 0; i < program.commands.size(); ++i)
{
EXPECT_EQ(program.commands[i].kind, ActionKind::Wait);
EXPECT_EQ(program.commands[i].waitDuration.count(), expected[i]);
EXPECT_EQ(program.commands[i].source, directory / "test.act");
EXPECT_EQ(program.commands[i].line, i + 2);
}
}
TEST_F(ActionFileTest, ParsesExactWaitFractionsWithoutRounding)
{
const auto program = Parse("# action: waits\nwait 0.001\nwait 1.125 s\nwait 1.000 ms\nwait 0.00005 min\n"
"wait 0.000005 h\nwait 0.0000003125 d\nwait 0002.500000 s\n"
"wait 0.0000000000000000000000000 ms\nwait 0.1230000000000000000000000 s\n");
const std::chrono::milliseconds::rep expected[] = {1, 1125, 1, 3, 18, 27, 2500, 0, 123};
ASSERT_EQ(program.commands.size(), std::size(expected));
for (std::size_t i = 0; i < program.commands.size(); ++i)
EXPECT_EQ(program.commands[i].waitDuration.count(), expected[i]);
}
TEST_F(ActionFileTest, AcceptsWaitLimitInEveryUnitAndRejectsOverflow)
{
for (const auto duration : {"31536000", "31536000 s", "31536000000 ms", "525600 min", "8760 h", "365 d",
"365.000000000000000000000000000000 d"})
{
SCOPED_TRACE(duration);
const auto program = Parse("# action: waits\nwait " + std::string(duration));
ASSERT_EQ(program.commands.size(), 1U);
EXPECT_EQ(program.commands[0].waitDuration.count(), 31536000000LL);
}
for (const auto duration :
{"31536000.001", "31536000.001 s", "31536000001 ms", "525600.00005 min", "8760.000005 h", "365.0000003125 d",
"366 d", "999999999999999999999999999999999999 s", "18446744073709551616 ms", "9223372036854775808 d"})
{
SCOPED_TRACE(duration);
Reject("# action: waits\nwait " + std::string(duration), "365 days");
}
}
TEST_F(ActionFileTest, RejectsSubMillisecondWaitFractions)
{
for (const auto duration : {"0.0001", "0.0001 s", "0.5 ms", "0.00001 min", "0.0000001 h", "0.000000001 d",
"0.000000000000000000000000000000000001 s", "1.0000000000000000000000001 ms"})
{
SCOPED_TRACE(duration);
Reject("# action: waits\nwait " + std::string(duration), "whole number of milliseconds");
}
}
TEST_F(ActionFileTest, RejectsInvalidWaitNumbersUnitsAndArgumentCounts)
{
for (const auto command :
{"wait", "wait s", "wait -1", "wait -0", "wait +1", "wait NaN", "wait nan",
"wait Inf", "wait inf", "wait infinity", "wait 1e3", "wait 1E3", "wait 0x10", "wait 1,5",
"wait .", "wait .5", "wait 1.", "wait 1.2.3", "wait 1s", "wait 1 S", "wait 1 m",
"wait 1 sec", "wait 1 seconds", "wait 1 unknown", "wait 1 ms extra", "wait 1 2 3", "wait 1 s ms"})
{
SCOPED_TRACE(command);
Reject("# action: waits\n" + std::string(command));
}
}
TEST_F(ActionFileTest, KeepsWaitImportOrderingLocationsAndErrorContext)
{
const auto child = Write("child.act", "# action: child\nwait 0.125 s\n");
const auto program = Parse("# action: parent\nwait 0\nimport child\nsendmsg still here\nwait 2 ms # pause\n");
ASSERT_EQ(program.commands.size(), 4U);
EXPECT_EQ(program.commands[0].waitDuration.count(), 0);
EXPECT_EQ(program.commands[1].kind, ActionKind::Wait);
EXPECT_EQ(program.commands[1].waitDuration.count(), 125);
EXPECT_EQ(program.commands[1].source, child);
EXPECT_EQ(program.commands[1].line, 2U);
EXPECT_EQ(program.commands[2].text, "still here");
EXPECT_EQ(program.commands[3].waitDuration.count(), 2);
Write("child.act", "# action: child\nwait 366 d\n");
Reject("# action: parent\nimport child\n", child.string() + ":2:");
}
TEST(InteractiveCommandTest, BlankAndCommentLinesHaveNoCommand)
{
for (const auto text : {"", " ", "\t", "# comment", " \t# action: not-a-file", "# wait 1", "# import child"})
EXPECT_FALSE(ParseInteractiveCommand(text).has_value()) << text;
}
TEST_F(ActionFileTest, InteractiveCommandsReuseEveryGameInstructionAndFlag)
{
for (const auto text : {"goto -1 +2 3",
"rclick 1 2 3",
"rclick 1 2 3 shift",
"lclick 1 2 3",
"lclick 1 2 3 destroy shift",
"lclick 1 2 3 shift destory",
"lclick 1 2 3 destory shift",
"lclick 1 2 3 shift destroy",
"rclick 1 2 3 entry",
"rclick 1 2 3 entry t shift",
"rclick 1 2 3 shift entry bottom",
"lclick 1 2 3 entry",
"lclick 1 2 3 entry south",
"lclick 1 2 3 entry n shift destroy",
"lclick 1 2 3 shift entry w destory",
"lclick 1 2 3 destory shift entry east",
"lclick 1 2 3 destroy entry shift",
"grclick 2 9",
"glclick 4 1",
"sw 9",
"swb 3 8 2",
"drop",
"drop all",
"drop 3",
"drop 3 all",
"drop all 3",
"sendcmd /say hello world",
"sendcmd say hi",
"sendmsg hello everyone",
"sendmsg @Farmer hello friend",
"sendmsg @玩家 你好 世界",
"\t sw\t2 # inline comment"})
{
SCOPED_TRACE(text);
const auto interactive = ParseInteractiveCommand(text);
ASSERT_TRUE(interactive.has_value());
const auto program = Parse("# action: test\n" + std::string(text));
ASSERT_EQ(program.commands.size(), 1U);
const auto &file = program.commands[0];
EXPECT_EQ(interactive->kind, file.kind);
EXPECT_EQ(interactive->x, file.x);
EXPECT_EQ(interactive->y, file.y);
EXPECT_EQ(interactive->z, file.z);
EXPECT_EQ(interactive->row, file.row);
EXPECT_EQ(interactive->col, file.col);
EXPECT_EQ(interactive->slot, file.slot);
EXPECT_EQ(interactive->shift, file.shift);
EXPECT_EQ(interactive->destroy, file.destroy);
EXPECT_EQ(interactive->entity, file.entity);
EXPECT_EQ(interactive->entityFace, file.entityFace);
EXPECT_EQ(interactive->all, file.all);
EXPECT_EQ(interactive->text, file.text);
EXPECT_EQ(interactive->recipient, file.recipient);
EXPECT_EQ(interactive->waitDuration, std::chrono::milliseconds{0});
EXPECT_EQ(interactive->waitDuration, file.waitDuration);
EXPECT_EQ(interactive->source, fs::path("<console>"));
EXPECT_EQ(interactive->line, 1U);
}
}
TEST(InteractiveCommandTest, PreservesMessageTextAndInlineCommentRules)
{
auto command = ParseInteractiveCommand(" sendmsg @玩家 你好 世界 # hidden");
ASSERT_TRUE(command.has_value());
EXPECT_EQ(command->recipient, "玩家");
EXPECT_EQ(command->text, "你好 世界");
command = ParseInteractiveCommand("sendmsg run child.act; wait 1");
ASSERT_TRUE(command.has_value());
EXPECT_EQ(command->kind, ActionKind::SendMessage);
EXPECT_EQ(command->text, "run child.act; wait 1");
}
TEST(InteractiveCommandTest, RejectsWaitAndImportWithRunGuidance)
{
for (const auto text : {"wait 0", "wait 1 s", "wait", "wait nonsense", "import child", "import ../child", "import"})
{
SCOPED_TRACE(text);
RejectInteractive(text, "run file.act");
}
}
TEST(InteractiveCommandTest, RejectsInvalidGameCommandsWithConsoleLocation)
{
for (const auto text :
{"unknown", "goto", "goto 1 2 3 4", "goto 2147483648 1 2", "rclick 1 2 3 destroy", "lclick 1 2 3 shift shift",
"grclick 0 1", "glclick 1 10", "sw 0", "swb 4 1 2", "drop all all", "drop 0", "sendcmd", "sendcmd /",
"sendmsg", "sendmsg @Player", "sendmsg @ hello", "run file.act", "sw 1; sw 2"})
{
SCOPED_TRACE(text);
RejectInteractive(text);
}
}
TEST(InteractiveCommandTest, RejectsNewlineAndNulEvenInsideComments)
{
for (const auto text : {"\n", "\r", "sw 1\n", "sw 1\r\n", "sw 1\nsw 2", "sendmsg hi\rsw 2", "# comment\nsw 2",
"# comment\r", "sendcmd /say hello\n/stop"})
{
SCOPED_TRACE(text);
RejectInteractive(text, "one line");
}
RejectInteractive(std::string("sendmsg hi") + '\0' + "hidden", "NUL");
RejectInteractive(std::string("# comment") + '\0', "NUL");
RejectInteractive(std::string(1, '\0'), "NUL");
}
TEST_F(ActionFileTest, EnforcesDepthLimitAndAcceptsBoundary)
{
for (int i = 0; i < 32; ++i)
{
std::string body = "# action: depth" + std::to_string(i) + "\n";
if (i != 31)
body += "import depth" + std::to_string(i + 1) + "\n";
Write("depth" + std::to_string(i) + ".act", body);
}
EXPECT_TRUE(LoadActionFile(directory / "depth0.act").commands.empty());
Reject("# action: root\nimport depth0\n", "depth limit");
}
TEST_F(ActionFileTest, EnforcesExpandedCommandLimitAndAcceptsBoundary)
{
std::string contents = "# action: test\n";
for (int i = 0; i < 100000; ++i)
contents += "sw 1\n";
EXPECT_EQ(Parse(contents).commands.size(), 100000U);
contents += "sw 1\n";
Reject(contents, "expanded command limit", 100002);
}
TEST_F(ActionFileTest, EnforcesExpandedCommandLimitAcrossImports)
{
std::string child = "# action: child\n";
for (int i = 0; i < 50001; ++i)
child += "sw 1\n";
Write("child.act", child);
Reject("# action: root\nimport child\nimport child\n", "expanded command limit", 3);
}
TEST_F(ActionFileTest, EnforcesIndividualFileSizeLimit)
{
std::string contents = "# action: test\n#";
contents.resize(1024 * 1024, 'x');
EXPECT_TRUE(Parse(contents).commands.empty());
contents += 'x';
Reject(contents, "file size limit", 1);
}
TEST_F(ActionFileTest, EnforcesTotalInputSizeLimit)
{
std::string child = "# action: child\n#";
child.resize(1024 * 1024, 'x');
Write("child.act", child);
std::string contents = "# action: root\n";
for (int i = 0; i < 16; ++i)
contents += "import child\n";
Reject(contents, "total action input limit", 17);
}
TEST_F(ActionFileTest, EnforcesLoadLimitEvenForEmptyImports)
{
Write("empty.act", "# action: empty\n");
std::string contents = "# action: root\n";
for (int i = 0; i < 4096; ++i)
contents += "import empty\n";
Reject(contents, "file load limit", 4097);
}
} // namespace
+177
View File
@@ -0,0 +1,177 @@
#include "ActionScheduler.h"
#include <gtest/gtest.h>
using namespace std::chrono_literals;
namespace
{
using namespace Bilicraft;
ActionCommand Command(std::string text)
{
ActionCommand command{};
command.kind = ActionKind::SendMessage;
command.text = std::move(text);
return command;
}
ActionCommand Wait(std::chrono::milliseconds delay)
{
ActionCommand command{};
command.kind = ActionKind::Wait;
command.waitDuration = delay;
return command;
}
const ActionScheduler::Clock::time_point start{};
TEST(ActionScheduler, NewestActionFirstButRunningActionIsNotPreempted)
{
ActionScheduler queue;
queue.Enqueue({"old", {Command("old")}});
queue.Enqueue({"new", {Command("new1"), Command("new2")}});
ASSERT_EQ(queue.Next(start)->command.text, "new1");
queue.Enqueue({"newest", {Command("newest")}});
queue.Finish(true);
EXPECT_EQ(queue.Next(start)->command.text, "new2");
queue.Finish(true);
EXPECT_EQ(queue.Next(start)->command.text, "newest");
queue.Finish(true);
EXPECT_EQ(queue.Next(start)->command.text, "old");
queue.Finish(true);
EXPECT_FALSE(queue.HasWork());
}
TEST(ActionScheduler, WaitBlocksOnlyItsActionAndResumesAtFollowingCommand)
{
ActionScheduler queue;
queue.Enqueue({"other", {Command("other")}});
const auto id = queue.Enqueue({"waiting", {Wait(2s), Command("resumed")}});
EXPECT_EQ(queue.Next(start)->command.text, "other");
const auto tasks = queue.Tasks();
ASSERT_EQ(tasks.size(), 2U);
EXPECT_EQ(tasks[1].id, id);
EXPECT_EQ(tasks[1].state, ActionScheduler::State::Blocked);
EXPECT_EQ(tasks[1].nextCommand, 1U);
queue.Finish(true);
EXPECT_FALSE(queue.Next(start + 1999ms));
EXPECT_EQ(queue.NextWake(), start + 2s);
EXPECT_EQ(queue.Next(start + 2s)->command.text, "resumed");
queue.Finish(true);
EXPECT_FALSE(queue.HasWork());
}
TEST(ActionScheduler, InteractiveWaitsForActionBoundaryButWinsOverQueuedTasks)
{
ActionScheduler queue;
queue.Enqueue({"active", {Command("a"), Command("b")}});
queue.Next(start);
queue.SubmitInteractive(Command("interactive"));
queue.Enqueue({"queued", {Command("queued")}});
EXPECT_THROW(queue.SubmitInteractive(Command("second")), std::runtime_error);
queue.Finish(true);
EXPECT_EQ(queue.Next(start)->command.text, "b");
queue.Finish(true);
auto work = queue.Next(start);
ASSERT_TRUE(work);
EXPECT_TRUE(work->interactive);
EXPECT_EQ(work->command.text, "interactive");
EXPECT_TRUE(queue.InteractivePending());
queue.Finish(true);
EXPECT_FALSE(queue.InteractivePending());
EXPECT_EQ(queue.Next(start)->command.text, "queued");
}
TEST(ActionScheduler, InteractiveRunsWhenActiveActionReachesWait)
{
ActionScheduler queue;
queue.Enqueue({"active", {Command("a"), Wait(10s), Command("b")}});
queue.Next(start);
queue.SubmitInteractive(Command("interactive"));
queue.Finish(true);
EXPECT_TRUE(queue.Next(start)->interactive);
queue.Finish(true);
EXPECT_FALSE(queue.Next(start + 1s));
EXPECT_EQ(queue.Next(start + 10s)->command.text, "b");
}
TEST(ActionScheduler, AwakenedActionDoesNotInterruptRunningAction)
{
ActionScheduler queue;
queue.Enqueue({"other", {Command("a"), Command("b")}});
queue.Enqueue({"sleeper", {Wait(1s), Command("awake")}});
EXPECT_EQ(queue.Next(start)->command.text, "a");
queue.Finish(true);
EXPECT_EQ(queue.Next(start + 2s)->command.text, "b");
queue.Finish(true);
EXPECT_EQ(queue.Next(start + 2s)->command.text, "awake");
}
TEST(ActionScheduler, ZeroWaitYieldsAndFinalWaitCompletesOnlyAfterDeadline)
{
ActionScheduler queue;
queue.Enqueue({"other", {Command("other")}});
queue.Enqueue({"zero", {Wait(0ms), Command("zero")}});
EXPECT_EQ(queue.Next(start)->command.text, "other");
queue.Finish(true);
EXPECT_EQ(queue.Next(start)->command.text, "zero");
queue.Finish(true);
queue.Enqueue({"final", {Wait(1h)}});
EXPECT_FALSE(queue.Next(start));
EXPECT_TRUE(queue.HasWork());
EXPECT_FALSE(queue.Next(start + 1h));
EXPECT_FALSE(queue.HasWork());
}
TEST(ActionScheduler, FailedActionDoesNotDiscardOtherJobsOrPendingInteractive)
{
ActionScheduler queue;
queue.Enqueue({"other", {Command("other")}});
queue.Enqueue({"bad", {Command("fail"), Command("must not execute")}});
queue.Next(start);
queue.SubmitInteractive(Command("interactive"));
queue.Finish(false);
EXPECT_TRUE(queue.Next(start)->interactive);
queue.Finish(false);
EXPECT_FALSE(queue.InteractivePending());
EXPECT_EQ(queue.Next(start)->command.text, "other");
}
TEST(ActionScheduler, RejectsInteractiveWaitInvalidDurationsAndDuplicateDispatch)
{
ActionScheduler queue;
EXPECT_THROW(queue.SubmitInteractive(Wait(1s)), std::runtime_error);
EXPECT_THROW(queue.Enqueue({"bad", {Wait(-1ms)}}), std::runtime_error);
EXPECT_THROW(queue.Enqueue({"bad", {Wait(24h * 366)}}), std::runtime_error);
EXPECT_THROW(queue.Finish(true), std::logic_error);
queue.Enqueue({"good", {Command("one")}});
queue.Next(start);
EXPECT_THROW(queue.Next(start), std::logic_error);
queue.Finish(true);
EXPECT_FALSE(queue.Next(start));
}
TEST(ActionScheduler, MultipleWakeupsUseNewestReadyOrderAndInteractivePriority)
{
ActionScheduler queue;
queue.Enqueue({"later", {Wait(2s), Command("later")}});
queue.Enqueue({"earlier", {Wait(1s), Command("earlier")}});
EXPECT_FALSE(queue.Next(start));
queue.SubmitInteractive(Command("interactive"));
EXPECT_TRUE(queue.Next(start + 3s)->interactive);
queue.Finish(true);
EXPECT_EQ(queue.Next(start + 3s)->command.text, "later");
queue.Finish(true);
EXPECT_EQ(queue.Next(start + 3s)->command.text, "earlier");
}
TEST(ActionScheduler, NewSubmissionAfterWaitExpiryIsNewerThanTheAwakenedTask)
{
ActionScheduler queue;
queue.Enqueue({"running", {Command("long")}}, start);
queue.Enqueue({"sleeping", {Wait(1s), Command("awake")}}, start);
EXPECT_EQ(queue.Next(start)->command.text, "long");
queue.Enqueue({"new submission", {Command("new")}}, start + 5s);
queue.Finish(true);
EXPECT_EQ(queue.Next(start + 10s)->command.text, "new");
queue.Finish(true);
EXPECT_EQ(queue.Next(start + 10s)->command.text, "awake");
}
} // namespace
+86
View File
@@ -0,0 +1,86 @@
#include "AppConfig.h"
#include <initializer_list>
#include <stdexcept>
#include <string_view>
#include <gtest/gtest.h>
namespace
{
Bilicraft::AppConfig Parse(std::initializer_list<std::string_view> arguments)
{
return Bilicraft::ParseArguments({arguments.begin(), arguments.size()});
}
TEST(AppConfig, DefaultsMatchBilicraftServer)
{
const auto config = Parse({});
EXPECT_EQ(config.server, "mc.bilicraft.com:25577");
EXPECT_EQ(Bilicraft::kGameVersion, "1.21.11");
EXPECT_TRUE(config.account.empty());
EXPECT_FALSE(config.help);
}
TEST(AppConfig, OverridesServerAndCacheKey)
{
const auto config = Parse({"--server", "localhost:25565", "--account", "farmer"});
EXPECT_EQ(config.server, "localhost:25565");
EXPECT_EQ(config.account, "farmer");
}
TEST(AppConfig, LastRepeatedOptionWins)
{
const auto config = Parse({"--account", "first", "--account", "second"});
EXPECT_EQ(config.account, "second");
}
TEST(AppConfig, AcceptsHelpAliases)
{
EXPECT_TRUE(Parse({"--help"}).help);
EXPECT_TRUE(Parse({"-h"}).help);
}
TEST(AppConfig, RejectsUnknownOptionsAndPositionalArguments)
{
EXPECT_THROW(Parse({"--unknown"}), std::invalid_argument);
EXPECT_THROW(Parse({"localhost:25565"}), std::invalid_argument);
}
TEST(AppConfig, RejectsMissingValues)
{
EXPECT_THROW(Parse({"--server"}), std::invalid_argument);
EXPECT_THROW(Parse({"--account"}), std::invalid_argument);
EXPECT_THROW(Parse({"--server", "--account", "farmer"}), std::invalid_argument);
EXPECT_THROW(Parse({"--account", "--help"}), std::invalid_argument);
}
TEST(AppConfig, RejectsEmptyValues)
{
EXPECT_THROW(Parse({"--server", ""}), std::invalid_argument);
EXPECT_THROW(Parse({"--account", ""}), std::invalid_argument);
}
TEST(AppConfig, ActionExecutionAndOfflineCheck)
{
auto config = Parse({"--action", "farm.act"});
EXPECT_EQ(config.actionFile, "farm.act");
EXPECT_FALSE(config.checkAction);
config = Parse({"--check-action", "farm.act"});
EXPECT_EQ(config.actionFile, "farm.act");
EXPECT_TRUE(config.checkAction);
EXPECT_THROW(Parse({"--action"}), std::invalid_argument);
EXPECT_THROW(Parse({"--check-action", ""}), std::invalid_argument);
EXPECT_THROW(Parse({"--action", "a.act", "--check-action", "b.act"}), std::invalid_argument);
EXPECT_THROW(Parse({"--action", "a.act", "--action", "b.act"}), std::invalid_argument);
}
TEST(AppConfig, HelpDescribesDefaultsAndMicrosoftAuthentication)
{
const auto usage = Bilicraft::Usage();
EXPECT_TRUE(usage.starts_with("Usage: bilicraft-bot "));
EXPECT_NE(usage.find("1.21.11"), std::string::npos);
EXPECT_NE(usage.find("mc.bilicraft.com:25577"), std::string::npos);
EXPECT_NE(usage.find("Microsoft"), std::string::npos);
}
} // namespace
+75
View File
@@ -0,0 +1,75 @@
#include "BilicraftClient.h"
#include <string>
#include <stdexcept>
#include <gtest/gtest.h>
namespace
{
ProtocolCraft::Chat DisconnectReason()
{
// Protocol 774 encodes chat as unnamed NBT. A string tag is sufficient.
const std::string reason = "Test disconnect";
ProtocolCraft::WriteContainer bytes{8};
ProtocolCraft::WriteData<unsigned short>(static_cast<unsigned short>(reason.size()), bytes);
bytes.insert(bytes.end(), reason.begin(), reason.end());
auto iterator = bytes.cbegin();
auto remaining = bytes.size();
ProtocolCraft::Chat chat;
chat.Read(iterator, remaining);
return chat;
}
TEST(BilicraftClient, StartsWithoutNetworkOrGameSession)
{
Bilicraft::BilicraftClient client;
EXPECT_FALSE(client.GetNetworkManager());
EXPECT_FALSE(client.WasDisconnected());
EXPECT_FALSE(client.HasEnteredPlay());
EXPECT_FALSE(client.GetAutoRespawn());
client.Disconnect();
client.Disconnect(); // Cleanup is intentionally idempotent.
}
TEST(BilicraftClient, ActionYieldRunsSynchronouslyAndPropagatesCancellation)
{
Bilicraft::BilicraftClient client;
int ticks = 0;
client.SetActionYieldHandler([&ticks] { ++ticks; });
client.Yield();
client.Yield();
EXPECT_EQ(ticks, 2);
client.SetActionYieldHandler([] { throw std::runtime_error("cancelled"); });
EXPECT_THROW(client.Yield(), std::runtime_error);
client.SetActionYieldHandler({});
}
TEST(BilicraftClient, LoginDisconnectSignalsMainThread)
{
Bilicraft::BilicraftClient client;
ProtocolCraft::ClientboundLoginDisconnectPacket packet;
packet.SetReason(R"({"text":"Test disconnect"})");
packet.Dispatch(&client);
EXPECT_TRUE(client.WasDisconnected());
EXPECT_FALSE(client.HasEnteredPlay());
}
TEST(BilicraftClient, ConfigurationDisconnectSignalsMainThread)
{
Bilicraft::BilicraftClient client;
ProtocolCraft::ClientboundDisconnectConfigurationPacket packet;
packet.SetReason(DisconnectReason());
packet.Dispatch(&client);
EXPECT_TRUE(client.WasDisconnected());
}
TEST(BilicraftClient, PlayDisconnectSignalsMainThread)
{
Bilicraft::BilicraftClient client;
ProtocolCraft::ClientboundDisconnectPacket packet;
packet.SetReason(DisconnectReason());
packet.Dispatch(&client);
EXPECT_TRUE(client.WasDisconnected());
}
} // namespace
+125
View File
@@ -0,0 +1,125 @@
#include "ConsoleCommand.h"
#include "ActionScheduler.h"
#include "TerminalInput.h"
#include <gtest/gtest.h>
#include <thread>
#ifndef _WIN32
#include <cstdlib>
#include <fcntl.h>
#include <unistd.h>
#endif
namespace
{
using namespace Bilicraft;
TEST(ConsoleCommand, ParsesControlCommandsAndPathsWithSpaces)
{
EXPECT_EQ(ParseConsoleCommand(" ").kind, ConsoleKind::Empty);
EXPECT_EQ(ParseConsoleCommand("# comment").kind, ConsoleKind::Empty);
EXPECT_EQ(ParseConsoleCommand("help # help").kind, ConsoleKind::Help);
EXPECT_EQ(ParseConsoleCommand("tasks").kind, ConsoleKind::Tasks);
EXPECT_EQ(ParseConsoleCommand("exit").kind, ConsoleKind::Quit);
EXPECT_EQ(ParseConsoleCommand("quit").kind, ConsoleKind::Quit);
EXPECT_EQ(ParseConsoleCommand("run ../../actions/demo.act").path, "../../actions/demo.act");
EXPECT_EQ(ParseConsoleCommand("run \"path with spaces.act\"").path, "path with spaces.act");
EXPECT_EQ(ParseConsoleCommand("run 'path with spaces.act'").path, "path with spaces.act");
}
TEST(ConsoleCommand, RejectsInvalidControlsAndInteractiveWaitOrImport)
{
for (auto text : {"run", "run \"\"", "help now", "tasks 1", "quit now", "wait 3", "import demo",
"sw 1\nsw 2", "sw 1\rsw 2"})
EXPECT_THROW(ParseConsoleCommand(text), std::exception) << text;
EXPECT_THROW(ParseConsoleCommand(std::string("sw 1\0x", 6)), std::exception);
}
TEST(ConsoleCommand, UsesTheSameGameCommandParser)
{
const auto message = ParseConsoleCommand("sendmsg @Steve hello world");
ASSERT_EQ(message.kind, ConsoleKind::Action);
ASSERT_TRUE(message.action);
EXPECT_EQ(message.action->recipient, "Steve");
EXPECT_EQ(message.action->text, "hello world");
EXPECT_EQ(ParseConsoleCommand("drop all").action->kind, ActionKind::Drop);
EXPECT_TRUE(ParseConsoleCommand("drop all").action->all);
}
#ifndef _WIN32
TEST(ConsoleCommand, NativePseudoTerminalWaitsForEnterAndParsesTheCommand)
{
const int master = posix_openpt(O_RDWR | O_NOCTTY);
ASSERT_GE(master, 0);
struct Fd
{
int value;
~Fd() { if (value >= 0) close(value); }
} masterGuard{master};
ASSERT_EQ(grantpt(master), 0);
ASSERT_EQ(unlockpt(master), 0);
const char *name = ptsname(master);
ASSERT_NE(name, nullptr);
const int slave = open(name, O_RDWR | O_NOCTTY);
ASSERT_GE(slave, 0);
Fd slaveGuard{slave};
TerminalInput terminal(slave);
ASSERT_TRUE(terminal.IsInteractive());
ASSERT_EQ(write(master, "sw 3", 4), 4);
EXPECT_FALSE(terminal.PollLine());
ASSERT_EQ(write(master, "\n", 1), 1);
// Delivery through a PTY can be asynchronous; a bounded poll, not a blocking read.
std::optional<std::string> line;
const auto deadline = ActionScheduler::Clock::now() + std::chrono::seconds(1);
while (!line && ActionScheduler::Clock::now() < deadline)
{
line = terminal.PollLine();
if (!line) std::this_thread::yield();
}
ASSERT_TRUE(line);
const auto command = ParseConsoleCommand(*line);
ASSERT_TRUE(command.action);
EXPECT_EQ(command.action->kind, ActionKind::SelectHotbar);
EXPECT_EQ(command.action->slot, 3);
}
TEST(ConsoleCommand, PipeInputDoesNotConsumeNextCommandUntilPreviousExecutionFinishes)
{
int descriptors[2];
ASSERT_EQ(pipe(descriptors), 0);
struct Close
{
int a, b;
~Close() { close(a); close(b); }
} closePipe{descriptors[0], descriptors[1]};
const std::string input = "sendmsg first\nsendmsg second\n";
ASSERT_EQ(write(descriptors[1], input.data(), input.size()), static_cast<ssize_t>(input.size()));
TerminalInput terminal(descriptors[0]);
ActionScheduler scheduler;
const auto now = ActionScheduler::Clock::time_point{};
scheduler.Enqueue({"active", {*ParseInteractiveCommand("sendmsg active")}});
auto work = scheduler.Next(now);
ASSERT_EQ(work->command.text, "active");
int linesRead = 0;
const auto pump = [&] {
if (scheduler.InteractivePending()) return;
if (auto line = terminal.PollLine())
{
++linesRead;
scheduler.SubmitInteractive(*ParseConsoleCommand(*line).action);
}
};
pump();
pump();
EXPECT_EQ(linesRead, 1);
scheduler.Finish(true);
work = scheduler.Next(now);
ASSERT_TRUE(work->interactive);
EXPECT_EQ(work->command.text, "first");
pump();
EXPECT_EQ(linesRead, 1);
scheduler.Finish(true);
pump();
EXPECT_EQ(linesRead, 2);
EXPECT_EQ(scheduler.Next(now)->command.text, "second");
}
#endif
} // namespace
+325
View File
@@ -0,0 +1,325 @@
#include "EntityInteraction.h"
#include <array>
#include <climits>
#include <limits>
#include <stdexcept>
#include <gtest/gtest.h>
#include "botcraft/Game/Entities/EntityManager.hpp"
#include "botcraft/Game/Entities/entities/UnknownEntity.hpp"
#include "botcraft/Game/Entities/entities/decoration/GlowItemFrameEntity.hpp"
#include "botcraft/Game/Entities/entities/decoration/ItemFrameEntity.hpp"
#include "botcraft/Game/Entities/entities/decoration/painting/PaintingEntity.hpp"
#include "protocolCraft/Packets/Game/Serverbound/ServerboundInteractPacket.hpp"
namespace
{
using namespace Bilicraft;
using Botcraft::Vector3;
struct FaceCase
{
EntityFace face;
int direction;
Vector3<double> normal;
};
const std::array<FaceCase, 6> Faces = {{{EntityFace::Bottom, 0, {0, -1, 0}},
{EntityFace::Top, 1, {0, 1, 0}},
{EntityFace::North, 2, {0, 0, -1}},
{EntityFace::South, 3, {0, 0, 1}},
{EntityFace::West, 4, {-1, 0, 0}},
{EntityFace::East, 5, {1, 0, 0}}}};
ActionCommand Command(int x = 0, int y = 0, int z = 0, EntityFace face = EntityFace::Any)
{
ActionCommand command{};
command.kind = ActionKind::RightClick;
command.entity = true;
command.x = x;
command.y = y;
command.z = z;
command.entityFace = face;
return command;
}
std::shared_ptr<Botcraft::ItemFrameEntity> Frame(int id, const Vector3<double> &anchor, int direction, bool glow = false)
{
std::shared_ptr<Botcraft::ItemFrameEntity> frame;
if (glow)
frame = std::make_shared<Botcraft::GlowItemFrameEntity>();
else
frame = std::make_shared<Botcraft::ItemFrameEntity>();
frame->SetEntityID(id);
frame->SetPosition(anchor);
frame->SetDataDirection(direction);
return frame;
}
TEST(EntityInteraction, AllSixFacesUseIntegralAttachmentCellsForBothFrameTypes)
{
for (bool glow : {false, true})
for (const auto &support : {Vector3<double>{0, 0, 0}, Vector3<double>{7, 64, 12}, Vector3<double>{-7, -64, -12}})
for (const auto &face : Faces)
{
Botcraft::EntityManager manager(nullptr);
const auto frame = Frame(42, support + face.normal, face.direction, glow);
manager.AddEntity(frame);
auto command = Command(static_cast<int>(support.x), static_cast<int>(support.y),
static_cast<int>(support.z));
EXPECT_EQ(FindItemFrame(manager, command), frame);
EXPECT_TRUE(MatchesItemFrame(*frame, command));
for (const auto &requested : Faces)
{
command.entityFace = requested.face;
EXPECT_EQ(MatchesItemFrame(*frame, command), requested.face == face.face);
EXPECT_EQ(FindItemFrame(manager, command) != nullptr, requested.face == face.face);
}
// The client-side collider's center is derived, not GetPosition().
const auto center = ItemFrameCenter(*frame);
EXPECT_DOUBLE_EQ(center.x, support.x + 0.5 + face.normal.x * 0.53125);
EXPECT_DOUBLE_EQ(center.y, support.y + 0.5 + face.normal.y * 0.53125);
EXPECT_DOUBLE_EQ(center.z, support.z + 0.5 + face.normal.z * 0.53125);
}
}
TEST(EntityInteraction, AnyRequiresUniqueFrameAndExplicitFaceDisambiguates)
{
Botcraft::EntityManager manager(nullptr);
EXPECT_EQ(FindItemFrame(manager, Command()), nullptr);
const auto south = Frame(1, {0, 0, 1}, 3);
const auto top = Frame(2, {0, 1, 0}, 1, true);
manager.AddEntity(south);
manager.AddEntity(top);
EXPECT_THROW(FindItemFrame(manager, Command()), std::runtime_error);
EXPECT_EQ(FindItemFrame(manager, Command(0, 0, 0, EntityFace::South)), south);
EXPECT_EQ(FindItemFrame(manager, Command(0, 0, 0, EntityFace::Top)), top);
EXPECT_EQ(FindItemFrame(manager, Command(0, 0, 0, EntityFace::West)), nullptr);
manager.AddEntity(Frame(3, {0, 0, 1}, 3, true));
EXPECT_THROW(FindItemFrame(manager, Command(0, 0, 0, EntityFace::South)), std::runtime_error);
}
TEST(EntityInteraction, IgnoresOtherEntitiesEvenHangingEntitiesAtExactAnchor)
{
Botcraft::EntityManager manager(nullptr);
const auto unknown = std::make_shared<Botcraft::UnknownEntity>();
unknown->SetEntityID(1);
unknown->SetPosition({0, 0, 1});
manager.AddEntity(unknown);
const auto painting = std::make_shared<Botcraft::PaintingEntity>();
painting->SetEntityID(2);
painting->SetPosition({0, 0, 1});
painting->SetDataDirection(3);
manager.AddEntity(painting);
EXPECT_EQ(FindItemFrame(manager, Command()), nullptr);
const auto frame = Frame(3, {0, 0, 1}, 3, true);
manager.AddEntity(frame);
EXPECT_EQ(FindItemFrame(manager, Command()), frame);
}
TEST(EntityInteraction, DoesNotRoundOrSearchNearbyInvalidPositions)
{
Botcraft::EntityManager manager(nullptr);
// None is the requested anchor or its exact vanilla center.
int id = 0;
for (const auto &anchor : {Vector3<double>{1, 0, 1}, Vector3<double>{0, 1, 1},
Vector3<double>{0, 0, 2}, Vector3<double>{0.5, 0.5, 1.031250001},
Vector3<double>{0, 0, 0.999999999}, Vector3<double>{-0.000000001, 0, 1}})
manager.AddEntity(Frame(++id, anchor, 3));
EXPECT_EQ(FindItemFrame(manager, Command()), nullptr);
const auto valid = Frame(++id, {0, 0, 1}, 3);
manager.AddEntity(valid);
EXPECT_EQ(FindItemFrame(manager, Command()), valid);
valid->SetPosition({1, 0, 1});
EXPECT_FALSE(MatchesItemFrame(*valid, Command()));
}
TEST(EntityInteraction, ExactCentersResolveAllFacesWithoutApplyingCenterOffsetTwice)
{
for (bool glow : {false, true})
for (const auto &support : {Vector3<double>{16487, 94, 3129}, Vector3<double>{-7, -64, -12}})
for (const auto &face : Faces)
{
const Vector3<double> center = support + Vector3<double>{0.5, 0.5, 0.5} + face.normal * 0.53125;
const auto frame = Frame(42, center, face.direction, glow);
const auto command = Command(static_cast<int>(support.x), static_cast<int>(support.y),
static_cast<int>(support.z), face.face);
Botcraft::EntityManager manager(nullptr);
manager.AddEntity(frame);
EXPECT_EQ(FindItemFrame(manager, command), frame);
const auto actual = ItemFrameCenter(*frame);
EXPECT_DOUBLE_EQ(actual.x, center.x);
EXPECT_DOUBLE_EQ(actual.y, center.y);
EXPECT_DOUBLE_EQ(actual.z, center.z);
for (const auto &other : Faces)
if (other.face != face.face)
EXPECT_FALSE(MatchesItemFrame(*frame, Command(command.x, command.y, command.z, other.face)));
}
}
TEST(EntityInteraction, MixedAnchorAndCenterRepresentationsStillRejectAmbiguity)
{
Botcraft::EntityManager manager(nullptr);
manager.AddEntity(Frame(1, {0, 0, 1}, 3));
manager.AddEntity(Frame(2, {0.5, 0.5, 1.03125}, 3, true));
EXPECT_THROW(FindItemFrame(manager, Command()), std::runtime_error);
EXPECT_THROW(FindItemFrame(manager, Command(0, 0, 0, EntityFace::South)), std::runtime_error);
}
TEST(EntityInteraction, MissingTargetDiagnosticExplainsActualSupportDirectionAndCounts)
{
Botcraft::EntityManager manager(nullptr);
const auto request = Command(16487, 94, 3129, EntityFace::West);
EXPECT_NE(DescribeItemFrameTargets(manager, request).find("loaded_frames=0"), std::string::npos);
const auto frame = Frame(42, {16488.03125, 94.5, 3129.5}, 5);
manager.AddEntity(frame);
EXPECT_EQ(FindItemFrame(manager, request), nullptr);
const auto details = DescribeItemFrameTargets(manager, request);
EXPECT_NE(details.find("requested support=(16487,94,3129), face=w"), std::string::npos);
EXPECT_NE(details.find("loaded_frames=1; nearby_within_8=1"), std::string::npos);
EXPECT_NE(details.find("id=42 type=item_frame raw=(16488.03125,94.5,3129.5) direction=5(e) support=(16487,94,3129)"), std::string::npos);
EXPECT_DOUBLE_EQ(frame->GetPosition().x, 16488.03125); // Diagnostics never mutate or retarget.
EXPECT_EQ(FindItemFrame(manager, request), nullptr);
}
TEST(EntityInteraction, DiagnosticsAreBoundedAndExposeInvalidGeometryWithoutGuessing)
{
Botcraft::EntityManager manager(nullptr);
manager.AddEntity(Frame(1, {0.2, 0.3, 0.4}, -1));
for (int id = 2; id <= 12; ++id) manager.AddEntity(Frame(id, {0, 0, 1}, 3));
manager.AddEntity(Frame(13, {1000, 1000, 1000}, 3));
const auto text = DescribeItemFrameTargets(manager, Command());
EXPECT_NE(text.find("loaded_frames=13; nearby_within_8=12"), std::string::npos);
EXPECT_NE(text.find("support=unknown(invalid position/direction)"), std::string::npos);
EXPECT_NE(text.find("showing_nearest=8"), std::string::npos);
std::size_t count = 0;
for (std::size_t at = 0; (at = text.find("; id=", at)) != std::string::npos; at += 5) ++count;
EXPECT_EQ(count, 8U);
EXPECT_EQ(text.find("id=13 "), std::string::npos);
}
TEST(EntityInteraction, RejectsMalformedDirectionAndNonfiniteFractionalOrOutOfRangePositions)
{
auto frame = Frame(1, {0, 0, 1}, 3);
for (int direction : {-1, 6, INT_MIN, INT_MAX})
{
frame->SetDataDirection(direction);
EXPECT_FALSE(MatchesItemFrame(*frame, Command()));
EXPECT_THROW(ItemFrameCenter(*frame), std::runtime_error);
}
frame->SetDataDirection(3);
for (double value : {std::numeric_limits<double>::quiet_NaN(), std::numeric_limits<double>::infinity(),
-std::numeric_limits<double>::infinity(), 0.25, -0.25, 33554432.0, -33554433.0,
static_cast<double>(INT_MAX), static_cast<double>(INT_MIN)})
for (int axis = 0; axis < 3; ++axis)
{
Vector3<double> anchor{0, 0, 1};
anchor[axis] = value;
frame->SetPosition(anchor);
EXPECT_FALSE(MatchesItemFrame(*frame, Command()));
EXPECT_THROW(ItemFrameCenter(*frame), std::runtime_error);
}
for (double y : {-2049.0, 2048.0})
{
frame->SetPosition({0, y, 1});
EXPECT_THROW(ItemFrameCenter(*frame), std::runtime_error);
}
}
TEST(EntityInteraction, ValidatesCommandBeforeEmptyManagerSearch)
{
Botcraft::EntityManager manager(nullptr);
auto command = Command();
command.entity = false;
EXPECT_THROW(FindItemFrame(manager, command), std::runtime_error);
command = Command();
command.kind = ActionKind::Goto;
EXPECT_THROW(FindItemFrame(manager, command), std::runtime_error);
command = Command();
command.entityFace = static_cast<EntityFace>(99);
EXPECT_THROW(FindItemFrame(manager, command), std::runtime_error);
for (int value : {INT_MIN, -33554433, 33554432, INT_MAX})
{
EXPECT_THROW(FindItemFrame(manager, Command(value, 0, 0)), std::runtime_error);
EXPECT_THROW(FindItemFrame(manager, Command(0, 0, value)), std::runtime_error);
}
for (int value : {INT_MIN, -2049, 2048, INT_MAX})
EXPECT_THROW(FindItemFrame(manager, Command(0, value, 0)), std::runtime_error);
}
TEST(EntityInteraction, HandlesNegativeAndPositiveProtocolEdgesWithoutWrapping)
{
for (const auto &face : Faces)
for (const auto &support : {Vector3<double>{-33554431, -2047, -33554431},
Vector3<double>{33554430, 2046, 33554430}})
{
const auto frame = Frame(1, support + face.normal, face.direction);
const auto command = Command(static_cast<int>(support.x), static_cast<int>(support.y),
static_cast<int>(support.z), face.face);
EXPECT_TRUE(MatchesItemFrame(*frame, command));
EXPECT_NO_THROW(ItemFrameCenter(*frame));
}
EXPECT_TRUE(MatchesItemFrame(*Frame(1, {-33554432, -2048, -33554431}, 3),
Command(-33554432, -2048, -33554432)));
EXPECT_TRUE(MatchesItemFrame(*Frame(1, {33554431, 2047, 33554430}, 2),
Command(33554431, 2047, 33554431)));
EXPECT_FALSE(MatchesItemFrame(*Frame(1, {33554432, 0, 0}, 5), Command(33554431, 0, 0)));
EXPECT_FALSE(MatchesItemFrame(*Frame(1, {0, -2049, 0}, 0), Command(0, -2048, 0)));
}
TEST(EntityInteraction, ManagerLockIsReleasedOnSuccessAndAmbiguity)
{
Botcraft::EntityManager manager(nullptr);
const auto first = Frame(1, {0, 0, 1}, 3);
manager.AddEntity(first);
const auto selected = FindItemFrame(manager, Command());
EXPECT_EQ(selected, first);
manager.AddEntity(Frame(2, {0, 0, 1}, 3));
EXPECT_THROW(FindItemFrame(manager, Command()), std::runtime_error);
manager.AddEntity(Frame(2, {10, 10, 10}, 3));
EXPECT_EQ(FindItemFrame(manager, Command()), first);
}
TEST(EntityInteraction, InteractWireRoundTripUsesMainHandOnlyForRightClick)
{
using namespace ProtocolCraft;
for (int id : {0, 127, 128, 123456, INT_MAX, -1})
for (bool attack : {false, true})
for (bool secondary : {false, true})
{
const auto packet = MakeEntityInteractionPacket(id, attack, secondary);
EXPECT_EQ(packet->GetEntityId(), id);
EXPECT_EQ(packet->GetAction(), attack ? 1 : 0);
EXPECT_EQ(packet->GetUsingSecondaryAction(), secondary);
WriteContainer bytes;
packet->Write(bytes);
auto iter = bytes.cbegin();
std::size_t remaining = bytes.size();
ASSERT_EQ(ReadData<VarInt>(iter, remaining), packet->GetId());
const auto payloadBegin = iter;
const auto payloadSize = remaining;
EXPECT_EQ(ReadData<VarInt>(iter, remaining), id);
EXPECT_EQ(ReadData<VarInt>(iter, remaining), attack ? 1 : 0);
// Exactly secondary bool for attack; main-hand VarInt + bool
// for right-click. No hidden hand or interact-at coordinates.
ASSERT_EQ(remaining, attack ? 1u : 2u);
if (!attack)
EXPECT_EQ(ReadData<VarInt>(iter, remaining), 0);
EXPECT_EQ(ReadData<bool>(iter, remaining), secondary);
EXPECT_EQ(remaining, 0u);
ServerboundInteractPacket decoded;
iter = payloadBegin;
remaining = payloadSize;
decoded.Read(iter, remaining);
EXPECT_EQ(remaining, 0u);
EXPECT_EQ(decoded.GetEntityId(), id);
EXPECT_EQ(decoded.GetAction(), attack ? 1 : 0);
EXPECT_EQ(decoded.GetUsingSecondaryAction(), secondary);
WriteContainer roundTrip;
decoded.Write(roundTrip);
EXPECT_EQ(roundTrip, bytes);
}
}
} // namespace
+172
View File
@@ -0,0 +1,172 @@
#include "ActionExecutor.h"
#include <gtest/gtest.h>
#include "botcraft/Game/Inventory/InventoryManager.hpp"
#include "botcraft/Game/Inventory/Window.hpp"
namespace
{
using namespace ProtocolCraft;
Slot Item(int count)
{
Slot item;
item.SetItemId(1);
item.SetItemCount(count);
return item;
}
class InventorySync : public testing::Test
{
protected:
Botcraft::InventoryManager inventory{nullptr}; // Packet replay only, no socket or assets.
void Full(const Slot &cursor = Slot())
{
ClientboundContainerSetContentPacket packet;
packet.SetContainerId(0);
packet.SetStateId(7);
std::vector<Slot> slots(46);
slots[0] = Item(3); // Sentinel: hotbar updates must not touch crafting output.
slots[36] = Item(8);
packet.SetItems(slots);
packet.SetCarriedItem(cursor);
packet.Dispatch(&inventory);
}
void PlayerSlot(int index, const Slot &contents)
{
ClientboundSetPlayerInventoryPacket packet;
packet.SetSlot(index);
packet.SetContents(contents);
packet.Dispatch(&inventory);
}
};
TEST_F(InventorySync, EmptyHotbarUpdateClearsHeldItemInsteadOfCraftingOutput)
{
Full();
PlayerSlot(0, Slot());
EXPECT_TRUE(inventory.GetHotbarSelected().IsEmptySlot());
EXPECT_TRUE(Bilicraft::ReadDropSlot(*inventory.GetPlayerInventory(), 36).IsEmptySlot());
EXPECT_EQ(inventory.GetPlayerInventory()->GetSlot(0).GetItemCount(), 3);
}
TEST_F(InventorySync, MapsEveryPlayerInventoryIndexToMenuSlots)
{
Full();
for (int index = 0; index <= 40; ++index)
{
const int mapped = index < 9 ? 36 + index : index < 36 ? index : index < 40 ? 44 - index : 45;
PlayerSlot(index, Item(index + 1));
EXPECT_EQ(inventory.GetPlayerInventory()->GetSlot(mapped).GetItemCount(), index + 1) << index;
}
EXPECT_EQ(inventory.GetPlayerInventory()->GetSlot(0).GetItemCount(), 3);
}
TEST_F(InventorySync, IgnoresOutOfRangeInventoryIndices)
{
Full();
const auto before = inventory.GetPlayerInventory()->GetSlots();
PlayerSlot(-1, Item(2));
PlayerSlot(41, Item(2));
PlayerSlot(65536, Item(2));
EXPECT_EQ(inventory.GetPlayerInventory()->GetSlots().size(), before.size());
EXPECT_EQ(inventory.GetPlayerInventory()->GetSlot(0).GetItemCount(), 3);
}
TEST_F(InventorySync, CursorPacketNeverOverwritesTheSelectedHotbar)
{
Full();
ClientboundSetCursorItemPacket packet;
packet.SetContents(Item(5));
packet.Dispatch(&inventory);
EXPECT_EQ(inventory.GetCursor().GetItemCount(), 5);
EXPECT_EQ(inventory.GetHotbarSelected().GetItemCount(), 8);
packet.SetContents(Slot());
packet.Dispatch(&inventory);
EXPECT_TRUE(inventory.GetCursor().IsEmptySlot());
EXPECT_EQ(inventory.GetHotbarSelected().GetItemCount(), 8);
}
TEST_F(InventorySync, FullResyncUpdatesAndClearsCursor)
{
Full(Item(4));
EXPECT_EQ(inventory.GetCursor().GetItemCount(), 4);
Full();
EXPECT_TRUE(inventory.GetCursor().IsEmptySlot());
EXPECT_EQ(inventory.GetPlayerInventory()->GetStateId(), 7);
}
TEST_F(InventorySync, SwapWithEmptyHotbarAndDropClearBothUseAuthoritativeUpdates)
{
Full();
PlayerSlot(0, Slot());
PlayerSlot(9, Item(16));
auto window = inventory.GetPlayerInventory();
ASSERT_TRUE(window->GetSlot(36).IsEmptySlot());
// Server reports swb 1 1 1: storage becomes empty, hotbar receives its stack.
PlayerSlot(9, Slot());
PlayerSlot(0, Item(16));
EXPECT_TRUE(window->GetSlot(9).IsEmptySlot());
EXPECT_EQ(window->GetSlot(36).GetItemCount(), 16);
// Then drop all: an empty authoritative slot, not a stale sixteen-item stack.
PlayerSlot(0, Slot());
EXPECT_TRUE(Bilicraft::ReadDropSlot(*window, 36).IsEmptySlot());
}
TEST_F(InventorySync, LegacyDirectInventoryUpdatesUseSameIndexMapping)
{
Full();
ClientboundContainerSetSlotPacket packet;
packet.SetContainerId(-2);
packet.SetStateId(9);
packet.SetSlot(9);
packet.SetItemStack(Item(12));
packet.Dispatch(&inventory);
EXPECT_EQ(inventory.GetPlayerInventory()->GetSlot(9).GetItemCount(), 12);
EXPECT_TRUE(inventory.GetPlayerInventory()->GetSlot(18).IsEmptySlot());
}
TEST_F(InventorySync, FullPacketWireRoundTripClearsPreviouslyOccupiedHotbar)
{
Full(Item(4));
ClientboundContainerSetContentPacket sent, received;
sent.SetContainerId(0);
sent.SetStateId(8);
sent.SetCarriedItem(Slot());
std::vector<Slot> contents(46);
// Reuse the receive object across occupied and empty updates, like a packet replay.
for (int count : {8, 0})
{
contents[36] = count == 0 ? Slot() : Item(count);
sent.SetItems(contents);
WriteContainer wire;
sent.Write(wire);
auto iter = wire.cbegin();
std::size_t remaining = wire.size();
ASSERT_EQ(ReadData<VarInt>(iter, remaining), sent.GetId());
received.Read(iter, remaining);
ASSERT_EQ(remaining, 0U);
received.Dispatch(&inventory);
EXPECT_EQ(inventory.GetHotbarSelected().GetItemCount(), count);
EXPECT_EQ(inventory.GetHotbarSelected().IsEmptySlot(), count == 0);
EXPECT_TRUE(inventory.GetCursor().IsEmptySlot());
}
}
TEST_F(InventorySync, SwapEmptyBackpackIntoOccupiedHotbarAndThenBothEmpty)
{
Full();
auto window = inventory.GetPlayerInventory();
ASSERT_TRUE(window->GetSlot(9).IsEmptySlot());
PlayerSlot(9, Item(8));
PlayerSlot(0, Slot());
EXPECT_EQ(window->GetSlot(9).GetItemCount(), 8);
EXPECT_TRUE(window->GetSlot(36).IsEmptySlot());
PlayerSlot(9, Slot());
EXPECT_TRUE(window->GetSlot(9).IsEmptySlot());
EXPECT_TRUE(window->GetSlot(36).IsEmptySlot());
}
} // namespace
+275
View File
@@ -0,0 +1,275 @@
#include "EntityInteraction.h"
#include <array>
#include <limits>
#include <stdexcept>
#include <gtest/gtest.h>
#include "botcraft/Game/Entities/EntityManager.hpp"
#include "botcraft/Game/Entities/entities/decoration/ItemFrameEntity.hpp"
#include "botcraft/Game/Entities/entities/decoration/painting/PaintingEntity.hpp"
#include "botcraft/Game/Enums.hpp"
#include "protocolCraft/Packets/Game/Clientbound/ClientboundAddEntityPacket.hpp"
#include "protocolCraft/Packets/Game/Clientbound/ClientboundSetEntityDataPacket.hpp"
#include "protocolCraft/Packets/Game/Clientbound/ClientboundEntityPositionSyncPacket.hpp"
#include "protocolCraft/Packets/Game/Clientbound/ClientboundTeleportEntityPacket.hpp"
static_assert(PROTOCOL_VERSION == 774, "Spawn/metadata replay fixtures describe Minecraft 1.21.11");
namespace
{
using Botcraft::EntityType;
using namespace ProtocolCraft;
constexpr int EntityId = 715;
const UUID EntityUuid{0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70, 0x80,
0x90, 0xa0, 0xb0, 0xc0, 0xd0, 0xe0, 0xf0, 0x01};
// Direction 3D data order: Down, Up, North, South, West, East.
const std::array<Botcraft::Position, 6> Normals{{{0, -1, 0}, {0, 1, 0}, {0, 0, -1},
{0, 0, 1}, {-1, 0, 0}, {1, 0, 0}}};
Bilicraft::ActionCommand SupportFor(int direction)
{
Bilicraft::ActionCommand command{};
command.kind = Bilicraft::ActionKind::RightClick;
command.entity = true;
command.x = -17 - Normals[direction].x;
command.y = 64 - Normals[direction].y;
command.z = -31 - Normals[direction].z;
return command;
}
// Exercise the public packet dispatch path, including VarInt decoding, rather
// than bypassing EntityManager with direct frame setters or an exposed Handle.
void Spawn(Botcraft::EntityManager &manager, EntityType type, int data)
{
ClientboundAddEntityPacket sent, received;
sent.SetEntityId(EntityId);
sent.SetUuid(EntityUuid);
sent.SetType(static_cast<int>(type));
sent.SetX(-17.0);
sent.SetY(64.0);
sent.SetZ(-31.0);
LpVec3 movement;
movement.SetX(0.0);
movement.SetY(0.0);
movement.SetZ(0.0);
sent.SetMovement(movement);
// Deliberately unrelated angles: facing must come from Data.
sent.SetXRot(32);
sent.SetYRot(64);
sent.SetYHeadRot(128);
sent.SetData(data);
WriteContainer wire;
sent.Write(wire);
auto iter = wire.cbegin();
std::size_t remaining = wire.size();
ASSERT_EQ(ReadData<VarInt>(iter, remaining), sent.GetId());
received.Read(iter, remaining);
ASSERT_EQ(remaining, 0U);
received.Dispatch(&manager);
}
void MetadataDirection(Botcraft::EntityManager &manager, int direction)
{
// Official 1.21.11 HangingEntity DATA_DIRECTION: index 8, DIRECTION=12.
// This decodes to Botcraft::Direction in std::any, NOT an int serializer.
// Use the real manager metadata path so later authoritative updates must
// override the initial spawn value, including the invalid-data sentinel.
WriteContainer packed;
WriteData<unsigned char>(8, packed);
WriteData<VarInt>(12, packed);
WriteData<VarInt>(direction, packed);
WriteData<unsigned char>(0xff, packed);
ClientboundSetEntityDataPacket sent, received;
sent.SetEntityId(EntityId);
sent.SetPackedItems(packed);
WriteContainer wire;
sent.Write(wire);
auto iter = wire.cbegin();
std::size_t remaining = wire.size();
ASSERT_EQ(ReadData<VarInt>(iter, remaining), sent.GetId());
received.Read(iter, remaining);
ASSERT_EQ(remaining, 0U);
received.Dispatch(&manager);
}
void ExpectSpawnFields(const Botcraft::Entity &entity, EntityType type)
{
EXPECT_EQ(entity.GetType(), type);
EXPECT_EQ(entity.GetEntityID(), EntityId);
EXPECT_EQ(entity.GetUUID(), EntityUuid);
// The packet contains the attachment cell, not a rendered frame center.
EXPECT_DOUBLE_EQ(entity.GetX(), -17.0);
EXPECT_DOUBLE_EQ(entity.GetY(), 64.0);
EXPECT_DOUBLE_EQ(entity.GetZ(), -31.0);
EXPECT_FLOAT_EQ(entity.GetYaw(), 90.0f);
EXPECT_FLOAT_EQ(entity.GetPitch(), 45.0f);
EXPECT_DOUBLE_EQ(entity.GetSpeed().x, 0.0);
EXPECT_DOUBLE_EQ(entity.GetSpeed().y, 0.0);
EXPECT_DOUBLE_EQ(entity.GetSpeed().z, 0.0);
}
class ItemFrameSpawn : public testing::TestWithParam<EntityType>
{
protected:
Botcraft::EntityManager manager{nullptr}; // Offline packet replay; no connection.
std::shared_ptr<Botcraft::ItemFrameEntity> Frame() const
{
return std::dynamic_pointer_cast<Botcraft::ItemFrameEntity>(manager.GetEntity(EntityId));
}
};
TEST_P(ItemFrameSpawn, AllSixDirectionsAreAvailableImmediatelyWithoutMetadata)
{
for (int direction = 0; direction < 6; ++direction)
{
SCOPED_TRACE(direction);
Spawn(manager, GetParam(), direction);
const auto frame = Frame();
ASSERT_NE(frame, nullptr);
EXPECT_EQ(frame->GetDataDirection(), direction);
ExpectSpawnFields(*frame, GetParam());
EXPECT_EQ(Bilicraft::FindItemFrame(manager, SupportFor(direction)), frame);
// Before the fix, non-South frames were selected on this WRONG block.
for (int other = 0; other < 6; ++other)
{
if (other != direction)
EXPECT_EQ(Bilicraft::FindItemFrame(manager, SupportFor(other)), nullptr);
}
}
}
template <typename Packet>
void PositionRoundTrip(Packet &sent, Botcraft::EntityManager &manager)
{
WriteContainer bytes;
sent.Write(bytes);
auto iter = bytes.cbegin();
std::size_t remaining = bytes.size();
ASSERT_EQ(ReadData<VarInt>(iter, remaining), sent.GetId());
Packet received;
received.Read(iter, remaining);
ASSERT_EQ(remaining, 0U);
received.Dispatch(&manager);
}
TEST_P(ItemFrameSpawn, AbsoluteCenterUpdatesPreserveTargetAndTeleportChangesSupport)
{
for (int direction = 0; direction < 6; ++direction)
{
SCOPED_TRACE(direction);
Spawn(manager, GetParam(), direction);
const auto frame = Frame();
auto command = SupportFor(direction);
const auto center = Bilicraft::ItemFrameCenter(*frame);
PositionMoveRotation values;
values.SetPosition({center.x, center.y, center.z});
values.SetDeltaMovement({0.0, 0.0, 0.0});
values.SetYRot(0.0f);
values.SetXRot(0.0f);
ClientboundEntityPositionSyncPacket sync;
sync.SetEntityId(EntityId);
sync.SetValues(values);
sync.SetOnGround(false);
PositionRoundTrip(sync, manager);
EXPECT_EQ(Bilicraft::FindItemFrame(manager, command), frame);
EXPECT_NO_THROW({
const auto actual = Bilicraft::ItemFrameCenter(*frame);
EXPECT_DOUBLE_EQ(actual.x, center.x);
EXPECT_DOUBLE_EQ(actual.y, center.y);
EXPECT_DOUBLE_EQ(actual.z, center.z);
});
values.SetPosition({center.x + 16.0, center.y, center.z});
ClientboundTeleportEntityPacket teleport;
teleport.SetEntityId(EntityId);
teleport.SetChange(values);
teleport.SetRelatives(0);
teleport.SetOnGround(false);
PositionRoundTrip(teleport, manager);
EXPECT_EQ(Bilicraft::FindItemFrame(manager, command), nullptr);
command.x += 16;
EXPECT_EQ(Bilicraft::FindItemFrame(manager, command), frame);
}
}
TEST_P(ItemFrameSpawn, UnrelatedMetadataDoesNotResetSpawnDirection)
{
Spawn(manager, GetParam(), 2); // North, not the constructor's South default.
const auto frame = Frame();
ASSERT_NE(frame, nullptr);
ClientboundSetEntityDataPacket packet;
packet.SetEntityId(EntityId);
// ItemFrame item rotation: metadata index 10, serializer INT=1, rotation 3.
packet.SetPackedItems({10, 1, 3, 0xff});
packet.Dispatch(&manager);
EXPECT_EQ(frame->GetDataDirection(), 2);
EXPECT_EQ(frame->GetDataRotation(), 3);
EXPECT_EQ(Bilicraft::FindItemFrame(manager, SupportFor(2)), frame);
}
TEST_P(ItemFrameSpawn, LaterDirectionMetadataOverridesSpawnWithoutChangingIdentityOrPosition)
{
Spawn(manager, GetParam(), 2);
const auto frame = Frame();
ASSERT_NE(frame, nullptr);
for (int direction = 0; direction < 6; ++direction)
{
SCOPED_TRACE(direction);
MetadataDirection(manager, direction);
EXPECT_EQ(Frame(), frame);
EXPECT_EQ(frame->GetDataDirection(), direction);
ExpectSpawnFields(*frame, GetParam());
EXPECT_EQ(Bilicraft::FindItemFrame(manager, SupportFor(direction)), frame);
}
}
TEST_P(ItemFrameSpawn, InvalidSpawnDataNeverAliasesAValidFaceAndMetadataCanRecover)
{
for (int data : {-1, 6, 255, std::numeric_limits<int>::min(), std::numeric_limits<int>::max()})
{
SCOPED_TRACE(data);
Spawn(manager, GetParam(), data);
const auto frame = Frame();
ASSERT_NE(frame, nullptr);
EXPECT_EQ(frame->GetDataDirection(), -1);
ExpectSpawnFields(*frame, GetParam());
for (int direction = 0; direction < 6; ++direction)
EXPECT_EQ(Bilicraft::FindItemFrame(manager, SupportFor(direction)), nullptr);
EXPECT_THROW(Bilicraft::ItemFrameCenter(*frame), std::runtime_error);
MetadataDirection(manager, 4);
EXPECT_EQ(frame->GetDataDirection(), 4);
EXPECT_EQ(Bilicraft::FindItemFrame(manager, SupportFor(4)), frame);
}
}
INSTANTIATE_TEST_SUITE_P(OrdinaryAndGlow, ItemFrameSpawn,
testing::Values(EntityType::ItemFrame, EntityType::GlowItemFrame));
TEST(ItemFrameSpawnOtherEntities, DoesNotInterpretOtherEntitiesDataAsFrameDirection)
{
Botcraft::EntityManager manager{nullptr};
for (const auto type : {EntityType::Painting, EntityType::ItemEntity})
{
for (int data : {0, 5, 6, -1})
{
SCOPED_TRACE(static_cast<int>(type));
SCOPED_TRACE(data);
Spawn(manager, type, data);
const auto entity = manager.GetEntity(EntityId);
ASSERT_NE(entity, nullptr);
ExpectSpawnFields(*entity, type);
EXPECT_EQ(std::dynamic_pointer_cast<Botcraft::ItemFrameEntity>(entity), nullptr);
if (type == EntityType::Painting)
{
const auto painting = std::dynamic_pointer_cast<Botcraft::PaintingEntity>(entity);
ASSERT_NE(painting, nullptr);
EXPECT_EQ(painting->GetDataDirection(), static_cast<int>(Botcraft::Direction::South));
}
}
}
}
} // namespace
+466
View File
@@ -0,0 +1,466 @@
#include "LineEditor.h"
#include <stdexcept>
#include <string>
#include <string_view>
#include <vector>
#include <gtest/gtest.h>
namespace
{
using Bilicraft::LineEditor;
constexpr std::string_view Up = "\x1b[A";
constexpr std::string_view Down = "\x1b[B";
constexpr std::string_view Left = "\x1b[D";
constexpr std::string_view Right = "\x1b[C";
constexpr std::string_view Home = "\x1b[H";
constexpr std::string_view End = "\x1b[F";
constexpr std::string_view Delete = "\x1b[3~";
const std::string Chinese = "\xe4\xb8\xad\xe6\x96\x87";
const std::string Emoji = "\xf0\x9f\x8c\xb1";
void Type(LineEditor &editor, std::string_view bytes)
{
for (const char byte : bytes)
EXPECT_FALSE(editor.Feed(byte));
}
void Submit(LineEditor &editor, std::string_view text)
{
Type(editor, text);
EXPECT_EQ(editor.Feed('\n'), std::optional<std::string>(text));
EXPECT_TRUE(editor.Text().empty());
EXPECT_EQ(editor.Cursor(), 0U);
}
TEST(LineEditorTest, EmptyEditorAndEmptySubmission)
{
LineEditor editor;
EXPECT_TRUE(editor.Text().empty());
EXPECT_EQ(editor.Cursor(), 0U);
EXPECT_FALSE(editor.IsEof());
EXPECT_EQ(editor.Feed('\n'), std::optional<std::string>(""));
Type(editor, Up);
EXPECT_TRUE(editor.Text().empty());
}
TEST(LineEditorTest, SubmitsOneLineAtATimeAndClearsText)
{
LineEditor editor;
std::vector<std::string> lines;
for (const char byte : std::string("one\ntwo\rthree\r\nfour\n"))
if (auto line = editor.Feed(byte))
lines.push_back(*line);
EXPECT_EQ(lines, (std::vector<std::string>{"one", "two", "three", "four"}));
EXPECT_TRUE(editor.Text().empty());
}
TEST(LineEditorTest, CrLfSuppressionPersistsAcrossRequestBoundaries)
{
LineEditor editor;
Type(editor, "one");
EXPECT_EQ(editor.Feed('\r'), std::optional<std::string>("one"));
EXPECT_TRUE(editor.Text().empty());
// No further input is fed until the next request is allowed.
EXPECT_FALSE(editor.Feed('\n'));
EXPECT_EQ(editor.Feed('\n'), std::optional<std::string>(""));
EXPECT_EQ(editor.Feed('\r'), std::optional<std::string>(""));
Type(editor, "x");
EXPECT_EQ(editor.Feed('\n'), std::optional<std::string>("x"));
EXPECT_EQ(editor.Feed('\r'), std::optional<std::string>(""));
EXPECT_EQ(editor.Feed('\r'), std::optional<std::string>(""));
}
TEST(LineEditorTest, HistoryBrowsesBothDirectionsAndClampsAtEnds)
{
LineEditor editor;
Submit(editor, "one");
Submit(editor, "two");
Type(editor, Up);
EXPECT_EQ(editor.Text(), "two");
Type(editor, Up);
EXPECT_EQ(editor.Text(), "one");
Type(editor, Up);
EXPECT_EQ(editor.Text(), "one");
Type(editor, Down);
EXPECT_EQ(editor.Text(), "two");
Type(editor, Down);
EXPECT_TRUE(editor.Text().empty());
Type(editor, Down);
EXPECT_TRUE(editor.Text().empty());
}
TEST(LineEditorTest, HistoryRestoresDraftAndItsUtf8Cursor)
{
LineEditor editor;
Submit(editor, "old");
Type(editor, "a" + Chinese + "z");
Type(editor, Left);
Type(editor, Left);
const auto expectedText = editor.Text();
const auto expectedCursor = editor.Cursor();
ASSERT_EQ(expectedCursor, 4U);
Type(editor, Up);
EXPECT_EQ(editor.Text(), "old");
Type(editor, Down);
EXPECT_EQ(editor.Text(), expectedText);
EXPECT_EQ(editor.Cursor(), expectedCursor);
Type(editor, "!");
Type(editor, Up);
Type(editor, Down);
EXPECT_EQ(editor.Text(), "a" + Chinese.substr(0, 3) + "!" + Chinese.substr(3) + "z");
EXPECT_EQ(editor.Cursor(), expectedCursor + 1);
}
TEST(LineEditorTest, EditingRecalledLineDoesNotMutateHistory)
{
LineEditor editor;
Submit(editor, "first");
Submit(editor, "second");
Type(editor, Up);
Type(editor, " changed");
Type(editor, Up);
EXPECT_EQ(editor.Text(), "first");
Type(editor, Down);
EXPECT_EQ(editor.Text(), "second");
Type(editor, Down);
EXPECT_TRUE(editor.Text().empty());
}
TEST(LineEditorTest, SubmittingEditedHistoryAddsNewEntryAndResetsDraft)
{
LineEditor editor;
Submit(editor, "original");
Type(editor, "draft");
Type(editor, Up);
Type(editor, "!");
EXPECT_EQ(editor.Feed('\n'), std::optional<std::string>("original!"));
Type(editor, Up);
EXPECT_EQ(editor.Text(), "original!");
Type(editor, Up);
EXPECT_EQ(editor.Text(), "original");
Type(editor, Down);
Type(editor, Down);
EXPECT_TRUE(editor.Text().empty());
}
TEST(LineEditorTest, IgnoresWhitespaceHistoryAndOnlyDeduplicatesConsecutiveEntries)
{
LineEditor editor;
Submit(editor, "alpha");
Submit(editor, "alpha");
Submit(editor, " \t ");
Submit(editor, "");
Submit(editor, "alpha");
Submit(editor, "beta");
Submit(editor, "alpha");
Type(editor, Up);
EXPECT_EQ(editor.Text(), "alpha");
Type(editor, Up);
EXPECT_EQ(editor.Text(), "beta");
Type(editor, Up);
EXPECT_EQ(editor.Text(), "alpha");
Type(editor, Up);
EXPECT_EQ(editor.Text(), "alpha");
}
TEST(LineEditorTest, HistoryPreservesNonblankWhitespaceExactly)
{
LineEditor editor;
Submit(editor, " command\t ");
Type(editor, Up);
EXPECT_EQ(editor.Text(), " command\t ");
}
TEST(LineEditorTest, HistoryRetainsOnlyLatestTwoHundredEntries)
{
LineEditor editor;
for (std::size_t index = 0; index < LineEditor::MaxHistoryEntries + 7; ++index)
Submit(editor, "entry" + std::to_string(index));
for (std::size_t index = 0; index < LineEditor::MaxHistoryEntries + 10; ++index)
Type(editor, Up);
EXPECT_EQ(editor.Text(), "entry7");
Type(editor, Down);
EXPECT_EQ(editor.Text(), "entry8");
for (std::size_t index = 0; index < LineEditor::MaxHistoryEntries; ++index)
Type(editor, Down);
EXPECT_TRUE(editor.Text().empty());
Submit(editor, "new");
Type(editor, Up);
EXPECT_EQ(editor.Text(), "new");
}
TEST(LineEditorTest, HistoryIsLocalToEachEditor)
{
LineEditor first;
Submit(first, "private");
LineEditor second;
Type(second, Up);
EXPECT_TRUE(second.Text().empty());
}
TEST(LineEditorTest, FragmentedCsiAndSs3ArrowsAreNotInserted)
{
LineEditor editor;
Submit(editor, "first");
Submit(editor, "second");
EXPECT_FALSE(editor.Feed('\x1b'));
EXPECT_TRUE(editor.Text().empty());
EXPECT_FALSE(editor.Feed('['));
EXPECT_TRUE(editor.Text().empty());
EXPECT_FALSE(editor.Feed('A'));
EXPECT_EQ(editor.Text(), "second");
EXPECT_FALSE(editor.Feed('\x1b'));
EXPECT_FALSE(editor.Feed('O'));
EXPECT_EQ(editor.Text(), "second");
EXPECT_FALSE(editor.Feed('A'));
EXPECT_EQ(editor.Text(), "first");
Type(editor, "\x1bOB");
EXPECT_EQ(editor.Text(), "second");
Type(editor, "\x1bOB");
EXPECT_TRUE(editor.Text().empty());
}
TEST(LineEditorTest, InsertDeleteAndBackspaceAtAsciiCursor)
{
LineEditor editor;
Type(editor, "ac");
Type(editor, Left);
Type(editor, "b");
EXPECT_EQ(editor.Text(), "abc");
EXPECT_EQ(editor.Cursor(), 2U);
Type(editor, Delete);
EXPECT_EQ(editor.Text(), "ab");
Type(editor, "\x7f");
EXPECT_EQ(editor.Text(), "a");
Type(editor, "\x08");
EXPECT_TRUE(editor.Text().empty());
Type(editor, "\x08\x7f");
Type(editor, Delete);
Type(editor, Left);
Type(editor, Right);
EXPECT_EQ(editor.Cursor(), 0U);
}
TEST(LineEditorTest, Utf8CodepointsAreInsertedAtomicallyAndEditedAtByteBoundaries)
{
LineEditor editor;
EXPECT_FALSE(editor.Feed(Chinese[0]));
EXPECT_FALSE(editor.Feed(Chinese[1]));
EXPECT_TRUE(editor.Text().empty());
EXPECT_EQ(editor.Cursor(), 0U);
EXPECT_FALSE(editor.Feed(Chinese[2]));
EXPECT_EQ(editor.Text(), Chinese.substr(0, 3));
Type(editor, Chinese.substr(3) + Emoji);
EXPECT_EQ(editor.Cursor(), 10U);
Type(editor, Left);
EXPECT_EQ(editor.Cursor(), 6U);
Type(editor, Left);
EXPECT_EQ(editor.Cursor(), 3U);
Type(editor, Delete);
EXPECT_EQ(editor.Text(), Chinese.substr(0, 3) + Emoji);
Type(editor, "\x7f");
EXPECT_EQ(editor.Text(), Emoji);
EXPECT_EQ(editor.Cursor(), 0U);
Type(editor, Right);
EXPECT_EQ(editor.Cursor(), 4U);
Type(editor, "\x08");
EXPECT_TRUE(editor.Text().empty());
}
TEST(LineEditorTest, MovementClampsAndSupportsAllCommonHomeEndForms)
{
for (const auto home : {Home, std::string_view("\x1bOH"), std::string_view("\x1b[1~"), std::string_view("\x1b[7~")})
{
for (const auto end :
{End, std::string_view("\x1bOF"), std::string_view("\x1b[4~"), std::string_view("\x1b[8~")})
{
LineEditor editor;
Type(editor, Chinese);
Type(editor, home);
EXPECT_EQ(editor.Cursor(), 0U);
Type(editor, Left);
EXPECT_EQ(editor.Cursor(), 0U);
Type(editor, end);
EXPECT_EQ(editor.Cursor(), Chinese.size());
Type(editor, Right);
EXPECT_EQ(editor.Cursor(), Chinese.size());
}
}
}
TEST(LineEditorTest, Ss3LeftRightMoveByCodepoint)
{
LineEditor editor;
Type(editor, Chinese);
Type(editor, "\x1bOD");
EXPECT_EQ(editor.Cursor(), 3U);
Type(editor, "\x1bOC");
EXPECT_EQ(editor.Cursor(), 6U);
}
TEST(LineEditorTest, CtrlAEndKillAndClearRespectCursor)
{
LineEditor editor;
Type(editor, "a" + Chinese + "z");
Type(editor, "\x01");
EXPECT_EQ(editor.Cursor(), 0U);
Type(editor, Right);
Type(editor, Right);
Type(editor, "\x15");
EXPECT_EQ(editor.Text(), Chinese.substr(3) + "z");
EXPECT_EQ(editor.Cursor(), 0U);
Type(editor, Right);
Type(editor, "\x0b");
EXPECT_EQ(editor.Text(), Chinese.substr(3));
Type(editor, "\x05");
EXPECT_EQ(editor.Cursor(), 3U);
Type(editor, "\x15");
EXPECT_TRUE(editor.Text().empty());
}
TEST(LineEditorTest, CtrlDEmptyLatchesEofAndFutureInputIsIgnored)
{
LineEditor editor;
EXPECT_FALSE(editor.Feed('\x04'));
EXPECT_TRUE(editor.IsEof());
Type(editor, "ignored\n\r\x1b[A");
EXPECT_TRUE(editor.Text().empty());
EXPECT_EQ(editor.Cursor(), 0U);
}
TEST(LineEditorTest, CtrlDOnNonemptyLineDeletesCodepointButDoesNotSetEof)
{
LineEditor editor;
Type(editor, Chinese);
Type(editor, "\x04");
EXPECT_EQ(editor.Text(), Chinese);
EXPECT_FALSE(editor.IsEof());
Type(editor, Home);
Type(editor, "\x04");
EXPECT_EQ(editor.Text(), Chinese.substr(3));
Type(editor, "\x04");
EXPECT_TRUE(editor.Text().empty());
EXPECT_FALSE(editor.IsEof());
Type(editor, "\x04");
EXPECT_TRUE(editor.IsEof());
}
TEST(LineEditorTest, UnknownEscapesAreSwallowedAsWholeSequences)
{
LineEditor editor;
Type(editor, "safe");
Type(editor, "\x1b[99~\x1b[?25l\x1b[1;5D\x1bOP\x1b(0\x1bz");
EXPECT_EQ(editor.Text(), "safe");
EXPECT_EQ(editor.Cursor(), 4U);
Type(editor, "!");
EXPECT_EQ(editor.Feed('\n'), std::optional<std::string>("safe!"));
}
TEST(LineEditorTest, OscAndControlStringsAreSwallowedThroughTheirTerminator)
{
LineEditor editor;
Type(editor, "a\x1b]0;window title\x07");
Type(editor, "b\x1bPignored [A payload\x1b\\");
Type(editor, "c\x1b]title\x1b\\");
EXPECT_EQ(editor.Text(), "abc");
}
TEST(LineEditorTest, OverlongEscapeHasBoundedStorageAndDoesNotLeakTail)
{
LineEditor editor;
Type(editor, "safe\x1b[");
Type(editor, std::string(10000, '1'));
Type(editor, "~done");
EXPECT_EQ(editor.Text(), "safedone");
Type(editor, "\x1b]" + std::string(10000, 'x') + "\x07");
Type(editor, "!");
EXPECT_EQ(editor.Text(), "safedone!");
}
TEST(LineEditorTest, NewlineAndNewEscapeRecoverFromTruncatedSequences)
{
LineEditor editor;
Type(editor, "ok\x1b[123");
EXPECT_EQ(editor.Feed('\n'), std::optional<std::string>("ok"));
Type(editor, "draft\x1b[12");
Type(editor, Up);
EXPECT_EQ(editor.Text(), "ok");
Type(editor, Down);
EXPECT_EQ(editor.Text(), "draft");
Type(editor, "\x1b]unterminated");
EXPECT_EQ(editor.Feed('\n'), std::optional<std::string>("draft"));
}
TEST(LineEditorTest, MalformedUtf8IsDiscardedAndAsciiInputRecovers)
{
LineEditor editor;
Type(editor, "\x80\xbf\xc0\xaf\xf5\xff\xe0\x80\x80\xed\xa0\x80\xf4\x90\x80\x80");
EXPECT_TRUE(editor.Text().empty());
Type(editor, "\xe4");
Type(editor, "valid");
EXPECT_EQ(editor.Text(), "valid");
Type(editor, "\xe4\xb8");
Type(editor, Left);
Type(editor, "!");
EXPECT_EQ(editor.Text(), "vali!d");
EXPECT_EQ(editor.Cursor(), 5U);
Type(editor, "\xe4\xb8");
EXPECT_EQ(editor.Feed('\n'), std::optional<std::string>("vali!d"));
Type(editor, "next");
EXPECT_EQ(editor.Text(), "next");
}
TEST(LineEditorTest, InvalidDecoderPrefixCanBeFollowedByNewValidCodepoint)
{
LineEditor editor;
Type(editor, "\xe4" + Emoji + "\xe4\xb8" + Chinese);
EXPECT_EQ(editor.Text(), Emoji + Chinese);
EXPECT_EQ(editor.Cursor(), Emoji.size() + Chinese.size());
}
TEST(LineEditorTest, EmbeddedNulAndUnsupportedControlsAreNotStored)
{
LineEditor editor;
Type(editor, "a");
EXPECT_FALSE(editor.Feed('\0'));
Type(editor, "\x02\x03\x06\x0c");
Type(editor, "b");
EXPECT_EQ(editor.Text(), "ab");
}
TEST(LineEditorTest, ExactLineLimitAcceptedAndOverflowCanRecoverByEditing)
{
LineEditor editor;
const std::string full(LineEditor::MaxLineBytes, 'x');
Type(editor, full);
EXPECT_EQ(editor.Text(), full);
EXPECT_THROW(editor.Feed('y'), std::length_error);
EXPECT_EQ(editor.Text(), full);
EXPECT_EQ(editor.Cursor(), full.size());
EXPECT_FALSE(editor.IsEof());
Type(editor, "\x7f");
Type(editor, "y");
EXPECT_EQ(editor.Feed('\n'), std::optional<std::string>(full.substr(1) + "y"));
Submit(editor, "next");
}
TEST(LineEditorTest, Utf8OverflowIsAtomicAndDecoderRecovers)
{
LineEditor editor;
const std::string prefix(LineEditor::MaxLineBytes - 2, 'x');
Type(editor, prefix);
EXPECT_FALSE(editor.Feed(Chinese[0]));
EXPECT_FALSE(editor.Feed(Chinese[1]));
EXPECT_THROW(editor.Feed(Chinese[2]), std::length_error);
EXPECT_EQ(editor.Text(), prefix);
EXPECT_EQ(editor.Cursor(), prefix.size());
Type(editor, "\x7f");
Type(editor, Chinese.substr(0, 3));
EXPECT_EQ(editor.Text().size(), LineEditor::MaxLineBytes);
EXPECT_EQ(editor.Cursor(), LineEditor::MaxLineBytes);
Type(editor, "\x7f");
EXPECT_EQ(editor.Text(), prefix.substr(1));
}
} // namespace
+439
View File
@@ -0,0 +1,439 @@
#include "TerminalConsole.h"
#include <gtest/gtest.h>
#include <cerrno>
#include <cstdlib>
#include <optional>
#include <stdexcept>
#include <string>
#include <string_view>
#include <thread>
#ifndef _WIN32
#include <csignal>
#include <fcntl.h>
#include <poll.h>
#include <sys/ioctl.h>
#include <sys/wait.h>
#include <termios.h>
#include <unistd.h>
namespace
{
using Bilicraft::TerminalConsole;
void Put(int fd, std::string_view text)
{
while (!text.empty())
{
const auto count = write(fd, text.data(), text.size());
if (count < 0 && errno == EINTR) continue;
if (count <= 0) throw std::runtime_error("test write failed");
text.remove_prefix(static_cast<std::size_t>(count));
}
}
std::string Drain(int fd)
{
std::string result;
char bytes[2048];
for (;;)
{
const auto count = read(fd, bytes, sizeof(bytes));
if (count > 0) result.append(bytes, static_cast<std::size_t>(count));
else if (count < 0 && errno == EINTR) continue;
else break;
}
return result;
}
class Pipe
{
public:
Pipe()
{
if (pipe(fds) != 0) throw std::runtime_error("pipe failed");
if (fcntl(fds[0], F_SETFL, O_NONBLOCK) < 0) throw std::runtime_error("fcntl failed");
}
~Pipe() { if (fds[0] >= 0) close(fds[0]); if (fds[1] >= 0) close(fds[1]); }
void CloseWriter() { close(fds[1]); fds[1] = -1; }
int fds[2]{-1, -1};
};
class Pty : public ::testing::Test
{
protected:
void SetUp() override
{
if (const char *value = std::getenv("TERM")) oldTerm = value;
ASSERT_EQ(setenv("TERM", "xterm-256color", 1), 0);
master = posix_openpt(O_RDWR | O_NOCTTY | O_NONBLOCK);
if (master < 0) GTEST_SKIP() << "No POSIX PTY available";
ASSERT_EQ(grantpt(master), 0);
ASSERT_EQ(unlockpt(master), 0);
const char *name = ptsname(master);
ASSERT_NE(name, nullptr);
slave = open(name, O_RDWR | O_NOCTTY);
ASSERT_GE(slave, 0);
Size(24, 80);
ASSERT_EQ(tcgetattr(slave, &original), 0);
}
void TearDown() override
{
if (slave >= 0) { tcsetattr(slave, TCSANOW, &original); close(slave); }
if (master >= 0) close(master);
if (oldTerm) setenv("TERM", oldTerm->c_str(), 1);
else unsetenv("TERM");
}
void Size(unsigned short rows, unsigned short columns)
{
winsize size{};
size.ws_row = rows;
size.ws_col = columns;
ASSERT_EQ(ioctl(slave, TIOCSWINSZ, &size), 0);
}
void Input(std::string_view text)
{
Put(master, text);
pollfd item{slave, POLLIN, 0};
ASSERT_GT(poll(&item, 1, 1000), 0);
}
int Available()
{
int count = -1;
EXPECT_EQ(ioctl(slave, FIONREAD, &count), 0);
return count;
}
void ExpectRestored()
{
termios current{};
ASSERT_EQ(tcgetattr(slave, &current), 0);
EXPECT_EQ(current.c_iflag, original.c_iflag);
EXPECT_EQ(current.c_oflag, original.c_oflag);
EXPECT_EQ(current.c_cflag, original.c_cflag);
EXPECT_EQ(current.c_lflag, original.c_lflag);
EXPECT_EQ(cfgetispeed(&current), cfgetispeed(&original));
EXPECT_EQ(cfgetospeed(&current), cfgetospeed(&original));
for (std::size_t i = 0; i < NCCS; ++i) EXPECT_EQ(current.c_cc[i], original.c_cc[i]);
}
int master = -1, slave = -1;
termios original{};
std::optional<std::string> oldTerm;
};
TEST_F(Pty, PlainBeforeStartThenRawAndFullRestoration)
{
{
TerminalConsole console(slave, slave, slave);
console.Out() << "login\n";
EXPECT_EQ(Drain(master).find('\033'), std::string::npos);
console.Start();
ASSERT_TRUE(console.IsSplit());
termios raw{};
ASSERT_EQ(tcgetattr(slave, &raw), 0);
EXPECT_EQ(raw.c_lflag & (ICANON | ECHO | IEXTEN), 0U);
EXPECT_NE(raw.c_lflag & ISIG, 0U);
EXPECT_EQ(raw.c_iflag & IXON, 0U);
EXPECT_EQ(raw.c_cc[VMIN], 0);
EXPECT_EQ(raw.c_cc[VTIME], 0);
#ifdef VQUIT
EXPECT_EQ(raw.c_cc[VQUIT], _POSIX_VDISABLE);
#endif
#ifdef VSUSP
EXPECT_EQ(raw.c_cc[VSUSP], _POSIX_VDISABLE);
#endif
const auto screen = Drain(master);
EXPECT_NE(screen.find("\033[1;22r"), std::string::npos);
EXPECT_NE(screen.find("\033[23;1H"), std::string::npos);
EXPECT_NE(screen.find("\033[24;1H"), std::string::npos);
EXPECT_EQ(screen.find("?1049"), std::string::npos);
console.Start(); // no second mode switch or duplicated prompt
EXPECT_TRUE(Drain(master).empty());
}
ExpectRestored();
const auto cleanup = Drain(master);
EXPECT_NE(cleanup.find("\033[r"), std::string::npos);
EXPECT_NE(cleanup.find("\033[?25h"), std::string::npos);
EXPECT_NE(fcntl(slave, F_GETFD), -1); // borrowed descriptor is still open
}
TEST_F(Pty, ExceptionUnwindingRestoresTerminal)
{
try
{
TerminalConsole console(slave, slave, slave);
console.Start();
ASSERT_TRUE(console.IsSplit());
throw std::runtime_error("application failure");
}
catch (const std::runtime_error &) {}
ExpectRestored();
}
TEST_F(Pty, BusyConsumesNothingAndSubmissionDoesNotReadAhead)
{
TerminalConsole console(slave, slave, slave);
console.Start();
Drain(master);
console.SetInputEnabled(false);
Input("first\nsecond\n");
const int before = Available();
EXPECT_FALSE(console.PollLine());
console.Tick();
EXPECT_EQ(Available(), before);
EXPECT_NE(Drain(master).find("busy / pending"), std::string::npos);
console.SetInputEnabled(true);
EXPECT_EQ(console.PollLine(), std::optional<std::string>("first"));
EXPECT_EQ(Available(), 7);
EXPECT_EQ(console.PollLine(), std::optional<std::string>("second"));
}
TEST_F(Pty, ArrowHistoryDraftAndUnicodeRemainEditableAcrossThreadedLogs)
{
TerminalConsole console(slave, slave, slave);
console.Start();
Input("old\n");
ASSERT_EQ(console.PollLine(), std::optional<std::string>("old"));
Input("draft\033[A");
EXPECT_FALSE(console.PollLine());
Drain(master);
std::thread logger([&console] { console.WriteLog("network log\n"); });
logger.join();
const auto logged = Drain(master);
EXPECT_NE(logged.find("network log"), std::string::npos);
EXPECT_NE(logged.find(">>> old"), std::string::npos);
Input("\033[B\n");
EXPECT_EQ(console.PollLine(), std::optional<std::string>("draft"));
Input("中文\033[D\177\n");
EXPECT_EQ(console.PollLine(), std::optional<std::string>("文"));
}
TEST_F(Pty, StripsFragmentedAnsiOscAndControlCharactersFromLogs)
{
TerminalConsole console(slave, slave, slave);
console.Start();
Drain(master);
console.WriteLog("before\033[");
console.WriteLog("999;999Hafter\033]52;c;BAD");
console.WriteLog("\aend\033Psecret\033\\\x01\n");
const auto screen = Drain(master);
EXPECT_NE(screen.find("before"), std::string::npos);
EXPECT_NE(screen.find("after"), std::string::npos);
EXPECT_NE(screen.find("end"), std::string::npos);
EXPECT_EQ(screen.find("999;999H"), std::string::npos);
EXPECT_EQ(screen.find("52;c;BAD"), std::string::npos);
EXPECT_EQ(screen.find("secret"), std::string::npos);
EXPECT_EQ(screen.find('\x01'), std::string::npos);
EXPECT_NE(screen.find("\0338"), std::string::npos);
EXPECT_NE(screen.find("\0337"), std::string::npos);
}
TEST_F(Pty, MalformedLogEscapesRecoverAtNewlineAndPreserveUtf8Fragments)
{
TerminalConsole console(slave, slave, slave);
console.Start();
Drain(master);
console.WriteLog("\033]unterminated\nvisible-one\n");
console.WriteLog("\033[12;\nvisible-two\n");
console.WriteLog("\xe4\xb8");
console.WriteLog("\xad\xe6\x96\x87\n");
const auto screen = Drain(master);
EXPECT_EQ(screen.find("unterminated"), std::string::npos);
EXPECT_NE(screen.find("visible-one"), std::string::npos);
EXPECT_NE(screen.find("visible-two"), std::string::npos);
EXPECT_NE(screen.find("中文"), std::string::npos);
}
TEST_F(Pty, RedirectedStderrContainsOnlyOriginalLogBytes)
{
Pipe errors;
TerminalConsole console(slave, slave, errors.fds[1]);
console.Start();
Drain(master);
console.Err() << "error " << 42 << '\n';
EXPECT_EQ(Drain(errors.fds[0]), "error 42\n");
EXPECT_TRUE(Drain(master).empty());
}
TEST_F(Pty, BrokenRedirectedPipeDoesNotRaiseSigpipeOrPreventCleanup)
{
Pipe errors;
close(errors.fds[0]);
errors.fds[0] = -1;
const pid_t child = fork();
ASSERT_GE(child, 0);
if (child == 0)
{
struct sigaction action{};
action.sa_handler = SIG_DFL;
sigemptyset(&action.sa_mask);
sigaction(SIGPIPE, &action, nullptr);
sigset_t mask;
sigemptyset(&mask);
sigaddset(&mask, SIGPIPE);
sigprocmask(SIG_UNBLOCK, &mask, nullptr);
{
TerminalConsole console(slave, slave, errors.fds[1]);
console.Start();
console.WriteLog("closed destination\n", true);
}
_exit(0);
}
int status = 0;
ASSERT_EQ(waitpid(child, &status, 0), child);
ASSERT_TRUE(WIFEXITED(status));
EXPECT_EQ(WEXITSTATUS(status), 0);
ExpectRestored();
}
TEST_F(Pty, ResizesMarginsAndClipsChineseLineWithoutWrapping)
{
TerminalConsole console(slave, slave, slave);
console.Start();
Drain(master);
Size(8, 20);
console.Tick();
EXPECT_NE(Drain(master).find("\033[1;6r"), std::string::npos);
Input("中文中文中文中文中文中文中文");
EXPECT_FALSE(console.PollLine());
const auto narrow = Drain(master);
// 19 usable columns - 4 prompt columns = 15; seven CJK glyphs fit.
EXPECT_EQ(narrow.find("中文中文中文中文"), std::string::npos);
EXPECT_NE(narrow.find("\033[8;"), std::string::npos);
Size(2, 5);
console.Tick();
Drain(master);
console.WriteLog("must not overwrite editor\n");
EXPECT_EQ(Drain(master).find("must not overwrite editor"), std::string::npos);
Size(30, 100);
console.Tick();
EXPECT_NE(Drain(master).find("\033[1;28r"), std::string::npos);
Input("\n");
EXPECT_EQ(console.PollLine(), std::optional<std::string>("中文中文中文中文中文中文中文"));
}
TEST_F(Pty, CtrlDAndHangupLatchEof)
{
{
TerminalConsole console(slave, slave, slave);
console.Start();
Input("\004");
EXPECT_FALSE(console.PollLine());
EXPECT_TRUE(console.IsEof());
EXPECT_FALSE(console.PollLine());
}
ExpectRestored();
TerminalConsole console(slave, slave, slave);
console.Start();
close(master);
master = -1;
EXPECT_NO_THROW(console.PollLine());
EXPECT_TRUE(console.IsEof());
EXPECT_FALSE(console.PollLine());
}
TEST_F(Pty, DumbSmallOrDifferentOutputFallsBackWithoutAnsi)
{
setenv("TERM", "dumb", 1);
{
TerminalConsole console(slave, slave, slave);
console.Start();
EXPECT_FALSE(console.IsSplit());
EXPECT_EQ(Drain(master), ">>> ");
ExpectRestored();
}
setenv("TERM", "xterm", 1);
Size(3, 19);
{
TerminalConsole console(slave, slave, slave);
console.Start();
EXPECT_FALSE(console.IsSplit());
EXPECT_EQ(Drain(master), ">>> ");
ExpectRestored();
}
Size(24, 80);
Pipe output;
TerminalConsole console(slave, output.fds[1], output.fds[1]);
console.Start();
EXPECT_FALSE(console.IsSplit());
EXPECT_EQ(Drain(output.fds[0]), ">>> ");
ExpectRestored();
}
volatile std::sig_atomic_t interrupted = 0;
void NotifyInterrupt(int) { interrupted = 1; }
TEST_F(Pty, SigintNotificationThenNormalUnwindRestoresTermios)
{
int ready[2];
ASSERT_EQ(pipe(ready), 0);
const pid_t child = fork();
ASSERT_GE(child, 0);
if (child == 0)
{
close(ready[0]);
sigset_t blocked, previous;
sigemptyset(&blocked);
sigaddset(&blocked, SIGINT);
sigprocmask(SIG_BLOCK, &blocked, &previous);
struct sigaction action{};
action.sa_handler = NotifyInterrupt;
sigemptyset(&action.sa_mask);
sigaction(SIGINT, &action, nullptr);
{
TerminalConsole console(slave, slave, slave);
console.Start();
const char state = console.IsSplit() ? 'Y' : 'N';
if (write(ready[1], &state, 1) != 1) _exit(3);
while (!interrupted) sigsuspend(&previous);
}
_exit(0);
}
close(ready[1]);
pollfd item{ready[0], POLLIN, 0};
const int readyResult = poll(&item, 1, 3000);
char state = 0;
const auto count = readyResult > 0 ? read(ready[0], &state, 1) : -1;
close(ready[0]);
// Always reap, even if startup fails, so a failed test leaves no child.
kill(child, count == 1 && state == 'Y' ? SIGINT : SIGKILL);
int status = 0;
ASSERT_EQ(waitpid(child, &status, 0), child);
ASSERT_EQ(count, 1);
ASSERT_EQ(state, 'Y');
ASSERT_TRUE(WIFEXITED(status));
EXPECT_EQ(WEXITSTATUS(status), 0);
ExpectRestored();
}
TEST(TerminalConsoleTest, PipeFallbackPromptsOnceAndNeverConsumesWhileBusy)
{
Pipe input, output;
TerminalConsole console(input.fds[0], output.fds[1], output.fds[1]);
console.Out() << "login\n";
EXPECT_EQ(Drain(output.fds[0]), "login\n");
console.SetInputEnabled(false);
console.Start();
EXPECT_FALSE(console.IsSplit());
EXPECT_TRUE(Drain(output.fds[0]).empty());
Put(input.fds[1], "first\nsecond\n");
EXPECT_FALSE(console.PollLine());
console.SetInputEnabled(true);
console.Tick();
console.Tick();
EXPECT_EQ(Drain(output.fds[0]), ">>> ");
EXPECT_EQ(console.PollLine(), std::optional<std::string>("first"));
int remaining = 0;
ASSERT_EQ(ioctl(input.fds[0], FIONREAD, &remaining), 0);
EXPECT_EQ(remaining, 7);
console.Tick();
EXPECT_EQ(Drain(output.fds[0]), "\n>>> ");
EXPECT_EQ(console.PollLine(), std::optional<std::string>("second"));
input.CloseWriter();
EXPECT_FALSE(console.PollLine());
EXPECT_TRUE(console.IsEof());
EXPECT_EQ(Drain(output.fds[0]).find('\033'), std::string::npos);
}
} // namespace
#endif
+345
View File
@@ -0,0 +1,345 @@
#include "TerminalInput.h"
#include <chrono>
#include <cstdio>
#include <memory>
#include <stdexcept>
#include <string>
#include <string_view>
#include <gtest/gtest.h>
#ifdef _WIN32
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <Windows.h>
#include <fcntl.h>
#include <io.h>
#else
#include <fcntl.h>
#include <sys/ioctl.h>
#include <unistd.h>
#endif
namespace
{
using Bilicraft::TerminalInput;
void CloseDescriptor(int fd)
{
#ifdef _WIN32
_close(fd);
#else
close(fd);
#endif
}
class InputPipe
{
public:
InputPipe()
{
#ifdef _WIN32
if (_pipe(descriptors, 4096, _O_BINARY) != 0)
#else
if (pipe(descriptors) != 0)
#endif
throw std::runtime_error("Cannot create test pipe");
}
~InputPipe()
{
for (const int fd : descriptors)
if (fd >= 0)
CloseDescriptor(fd);
}
InputPipe(const InputPipe &) = delete;
InputPipe &operator=(const InputPipe &) = delete;
int Reader() const
{
return descriptors[0];
}
void CloseWriter()
{
CloseDescriptor(descriptors[1]);
descriptors[1] = -1;
}
void Write(std::string_view text)
{
// These tests only write small messages that fit into the empty pipe.
while (!text.empty())
{
#ifdef _WIN32
const auto count = _write(descriptors[1], text.data(), static_cast<unsigned>(text.size()));
#else
const auto count = write(descriptors[1], text.data(), text.size());
#endif
if (count <= 0)
throw std::runtime_error("Cannot write test pipe");
text.remove_prefix(static_cast<std::size_t>(count));
}
}
std::size_t BytesAvailable() const
{
#ifdef _WIN32
DWORD bytes = 0;
if (!PeekNamedPipe(reinterpret_cast<HANDLE>(_get_osfhandle(Reader())), nullptr, 0, nullptr, &bytes, nullptr))
#else
int bytes = 0;
if (ioctl(Reader(), FIONREAD, &bytes) != 0)
#endif
throw std::runtime_error("Cannot inspect test pipe");
return static_cast<std::size_t>(bytes);
}
private:
int descriptors[2]{-1, -1};
};
class InputFile
{
public:
explicit InputFile(std::string_view text) : file(std::tmpfile())
{
if (!file || std::fwrite(text.data(), 1, text.size(), file.get()) != text.size() ||
std::fflush(file.get()) != 0 || std::fseek(file.get(), 0, SEEK_SET) != 0)
throw std::runtime_error("Cannot create test input file");
}
int Descriptor() const
{
#ifdef _WIN32
return _fileno(file.get());
#else
return fileno(file.get());
#endif
}
private:
struct CloseFile
{
void operator()(std::FILE *value) const { std::fclose(value); }
};
std::unique_ptr<std::FILE, CloseFile> file;
};
std::optional<std::string> PollAvailableLine(TerminalInput &input)
{
// A call has a bounded byte budget. These files contain at most 64 KiB+1.
for (int attempt = 0; attempt < 64 && !input.IsEof(); ++attempt)
if (auto line = input.PollLine())
return line;
return std::nullopt;
}
TEST(TerminalInputTest, EmptyOpenPipeReturnsImmediatelyWithoutEof)
{
InputPipe pipe;
TerminalInput input(pipe.Reader());
const auto start = std::chrono::steady_clock::now();
EXPECT_FALSE(input.PollLine());
EXPECT_LT(std::chrono::steady_clock::now() - start, std::chrono::milliseconds(500));
EXPECT_FALSE(input.IsEof());
EXPECT_FALSE(input.IsInteractive());
}
TEST(TerminalInputTest, ReturnsCompleteLineWithoutWaitingForWriterToClose)
{
InputPipe pipe;
TerminalInput input(pipe.Reader());
pipe.Write("hello\n");
EXPECT_EQ(input.PollLine(), std::optional<std::string>("hello"));
EXPECT_FALSE(input.IsEof());
EXPECT_FALSE(input.PollLine());
}
TEST(TerminalInputTest, DoesNotReadAnyByteOfNextLine)
{
InputPipe pipe;
TerminalInput input(pipe.Reader());
pipe.Write("first\nsecond\n");
EXPECT_EQ(input.PollLine(), std::optional<std::string>("first"));
// Check the OS pipe, not just a private buffer: no read-ahead is allowed.
EXPECT_EQ(pipe.BytesAvailable(), std::string_view("second\n").size());
EXPECT_EQ(input.PollLine(), std::optional<std::string>("second"));
EXPECT_EQ(pipe.BytesAvailable(), 0U);
}
TEST(TerminalInputTest, RetainsPartialLineWithoutWaitingForMoreBytes)
{
InputPipe pipe;
TerminalInput input(pipe.Reader());
pipe.Write("par");
const auto start = std::chrono::steady_clock::now();
EXPECT_FALSE(input.PollLine());
EXPECT_LT(std::chrono::steady_clock::now() - start, std::chrono::milliseconds(500));
EXPECT_FALSE(input.IsEof());
pipe.Write("tial\nnext\n");
EXPECT_EQ(input.PollLine(), std::optional<std::string>("partial"));
EXPECT_EQ(pipe.BytesAvailable(), std::string_view("next\n").size());
}
TEST(TerminalInputTest, ReturnsFinalUnterminatedLineOnceAndMarksEof)
{
InputPipe pipe;
TerminalInput input(pipe.Reader());
pipe.Write("last");
pipe.CloseWriter();
EXPECT_EQ(input.PollLine(), std::optional<std::string>("last"));
EXPECT_TRUE(input.IsEof());
EXPECT_FALSE(input.PollLine());
EXPECT_FALSE(input.PollLine());
}
TEST(TerminalInputTest, EmptyClosedPipeMarksEofWithoutAnEmptyLine)
{
InputPipe pipe;
TerminalInput input(pipe.Reader());
pipe.CloseWriter();
EXPECT_FALSE(input.PollLine());
EXPECT_TRUE(input.IsEof());
}
TEST(TerminalInputTest, DrainsLinesBeforeReportingHangupAndAddsNoPhantomLine)
{
InputPipe pipe;
TerminalInput input(pipe.Reader());
pipe.Write("first\n\n");
pipe.CloseWriter();
EXPECT_EQ(input.PollLine(), std::optional<std::string>("first"));
EXPECT_FALSE(input.IsEof());
EXPECT_EQ(input.PollLine(), std::optional<std::string>(""));
EXPECT_FALSE(input.IsEof());
EXPECT_FALSE(input.PollLine());
EXPECT_TRUE(input.IsEof());
}
TEST(TerminalInputTest, RemovesOnlyCrImmediatelyBeforeLfIncludingAcrossCalls)
{
InputPipe pipe;
TerminalInput input(pipe.Reader());
pipe.Write("one\r");
EXPECT_FALSE(input.PollLine());
pipe.Write("\n\r\nx\ry\nfinal\r");
pipe.CloseWriter();
EXPECT_EQ(input.PollLine(), std::optional<std::string>("one"));
EXPECT_EQ(input.PollLine(), std::optional<std::string>(""));
EXPECT_EQ(input.PollLine(), std::optional<std::string>("x\ry"));
EXPECT_EQ(input.PollLine(), std::optional<std::string>("final\r"));
EXPECT_TRUE(input.IsEof());
}
TEST(TerminalInputTest, ReadsRegularFileAndFinalPartialLine)
{
InputFile file("first\r\nlast");
TerminalInput input(file.Descriptor());
EXPECT_FALSE(input.IsInteractive());
EXPECT_EQ(input.PollLine(), std::optional<std::string>("first"));
EXPECT_EQ(input.PollLine(), std::optional<std::string>("last"));
EXPECT_TRUE(input.IsEof());
}
TEST(TerminalInputTest, AcceptsExactLengthLimitWithNewline)
{
const std::string line(TerminalInput::MaxLineBytes, 'x');
InputFile file(line + "\n");
TerminalInput input(file.Descriptor());
EXPECT_EQ(PollAvailableLine(input), std::optional<std::string>(line));
EXPECT_FALSE(input.IsEof());
EXPECT_FALSE(input.PollLine());
EXPECT_TRUE(input.IsEof());
}
TEST(TerminalInputTest, AcceptsExactLengthLimitWithoutNewline)
{
const std::string line(TerminalInput::MaxLineBytes, 'x');
InputFile file(line);
TerminalInput input(file.Descriptor());
EXPECT_EQ(PollAvailableLine(input), std::optional<std::string>(line));
EXPECT_TRUE(input.IsEof());
}
TEST(TerminalInputTest, RejectsOverlongLineOnceRatherThanExecutingTruncatedCommand)
{
InputFile file(std::string(TerminalInput::MaxLineBytes + 1, 'x') + "\nnext\n");
TerminalInput input(file.Descriptor());
EXPECT_THROW(PollAvailableLine(input), std::length_error);
EXPECT_TRUE(input.IsEof());
EXPECT_NO_THROW(EXPECT_FALSE(input.PollLine()));
EXPECT_NO_THROW(EXPECT_FALSE(input.PollLine()));
}
TEST(TerminalInputTest, InvalidDescriptorReportsErrorOnlyOnce)
{
TerminalInput input(-1);
EXPECT_THROW(input.PollLine(), std::runtime_error);
EXPECT_TRUE(input.IsEof());
EXPECT_NO_THROW(EXPECT_FALSE(input.PollLine()));
}
TEST(TerminalInputTest, DestructionDoesNotCloseBorrowedDescriptor)
{
InputPipe pipe;
{
TerminalInput input(pipe.Reader());
EXPECT_FALSE(input.IsEof());
}
pipe.Write("still open\n");
TerminalInput next(pipe.Reader());
EXPECT_EQ(next.PollLine(), std::optional<std::string>("still open"));
}
#ifndef _WIN32
TEST(TerminalInputTest, PreservesBlockingAndNonblockingDescriptorFlags)
{
InputPipe pipe;
const int original = fcntl(pipe.Reader(), F_GETFL);
ASSERT_NE(original, -1);
{
TerminalInput input(pipe.Reader());
EXPECT_FALSE(input.PollLine());
EXPECT_EQ(fcntl(pipe.Reader(), F_GETFL), original);
}
ASSERT_NE(fcntl(pipe.Reader(), F_SETFL, original | O_NONBLOCK), -1);
{
TerminalInput input(pipe.Reader());
EXPECT_FALSE(input.PollLine());
pipe.Write("ready\n");
EXPECT_EQ(input.PollLine(), std::optional<std::string>("ready"));
}
EXPECT_EQ(fcntl(pipe.Reader(), F_GETFL), original | O_NONBLOCK);
}
TEST(TerminalInputTest, ClosedDescriptorReportsPollingErrorOnlyOnce)
{
InputPipe pipe;
const int duplicate = dup(pipe.Reader());
ASSERT_NE(duplicate, -1);
TerminalInput input(duplicate);
ASSERT_EQ(close(duplicate), 0);
EXPECT_THROW(input.PollLine(), std::runtime_error);
EXPECT_TRUE(input.IsEof());
EXPECT_NO_THROW(EXPECT_FALSE(input.PollLine()));
}
TEST(TerminalInputTest, ReadErrorDiscardsPartialLineAndLatchesEof)
{
InputPipe pipe;
const int duplicate = dup(pipe.Reader());
ASSERT_NE(duplicate, -1);
TerminalInput input(duplicate);
pipe.Write("do not execute");
EXPECT_FALSE(input.PollLine());
ASSERT_EQ(close(duplicate), 0);
EXPECT_THROW(input.PollLine(), std::runtime_error);
EXPECT_TRUE(input.IsEof());
EXPECT_FALSE(input.PollLine());
}
#endif
} // namespace