浏览代码

Add more tests.
Add error messages.
Fix error with tuple_element.

Sam Jaffe 5 年之前
父节点
当前提交
c852e65bd3
共有 3 个文件被更改,包括 30 次插入5 次删除
  1. 7 3
      include/cli/cli.h
  2. 5 2
      src/cli.cxx
  3. 18 0
      test/cli_test.cxx

+ 7 - 3
include/cli/cli.h

@@ -46,14 +46,18 @@ template <typename... Args, size_t... Is>
 void cli_invoke(std::function<void(Args...)> cb, cli::args_t const & args,
                 std::index_sequence<Is...>) {
   using tuple = std::tuple<Args...>;
-  cb(cli::from_string<std::tuple_element<Is, tuple>>(args[Is])...);
+  cb(cli::from_string<std::tuple_element_t<Is, tuple>>(args[Is])...);
 }
 
 template <typename... Args>
 cli & cli::register_callback(std::string const & handle,
                              std::function<void(Args...)> cb) {
-  callbacks_.emplace(handle, [cb](args_t const & args) {
-    if (sizeof...(Args) > args.size()) return; // TODO: Error message
+  callbacks_.emplace(handle, [=](args_t const & args) {
+    if (sizeof...(Args) > args.size()) {
+      std::cerr << "Missing Args in command '" << handle << "', " <<
+          sizeof...(Args) << " required, but " << args.size() << " input\n";
+      return;
+    }
     cli_invoke(cb, args, std::make_index_sequence<sizeof...(Args)>());
   });
   return *this;

+ 5 - 2
src/cli.cxx

@@ -18,11 +18,14 @@ cli::cli(std::istream &in) : in_(in), callbacks_(), eof_(false) {
 
 void cli::run() const {
   std::string command;
-  while (!eof_ && std::getline(in_, command).good()) {
+  while (!eof_ && std::getline(in_, command)) {
     auto views = string_utils::split(command, " ");
     command = views.front();
     views.erase(views.begin());
-    if (!callbacks_.count(command)) continue; // TODO: Error message
+    if (!callbacks_.count(command)) {
+      std::cerr << "Unknown command: " << command << "\n";
+      continue;
+    }
     callbacks_.at(command)(views);
   }
 }

+ 18 - 0
test/cli_test.cxx

@@ -16,9 +16,27 @@
 // unit tests.
 #undef EXPECT_THAT
 #define EXPECT_THAT ASSERT_THAT
+#undef EXPECT_TRUE
+#define EXPECT_TRUE ASSERT_TRUE
+#undef EXPECT_FALSE
+#define EXPECT_FALSE ASSERT_FALSE
 #endif
 
 TEST(CliTest, EndsOnQuit) {
   std::stringstream input{R"(quit)"};
   cli::cli(input).run();
 }
+
+TEST(CliTest, CanInputNoArgsCommand) {
+  bool was_hit{false};
+  std::stringstream input{R"(act)"};
+  cli::cli(input).register_callback("act", [&](){ was_hit = true; }).run();
+  EXPECT_TRUE(was_hit);
+}
+
+TEST(CliTest, WillSkipCallbackIfNotEnoughArgs) {
+  bool was_hit{false};
+  std::stringstream input{R"(act)"};
+  cli::cli(input).register_callback("act", [&](int){ was_hit = true; }).run();
+  EXPECT_FALSE(was_hit);
+}