aboutsummaryrefslogtreecommitdiffstats
path: root/nihil.cli/test.cc
blob: c82281edac11fb325b91758a27931c66e3f69321 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
/*
 * This source code is released into the public domain.
 */

#include <iostream>
#include <vector>

#include <catch2/catch_test_macros.hpp>

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<char const *>{
			"cmd", "sub1", nullptr
		};
		auto argv = const_cast<char **>(args.data());

		int ret = nihil::dispatch_command(
				static_cast<int>(args.size()) - 1, argv);
		REQUIRE(ret == 0);
		REQUIRE(cmd_sub1_called == true);
		REQUIRE(cmd_sub2_called == false);
	}

	SECTION("cmd sub2") {
		auto args = std::vector<char const *>{
			"cmd", "sub2", nullptr
		};
		auto argv = const_cast<char **>(args.data());

		int ret = nihil::dispatch_command(
				static_cast<int>(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<char const *>{
		"nocomd", "sub", nullptr
	};
	auto argv = const_cast<char **>(args.data());

	auto output = std::string();
	auto ret = int{};
	{
		auto capture = nihil::capture_stream(std::cerr);
		ret = nihil::dispatch_command(
				static_cast<int>(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<char const *>{
		"cmd", nullptr
	};
	auto argv = const_cast<char **>(args.data());

	auto output = std::string();
	auto ret = int{};
	{
		auto capture = nihil::capture_stream(std::cerr);
		ret = nihil::dispatch_command(
				static_cast<int>(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));
}