opt_ut.cpp 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. #include <library/cpp/getopt/opt.h>
  2. #include <library/cpp/testing/unittest/registar.h>
  3. #include <util/string/vector.h>
  4. Y_UNIT_TEST_SUITE(OptTest) {
  5. Y_UNIT_TEST(TestSimple) {
  6. int argc = 3;
  7. char* argv[] = {
  8. (char*)"cmd", (char*)"-x"};
  9. Opt opt(argc, argv, "");
  10. opt.Err = false; // be quiet
  11. UNIT_ASSERT_VALUES_EQUAL('?', opt.Get());
  12. UNIT_ASSERT_VALUES_EQUAL(EOF, opt.Get());
  13. UNIT_ASSERT_VALUES_EQUAL(EOF, opt.Get());
  14. UNIT_ASSERT_VALUES_EQUAL(EOF, opt.Get());
  15. }
  16. Y_UNIT_TEST(TestFreeArguments) {
  17. Opt::Ion options[] = {
  18. {"some-option", Opt::WithArg, nullptr, 123},
  19. {nullptr, Opt::WithoutArg, nullptr, 0}};
  20. const char* argv[] = {"cmd", "ARG1", "-some-option", "ARG2", "ARG3", nullptr};
  21. int argc = 5;
  22. Opt opts(argc, argv, "", options);
  23. UNIT_ASSERT_VALUES_EQUAL(JoinStrings(opts.GetFreeArgs(), ", "), "ARG1, ARG3");
  24. }
  25. Y_UNIT_TEST(TestLongOption) {
  26. const int SOME_OPTION_ID = 12345678;
  27. Opt::Ion options[] = {
  28. {"some-option", Opt::WithArg, nullptr, SOME_OPTION_ID},
  29. {nullptr, Opt::WithoutArg, nullptr, 0}};
  30. for (int doubleDash = 0; doubleDash <= 1; ++doubleDash) {
  31. const char* argv[] = {"cmd", "ARG1", (doubleDash ? "--some-option" : "-some-option"), "ARG2", "ARG3", nullptr};
  32. int argc = 5;
  33. Opt opts(argc, argv, "", options);
  34. TString optionValue = "";
  35. int optlet = 0;
  36. while ((optlet = opts.Get()) != EOF) {
  37. if (optlet == SOME_OPTION_ID) {
  38. optionValue = opts.GetArg();
  39. } else {
  40. UNIT_FAIL("don't expected any options, except -some-option");
  41. }
  42. }
  43. UNIT_ASSERT_VALUES_EQUAL(optionValue, "ARG2");
  44. }
  45. }
  46. }