cxxopt/test/options.cpp

89 lines
1.8 KiB
C++
Raw Normal View History

2016-08-25 00:49:56 +02:00
#define CATCH_CONFIG_MAIN
#include "catch.hpp"
2016-08-26 11:20:55 +02:00
#include <initializer_list>
2016-08-26 00:22:04 +02:00
#include "../src/cxxopts.hpp"
class Argv {
public:
2016-08-26 11:20:55 +02:00
Argv(std::initializer_list<const char*> argv)
: m_argv(new char*[argv.size()])
, m_argc(argv.size())
2016-08-26 00:22:04 +02:00
{
2016-08-26 11:20:55 +02:00
int i = 0;
auto iter = argv.begin();
while (iter != argv.end()) {
auto len = strlen(*iter) + 1;
2016-08-26 00:22:04 +02:00
auto ptr = std::unique_ptr<char[]>(new char[len]);
2016-08-26 11:20:55 +02:00
strcpy(ptr.get(), *iter);
2016-08-26 00:22:04 +02:00
m_args.push_back(std::move(ptr));
m_argv.get()[i] = m_args.back().get();
2016-08-26 11:20:55 +02:00
++iter;
++i;
2016-08-26 00:22:04 +02:00
}
}
char** argv() const {
return m_argv.get();
}
2016-08-26 11:20:55 +02:00
int argc() const {
return m_argc;
}
2016-08-26 00:22:04 +02:00
private:
std::vector<std::unique_ptr<char[]>> m_args;
std::unique_ptr<char*[]> m_argv;
2016-08-26 11:20:55 +02:00
int m_argc;
2016-08-26 00:22:04 +02:00
};
2016-08-25 00:49:56 +02:00
TEST_CASE("Basic options", "[options]")
{
2016-08-26 00:22:04 +02:00
cxxopts::Options options("tester", " - test basic options");
options.add_options()
("long", "a long option")
("s,short", "a short option")
("value", "an option with a value", cxxopts::value<std::string>())
2016-08-26 10:58:28 +02:00
("a,av", "a short option with a value", cxxopts::value<std::string>());
2016-08-26 00:22:04 +02:00
2016-08-26 11:20:55 +02:00
Argv argv({
2016-08-26 00:22:04 +02:00
"tester",
"--long",
"-s",
"--value",
"value",
"-a",
"b"
2016-08-26 11:20:55 +02:00
});
2016-08-26 00:22:04 +02:00
char** actual_argv = argv.argv();
2016-08-26 11:20:55 +02:00
auto argc = argv.argc();
2016-08-26 00:22:04 +02:00
options.parse(argc, actual_argv);
CHECK(options.count("long") == 1);
2016-08-26 11:09:40 +02:00
CHECK(options.count("s") == 1);
CHECK(options.count("value") == 1);
CHECK(options.count("a") == 1);
CHECK(options["value"].as<std::string>() == "value");
CHECK(options["a"].as<std::string>() == "b");
2016-08-25 00:49:56 +02:00
}
2016-08-26 11:20:55 +02:00
TEST_CASE("No positional", "[positional]")
{
cxxopts::Options options("test_positional", " - test no positional options");
Argv argv({"tester", "a", "b", "def"});
char** passed_argv = argv.argv();
auto argc = argv.argc();
options.parse(argc, passed_argv);
}