From 47999457e647352ae7e71d43c65e7b39ae5ca567 Mon Sep 17 00:00:00 2001 From: Lexi Winter Date: Tue, 1 Jul 2025 22:02:48 +0100 Subject: cli: add tests for command_tree --- nihil.cli/dispatch_command.test.cc | 102 +++++++++++++++++++++++++++++++++++++ 1 file changed, 102 insertions(+) create mode 100644 nihil.cli/dispatch_command.test.cc (limited to 'nihil.cli/dispatch_command.test.cc') diff --git a/nihil.cli/dispatch_command.test.cc b/nihil.cli/dispatch_command.test.cc new file mode 100644 index 0000000..8253bdc --- /dev/null +++ b/nihil.cli/dispatch_command.test.cc @@ -0,0 +1,102 @@ +// This source code is released into the public domain. + +#include + +#include + +import nihil.std; +import nihil.cli; +import nihil.util; + +namespace { + +auto cmd_sub1_called = false; +auto cmd_sub1 = nihil::command("cmd sub1", "", [](int, char **) -> int +{ + cmd_sub1_called = true; + return 0; +}); + +auto cmd_sub2_called = false; +auto cmd_sub2 = nihil::command("cmd sub2", "", [](int, char **) -> int +{ + cmd_sub2_called = true; + return 0; +}); + +} // anonymous namespace + +TEST_CASE("nihil.cli: dispatch_command: basic", "[nihil.cli]") +{ + SECTION("cmd sub1") { + auto args = std::vector{ + "cmd", "sub1", nullptr + }; + auto *argv = const_cast(args.data()); + + auto const ret = nihil::dispatch_command( + static_cast(args.size()) - 1, argv); + REQUIRE(ret == 0); + REQUIRE(cmd_sub1_called == true); + REQUIRE(cmd_sub2_called == false); + } + + SECTION("cmd sub2") { + auto args = std::vector{ + "cmd", "sub2", nullptr + }; + auto *argv = const_cast(args.data()); + + auto const ret = nihil::dispatch_command( + static_cast(args.size()) - 1, argv); + REQUIRE(ret == 0); + REQUIRE(cmd_sub2_called == true); + } +} + +TEST_CASE("nihil.cli: dispatch_command: unknown command", "[nihil.cli]") +{ + auto args = std::vector{ + "nocomd", "sub", nullptr + }; + auto *argv = const_cast(args.data()); + + auto output = std::string(); + auto ret = int{}; + { + auto capture = nihil::capture_stream(std::cerr); + ret = nihil::dispatch_command( + static_cast(args.size()) - 1, argv); + std::cerr.flush(); + output = capture.str(); + } + + REQUIRE(ret == EX_USAGE); + + auto const *progname = ::getprogname(); + REQUIRE(output == std::format("{}: usage:\n cmd\n", progname)); +} + +TEST_CASE("nihil.cli: dispatch_command: incomplete command", "[nihil.cli]") +{ + auto args = std::vector{ + "cmd", nullptr + }; + auto *argv = const_cast(args.data()); + + auto output = std::string(); + auto ret = int{}; + { + auto capture = nihil::capture_stream(std::cerr); + ret = nihil::dispatch_command( + static_cast(args.size()) - 1, argv); + std::cerr.flush(); + output = capture.str(); + } + + REQUIRE(ret == EX_USAGE); + + auto const *progname = ::getprogname(); + REQUIRE(output == std::format("{}: usage:\n cmd sub1\n cmd sub2\n", + progname)); +} -- cgit v1.2.3