4#include "../conversion/stringbuilder.h"
5#include "../conversion/stringconversion.h"
7#include "../application/argumentparser.h"
8#include "../application/argumentparserprivate.h"
9#include "../application/commandlineutils.h"
10#include "../application/fakeqtconfigarguments.h"
12#include "../io/ansiescapecodes.h"
13#include "../io/path.h"
15#include "../misc/parseerror.h"
17#include "resources/config.h"
19#include <cppunit/TestFixture.h>
20#include <cppunit/extensions/HelperMacros.h>
25#ifdef PLATFORM_WINDOWS
33using namespace CPPUNIT_NS;
45#ifndef PLATFORM_WINDOWS
50 CPPUNIT_TEST_SUITE_END();
53 void setUp()
override;
61#ifndef PLATFORM_WINDOWS
69 [[noreturn]]
void failOnExit(
int code);
76#ifndef PLATFORM_WINDOWS
77 setenv(
"ENABLE_ESCAPE_CODES",
"0", 1);
86[[noreturn]]
void ArgumentParserTests::failOnExit(
int code)
88 CPPUNIT_FAIL(
argsToString(
"Exited unexpectedly with code ", code));
96 Argument argument(
"test",
't',
"some description");
97 CPPUNIT_ASSERT_EQUAL(
false, argument.
isRequired());
99 CPPUNIT_ASSERT_EQUAL(
true, argument.
isRequired());
100 Argument subArg(
"sub",
's',
"sub arg");
102 CPPUNIT_ASSERT_EQUAL(&argument, subArg.
parents().at(0));
106#ifndef PLATFORM_WINDOWS
107 setenv(
"FOO_ENV_VAR",
"foo", 1);
108 CPPUNIT_ASSERT_EQUAL(
"foo"s,
string(argument.
firstValue()));
111 occurrence.
values.emplace_back(
"bar");
112 argument.m_occurrences.emplace_back(move(occurrence));
113 CPPUNIT_ASSERT_EQUAL(
"bar"s,
string(argument.
firstValue()));
123 parser.setExitFunction(std::bind(&ArgumentParserTests::failOnExit,
this, std::placeholders::_1));
126 auto verboseArg =
Argument(
"verbose",
'v',
"be verbose");
127 verboseArg.setCombinable(
true);
128 auto fileArg =
Argument(
"file",
'f',
"specifies the path of the file to be opened");
129 fileArg.setValueNames({
"path" });
130 fileArg.setRequiredValueCount(1);
131 fileArg.setEnvironmentVariable(
"PATH");
132 auto filesArg =
Argument(
"files",
'f',
"specifies the path of the file(s) to be opened");
133 filesArg.setValueNames({
"path 1",
"path 2" });
134 filesArg.setRequiredValueCount(Argument::varValueCount);
135 auto outputFileArg =
Argument(
"output-file",
'o',
"specifies the path of the output file");
136 outputFileArg.setValueNames({
"path" });
137 outputFileArg.setRequiredValueCount(1);
138 outputFileArg.setRequired(
true);
139 outputFileArg.setCombinable(
true);
140 auto printFieldNamesArg =
Argument(
"print-field-names",
'\0',
"prints available field names");
141 auto displayFileInfoArg =
Argument(
"display-file-info",
'i',
"displays general file information");
142 auto notAlbumArg =
Argument(
"album",
'a',
"should not be confused with album value");
143 displayFileInfoArg.setDenotesOperation(
true);
144 displayFileInfoArg.setSubArguments({ &fileArg, &verboseArg, ¬AlbumArg });
145 auto fieldsArg =
Argument(
"fields",
'\0',
"specifies the fields");
146 fieldsArg.setRequiredValueCount(Argument::varValueCount);
147 fieldsArg.setValueNames({
"title",
"album",
"artist",
"trackpos" });
148 fieldsArg.setImplicit(
true);
149 auto displayTagInfoArg =
Argument(
"get",
'p',
"displays the values of all specified tag fields (displays all fields if none specified)");
150 displayTagInfoArg.setDenotesOperation(
true);
151 displayTagInfoArg.setSubArguments({ &fieldsArg, &filesArg, &verboseArg, ¬AlbumArg });
152 parser.setMainArguments(
153 { &qtConfigArgs.qtWidgetsGuiArg(), &printFieldNamesArg, &displayTagInfoArg, &displayFileInfoArg, &parser.noColorArg(), &parser.helpArg() });
156 parser.parseArgs(0,
nullptr, ParseArgumentBehavior::CheckConstraints | ParseArgumentBehavior::InvokeCallbacks);
157 CPPUNIT_ASSERT(!parser.executable());
158 CPPUNIT_ASSERT(!parser.specifiedOperation());
159 CPPUNIT_ASSERT_EQUAL(0u, parser.actualArgumentCount());
162 const char *argv[] = {
"tageditor",
"get",
"album",
"title",
"diskpos",
"-f",
"somefile" };
165 parser.parseArgs(7, argv, ParseArgumentBehavior::CheckConstraints | ParseArgumentBehavior::InvokeCallbacks);
166 CPPUNIT_FAIL(
"Exception expected.");
168 CPPUNIT_ASSERT_EQUAL(
"The argument \"files\" can not be combined with \"fields\"."s,
string(e.what()));
170 auto ss = std::stringstream();
172 CPPUNIT_ASSERT_EQUAL(
173 "Error: Unable to parse arguments: The argument \"files\" can not be combined with \"fields\".\nSee --help for available commands.\n"sv,
174 std::string_view(ss.str()));
176 CPPUNIT_ASSERT(parser.isUncombinableMainArgPresent());
179 filesArg.setCombinable(
true);
181 parser.parseArgs(7, argv, ParseArgumentBehavior::CheckConstraints | ParseArgumentBehavior::InvokeCallbacks);
183 CPPUNIT_ASSERT(!qtConfigArgs.qtWidgetsGuiArg().isPresent());
184 CPPUNIT_ASSERT(!displayFileInfoArg.isPresent());
185 CPPUNIT_ASSERT_EQUAL(
"tageditor"sv, std::string_view(parser.executable()));
186 CPPUNIT_ASSERT(!verboseArg.isPresent());
187 CPPUNIT_ASSERT(displayTagInfoArg.isPresent());
188 CPPUNIT_ASSERT(fieldsArg.isPresent());
189 CPPUNIT_ASSERT_EQUAL(
"album"sv, std::string_view(fieldsArg.values().at(0)));
190 CPPUNIT_ASSERT_EQUAL(
"title"sv, std::string_view(fieldsArg.values().at(1)));
191 CPPUNIT_ASSERT_EQUAL(
"diskpos"sv, std::string_view(fieldsArg.values().at(2)));
192 CPPUNIT_ASSERT_THROW(displayTagInfoArg.values().at(3), std::out_of_range);
193 CPPUNIT_ASSERT_EQUAL(&displayTagInfoArg, parser.specifiedOperation());
196 const char *argv2[] = {
"tageditor",
"",
"-p",
"album",
"title",
"diskpos",
"",
"--files",
"somefile" };
199 parser.parseArgs(9, argv2, ParseArgumentBehavior::CheckConstraints | ParseArgumentBehavior::InvokeCallbacks);
201 CPPUNIT_ASSERT(!qtConfigArgs.qtWidgetsGuiArg().isPresent());
202 CPPUNIT_ASSERT(!displayFileInfoArg.isPresent());
203 CPPUNIT_ASSERT(!verboseArg.isPresent());
204 CPPUNIT_ASSERT(displayTagInfoArg.isPresent());
205 CPPUNIT_ASSERT(fieldsArg.isPresent());
206 CPPUNIT_ASSERT_EQUAL(
"album"sv, std::string_view(fieldsArg.values().at(0)));
207 CPPUNIT_ASSERT_EQUAL(
"title"sv, std::string_view(fieldsArg.values().at(1)));
208 CPPUNIT_ASSERT_EQUAL(
"diskpos"sv, std::string_view(fieldsArg.values().at(2)));
209 CPPUNIT_ASSERT_EQUAL(
""sv, std::string_view(fieldsArg.values().at(3)));
210 CPPUNIT_ASSERT_THROW(fieldsArg.values().at(4), std::out_of_range);
211 CPPUNIT_ASSERT(filesArg.isPresent());
212 CPPUNIT_ASSERT_EQUAL(
"somefile"sv, std::string_view(filesArg.values().at(0)));
215 const char *argv3[] = {
"tageditor",
"album",
"title",
"diskpos",
"--files",
"somefile" };
218 parser.parseArgs(6, argv3, ParseArgumentBehavior::CheckConstraints | ParseArgumentBehavior::InvokeCallbacks);
219 CPPUNIT_FAIL(
"Exception expected.");
221 CPPUNIT_ASSERT_EQUAL(
"The specified argument \"album\" is unknown.\nDid you mean get or --help?"sv, std::string_view(e.what()));
225 const char *argv18[] = {
"tageditor",
"get",
"album",
"title",
"diskpos",
"--verbose",
"--fi" };
228 parser.parseArgs(7, argv18, ParseArgumentBehavior::CheckConstraints | ParseArgumentBehavior::InvokeCallbacks);
229 CPPUNIT_FAIL(
"Exception expected.");
231 CPPUNIT_ASSERT_EQUAL(
"The specified argument \"--fi\" is unknown.\nDid you mean --files or --no-color?"sv, std::string_view(e.what()));
235 parser.setUnknownArgumentBehavior(UnknownArgumentBehavior::Warn);
237#ifndef PLATFORM_WINDOWS
238 const OutputCheck outputCheck(
"Warning: The specified argument \"album\" is unknown and will be ignored.\n"s
239 "Warning: The specified argument \"title\" is unknown and will be ignored.\n"s
240 "Warning: The specified argument \"diskpos\" is unknown and will be ignored.\n"s
241 "Warning: The specified argument \"--files\" is unknown and will be ignored.\n"s
242 "Warning: The specified argument \"somefile\" is unknown and will be ignored.\n"s,
247 parser.parseArgs(6, argv3, ParseArgumentBehavior::CheckConstraints | ParseArgumentBehavior::InvokeCallbacks);
250 CPPUNIT_ASSERT(!qtConfigArgs.qtWidgetsGuiArg().isPresent());
251 CPPUNIT_ASSERT(!displayFileInfoArg.isPresent());
252 CPPUNIT_ASSERT(!displayTagInfoArg.isPresent());
253 CPPUNIT_ASSERT(!fieldsArg.isPresent());
254 CPPUNIT_ASSERT(!filesArg.isPresent());
258 const char *argv4[] = {
"tageditor",
"-i",
"-vf",
"test" };
259 parser.setUnknownArgumentBehavior(UnknownArgumentBehavior::Fail);
261 parser.parseArgs(4, argv4, ParseArgumentBehavior::CheckConstraints | ParseArgumentBehavior::InvokeCallbacks);
262 CPPUNIT_ASSERT(!qtConfigArgs.qtWidgetsGuiArg().isPresent());
263 CPPUNIT_ASSERT(displayFileInfoArg.isPresent());
264 CPPUNIT_ASSERT(verboseArg.isPresent());
265 CPPUNIT_ASSERT(!displayTagInfoArg.isPresent());
266 CPPUNIT_ASSERT(!filesArg.isPresent());
267 CPPUNIT_ASSERT(fileArg.isPresent());
268 CPPUNIT_ASSERT_EQUAL(
"test"sv, std::string_view(fileArg.values().at(0)));
269 CPPUNIT_ASSERT_THROW(fileArg.values().at(1), std::out_of_range);
272 displayFileInfoArg.reset();
275 parser.parseArgs(4, argv4, ParseArgumentBehavior::CheckConstraints | ParseArgumentBehavior::InvokeCallbacks);
276 CPPUNIT_FAIL(
"Exception expected.");
278 CPPUNIT_ASSERT(!qtConfigArgs.qtWidgetsGuiArg().isPresent());
279 CPPUNIT_ASSERT_EQUAL(
"The argument \"verbose\" mustn't be specified more than 1 time."sv, std::string_view(e.what()));
283 displayFileInfoArg.reset();
285 verboseArg.setConstraints(0, Argument::varValueCount);
286 parser.parseArgs(4, argv4, ParseArgumentBehavior::CheckConstraints | ParseArgumentBehavior::InvokeCallbacks);
287 CPPUNIT_ASSERT(!qtConfigArgs.qtWidgetsGuiArg().isPresent());
290 verboseArg.setRequired(
true);
292 parser.parseArgs(4, argv4, ParseArgumentBehavior::CheckConstraints | ParseArgumentBehavior::InvokeCallbacks);
293 CPPUNIT_ASSERT(!qtConfigArgs.qtWidgetsGuiArg().isPresent());
296 const char *argv5[] = {
"tageditor",
"-i",
"-f",
"test" };
297 displayFileInfoArg.reset();
301 parser.parseArgs(4, argv5, ParseArgumentBehavior::CheckConstraints | ParseArgumentBehavior::InvokeCallbacks);
302 CPPUNIT_FAIL(
"Exception expected.");
304 CPPUNIT_ASSERT(!qtConfigArgs.qtWidgetsGuiArg().isPresent());
305 CPPUNIT_ASSERT_EQUAL(
"The argument \"verbose\" must be specified at least 1 time."sv, std::string_view(e.what()));
307 verboseArg.setRequired(
false);
310 const char *argv10[] = {
"tageditor",
"-pf",
"test" };
312 parser.parseArgs(3, argv10, ParseArgumentBehavior::CheckConstraints | ParseArgumentBehavior::InvokeCallbacks);
313 CPPUNIT_ASSERT(displayTagInfoArg.isPresent());
314 CPPUNIT_ASSERT(!displayFileInfoArg.isPresent());
315 CPPUNIT_ASSERT(!fileArg.isPresent());
316 CPPUNIT_ASSERT(filesArg.isPresent());
317 CPPUNIT_ASSERT_EQUAL(1_st, filesArg.values(0).size());
318 CPPUNIT_ASSERT_EQUAL(
"test"sv, std::string_view(filesArg.values(0).at(0)));
319 CPPUNIT_ASSERT(!qtConfigArgs.qtWidgetsGuiArg().isPresent());
322 const char *argv6[] = {
"tageditor",
"-g" };
324 parser.parseArgs(2, argv6, ParseArgumentBehavior::CheckConstraints | ParseArgumentBehavior::InvokeCallbacks);
325 CPPUNIT_ASSERT(qtConfigArgs.qtWidgetsGuiArg().isPresent());
328 const char *argv7[] = {
"tageditor",
"-f",
"test" };
331 parser.parseArgs(3, argv7, ParseArgumentBehavior::CheckConstraints | ParseArgumentBehavior::InvokeCallbacks);
332 CPPUNIT_FAIL(
"Exception expected.");
334 CPPUNIT_ASSERT(!qtConfigArgs.qtWidgetsGuiArg().isPresent());
335 CPPUNIT_ASSERT_EQUAL(
"The specified argument \"-f\" is unknown.\nDid you mean get or --help?"sv, std::string_view(e.what()));
339 const char *argv11[] = {
"tageditor",
"-if=test-v" };
341 parser.parseArgs(2, argv11, ParseArgumentBehavior::CheckConstraints | ParseArgumentBehavior::InvokeCallbacks);
342 CPPUNIT_ASSERT(!filesArg.isPresent());
343 CPPUNIT_ASSERT(fileArg.isPresent());
344 CPPUNIT_ASSERT(!verboseArg.isPresent());
345 CPPUNIT_ASSERT_EQUAL(1_st, fileArg.values(0).size());
346 CPPUNIT_ASSERT_EQUAL(
"test-v"s,
string(fileArg.values(0).front()));
347 const char *argv15[] = {
"tageditor",
"-i",
"--file=test",
"-v" };
349 parser.parseArgs(4, argv15, ParseArgumentBehavior::CheckConstraints | ParseArgumentBehavior::InvokeCallbacks);
350 CPPUNIT_ASSERT(!filesArg.isPresent());
351 CPPUNIT_ASSERT(fileArg.isPresent());
352 CPPUNIT_ASSERT(verboseArg.isPresent());
353 CPPUNIT_ASSERT_EQUAL(1_st, fileArg.values(0).size());
354 CPPUNIT_ASSERT_EQUAL(
"test"sv, std::string_view(fileArg.values(0).front()));
357 const char *argv12[] = {
"tageditor",
"-iftest" };
359 parser.parseArgs(2, argv12, ParseArgumentBehavior::CheckConstraints | ParseArgumentBehavior::InvokeCallbacks);
360 CPPUNIT_ASSERT(!filesArg.isPresent());
361 CPPUNIT_ASSERT(fileArg.isPresent());
362 CPPUNIT_ASSERT_EQUAL(1_st, fileArg.values(0).size());
363 CPPUNIT_ASSERT_EQUAL(
"test"sv, std::string_view(fileArg.values().at(0)));
366 const char *argv17[] = {
"tageditor",
"-if=test-v",
"--no-color" };
368 parser.parseArgs(3, argv17, ParseArgumentBehavior::CheckConstraints | ParseArgumentBehavior::InvokeCallbacks);
369 CPPUNIT_ASSERT(!filesArg.isPresent());
370 CPPUNIT_ASSERT(fileArg.isPresent());
371 CPPUNIT_ASSERT(!verboseArg.isPresent());
372 CPPUNIT_ASSERT(parser.noColorArg().isPresent());
373 CPPUNIT_ASSERT_EQUAL(1_st, fileArg.values(0).size());
374 CPPUNIT_ASSERT_EQUAL(
"test-v"sv, std::string_view(fileArg.values(0).front()));
377 const char *argv8[] = {
"tageditor" };
379 parser.parseArgs(1, argv8, ParseArgumentBehavior::CheckConstraints | ParseArgumentBehavior::InvokeCallbacks);
380 CPPUNIT_ASSERT(qtConfigArgs.qtWidgetsGuiArg().isPresent());
381 CPPUNIT_ASSERT(!displayFileInfoArg.isPresent());
382 CPPUNIT_ASSERT(!verboseArg.isPresent());
383 CPPUNIT_ASSERT(!displayTagInfoArg.isPresent());
384 CPPUNIT_ASSERT(!filesArg.isPresent());
385 CPPUNIT_ASSERT(!fileArg.isPresent());
386 if (
const auto path = std::getenv(
"PATH")) {
387 CPPUNIT_ASSERT(fileArg.firstValue());
388 CPPUNIT_ASSERT_EQUAL(std::string_view(path), std::string_view(fileArg.firstValue()));
390 CPPUNIT_ASSERT(!fileArg.firstValue());
394 const char *argv13[] = {
"tageditor",
"get",
"--fields",
"album=test",
"title",
"diskpos",
"--files",
"somefile" };
395 verboseArg.setRequired(
false);
397 parser.parseArgs(8, argv13, ParseArgumentBehavior::CheckConstraints | ParseArgumentBehavior::InvokeCallbacks);
399 CPPUNIT_ASSERT(!qtConfigArgs.qtWidgetsGuiArg().isPresent());
400 CPPUNIT_ASSERT(!displayFileInfoArg.isPresent());
401 CPPUNIT_ASSERT(!verboseArg.isPresent());
402 CPPUNIT_ASSERT(displayTagInfoArg.isPresent());
403 CPPUNIT_ASSERT(fieldsArg.isPresent());
404 CPPUNIT_ASSERT_EQUAL(
"album=test"sv, std::string_view(fieldsArg.values().at(0)));
405 CPPUNIT_ASSERT_EQUAL(
"title"sv, std::string_view(fieldsArg.values().at(1)));
406 CPPUNIT_ASSERT_EQUAL(
"diskpos"sv, std::string_view(fieldsArg.values().at(2)));
407 CPPUNIT_ASSERT_THROW(fieldsArg.values().at(3), out_of_range);
408 CPPUNIT_ASSERT(filesArg.isPresent());
409 CPPUNIT_ASSERT_EQUAL(
"somefile"sv, std::string_view(filesArg.values().at(0)));
410 CPPUNIT_ASSERT(!notAlbumArg.isPresent());
413 const char *argv9[] = {
"tageditor",
"-p",
"album",
"title",
"diskpos" };
414 fieldsArg.setRequiredValueCount(4);
417 parser.parseArgs(5, argv9, ParseArgumentBehavior::CheckConstraints | ParseArgumentBehavior::InvokeCallbacks);
418 CPPUNIT_FAIL(
"Exception expected.");
420 CPPUNIT_ASSERT(!qtConfigArgs.qtWidgetsGuiArg().isPresent());
421 CPPUNIT_ASSERT_EQUAL(
422 "Not all parameters for argument \"fields\" provided. You have to provide the following parameters: title album artist trackpos"sv,
423 std::string_view(e.what()));
427 const char *argv16[] = {
"tageditor",
"--hel",
"-p",
"album",
"title",
"diskpos" };
428 fieldsArg.setRequiredValueCount(Argument::varValueCount);
431 parser.parseArgs(6, argv16, ParseArgumentBehavior::CheckConstraints | ParseArgumentBehavior::InvokeCallbacks);
432 CPPUNIT_FAIL(
"Exception expected.");
434 CPPUNIT_ASSERT(!qtConfigArgs.qtWidgetsGuiArg().isPresent());
435 CPPUNIT_ASSERT_EQUAL(
"The specified argument \"--hel\" is unknown.\nDid you mean --help or get?"sv, std::string_view(e.what()));
439 const char *argv14[] = {
"tageditor",
"get",
"fields",
"album=test",
"-f",
"somefile" };
441 fieldsArg.setDenotesOperation(
true);
442 parser.parseArgs(6, argv14, ParseArgumentBehavior::CheckConstraints | ParseArgumentBehavior::InvokeCallbacks);
443 CPPUNIT_ASSERT(displayTagInfoArg.isPresent());
444 CPPUNIT_ASSERT(fieldsArg.isPresent());
445 CPPUNIT_ASSERT_EQUAL(
"album=test"sv, std::string_view(fieldsArg.values().at(0)));
449 fieldsArg.setDenotesOperation(
false);
450 parser.parseArgs(6, argv14, ParseArgumentBehavior::CheckConstraints | ParseArgumentBehavior::InvokeCallbacks);
451 CPPUNIT_ASSERT(displayTagInfoArg.isPresent());
452 CPPUNIT_ASSERT(fieldsArg.isPresent());
453 CPPUNIT_ASSERT_EQUAL(
"fields"sv, std::string_view(fieldsArg.values().at(0)));
454 CPPUNIT_ASSERT_EQUAL(
"album=test"sv, std::string_view(fieldsArg.values().at(1)));
457 const char *argv19[] = {
"tageditor",
"get",
"--fields",
"foo",
"bar",
"--help" };
460 parser.parseArgs(6, argv19, ParseArgumentBehavior::CheckConstraints | ParseArgumentBehavior::InvokeCallbacks);
461 CPPUNIT_FAIL(
"Exception expected.");
463 CPPUNIT_ASSERT_EQUAL_MESSAGE(
"--help assumed to be an argument without greedy-flag (leading to error)",
464 "The argument \"help\" can not be combined with \"get\"."sv, std::string_view(e.what()));
467 fieldsArg.setFlags(Argument::Flags::Greedy,
true);
468 parser.parseArgs(6, argv19, ParseArgumentBehavior::CheckConstraints | ParseArgumentBehavior::InvokeCallbacks);
469 CPPUNIT_ASSERT(displayTagInfoArg.isPresent());
470 CPPUNIT_ASSERT(fieldsArg.isPresent());
471 CPPUNIT_ASSERT_MESSAGE(
"--help not considered an argument with greedy-flag", !parser.helpArg().isPresent());
472 CPPUNIT_ASSERT_EQUAL(
"foo"sv, std::string_view(fieldsArg.values().at(0)));
473 CPPUNIT_ASSERT_EQUAL(
"bar"sv, std::string_view(fieldsArg.values().at(1)));
474 CPPUNIT_ASSERT_EQUAL(
"--help"sv, std::string_view(fieldsArg.values().at(2)));
475 CPPUNIT_ASSERT_THROW(fieldsArg.values().at(3), std::out_of_range);
484 parser.
setExitFunction(std::bind(&ArgumentParserTests::failOnExit,
this, std::placeholders::_1));
485 Argument callbackArg(
"with-callback",
't',
"callback test");
488 CPPUNIT_ASSERT_EQUAL(0_st, occurrence.
index);
489 CPPUNIT_ASSERT(occurrence.
path.empty());
490 CPPUNIT_ASSERT_EQUAL(2_st, occurrence.
values.size());
491 CPPUNIT_ASSERT(!strcmp(occurrence.
values[0],
"val1"));
492 CPPUNIT_ASSERT(!strcmp(occurrence.
values[1],
"val2"));
495 Argument noCallbackArg(
"no-callback",
'l',
"callback test");
500 const char *argv[] = {
"test",
"-t",
"val1",
"val2" };
502 parser.
parseArgs(4, argv, ParseArgumentBehavior::CheckConstraints | ParseArgumentBehavior::InvokeCallbacks);
504 CPPUNIT_ASSERT_EQUAL(
i, 42);
509 const char *argv2[] = {
"test",
"-l",
"val1",
"val2" };
510 parser.
parseArgs(4, argv2, ParseArgumentBehavior::CheckConstraints | ParseArgumentBehavior::InvokeCallbacks);
513#ifndef PLATFORM_WINDOWS
517static bool exitCalled =
false;
528 parser.
setExitFunction(std::bind(&ArgumentParserTests::failOnExit,
this, std::placeholders::_1));
529 Argument verboseArg(
"verbose",
'v',
"be verbose");
531 Argument filesArg(
"files",
'f',
"specifies the path of the file(s) to be opened");
534 Argument nestedSubArg(
"nested-sub",
'\0',
"nested sub arg");
535 Argument subArg(
"sub",
'\0',
"sub arg");
537 Argument displayFileInfoArg(
"display-file-info",
'i',
"displays general file information");
539 displayFileInfoArg.
setSubArguments({ &filesArg, &verboseArg, &subArg });
540 Argument fieldsArg(
"fields",
'\0',
"specifies the fields");
544 Argument valuesArg(
"values",
'\0',
"specifies the fields");
548 valuesArg.
setValueCompletionBehavior(ValueCompletionBehavior::PreDefinedValues | ValueCompletionBehavior::AppendEquationSign);
549 Argument selectorsArg(
"selectors",
'\0',
"has some more pre-defined values");
556 Argument getArg(
"get",
'g',
"gets tag values");
558 Argument setArg(
"set",
's',
"sets tag values");
564 const char *
const argv1[] = {
"se" };
568 CPPUNIT_ASSERT(reader.
read());
569 parser.printBashCompletion(1, argv1, 0, reader);
578 parser.printBashCompletion(1, argv1, 0, reader);
582 const char *
const argv2[] = {
"set" };
587 parser.printBashCompletion(1, argv2, 0, reader);
593 const OutputCheck c(
"COMPREPLY=('--files' '--no-color' '--selectors' '--values' )\n");
595 parser.printBashCompletion(1, argv2, 1, reader);
602 const OutputCheck c(
"COMPREPLY=('files' '--no-color' '--selectors' '--values' )\n");
604 parser.printBashCompletion(1, argv2, 1, reader);
611 const OutputCheck c(
"COMPREPLY=('display-file-info' 'get' 'set' '--help' '--no-color' )\n");
613 parser.printBashCompletion(0,
nullptr, 0, reader);
617 const char *
const argv3[] = {
"get",
"--fields" };
620 const OutputCheck c(
"COMPREPLY=('title' 'album' 'artist' 'trackpos' '--files' '--no-color' )\n");
622 parser.printBashCompletion(2, argv3, 2, reader);
626 const char *
const argv4[] = {
"set",
"--values",
"a" };
629 const OutputCheck c(
"COMPREPLY=('album=' 'artist=' ); compopt -o nospace\n");
631 parser.printBashCompletion(3, argv4, 2, reader);
635 const char *
const argv12[] = {
"set",
"--selectors",
"tag=id3" };
638 const OutputCheck c(
"COMPREPLY=('tag=id3v1' 'tag=id3v2' )\n");
640 parser.printBashCompletion(3, argv12, 2, reader);
644 const char *
const argv13[] = {
"set",
"--selectors",
"tag",
"=",
"id3" };
647 const OutputCheck c(
"COMPREPLY=('id3v1' 'id3v2' )\n");
649 parser.printBashCompletion(5, argv13, 4, reader);
653 const OutputCheck c(
"COMPREPLY=('id3v1' 'id3v2' 'matroska' )\n");
655 parser.printBashCompletion(5, argv13, 3, reader);
662 const OutputCheck c(
"COMPREPLY=('matroska' 'mp4' 'vorbis' )\n");
664 parser.printBashCompletion(5, argv13, 3, reader);
670 const OutputCheck c(
"COMPREPLY=('title' 'album' 'artist' 'trackpos' '--fields' '--files' '--no-color' )\n");
672 parser.printBashCompletion(1, argv3, 2, reader);
677 iniFilePath.resize(iniFilePath.size() - 4);
679 mkvFilePath.resize(mkvFilePath.size() - 17);
681 const char *
const argv5[] = {
"get",
"--files", iniFilePath.c_str() };
683#ifdef CPP_UTILITIES_USE_STANDARD_FILESYSTEM
685 const OutputCheck c(
"COMPREPLY=('" % mkvFilePath %
" '\"'\"'with quote'\"'\"'.mkv' '" % iniFilePath +
".ini' ); compopt -o filenames\n",
686 "COMPREPLY=('" % iniFilePath %
".ini' '" % mkvFilePath +
" '\"'\"'with quote'\"'\"'.mkv' ); compopt -o filenames\n");
691 parser.printBashCompletion(3, argv5, 2, reader);
696 directoryPath.resize(directoryPath.size() - 4);
699 const char *
const argv14[] = {
"get",
"--files", directoryPath.c_str() };
701#ifdef CPP_UTILITIES_USE_STANDARD_FILESYSTEM
702 const OutputCheck c(
"COMPREPLY=('" % directoryPath +
"' ); compopt -o filenames\n");
707 parser.printBashCompletion(3, argv14, 2, reader);
711 const char *
const argv6[] = {
"set",
"--" };
714 const OutputCheck c(
"COMPREPLY=('--files' '--no-color' '--selectors' '--values' )\n");
716 parser.printBashCompletion(2, argv6, 1, reader);
720 const char *
const argv7[] = {
"-i",
"--sub",
"--" };
723 const OutputCheck c(
"COMPREPLY=('--files' '--nested-sub' '--no-color' '--verbose' )\n");
725 parser.printBashCompletion(3, argv7, 2, reader);
729 const char *
const argv8[] = {
"set",
"--values",
"t" };
732 const OutputCheck c(
"COMPREPLY=('title=' 'trackpos=' ); compopt -o nospace\n");
734 parser.printBashCompletion(3, argv8, 2, reader);
738 const char *
const argv9[] = {
"-gf" };
743 parser.printBashCompletion(1, argv9, 0, reader);
747 const OutputCheck c([](
const string &actualOutput) { CPPUNIT_ASSERT_EQUAL(0_st, actualOutput.find(
"COMPREPLY=('--fields' ")); });
749 parser.printBashCompletion(1, argv9, 1, reader);
756 const char *
const argv10[] = {
"/some/path/tageditor",
"--bash-completion-for",
"0" };
759 const OutputCheck c(
"COMPREPLY=('display-file-info' 'get' 'set' '--help' '--no-color' )\n");
762 CPPUNIT_ASSERT(!strcmp(
"/some/path/tageditor", parser.
executable()));
763 CPPUNIT_ASSERT(exitCalled);
766 const char *
const argv11[] = {
"/some/path/tageditor",
"--bash-completion-for",
"ge" };
775#ifndef PLATFORM_WINDOWS
785 CPPUNIT_ASSERT_EQUAL(
static_cast<unsigned char>(4 + 3), indent.
level);
789 parser.
setExitFunction(std::bind(&ArgumentParserTests::failOnExit,
this, std::placeholders::_1));
790 OperationArgument verboseArg(
"verbose",
'v',
"be verbose",
"actually not an operation");
792 ConfigValueArgument nestedSubArg(
"nested-sub",
'\0',
"nested sub arg", {
"value1",
"value2" });
794 Argument subArg(
"foo",
'f',
"dummy");
801 Argument filesArg(
"files",
'f',
"specifies the path of the file(s) to be opened");
805 Argument envArg(
"env",
'\0',
"env");
809 Argument deprecatedArg(
"deprecated");
816 const char *
const argv[] = {
"app",
"-h" };
818 const OutputCheck c(
"\e[1m" APP_NAME
", version " APP_VERSION
"\n"
820 "\e[0m" APP_DESCRIPTION
"\n"
822 "Available operations:\n"
823 "\e[1mverbose, -v\e[0m\n"
825 " example: actually not an operation\n"
827 "Available top-level options:\n"
828 "\e[1m--files, -f\e[0m\n"
829 " specifies the path of the file(s) to be opened\n"
832 " particularities: mandatory if parent argument is present\n"
833 " \e[1m--nested-sub\e[0m [value1] [value2] ...\n"
835 " example: sub arg example\n"
837 "\e[1m--env\e[0m [file] [value 2]\n"
839 " default environment variable: FILES\n"
841 "\e[1m--no-color\e[0m\n"
842 " disables formatted/colorized output\n"
843 " default environment variable: ENABLE_ESCAPE_CODES\n"
845 "Linked against: somelib, some other lib\n"
847 "Project website: " APP_URL
"\n");
849 parser.
parseArgs(2, argv, ParseArgumentBehavior::CheckConstraints | ParseArgumentBehavior::InvokeCallbacks);
855 const OutputCheck c(APP_NAME
", version " APP_VERSION
"\n"
856 "\n" APP_DESCRIPTION
"\n"
858 "Available arguments:\n"
861 " example: actually not an operation\n"
864 " specifies the path of the file(s) to be opened\n"
867 " particularities: mandatory if parent argument is present\n"
868 " --nested-sub [value1] [value2] ...\n"
870 " example: sub arg example\n"
872 "--env [file] [value 2]\n"
874 " default environment variable: FILES\n"
876 "Linked against: somelib, some other lib\n"
878 "Project website: " APP_URL
"\n");
881 parser.
parseArgs(2, argv, ParseArgumentBehavior::CheckConstraints | ParseArgumentBehavior::InvokeCallbacks);
892 parser.
setExitFunction(std::bind(&ArgumentParserTests::failOnExit,
this, std::placeholders::_1));
894 Argument subArg(
"sub-arg",
's',
"mandatory sub arg");
899 CPPUNIT_ASSERT_MESSAGE(
"clear main args", parser.
mainArguments().empty());
901 CPPUNIT_ASSERT_MESSAGE(
"no default due to required sub arg", !parser.
defaultArgument());
904 CPPUNIT_ASSERT_MESSAGE(
"default if no required sub arg", &helpArg == parser.
defaultArgument());
907#ifndef PLATFORM_WINDOWS
921 unsetenv(
"ENABLE_ESCAPE_CODES");
925 noColorArg.m_occurrences.emplace_back(0);
930 setenv(
"ENABLE_ESCAPE_CODES",
" 0 ", 1);
935 setenv(
"ENABLE_ESCAPE_CODES",
" 1 ", 1);
944 CPPUNIT_ASSERT_EQUAL_MESSAGE(message,
"foo"s, get<0>(values));
945 CPPUNIT_ASSERT_EQUAL_MESSAGE(message, 42u, get<1>(values));
946 CPPUNIT_ASSERT_EQUAL_MESSAGE(message, 7.5, get<2>(values));
947 CPPUNIT_ASSERT_EQUAL_MESSAGE(message, -42, get<3>(values));
957 occurrence.
values = {
"foo",
"42",
"7.5",
"-42" };
959 static_assert(std::is_same<std::tuple<>,
decltype(occurrence.
convertValues<>())>::value,
"specifying no types yields empty tuple");
963 arg.m_occurrences = { occurrence, occurrence };
966 const auto allValues = arg.
allValuesAs<string,
unsigned int, double,
int>();
967 CPPUNIT_ASSERT_EQUAL(2_st, allValues.size());
968 for (
const auto &values : allValues) {
971 static_assert(std::is_same<std::tuple<>,
decltype(arg.
valuesAs<>())>::value,
"specifying no types yields empty tuple");
975 occurrence.
convertValues<string,
unsigned int, double, int,
int>();
976 CPPUNIT_FAIL(
"Expected exception");
978 CPPUNIT_ASSERT_EQUAL(
"Expected 5 top-level values to be present but only 4 have been specified."s,
string(failure.what()));
982 CPPUNIT_FAIL(
"Expected exception");
984 CPPUNIT_ASSERT_EQUAL(
985 "Conversion of top-level value \"foo\" to type \"i\" failed: The character \"f\" is no valid digit."s,
string(failure.what()));
987 occurrence.
path = { &arg };
989 occurrence.
convertValues<string,
unsigned int, double, int,
int>();
990 CPPUNIT_FAIL(
"Expected exception");
992 CPPUNIT_ASSERT_EQUAL(
"Expected 5 values for argument --test to be present but only 4 have been specified."s,
string(failure.what()));
996 CPPUNIT_FAIL(
"Expected exception");
998 CPPUNIT_ASSERT_EQUAL(
"Conversion of value \"foo\" (for argument --test) to type \"i\" failed: The character \"f\" is no valid digit."s,
999 string(failure.what()));
#define SET_APPLICATION_INFO
Sets application meta data (including SET_DEPENDENCY_INFO) used by ArgumentParser::printHelp().
CPPUNIT_TEST_SUITE_REGISTRATION(ArgumentParserTests)
void checkConvertedValues(const std::string &message, const ValueTuple &values)
The ArgumentParserTests class tests the ArgumentParser and Argument classes.
void testNoColorArgument()
Tests whether NocolorArgument toggles escape codes correctly.
void testCallbacks()
Tests whether callbacks are called correctly.
void testValueConversion()
Tests value conversion provided by Argument and ArgumentOccurrence.
void testArgument()
Tests the behaviour of the argument class.
void testBashCompletion()
Tests bash completion.
void testHelp()
Tests –help output.
void testSetMainArguments()
Tests some corner cases in setMainArguments() which are not already checked in the other tests.
void testParsing()
Tests parsing command line arguments.
The ArgumentParser class provides a means for handling command line arguments.
const HelpArgument & helpArg() const
Returns the --help argument.
const char * executable() const
Returns the name of the current executable.
void readArgs(int argc, const char *const *argv)
Parses the specified command line arguments.
const ArgumentVector & mainArguments() const
Returns the main arguments.
Argument * defaultArgument() const
Returns the default argument.
void setMainArguments(const ArgumentInitializerList &mainArguments)
Sets the main arguments for the parser.
void setExitFunction(std::function< void(int)> exitFunction)
Specifies a function quit the application.
void addMainArgument(Argument *argument)
Adds the specified argument to the main argument.
void parseArgs(int argc, const char *const *argv, ParseArgumentBehavior behavior=ParseArgumentBehavior::CheckConstraints|ParseArgumentBehavior::InvokeCallbacks|ParseArgumentBehavior::ExitOnFailure)
Parses the specified command line arguments.
void resetArgs()
Resets all Argument instances assigned as mainArguments() and sub arguments.
const NoColorArgument & noColorArg() const
Returns the --no-color argument.
The ArgumentReader class internally encapsulates the process of reading command line arguments.
ArgumentReader & reset(const char *const *argv, const char *const *end)
Resets the ArgumentReader to continue reading new argv.
bool read()
Reads the commands line arguments specified when constructing the object.
The Argument class is a wrapper for command line argument information.
void addSubArgument(Argument *arg)
Adds arg as a secondary argument for this argument.
const char * firstValue() const
Returns the first parameter value of the first occurrence of the argument.
void setValueCompletionBehavior(ValueCompletionBehavior valueCompletionBehaviour)
Sets the items to be considered when generating completion for the values.
ValueCompletionBehavior valueCompletionBehaviour() const
Returns the items to be considered when generating completion for the values.
void setConstraints(std::size_t minOccurrences, std::size_t maxOccurrences)
Sets the allowed number of occurrences.
void setImplicit(bool implicit)
Sets whether the argument is an implicit argument.
void setDenotesOperation(bool denotesOperation)
Sets whether the argument denotes the operation.
void markAsDeprecated(const Argument *deprecatedBy=nullptr)
Marks the argument as deprecated.
void setAbbreviation(char abbreviation)
Sets the abbreviation of the argument.
void setDescription(const char *description)
Sets the description of the argument.
void appendValueName(const char *valueName)
Appends a value name.
std::vector< std::tuple< TargetType... > > allValuesAs() const
Converts the present values for all occurrence to the specified target types.
void reset()
Resets occurrences (indices, values and paths).
void setExample(const char *example)
Sets the a usage example for the argument.
Argument * conflictsWithArgument() const
Checks if this arguments conflicts with other arguments.
const ArgumentVector & parents() const
Returns the parents of this argument.
void setSubArguments(const ArgumentInitializerList &subArguments)
Sets the secondary arguments for this argument.
void setCombinable(bool combinable)
Sets whether this argument can be combined.
void setCallback(CallbackFunction callback)
Sets a callback function which will be called by the parser if the argument could be found and no par...
bool isRequired() const
Returns an indication whether the argument is mandatory.
void setRequired(bool required)
Sets whether this argument is mandatory or not.
void setPreDefinedCompletionValues(const char *preDefinedCompletionValues)
Assigns the values to be used when generating completion for the values.
void setEnvironmentVariable(const char *environmentVariable)
Sets the environment variable queried when firstValue() is called.
std::tuple< TargetType... > valuesAs(std::size_t occurrence=0) const
Converts the present values for the specified occurrence to the specified target types.
void setRequiredValueCount(std::size_t requiredValueCount)
Sets the number of values which are required to be given for this argument.
void setName(const char *name)
Sets the name of the argument.
The ConfigValueArgument class is an Argument where setCombinable() is true by default.
The HelpArgument class prints help information for an argument parser when present (–help,...
The Indentation class allows printing indentation conveniently, eg.
The NoColorArgument class allows to specify whether use of escape codes or similar technique to provi...
void apply() const
Sets EscapeCodes::enabled according to the presence of the first instantiation of NoColorArgument.
The OperationArgument class is an Argument where denotesOperation() is true by default.
The StandardOutputCheck class asserts whether the (standard) output written in the enclosing code blo...
The ParseError class is thrown by an ArgumentParser when a parsing error occurs.
#define QT_CONFIG_ARGUMENTS
CPP_UTILITIES_EXPORT bool enabled
Controls whether the functions inside the EscapeCodes namespace actually make use of escape codes.
Contains literals to ease asserting with CPPUNIT_ASSERT_EQUAL.
Contains all utilities provides by the c++utilities library.
CPP_UTILITIES_EXPORT std::string testFilePath(const std::string &relativeTestFilePath)
Convenience function to invoke TestApplication::testFilePath().
StringType argsToString(Args &&...args)
CPP_UTILITIES_EXPORT ApplicationInfo applicationInfo
Stores global application info used by ArgumentParser::printHelp() and AboutDialog.
std::vector< const char * > dependencyVersions
The ArgumentOccurrence struct holds argument values for an occurrence of an argument.
std::size_t index
The index of the occurrence.
std::vector< const char * > values
The parameter values which have been specified after the occurrence of the argument.
std::tuple< RemainingTargetTypes... > convertValues() const
Converts the present values to the specified target types.
std::vector< Argument * > path
The "path" of the occurrence (the parent elements which have been specified before).