From d24315268c11d435bb9accbce87b7f46dda6ed3e Mon Sep 17 00:00:00 2001 From: Lexi Winter Date: Sun, 29 Jun 2025 00:42:31 +0100 Subject: cli: improve command dispatch a bit --- nihil.cli/test.cc | 100 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 100 insertions(+) create mode 100644 nihil.cli/test.cc (limited to 'nihil.cli/test.cc') diff --git a/nihil.cli/test.cc b/nihil.cli/test.cc new file mode 100644 index 0000000..c265700 --- /dev/null +++ b/nihil.cli/test.cc @@ -0,0 +1,100 @@ +/* + * This source code is released into the public domain. + */ + +#include +#include + +#include + +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()); + + int ret = nihil::dispatch_command(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()); + + int ret = nihil::dispatch_command(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(args.size() - 1, argv); + std::cerr.flush(); + output = capture.str(); + } + + REQUIRE(ret == 1); + + auto *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(args.size() - 1, argv); + std::cerr.flush(); + output = capture.str(); + } + + REQUIRE(ret == 1); + + auto *progname = ::getprogname(); + REQUIRE(output == std::format("{}: usage:\n cmd sub1\n cmd sub2\n", + progname)); +} -- cgit v1.2.3