2 * Copyright 2016 Facebook, Inc.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 #include <folly/experimental/ProgramOptions.h>
19 #include <folly/FileUtil.h>
20 #include <folly/Subprocess.h>
21 #include <folly/experimental/io/FsUtil.h>
22 #include <folly/portability/GTest.h>
23 #include <glog/logging.h>
25 namespace folly { namespace test {
29 std::string getHelperPath() {
30 const auto basename = "program_options_test_helper";
31 auto path = fs::executable_path();
32 path.remove_filename() /= basename;
33 if (!fs::exists(path)) {
34 path = path.parent_path().parent_path() / basename / basename;
39 std::string callHelper(ProgramOptionsStyle style,
40 std::initializer_list<std::string> args) {
41 static std::string helperPath = getHelperPath();
43 std::vector<std::string> allArgs;
44 allArgs.reserve(args.size() + 1);
45 allArgs.push_back(helperPath);
46 allArgs.insert(allArgs.end(), args.begin(), args.end());
48 std::vector<std::string> env;
50 case ProgramOptionsStyle::GNU:
51 env.push_back("PROGRAM_OPTIONS_TEST_STYLE=GNU");
53 case ProgramOptionsStyle::GFLAGS:
54 env.push_back("PROGRAM_OPTIONS_TEST_STYLE=GFLAGS");
58 Subprocess proc(allArgs, Subprocess::pipeStdout(), nullptr, &env);
59 auto p = proc.communicate();
60 EXPECT_EQ(0, proc.wait().exitStatus());
69 TEST(ProgramOptionsTest, GFlagsStyleDefaultValues) {
75 callHelper(ProgramOptionsStyle::GFLAGS, {}));
78 TEST(ProgramOptionsTest, GFlagsStyleFlagsSet) {
84 callHelper(ProgramOptionsStyle::GFLAGS, {
88 "--flag_string", "bar"}));
91 TEST(ProgramOptionsTest, GFlagsStyleBoolFlagsNegation) {
97 callHelper(ProgramOptionsStyle::GFLAGS, {
99 "--noflag_bool_false"}));
102 TEST(ProgramOptionsTest, GNUStyleDefaultValues) {
105 "flag-bool-false 0\n"
108 callHelper(ProgramOptionsStyle::GNU, {}));
111 TEST(ProgramOptionsTest, GNUStyleFlagsSet) {
114 "flag-bool-false 1\n"
117 callHelper(ProgramOptionsStyle::GNU, {
121 "--flag-string", "bar"}));
124 TEST(ProgramOptionsTest, GNUStyleBoolFlagsNegation) {
127 "flag-bool-false 0\n"
130 callHelper(ProgramOptionsStyle::GNU, {
131 "--no-flag-bool-true",
132 "--no-flag-bool-false"}));
135 TEST(ProgramOptionsTest, GNUStyleSubCommand) {
138 "flag-bool-false 1\n"
146 callHelper(ProgramOptionsStyle::GNU, {
156 TEST(ProgramOptionsTest, GNUStyleSubCommandUnrecognizedOptionFirst) {
159 "flag-bool-false 1\n"
167 callHelper(ProgramOptionsStyle::GNU, {