Bitcoin Core  24.99.0
P2P Digital Currency
argsman_tests.cpp
Go to the documentation of this file.
1 // Copyright (c) 2011-2022 The Bitcoin Core developers
2 // Distributed under the MIT software license, see the accompanying
3 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
4 
5 #include <util/system.h>
6 #include <fs.h>
7 #include <sync.h>
8 #include <test/util/logging.h>
10 #include <test/util/str.h>
11 #include <util/strencodings.h>
12 #include <univalue.h>
13 
14 #include <array>
15 #include <optional>
16 #include <cstdint>
17 #include <cstring>
18 #include <vector>
19 
20 #include <boost/test/unit_test.hpp>
21 
22 BOOST_FIXTURE_TEST_SUITE(argsman_tests, BasicTestingSetup)
23 
24 BOOST_AUTO_TEST_CASE(util_datadir)
25 {
26  // Use local args variable instead of m_args to avoid making assumptions about test setup
28  args.ForceSetArg("-datadir", fs::PathToString(m_path_root));
29 
30  const fs::path dd_norm = args.GetDataDirBase();
31 
32  args.ForceSetArg("-datadir", fs::PathToString(dd_norm) + "/");
35 
36  args.ForceSetArg("-datadir", fs::PathToString(dd_norm) + "/.");
39 
40  args.ForceSetArg("-datadir", fs::PathToString(dd_norm) + "/./");
43 
44  args.ForceSetArg("-datadir", fs::PathToString(dd_norm) + "/.//");
47 }
48 
50 {
51  TestArgsManager() { m_network_only_args.clear(); }
52  void ReadConfigString(const std::string str_config)
53  {
54  std::istringstream streamConfig(str_config);
55  {
56  LOCK(cs_args);
57  m_settings.ro_config.clear();
58  m_config_sections.clear();
59  }
60  std::string error;
61  BOOST_REQUIRE(ReadConfigStream(streamConfig, "", error));
62  }
63  void SetNetworkOnlyArg(const std::string arg)
64  {
65  LOCK(cs_args);
66  m_network_only_args.insert(arg);
67  }
68  void SetupArgs(const std::vector<std::pair<std::string, unsigned int>>& args)
69  {
70  for (const auto& arg : args) {
71  AddArg(arg.first, "", arg.second, OptionsCategory::OPTIONS);
72  }
73  }
78  using ArgsManager::m_network;
79  using ArgsManager::m_settings;
80 };
81 
84 {
85 public:
86  struct Expect {
88  bool default_string = false;
89  bool default_int = false;
90  bool default_bool = false;
91  const char* string_value = nullptr;
92  std::optional<int64_t> int_value;
93  std::optional<bool> bool_value;
94  std::optional<std::vector<std::string>> list_value;
95  const char* error = nullptr;
96 
97  explicit Expect(util::SettingsValue s) : setting(std::move(s)) {}
98  Expect& DefaultString() { default_string = true; return *this; }
99  Expect& DefaultInt() { default_int = true; return *this; }
100  Expect& DefaultBool() { default_bool = true; return *this; }
101  Expect& String(const char* s) { string_value = s; return *this; }
102  Expect& Int(int64_t i) { int_value = i; return *this; }
103  Expect& Bool(bool b) { bool_value = b; return *this; }
104  Expect& List(std::vector<std::string> m) { list_value = std::move(m); return *this; }
105  Expect& Error(const char* e) { error = e; return *this; }
106  };
107 
108  void CheckValue(unsigned int flags, const char* arg, const Expect& expect)
109  {
110  TestArgsManager test;
111  test.SetupArgs({{"-value", flags}});
112  const char* argv[] = {"ignored", arg};
113  std::string error;
114  bool success = test.ParseParameters(arg ? 2 : 1, (char**)argv, error);
115 
116  BOOST_CHECK_EQUAL(test.GetSetting("-value").write(), expect.setting.write());
117  auto settings_list = test.GetSettingsList("-value");
118  if (expect.setting.isNull() || expect.setting.isFalse()) {
119  BOOST_CHECK_EQUAL(settings_list.size(), 0U);
120  } else {
121  BOOST_CHECK_EQUAL(settings_list.size(), 1U);
122  BOOST_CHECK_EQUAL(settings_list[0].write(), expect.setting.write());
123  }
124 
125  if (expect.error) {
126  BOOST_CHECK(!success);
127  BOOST_CHECK_NE(error.find(expect.error), std::string::npos);
128  } else {
129  BOOST_CHECK(success);
131  }
132 
133  if (expect.default_string) {
134  BOOST_CHECK_EQUAL(test.GetArg("-value", "zzzzz"), "zzzzz");
135  } else if (expect.string_value) {
136  BOOST_CHECK_EQUAL(test.GetArg("-value", "zzzzz"), expect.string_value);
137  } else {
138  BOOST_CHECK(!success);
139  }
140 
141  if (expect.default_int) {
142  BOOST_CHECK_EQUAL(test.GetIntArg("-value", 99999), 99999);
143  } else if (expect.int_value) {
144  BOOST_CHECK_EQUAL(test.GetIntArg("-value", 99999), *expect.int_value);
145  } else {
146  BOOST_CHECK(!success);
147  }
148 
149  if (expect.default_bool) {
150  BOOST_CHECK_EQUAL(test.GetBoolArg("-value", false), false);
151  BOOST_CHECK_EQUAL(test.GetBoolArg("-value", true), true);
152  } else if (expect.bool_value) {
153  BOOST_CHECK_EQUAL(test.GetBoolArg("-value", false), *expect.bool_value);
154  BOOST_CHECK_EQUAL(test.GetBoolArg("-value", true), *expect.bool_value);
155  } else {
156  BOOST_CHECK(!success);
157  }
158 
159  if (expect.list_value) {
160  auto l = test.GetArgs("-value");
161  BOOST_CHECK_EQUAL_COLLECTIONS(l.begin(), l.end(), expect.list_value->begin(), expect.list_value->end());
162  } else {
163  BOOST_CHECK(!success);
164  }
165  }
166 };
167 
169 {
170  using M = ArgsManager;
171 
172  CheckValue(M::ALLOW_ANY, nullptr, Expect{{}}.DefaultString().DefaultInt().DefaultBool().List({}));
173  CheckValue(M::ALLOW_ANY, "-novalue", Expect{false}.String("0").Int(0).Bool(false).List({}));
174  CheckValue(M::ALLOW_ANY, "-novalue=", Expect{false}.String("0").Int(0).Bool(false).List({}));
175  CheckValue(M::ALLOW_ANY, "-novalue=0", Expect{true}.String("1").Int(1).Bool(true).List({"1"}));
176  CheckValue(M::ALLOW_ANY, "-novalue=1", Expect{false}.String("0").Int(0).Bool(false).List({}));
177  CheckValue(M::ALLOW_ANY, "-novalue=2", Expect{false}.String("0").Int(0).Bool(false).List({}));
178  CheckValue(M::ALLOW_ANY, "-novalue=abc", Expect{true}.String("1").Int(1).Bool(true).List({"1"}));
179  CheckValue(M::ALLOW_ANY, "-value", Expect{""}.String("").Int(0).Bool(true).List({""}));
180  CheckValue(M::ALLOW_ANY, "-value=", Expect{""}.String("").Int(0).Bool(true).List({""}));
181  CheckValue(M::ALLOW_ANY, "-value=0", Expect{"0"}.String("0").Int(0).Bool(false).List({"0"}));
182  CheckValue(M::ALLOW_ANY, "-value=1", Expect{"1"}.String("1").Int(1).Bool(true).List({"1"}));
183  CheckValue(M::ALLOW_ANY, "-value=2", Expect{"2"}.String("2").Int(2).Bool(true).List({"2"}));
184  CheckValue(M::ALLOW_ANY, "-value=abc", Expect{"abc"}.String("abc").Int(0).Bool(false).List({"abc"}));
185 }
186 
188  std::string Parse(const char* arg)
189  {
190  TestArgsManager test;
191  test.SetupArgs({{"-includeconf", ArgsManager::ALLOW_ANY}});
192  std::array argv{"ignored", arg};
193  std::string error;
194  (void)test.ParseParameters(argv.size(), argv.data(), error);
195  return error;
196  }
197 };
198 
200 {
201  BOOST_CHECK_EQUAL(Parse("-noincludeconf"), "");
202  BOOST_CHECK_EQUAL(Parse("-includeconf"), "-includeconf cannot be used from commandline; -includeconf=\"\"");
203  BOOST_CHECK_EQUAL(Parse("-includeconf=file"), "-includeconf cannot be used from commandline; -includeconf=\"file\"");
204 }
205 
206 BOOST_AUTO_TEST_CASE(util_ParseParameters)
207 {
208  TestArgsManager testArgs;
209  const auto a = std::make_pair("-a", ArgsManager::ALLOW_ANY);
210  const auto b = std::make_pair("-b", ArgsManager::ALLOW_ANY);
211  const auto ccc = std::make_pair("-ccc", ArgsManager::ALLOW_ANY);
212  const auto d = std::make_pair("-d", ArgsManager::ALLOW_ANY);
213 
214  const char *argv_test[] = {"-ignored", "-a", "-b", "-ccc=argument", "-ccc=multiple", "f", "-d=e"};
215 
216  std::string error;
217  LOCK(testArgs.cs_args);
218  testArgs.SetupArgs({a, b, ccc, d});
219  BOOST_CHECK(testArgs.ParseParameters(0, (char**)argv_test, error));
220  BOOST_CHECK(testArgs.m_settings.command_line_options.empty() && testArgs.m_settings.ro_config.empty());
221 
222  BOOST_CHECK(testArgs.ParseParameters(1, (char**)argv_test, error));
223  BOOST_CHECK(testArgs.m_settings.command_line_options.empty() && testArgs.m_settings.ro_config.empty());
224 
225  BOOST_CHECK(testArgs.ParseParameters(7, (char**)argv_test, error));
226  // expectation: -ignored is ignored (program name argument),
227  // -a, -b and -ccc end up in map, -d ignored because it is after
228  // a non-option argument (non-GNU option parsing)
229  BOOST_CHECK(testArgs.m_settings.command_line_options.size() == 3 && testArgs.m_settings.ro_config.empty());
230  BOOST_CHECK(testArgs.IsArgSet("-a") && testArgs.IsArgSet("-b") && testArgs.IsArgSet("-ccc")
231  && !testArgs.IsArgSet("f") && !testArgs.IsArgSet("-d"));
232  BOOST_CHECK(testArgs.m_settings.command_line_options.count("a") && testArgs.m_settings.command_line_options.count("b") && testArgs.m_settings.command_line_options.count("ccc")
233  && !testArgs.m_settings.command_line_options.count("f") && !testArgs.m_settings.command_line_options.count("d"));
234 
235  BOOST_CHECK(testArgs.m_settings.command_line_options["a"].size() == 1);
236  BOOST_CHECK(testArgs.m_settings.command_line_options["a"].front().get_str() == "");
237  BOOST_CHECK(testArgs.m_settings.command_line_options["ccc"].size() == 2);
238  BOOST_CHECK(testArgs.m_settings.command_line_options["ccc"].front().get_str() == "argument");
239  BOOST_CHECK(testArgs.m_settings.command_line_options["ccc"].back().get_str() == "multiple");
240  BOOST_CHECK(testArgs.GetArgs("-ccc").size() == 2);
241 }
242 
243 BOOST_AUTO_TEST_CASE(util_ParseInvalidParameters)
244 {
245  TestArgsManager test;
246  test.SetupArgs({{"-registered", ArgsManager::ALLOW_ANY}});
247 
248  const char* argv[] = {"ignored", "-registered"};
249  std::string error;
250  BOOST_CHECK(test.ParseParameters(2, (char**)argv, error));
252 
253  argv[1] = "-unregistered";
254  BOOST_CHECK(!test.ParseParameters(2, (char**)argv, error));
255  BOOST_CHECK_EQUAL(error, "Invalid parameter -unregistered");
256 
257  // Make sure registered parameters prefixed with a chain name trigger errors.
258  // (Previously, they were accepted and ignored.)
259  argv[1] = "-test.registered";
260  BOOST_CHECK(!test.ParseParameters(2, (char**)argv, error));
261  BOOST_CHECK_EQUAL(error, "Invalid parameter -test.registered");
262 }
263 
264 static void TestParse(const std::string& str, bool expected_bool, int64_t expected_int)
265 {
266  TestArgsManager test;
267  test.SetupArgs({{"-value", ArgsManager::ALLOW_ANY}});
268  std::string arg = "-value=" + str;
269  const char* argv[] = {"ignored", arg.c_str()};
270  std::string error;
271  BOOST_CHECK(test.ParseParameters(2, (char**)argv, error));
272  BOOST_CHECK_EQUAL(test.GetBoolArg("-value", false), expected_bool);
273  BOOST_CHECK_EQUAL(test.GetBoolArg("-value", true), expected_bool);
274  BOOST_CHECK_EQUAL(test.GetIntArg("-value", 99998), expected_int);
275  BOOST_CHECK_EQUAL(test.GetIntArg("-value", 99999), expected_int);
276 }
277 
278 // Test bool and int parsing.
279 BOOST_AUTO_TEST_CASE(util_ArgParsing)
280 {
281  // Some of these cases could be ambiguous or surprising to users, and might
282  // be worth triggering errors or warnings in the future. But for now basic
283  // test coverage is useful to avoid breaking backwards compatibility
284  // unintentionally.
285  TestParse("", true, 0);
286  TestParse(" ", false, 0);
287  TestParse("0", false, 0);
288  TestParse("0 ", false, 0);
289  TestParse(" 0", false, 0);
290  TestParse("+0", false, 0);
291  TestParse("-0", false, 0);
292  TestParse("5", true, 5);
293  TestParse("5 ", true, 5);
294  TestParse(" 5", true, 5);
295  TestParse("+5", true, 5);
296  TestParse("-5", true, -5);
297  TestParse("0 5", false, 0);
298  TestParse("5 0", true, 5);
299  TestParse("050", true, 50);
300  TestParse("0.", false, 0);
301  TestParse("5.", true, 5);
302  TestParse("0.0", false, 0);
303  TestParse("0.5", false, 0);
304  TestParse("5.0", true, 5);
305  TestParse("5.5", true, 5);
306  TestParse("x", false, 0);
307  TestParse("x0", false, 0);
308  TestParse("x5", false, 0);
309  TestParse("0x", false, 0);
310  TestParse("5x", true, 5);
311  TestParse("0x5", false, 0);
312  TestParse("false", false, 0);
313  TestParse("true", false, 0);
314  TestParse("yes", false, 0);
315  TestParse("no", false, 0);
316 }
317 
318 BOOST_AUTO_TEST_CASE(util_GetBoolArg)
319 {
320  TestArgsManager testArgs;
321  const auto a = std::make_pair("-a", ArgsManager::ALLOW_ANY);
322  const auto b = std::make_pair("-b", ArgsManager::ALLOW_ANY);
323  const auto c = std::make_pair("-c", ArgsManager::ALLOW_ANY);
324  const auto d = std::make_pair("-d", ArgsManager::ALLOW_ANY);
325  const auto e = std::make_pair("-e", ArgsManager::ALLOW_ANY);
326  const auto f = std::make_pair("-f", ArgsManager::ALLOW_ANY);
327 
328  const char *argv_test[] = {
329  "ignored", "-a", "-nob", "-c=0", "-d=1", "-e=false", "-f=true"};
330  std::string error;
331  LOCK(testArgs.cs_args);
332  testArgs.SetupArgs({a, b, c, d, e, f});
333  BOOST_CHECK(testArgs.ParseParameters(7, (char**)argv_test, error));
334 
335  // Each letter should be set.
336  for (const char opt : "abcdef")
337  BOOST_CHECK(testArgs.IsArgSet({'-', opt}) || !opt);
338 
339  // Nothing else should be in the map
340  BOOST_CHECK(testArgs.m_settings.command_line_options.size() == 6 &&
341  testArgs.m_settings.ro_config.empty());
342 
343  // The -no prefix should get stripped on the way in.
344  BOOST_CHECK(!testArgs.IsArgSet("-nob"));
345 
346  // The -b option is flagged as negated, and nothing else is
347  BOOST_CHECK(testArgs.IsArgNegated("-b"));
348  BOOST_CHECK(!testArgs.IsArgNegated("-a"));
349 
350  // Check expected values.
351  BOOST_CHECK(testArgs.GetBoolArg("-a", false) == true);
352  BOOST_CHECK(testArgs.GetBoolArg("-b", true) == false);
353  BOOST_CHECK(testArgs.GetBoolArg("-c", true) == false);
354  BOOST_CHECK(testArgs.GetBoolArg("-d", false) == true);
355  BOOST_CHECK(testArgs.GetBoolArg("-e", true) == false);
356  BOOST_CHECK(testArgs.GetBoolArg("-f", true) == false);
357 }
358 
359 BOOST_AUTO_TEST_CASE(util_GetBoolArgEdgeCases)
360 {
361  // Test some awful edge cases that hopefully no user will ever exercise.
362  TestArgsManager testArgs;
363 
364  // Params test
365  const auto foo = std::make_pair("-foo", ArgsManager::ALLOW_ANY);
366  const auto bar = std::make_pair("-bar", ArgsManager::ALLOW_ANY);
367  const char *argv_test[] = {"ignored", "-nofoo", "-foo", "-nobar=0"};
368  testArgs.SetupArgs({foo, bar});
369  std::string error;
370  BOOST_CHECK(testArgs.ParseParameters(4, (char**)argv_test, error));
371 
372  // This was passed twice, second one overrides the negative setting.
373  BOOST_CHECK(!testArgs.IsArgNegated("-foo"));
374  BOOST_CHECK(testArgs.GetArg("-foo", "xxx") == "");
375 
376  // A double negative is a positive, and not marked as negated.
377  BOOST_CHECK(!testArgs.IsArgNegated("-bar"));
378  BOOST_CHECK(testArgs.GetArg("-bar", "xxx") == "1");
379 
380  // Config test
381  const char *conf_test = "nofoo=1\nfoo=1\nnobar=0\n";
382  BOOST_CHECK(testArgs.ParseParameters(1, (char**)argv_test, error));
383  testArgs.ReadConfigString(conf_test);
384 
385  // This was passed twice, second one overrides the negative setting,
386  // and the value.
387  BOOST_CHECK(!testArgs.IsArgNegated("-foo"));
388  BOOST_CHECK(testArgs.GetArg("-foo", "xxx") == "1");
389 
390  // A double negative is a positive, and does not count as negated.
391  BOOST_CHECK(!testArgs.IsArgNegated("-bar"));
392  BOOST_CHECK(testArgs.GetArg("-bar", "xxx") == "1");
393 
394  // Combined test
395  const char *combo_test_args[] = {"ignored", "-nofoo", "-bar"};
396  const char *combo_test_conf = "foo=1\nnobar=1\n";
397  BOOST_CHECK(testArgs.ParseParameters(3, (char**)combo_test_args, error));
398  testArgs.ReadConfigString(combo_test_conf);
399 
400  // Command line overrides, but doesn't erase old setting
401  BOOST_CHECK(testArgs.IsArgNegated("-foo"));
402  BOOST_CHECK(testArgs.GetArg("-foo", "xxx") == "0");
403  BOOST_CHECK(testArgs.GetArgs("-foo").size() == 0);
404 
405  // Command line overrides, but doesn't erase old setting
406  BOOST_CHECK(!testArgs.IsArgNegated("-bar"));
407  BOOST_CHECK(testArgs.GetArg("-bar", "xxx") == "");
408  BOOST_CHECK(testArgs.GetArgs("-bar").size() == 1
409  && testArgs.GetArgs("-bar").front() == "");
410 }
411 
412 BOOST_AUTO_TEST_CASE(util_ReadConfigStream)
413 {
414  const char *str_config =
415  "a=\n"
416  "b=1\n"
417  "ccc=argument\n"
418  "ccc=multiple\n"
419  "d=e\n"
420  "nofff=1\n"
421  "noggg=0\n"
422  "h=1\n"
423  "noh=1\n"
424  "noi=1\n"
425  "i=1\n"
426  "sec1.ccc=extend1\n"
427  "\n"
428  "[sec1]\n"
429  "ccc=extend2\n"
430  "d=eee\n"
431  "h=1\n"
432  "[sec2]\n"
433  "ccc=extend3\n"
434  "iii=2\n";
435 
436  TestArgsManager test_args;
437  LOCK(test_args.cs_args);
438  const auto a = std::make_pair("-a", ArgsManager::ALLOW_ANY);
439  const auto b = std::make_pair("-b", ArgsManager::ALLOW_ANY);
440  const auto ccc = std::make_pair("-ccc", ArgsManager::ALLOW_ANY);
441  const auto d = std::make_pair("-d", ArgsManager::ALLOW_ANY);
442  const auto e = std::make_pair("-e", ArgsManager::ALLOW_ANY);
443  const auto fff = std::make_pair("-fff", ArgsManager::ALLOW_ANY);
444  const auto ggg = std::make_pair("-ggg", ArgsManager::ALLOW_ANY);
445  const auto h = std::make_pair("-h", ArgsManager::ALLOW_ANY);
446  const auto i = std::make_pair("-i", ArgsManager::ALLOW_ANY);
447  const auto iii = std::make_pair("-iii", ArgsManager::ALLOW_ANY);
448  test_args.SetupArgs({a, b, ccc, d, e, fff, ggg, h, i, iii});
449 
450  test_args.ReadConfigString(str_config);
451  // expectation: a, b, ccc, d, fff, ggg, h, i end up in map
452  // so do sec1.ccc, sec1.d, sec1.h, sec2.ccc, sec2.iii
453 
454  BOOST_CHECK(test_args.m_settings.command_line_options.empty());
455  BOOST_CHECK(test_args.m_settings.ro_config.size() == 3);
456  BOOST_CHECK(test_args.m_settings.ro_config[""].size() == 8);
457  BOOST_CHECK(test_args.m_settings.ro_config["sec1"].size() == 3);
458  BOOST_CHECK(test_args.m_settings.ro_config["sec2"].size() == 2);
459 
460  BOOST_CHECK(test_args.m_settings.ro_config[""].count("a"));
461  BOOST_CHECK(test_args.m_settings.ro_config[""].count("b"));
462  BOOST_CHECK(test_args.m_settings.ro_config[""].count("ccc"));
463  BOOST_CHECK(test_args.m_settings.ro_config[""].count("d"));
464  BOOST_CHECK(test_args.m_settings.ro_config[""].count("fff"));
465  BOOST_CHECK(test_args.m_settings.ro_config[""].count("ggg"));
466  BOOST_CHECK(test_args.m_settings.ro_config[""].count("h"));
467  BOOST_CHECK(test_args.m_settings.ro_config[""].count("i"));
468  BOOST_CHECK(test_args.m_settings.ro_config["sec1"].count("ccc"));
469  BOOST_CHECK(test_args.m_settings.ro_config["sec1"].count("h"));
470  BOOST_CHECK(test_args.m_settings.ro_config["sec2"].count("ccc"));
471  BOOST_CHECK(test_args.m_settings.ro_config["sec2"].count("iii"));
472 
473  BOOST_CHECK(test_args.IsArgSet("-a"));
474  BOOST_CHECK(test_args.IsArgSet("-b"));
475  BOOST_CHECK(test_args.IsArgSet("-ccc"));
476  BOOST_CHECK(test_args.IsArgSet("-d"));
477  BOOST_CHECK(test_args.IsArgSet("-fff"));
478  BOOST_CHECK(test_args.IsArgSet("-ggg"));
479  BOOST_CHECK(test_args.IsArgSet("-h"));
480  BOOST_CHECK(test_args.IsArgSet("-i"));
481  BOOST_CHECK(!test_args.IsArgSet("-zzz"));
482  BOOST_CHECK(!test_args.IsArgSet("-iii"));
483 
484  BOOST_CHECK_EQUAL(test_args.GetArg("-a", "xxx"), "");
485  BOOST_CHECK_EQUAL(test_args.GetArg("-b", "xxx"), "1");
486  BOOST_CHECK_EQUAL(test_args.GetArg("-ccc", "xxx"), "argument");
487  BOOST_CHECK_EQUAL(test_args.GetArg("-d", "xxx"), "e");
488  BOOST_CHECK_EQUAL(test_args.GetArg("-fff", "xxx"), "0");
489  BOOST_CHECK_EQUAL(test_args.GetArg("-ggg", "xxx"), "1");
490  BOOST_CHECK_EQUAL(test_args.GetArg("-h", "xxx"), "0");
491  BOOST_CHECK_EQUAL(test_args.GetArg("-i", "xxx"), "1");
492  BOOST_CHECK_EQUAL(test_args.GetArg("-zzz", "xxx"), "xxx");
493  BOOST_CHECK_EQUAL(test_args.GetArg("-iii", "xxx"), "xxx");
494 
495  for (const bool def : {false, true}) {
496  BOOST_CHECK(test_args.GetBoolArg("-a", def));
497  BOOST_CHECK(test_args.GetBoolArg("-b", def));
498  BOOST_CHECK(!test_args.GetBoolArg("-ccc", def));
499  BOOST_CHECK(!test_args.GetBoolArg("-d", def));
500  BOOST_CHECK(!test_args.GetBoolArg("-fff", def));
501  BOOST_CHECK(test_args.GetBoolArg("-ggg", def));
502  BOOST_CHECK(!test_args.GetBoolArg("-h", def));
503  BOOST_CHECK(test_args.GetBoolArg("-i", def));
504  BOOST_CHECK(test_args.GetBoolArg("-zzz", def) == def);
505  BOOST_CHECK(test_args.GetBoolArg("-iii", def) == def);
506  }
507 
508  BOOST_CHECK(test_args.GetArgs("-a").size() == 1
509  && test_args.GetArgs("-a").front() == "");
510  BOOST_CHECK(test_args.GetArgs("-b").size() == 1
511  && test_args.GetArgs("-b").front() == "1");
512  BOOST_CHECK(test_args.GetArgs("-ccc").size() == 2
513  && test_args.GetArgs("-ccc").front() == "argument"
514  && test_args.GetArgs("-ccc").back() == "multiple");
515  BOOST_CHECK(test_args.GetArgs("-fff").size() == 0);
516  BOOST_CHECK(test_args.GetArgs("-nofff").size() == 0);
517  BOOST_CHECK(test_args.GetArgs("-ggg").size() == 1
518  && test_args.GetArgs("-ggg").front() == "1");
519  BOOST_CHECK(test_args.GetArgs("-noggg").size() == 0);
520  BOOST_CHECK(test_args.GetArgs("-h").size() == 0);
521  BOOST_CHECK(test_args.GetArgs("-noh").size() == 0);
522  BOOST_CHECK(test_args.GetArgs("-i").size() == 1
523  && test_args.GetArgs("-i").front() == "1");
524  BOOST_CHECK(test_args.GetArgs("-noi").size() == 0);
525  BOOST_CHECK(test_args.GetArgs("-zzz").size() == 0);
526 
527  BOOST_CHECK(!test_args.IsArgNegated("-a"));
528  BOOST_CHECK(!test_args.IsArgNegated("-b"));
529  BOOST_CHECK(!test_args.IsArgNegated("-ccc"));
530  BOOST_CHECK(!test_args.IsArgNegated("-d"));
531  BOOST_CHECK(test_args.IsArgNegated("-fff"));
532  BOOST_CHECK(!test_args.IsArgNegated("-ggg"));
533  BOOST_CHECK(test_args.IsArgNegated("-h")); // last setting takes precedence
534  BOOST_CHECK(!test_args.IsArgNegated("-i")); // last setting takes precedence
535  BOOST_CHECK(!test_args.IsArgNegated("-zzz"));
536 
537  // Test sections work
538  test_args.SelectConfigNetwork("sec1");
539 
540  // same as original
541  BOOST_CHECK_EQUAL(test_args.GetArg("-a", "xxx"), "");
542  BOOST_CHECK_EQUAL(test_args.GetArg("-b", "xxx"), "1");
543  BOOST_CHECK_EQUAL(test_args.GetArg("-fff", "xxx"), "0");
544  BOOST_CHECK_EQUAL(test_args.GetArg("-ggg", "xxx"), "1");
545  BOOST_CHECK_EQUAL(test_args.GetArg("-zzz", "xxx"), "xxx");
546  BOOST_CHECK_EQUAL(test_args.GetArg("-iii", "xxx"), "xxx");
547  // d is overridden
548  BOOST_CHECK(test_args.GetArg("-d", "xxx") == "eee");
549  // section-specific setting
550  BOOST_CHECK(test_args.GetArg("-h", "xxx") == "1");
551  // section takes priority for multiple values
552  BOOST_CHECK(test_args.GetArg("-ccc", "xxx") == "extend1");
553  // check multiple values works
554  const std::vector<std::string> sec1_ccc_expected = {"extend1","extend2","argument","multiple"};
555  const auto& sec1_ccc_res = test_args.GetArgs("-ccc");
556  BOOST_CHECK_EQUAL_COLLECTIONS(sec1_ccc_res.begin(), sec1_ccc_res.end(), sec1_ccc_expected.begin(), sec1_ccc_expected.end());
557 
558  test_args.SelectConfigNetwork("sec2");
559 
560  // same as original
561  BOOST_CHECK(test_args.GetArg("-a", "xxx") == "");
562  BOOST_CHECK(test_args.GetArg("-b", "xxx") == "1");
563  BOOST_CHECK(test_args.GetArg("-d", "xxx") == "e");
564  BOOST_CHECK(test_args.GetArg("-fff", "xxx") == "0");
565  BOOST_CHECK(test_args.GetArg("-ggg", "xxx") == "1");
566  BOOST_CHECK(test_args.GetArg("-zzz", "xxx") == "xxx");
567  BOOST_CHECK(test_args.GetArg("-h", "xxx") == "0");
568  // section-specific setting
569  BOOST_CHECK(test_args.GetArg("-iii", "xxx") == "2");
570  // section takes priority for multiple values
571  BOOST_CHECK(test_args.GetArg("-ccc", "xxx") == "extend3");
572  // check multiple values works
573  const std::vector<std::string> sec2_ccc_expected = {"extend3","argument","multiple"};
574  const auto& sec2_ccc_res = test_args.GetArgs("-ccc");
575  BOOST_CHECK_EQUAL_COLLECTIONS(sec2_ccc_res.begin(), sec2_ccc_res.end(), sec2_ccc_expected.begin(), sec2_ccc_expected.end());
576 
577  // Test section only options
578 
579  test_args.SetNetworkOnlyArg("-d");
580  test_args.SetNetworkOnlyArg("-ccc");
581  test_args.SetNetworkOnlyArg("-h");
582 
584  BOOST_CHECK(test_args.GetArg("-d", "xxx") == "e");
585  BOOST_CHECK(test_args.GetArgs("-ccc").size() == 2);
586  BOOST_CHECK(test_args.GetArg("-h", "xxx") == "0");
587 
588  test_args.SelectConfigNetwork("sec1");
589  BOOST_CHECK(test_args.GetArg("-d", "xxx") == "eee");
590  BOOST_CHECK(test_args.GetArgs("-d").size() == 1);
591  BOOST_CHECK(test_args.GetArgs("-ccc").size() == 2);
592  BOOST_CHECK(test_args.GetArg("-h", "xxx") == "1");
593 
594  test_args.SelectConfigNetwork("sec2");
595  BOOST_CHECK(test_args.GetArg("-d", "xxx") == "xxx");
596  BOOST_CHECK(test_args.GetArgs("-d").size() == 0);
597  BOOST_CHECK(test_args.GetArgs("-ccc").size() == 1);
598  BOOST_CHECK(test_args.GetArg("-h", "xxx") == "0");
599 }
600 
602 {
603  TestArgsManager testArgs;
604  LOCK(testArgs.cs_args);
605  testArgs.m_settings.command_line_options.clear();
606  testArgs.m_settings.command_line_options["strtest1"] = {"string..."};
607  // strtest2 undefined on purpose
608  testArgs.m_settings.command_line_options["inttest1"] = {"12345"};
609  testArgs.m_settings.command_line_options["inttest2"] = {"81985529216486895"};
610  // inttest3 undefined on purpose
611  testArgs.m_settings.command_line_options["booltest1"] = {""};
612  // booltest2 undefined on purpose
613  testArgs.m_settings.command_line_options["booltest3"] = {"0"};
614  testArgs.m_settings.command_line_options["booltest4"] = {"1"};
615 
616  // priorities
617  testArgs.m_settings.command_line_options["pritest1"] = {"a", "b"};
618  testArgs.m_settings.ro_config[""]["pritest2"] = {"a", "b"};
619  testArgs.m_settings.command_line_options["pritest3"] = {"a"};
620  testArgs.m_settings.ro_config[""]["pritest3"] = {"b"};
621  testArgs.m_settings.command_line_options["pritest4"] = {"a","b"};
622  testArgs.m_settings.ro_config[""]["pritest4"] = {"c","d"};
623 
624  BOOST_CHECK_EQUAL(testArgs.GetArg("strtest1", "default"), "string...");
625  BOOST_CHECK_EQUAL(testArgs.GetArg("strtest2", "default"), "default");
626  BOOST_CHECK_EQUAL(testArgs.GetIntArg("inttest1", -1), 12345);
627  BOOST_CHECK_EQUAL(testArgs.GetIntArg("inttest2", -1), 81985529216486895LL);
628  BOOST_CHECK_EQUAL(testArgs.GetIntArg("inttest3", -1), -1);
629  BOOST_CHECK_EQUAL(testArgs.GetBoolArg("booltest1", false), true);
630  BOOST_CHECK_EQUAL(testArgs.GetBoolArg("booltest2", false), false);
631  BOOST_CHECK_EQUAL(testArgs.GetBoolArg("booltest3", false), false);
632  BOOST_CHECK_EQUAL(testArgs.GetBoolArg("booltest4", false), true);
633 
634  BOOST_CHECK_EQUAL(testArgs.GetArg("pritest1", "default"), "b");
635  BOOST_CHECK_EQUAL(testArgs.GetArg("pritest2", "default"), "a");
636  BOOST_CHECK_EQUAL(testArgs.GetArg("pritest3", "default"), "a");
637  BOOST_CHECK_EQUAL(testArgs.GetArg("pritest4", "default"), "b");
638 }
639 
640 BOOST_AUTO_TEST_CASE(util_GetChainName)
641 {
642  TestArgsManager test_args;
643  const auto testnet = std::make_pair("-testnet", ArgsManager::ALLOW_ANY);
644  const auto regtest = std::make_pair("-regtest", ArgsManager::ALLOW_ANY);
645  test_args.SetupArgs({testnet, regtest});
646 
647  const char* argv_testnet[] = {"cmd", "-testnet"};
648  const char* argv_regtest[] = {"cmd", "-regtest"};
649  const char* argv_test_no_reg[] = {"cmd", "-testnet", "-noregtest"};
650  const char* argv_both[] = {"cmd", "-testnet", "-regtest"};
651 
652  // equivalent to "-testnet"
653  // regtest in testnet section is ignored
654  const char* testnetconf = "testnet=1\nregtest=0\n[test]\nregtest=1";
655  std::string error;
656 
657  BOOST_CHECK(test_args.ParseParameters(0, (char**)argv_testnet, error));
658  BOOST_CHECK_EQUAL(test_args.GetChainName(), "main");
659 
660  BOOST_CHECK(test_args.ParseParameters(2, (char**)argv_testnet, error));
661  BOOST_CHECK_EQUAL(test_args.GetChainName(), "test");
662 
663  BOOST_CHECK(test_args.ParseParameters(2, (char**)argv_regtest, error));
664  BOOST_CHECK_EQUAL(test_args.GetChainName(), "regtest");
665 
666  BOOST_CHECK(test_args.ParseParameters(3, (char**)argv_test_no_reg, error));
667  BOOST_CHECK_EQUAL(test_args.GetChainName(), "test");
668 
669  BOOST_CHECK(test_args.ParseParameters(3, (char**)argv_both, error));
670  BOOST_CHECK_THROW(test_args.GetChainName(), std::runtime_error);
671 
672  BOOST_CHECK(test_args.ParseParameters(0, (char**)argv_testnet, error));
673  test_args.ReadConfigString(testnetconf);
674  BOOST_CHECK_EQUAL(test_args.GetChainName(), "test");
675 
676  BOOST_CHECK(test_args.ParseParameters(2, (char**)argv_testnet, error));
677  test_args.ReadConfigString(testnetconf);
678  BOOST_CHECK_EQUAL(test_args.GetChainName(), "test");
679 
680  BOOST_CHECK(test_args.ParseParameters(2, (char**)argv_regtest, error));
681  test_args.ReadConfigString(testnetconf);
682  BOOST_CHECK_THROW(test_args.GetChainName(), std::runtime_error);
683 
684  BOOST_CHECK(test_args.ParseParameters(3, (char**)argv_test_no_reg, error));
685  test_args.ReadConfigString(testnetconf);
686  BOOST_CHECK_EQUAL(test_args.GetChainName(), "test");
687 
688  BOOST_CHECK(test_args.ParseParameters(3, (char**)argv_both, error));
689  test_args.ReadConfigString(testnetconf);
690  BOOST_CHECK_THROW(test_args.GetChainName(), std::runtime_error);
691 
692  // check setting the network to test (and thus making
693  // [test] regtest=1 potentially relevant) doesn't break things
694  test_args.SelectConfigNetwork("test");
695 
696  BOOST_CHECK(test_args.ParseParameters(0, (char**)argv_testnet, error));
697  test_args.ReadConfigString(testnetconf);
698  BOOST_CHECK_EQUAL(test_args.GetChainName(), "test");
699 
700  BOOST_CHECK(test_args.ParseParameters(2, (char**)argv_testnet, error));
701  test_args.ReadConfigString(testnetconf);
702  BOOST_CHECK_EQUAL(test_args.GetChainName(), "test");
703 
704  BOOST_CHECK(test_args.ParseParameters(2, (char**)argv_regtest, error));
705  test_args.ReadConfigString(testnetconf);
706  BOOST_CHECK_THROW(test_args.GetChainName(), std::runtime_error);
707 
708  BOOST_CHECK(test_args.ParseParameters(2, (char**)argv_test_no_reg, error));
709  test_args.ReadConfigString(testnetconf);
710  BOOST_CHECK_EQUAL(test_args.GetChainName(), "test");
711 
712  BOOST_CHECK(test_args.ParseParameters(3, (char**)argv_both, error));
713  test_args.ReadConfigString(testnetconf);
714  BOOST_CHECK_THROW(test_args.GetChainName(), std::runtime_error);
715 }
716 
717 // Test different ways settings can be merged, and verify results. This test can
718 // be used to confirm that updates to settings code don't change behavior
719 // unintentionally.
720 //
721 // The test covers:
722 //
723 // - Combining different setting actions. Possible actions are: configuring a
724 // setting, negating a setting (adding "-no" prefix), and configuring/negating
725 // settings in a network section (adding "main." or "test." prefixes).
726 //
727 // - Combining settings from command line arguments and a config file.
728 //
729 // - Combining SoftSet and ForceSet calls.
730 //
731 // - Testing "main" and "test" network values to make sure settings from network
732 // sections are applied and to check for mainnet-specific behaviors like
733 // inheriting settings from the default section.
734 //
735 // - Testing network-specific settings like "-wallet", that may be ignored
736 // outside a network section, and non-network specific settings like "-server"
737 // that aren't sensitive to the network.
738 //
742  static constexpr int MAX_ACTIONS = 3;
743 
746 
748  template <typename Fn>
749  void ForEachMergeSetup(Fn&& fn)
750  {
751  ActionList arg_actions = {};
752  // command_line_options do not have sections. Only iterate over SET and NEGATE
753  ForEachNoDup(arg_actions, SET, NEGATE, [&] {
754  ActionList conf_actions = {};
755  ForEachNoDup(conf_actions, SET, SECTION_NEGATE, [&] {
756  for (bool soft_set : {false, true}) {
757  for (bool force_set : {false, true}) {
758  for (const std::string& section : {CBaseChainParams::MAIN, CBaseChainParams::TESTNET, CBaseChainParams::SIGNET}) {
759  for (const std::string& network : {CBaseChainParams::MAIN, CBaseChainParams::TESTNET, CBaseChainParams::SIGNET}) {
760  for (bool net_specific : {false, true}) {
761  fn(arg_actions, conf_actions, soft_set, force_set, section, network, net_specific);
762  }
763  }
764  }
765  }
766  }
767  });
768  });
769  }
770 
772  std::vector<std::string> GetValues(const ActionList& actions,
773  const std::string& section,
774  const std::string& name,
775  const std::string& value_prefix)
776  {
777  std::vector<std::string> values;
778  int suffix = 0;
779  for (Action action : actions) {
780  if (action == NONE) break;
781  std::string prefix;
782  if (action == SECTION_SET || action == SECTION_NEGATE) prefix = section + ".";
783  if (action == SET || action == SECTION_SET) {
784  for (int i = 0; i < 2; ++i) {
785  values.push_back(prefix + name + "=" + value_prefix + ToString(++suffix));
786  }
787  }
788  if (action == NEGATE || action == SECTION_NEGATE) {
789  values.push_back(prefix + "no" + name + "=1");
790  }
791  }
792  return values;
793  }
794 };
795 
796 // Regression test covering different ways config settings can be merged. The
797 // test parses and merges settings, representing the results as strings that get
798 // compared against an expected hash. To debug, the result strings can be dumped
799 // to a file (see comments below).
801 {
802  CHash256 out_sha;
803  FILE* out_file = nullptr;
804  if (const char* out_path = getenv("ARGS_MERGE_TEST_OUT")) {
805  out_file = fsbridge::fopen(out_path, "w");
806  if (!out_file) throw std::system_error(errno, std::generic_category(), "fopen failed");
807  }
808 
809  ForEachMergeSetup([&](const ActionList& arg_actions, const ActionList& conf_actions, bool soft_set, bool force_set,
810  const std::string& section, const std::string& network, bool net_specific) {
811  TestArgsManager parser;
812  LOCK(parser.cs_args);
813 
814  std::string desc = "net=";
815  desc += network;
816  parser.m_network = network;
817 
818  const std::string& name = net_specific ? "wallet" : "server";
819  const std::string key = "-" + name;
821  if (net_specific) parser.SetNetworkOnlyArg(key);
822 
823  auto args = GetValues(arg_actions, section, name, "a");
824  std::vector<const char*> argv = {"ignored"};
825  for (auto& arg : args) {
826  arg.insert(0, "-");
827  desc += " ";
828  desc += arg;
829  argv.push_back(arg.c_str());
830  }
831  std::string error;
832  BOOST_CHECK(parser.ParseParameters(argv.size(), argv.data(), error));
834 
835  std::string conf;
836  for (auto& conf_val : GetValues(conf_actions, section, name, "c")) {
837  desc += " ";
838  desc += conf_val;
839  conf += conf_val;
840  conf += "\n";
841  }
842  std::istringstream conf_stream(conf);
843  BOOST_CHECK(parser.ReadConfigStream(conf_stream, "filepath", error));
845 
846  if (soft_set) {
847  desc += " soft";
848  parser.SoftSetArg(key, "soft1");
849  parser.SoftSetArg(key, "soft2");
850  }
851 
852  if (force_set) {
853  desc += " force";
854  parser.ForceSetArg(key, "force1");
855  parser.ForceSetArg(key, "force2");
856  }
857 
858  desc += " || ";
859 
860  if (!parser.IsArgSet(key)) {
861  desc += "unset";
862  BOOST_CHECK(!parser.IsArgNegated(key));
863  BOOST_CHECK_EQUAL(parser.GetArg(key, "default"), "default");
864  BOOST_CHECK(parser.GetArgs(key).empty());
865  } else if (parser.IsArgNegated(key)) {
866  desc += "negated";
867  BOOST_CHECK_EQUAL(parser.GetArg(key, "default"), "0");
868  BOOST_CHECK(parser.GetArgs(key).empty());
869  } else {
870  desc += parser.GetArg(key, "default");
871  desc += " |";
872  for (const auto& arg : parser.GetArgs(key)) {
873  desc += " ";
874  desc += arg;
875  }
876  }
877 
878  std::set<std::string> ignored = parser.GetUnsuitableSectionOnlyArgs();
879  if (!ignored.empty()) {
880  desc += " | ignored";
881  for (const auto& arg : ignored) {
882  desc += " ";
883  desc += arg;
884  }
885  }
886 
887  desc += "\n";
888 
889  out_sha.Write(MakeUCharSpan(desc));
890  if (out_file) {
891  BOOST_REQUIRE(fwrite(desc.data(), 1, desc.size(), out_file) == desc.size());
892  }
893  });
894 
895  if (out_file) {
896  if (fclose(out_file)) throw std::system_error(errno, std::generic_category(), "fclose failed");
897  out_file = nullptr;
898  }
899 
900  unsigned char out_sha_bytes[CSHA256::OUTPUT_SIZE];
901  out_sha.Finalize(out_sha_bytes);
902  std::string out_sha_hex = HexStr(out_sha_bytes);
903 
904  // If check below fails, should manually dump the results with:
905  //
906  // ARGS_MERGE_TEST_OUT=results.txt ./test_bitcoin --run_test=util_tests/util_ArgsMerge
907  //
908  // And verify diff against previous results to make sure the changes are expected.
909  //
910  // Results file is formatted like:
911  //
912  // <input> || <IsArgSet/IsArgNegated/GetArg output> | <GetArgs output> | <GetUnsuitable output>
913  BOOST_CHECK_EQUAL(out_sha_hex, "d1e436c1cd510d0ec44d5205d4b4e3bee6387d316e0075c58206cb16603f3d82");
914 }
915 
916 // Similar test as above, but for ArgsManager::GetChainName function.
918  static constexpr int MAX_ACTIONS = 2;
919 
922 
924  template <typename Fn>
925  void ForEachMergeSetup(Fn&& fn)
926  {
927  ActionList arg_actions = {};
928  ForEachNoDup(arg_actions, ENABLE_TEST, NEGATE_REG, [&] {
929  ActionList conf_actions = {};
930  ForEachNoDup(conf_actions, ENABLE_TEST, NEGATE_REG, [&] { fn(arg_actions, conf_actions); });
931  });
932  }
933 };
934 
936 {
937  CHash256 out_sha;
938  FILE* out_file = nullptr;
939  if (const char* out_path = getenv("CHAIN_MERGE_TEST_OUT")) {
940  out_file = fsbridge::fopen(out_path, "w");
941  if (!out_file) throw std::system_error(errno, std::generic_category(), "fopen failed");
942  }
943 
944  ForEachMergeSetup([&](const ActionList& arg_actions, const ActionList& conf_actions) {
945  TestArgsManager parser;
946  LOCK(parser.cs_args);
947  parser.AddArg("-regtest", "regtest", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
948  parser.AddArg("-testnet", "testnet", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
949 
950  auto arg = [](Action action) { return action == ENABLE_TEST ? "-testnet=1" :
951  action == DISABLE_TEST ? "-testnet=0" :
952  action == NEGATE_TEST ? "-notestnet=1" :
953  action == ENABLE_REG ? "-regtest=1" :
954  action == DISABLE_REG ? "-regtest=0" :
955  action == NEGATE_REG ? "-noregtest=1" : nullptr; };
956 
957  std::string desc;
958  std::vector<const char*> argv = {"ignored"};
959  for (Action action : arg_actions) {
960  const char* argstr = arg(action);
961  if (!argstr) break;
962  argv.push_back(argstr);
963  desc += " ";
964  desc += argv.back();
965  }
966  std::string error;
967  BOOST_CHECK(parser.ParseParameters(argv.size(), argv.data(), error));
969 
970  std::string conf;
971  for (Action action : conf_actions) {
972  const char* argstr = arg(action);
973  if (!argstr) break;
974  desc += " ";
975  desc += argstr + 1;
976  conf += argstr + 1;
977  conf += "\n";
978  }
979  std::istringstream conf_stream(conf);
980  BOOST_CHECK(parser.ReadConfigStream(conf_stream, "filepath", error));
982 
983  desc += " || ";
984  try {
985  desc += parser.GetChainName();
986  } catch (const std::runtime_error& e) {
987  desc += "error: ";
988  desc += e.what();
989  }
990  desc += "\n";
991 
992  out_sha.Write(MakeUCharSpan(desc));
993  if (out_file) {
994  BOOST_REQUIRE(fwrite(desc.data(), 1, desc.size(), out_file) == desc.size());
995  }
996  });
997 
998  if (out_file) {
999  if (fclose(out_file)) throw std::system_error(errno, std::generic_category(), "fclose failed");
1000  out_file = nullptr;
1001  }
1002 
1003  unsigned char out_sha_bytes[CSHA256::OUTPUT_SIZE];
1004  out_sha.Finalize(out_sha_bytes);
1005  std::string out_sha_hex = HexStr(out_sha_bytes);
1006 
1007  // If check below fails, should manually dump the results with:
1008  //
1009  // CHAIN_MERGE_TEST_OUT=results.txt ./test_bitcoin --run_test=util_tests/util_ChainMerge
1010  //
1011  // And verify diff against previous results to make sure the changes are expected.
1012  //
1013  // Results file is formatted like:
1014  //
1015  // <input> || <output>
1016  BOOST_CHECK_EQUAL(out_sha_hex, "f263493e300023b6509963887444c41386f44b63bc30047eb8402e8c1144854c");
1017 }
1018 
1019 BOOST_AUTO_TEST_CASE(util_ReadWriteSettings)
1020 {
1021  // Test writing setting.
1022  TestArgsManager args1;
1023  args1.ForceSetArg("-datadir", fs::PathToString(m_path_root));
1024  args1.LockSettings([&](util::Settings& settings) { settings.rw_settings["name"] = "value"; });
1025  args1.WriteSettingsFile();
1026 
1027  // Test reading setting.
1028  TestArgsManager args2;
1029  args2.ForceSetArg("-datadir", fs::PathToString(m_path_root));
1030  args2.ReadSettingsFile();
1031  args2.LockSettings([&](util::Settings& settings) { BOOST_CHECK_EQUAL(settings.rw_settings["name"].get_str(), "value"); });
1032 
1033  // Test error logging, and remove previously written setting.
1034  {
1035  ASSERT_DEBUG_LOG("Failed renaming settings file");
1036  fs::remove(args1.GetDataDirBase() / "settings.json");
1037  fs::create_directory(args1.GetDataDirBase() / "settings.json");
1038  args2.WriteSettingsFile();
1039  fs::remove(args1.GetDataDirBase() / "settings.json");
1040  }
1041 }
1042 
BOOST_FIXTURE_TEST_CASE(util_CheckValue, CheckValueTest)
static void TestParse(const std::string &str, bool expected_bool, int64_t expected_int)
BOOST_AUTO_TEST_CASE(util_datadir)
int flags
Definition: bitcoin-tx.cpp:525
std::set< std::string > GetUnsuitableSectionOnlyArgs() const
Log warnings for options in m_section_only_args when they are specified in the default section but no...
Definition: system.cpp:245
bool IsArgNegated(const std::string &strArg) const
Return true if the argument was originally passed as a negated option, i.e.
Definition: system.cpp:586
@ ALLOW_ANY
disable validation
Definition: system.h:172
bool ReadSettingsFile(std::vector< std::string > *errors=nullptr)
Read settings file.
Definition: system.cpp:536
void ForceSetArg(const std::string &strArg, const std::string &strValue)
Definition: system.cpp:680
bool ParseParameters(int argc, const char *const argv[], std::string &error)
Definition: system.cpp:287
std::vector< std::string > GetArgs(const std::string &strArg) const
Return a vector of strings of the given argument.
Definition: system.cpp:478
const fs::path & GetDataDirBase() const
Get data directory path.
Definition: system.h:287
void LockSettings(Fn &&fn)
Access settings with lock held.
Definition: system.h:466
bool SoftSetArg(const std::string &strArg, const std::string &strValue)
Set an argument if it doesn't already have a value.
Definition: system.cpp:664
void SelectConfigNetwork(const std::string &network)
Select the network in use.
Definition: system.cpp:281
void ClearPathCache()
Clear cached directory paths.
Definition: system.cpp:449
bool IsArgSet(const std::string &strArg) const
Return true if the given argument has been manually set.
Definition: system.cpp:487
bool WriteSettingsFile(std::vector< std::string > *errors=nullptr, bool backup=false) const
Write settings file or backup settings file.
Definition: system.cpp:559
int64_t GetIntArg(const std::string &strArg, int64_t nDefault) const
Return integer argument or default value.
Definition: system.cpp:616
std::vector< util::SettingsValue > GetSettingsList(const std::string &arg) const
Get list of setting values.
Definition: system.cpp:1103
RecursiveMutex cs_args
Definition: system.h:200
std::string GetArg(const std::string &strArg, const std::string &strDefault) const
Return string argument or default value.
Definition: system.cpp:591
util::SettingsValue GetSetting(const std::string &arg) const
Get setting value.
Definition: system.cpp:1095
bool ReadConfigStream(std::istream &stream, const std::string &filepath, std::string &error, bool ignore_invalid_keys=false)
Definition: system.cpp:939
bool GetBoolArg(const std::string &strArg, bool fDefault) const
Return boolean argument or default value.
Definition: system.cpp:641
void AddArg(const std::string &name, const std::string &help, unsigned int flags, const OptionsCategory &cat)
Add argument.
Definition: system.cpp:698
std::string GetChainName() const
Returns the appropriate chain name from the program arguments.
Definition: system.cpp:1060
static const std::string TESTNET
static const std::string SIGNET
static const std::string MAIN
Chain name strings.
A hasher class for Bitcoin's 256-bit hash (double SHA-256).
Definition: hash.h:25
CHash256 & Write(Span< const unsigned char > input)
Definition: hash.h:38
void Finalize(Span< unsigned char > output)
Definition: hash.h:31
static const size_t OUTPUT_SIZE
Definition: sha256.h:21
Test GetSetting and GetArg type coercion, negation, and default value handling.
void CheckValue(unsigned int flags, const char *arg, const Expect &expect)
std::string write(unsigned int prettyIndent=0, unsigned int indentLevel=0) const
Path class wrapper to block calls to the fs::path(std::string) implicit constructor and the fs::path:...
Definition: fs.h:31
BOOST_AUTO_TEST_SUITE_END()
std::unique_ptr< Descriptor > Parse(const std::string &descriptor, FlatSigningProvider &out, std::string &error, bool require_checksum)
Parse a descriptor string.
static std::string PathToString(const path &path)
Convert path object to a byte string.
Definition: fs.h:150
FILE * fopen(const fs::path &p, const char *mode)
Definition: fs.cpp:25
ArgsManager args
#define BOOST_CHECK_THROW(stmt, excMatch)
Definition: object.cpp:19
#define BOOST_CHECK_EQUAL(v1, v2)
Definition: object.cpp:18
#define BOOST_CHECK(expr)
Definition: object.cpp:17
const char * prefix
Definition: rest.cpp:974
const char * name
Definition: rest.cpp:46
static const int64_t values[]
A selection of numbers that do not trigger int64_t overflow when added/subtracted.
constexpr auto MakeUCharSpan(V &&v) -> decltype(UCharSpanCast(Span{std::forward< V >(v)}))
Like the Span constructor, but for (const) unsigned char member types only.
Definition: span.h:285
void ForEachNoDup(CharType(&string)[StringLength], CharType min_char, CharType max_char, Fn &&fn)
Iterate over string values and call function for each string without successive duplicate characters.
Definition: str.h:32
std::string ToString(const T &t)
Locale-independent version of std::to_string.
Definition: string.h:109
std::vector< std::string > GetValues(const ActionList &actions, const std::string &section, const std::string &name, const std::string &value_prefix)
Translate actions into a list of <key>=setting strings.
void ForEachMergeSetup(Fn &&fn)
Enumerate all possible test configurations.
static constexpr int MAX_ACTIONS
Max number of actions to sequence together.
Action[MAX_ACTIONS] ActionList
Basic testing setup.
Definition: setup_common.h:85
void ForEachMergeSetup(Fn &&fn)
Enumerate all possible test configurations.
Action[MAX_ACTIONS] ActionList
static constexpr int MAX_ACTIONS
Expect(util::SettingsValue s)
Expect & Error(const char *e)
std::optional< int64_t > int_value
Expect & Int(int64_t i)
Expect & List(std::vector< std::string > m)
std::optional< std::vector< std::string > > list_value
Expect & Bool(bool b)
std::optional< bool > bool_value
util::SettingsValue setting
Expect & String(const char *s)
std::string Parse(const char *arg)
void SetupArgs(const std::vector< std::pair< std::string, unsigned int >> &args)
void SetNetworkOnlyArg(const std::string arg)
void ReadConfigString(const std::string str_config)
std::vector< util::SettingsValue > GetSettingsList(const std::string &arg) const
Get list of setting values.
Definition: system.cpp:1103
RecursiveMutex cs_args
Definition: system.h:200
util::SettingsValue GetSetting(const std::string &arg) const
Get setting value.
Definition: system.cpp:1095
bool ReadConfigStream(std::istream &stream, const std::string &filepath, std::string &error, bool ignore_invalid_keys=false)
Definition: system.cpp:939
Testing fixture that pre-creates a 100-block REGTEST-mode block chain.
Definition: setup_common.h:134
Stored settings.
Definition: settings.h:31
std::map< std::string, SettingsValue > rw_settings
Map of setting name to read-write file setting value.
Definition: settings.h:37
#define LOCK(cs)
Definition: sync.h:258
bool error(const char *fmt, const Args &... args)
Definition: system.h:48
#define ASSERT_DEBUG_LOG(message)
Definition: logging.h:39
#define expect(bit)
std::string HexStr(const Span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.