File: testJsonArgumentParser.cpp

package info (click to toggle)
visp 3.6.0-5
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 119,296 kB
  • sloc: cpp: 500,914; ansic: 52,904; xml: 22,642; python: 7,365; java: 4,247; sh: 482; makefile: 237; objc: 145
file content (370 lines) | stat: -rw-r--r-- 11,331 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
/****************************************************************************
 *
 * ViSP, open source Visual Servoing Platform software.
 * Copyright (C) 2005 - 2023 by Inria. All rights reserved.
 *
 * This software is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 * See the file LICENSE.txt at the root directory of this source
 * distribution for additional information about the GNU GPL.
 *
 * For using ViSP with software that can not be combined with the GNU
 * GPL, please contact Inria about acquiring a ViSP Professional
 * Edition License.
 *
 * See https://visp.inria.fr for more information.
 *
 * This software was developed at:
 * Inria Rennes - Bretagne Atlantique
 * Campus Universitaire de Beaulieu
 * 35042 Rennes Cedex
 * France
 *
 * If you have questions regarding the use of this file, please contact
 * Inria at visp@inria.fr
 *
 * This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
 * WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 *
 * Description:
 * Test vpJsonArgumentParser
 *
*****************************************************************************/

 /*!
   \file testJsonArgumentParser.cpp

   Test parsing command line argument and json files with vpJsonArgumentParser
 */

#include <visp3/core/vpIoTools.h>
#include <visp3/io/vpJsonArgumentParser.h>

#if defined(VISP_HAVE_NLOHMANN_JSON) && defined(VISP_HAVE_CATCH2)
#include <nlohmann/json.hpp>
using json = nlohmann::json; //! json namespace shortcut

#define CATCH_CONFIG_RUNNER
#include <catch.hpp>

std::pair<int, std::vector<char *>> convertToArgcAndArgv(const std::vector<std::string> &args)
{
  std::vector<char *> argvs;
  argvs.reserve(args.size());
  int argc = static_cast<int>(args.size());
  for (unsigned i = 0; i < args.size(); ++i) {
    argvs.push_back(const_cast<char *>(args[i].c_str()));
  }
  return std::make_pair(argc, argvs);
}

json loadJson(const std::string &path)
{
  std::ifstream json_file(path);
  if (!json_file.good()) {
    throw vpException(vpException::ioError, "Could not open JSON settings file");
  }
  json j = json::parse(json_file);
  json_file.close();
  return j;
}

void saveJson(const json &j, const std::string &path)
{
  std::ofstream json_file(path);
  if (!json_file.good()) {
    throw vpException(vpException::ioError, "Could not open JSON settings file to write modifications");
  }
  json_file << j.dump();
  json_file.close();
}

SCENARIO("Parsing arguments from JSON file", "[json]")
{
  // setup test dir
  // Get the user login name

  std::string tmp_dir = vpIoTools::makeTempDirectory(vpIoTools::getTempPath() + vpIoTools::path("/") + "visp_test_json_argument_parsing");
  const std::string jsonPath = tmp_dir + "/" + "arguments.json";

  const auto modifyJson = [&jsonPath](std::function<void(json &)> modify) -> void {
    json j = loadJson(jsonPath);
    modify(j);
    saveJson(j, jsonPath);
  };

  GIVEN("Some specific arguments")
  {
    const std::string s = "hello";
    WHEN("Converting a string to a json rep")
    {
      const json js = convertCommandLineArgument<std::string>(s);
      const json truejs = s;
      THEN("Conversion is correct")
      {
        REQUIRE(js == truejs);
      }
    }
  }

  GIVEN("Some JSON parameters saved in a file, and some C++ variables")
  {
    json j = json {
      {"a", 2},
      {"b", 2.0},
      {"c", "a string"},
      {"d", true},
      {"e", {
        {"a", 5}
      }}
    };
    saveJson(j, jsonPath);

    int a = 1;
    double b = 1.0;
    std::string c = "";
    bool d = false;
    int ea = 4;
    WHEN("Declaring a parser with all parameters required")
    {
      vpJsonArgumentParser parser("A program", "--config", "/");
      parser.addArgument("a", a, true)
        .addArgument("b", b, true)
        .addArgument("c", c, true)
        .addArgument("d", d, true)
        .addArgument("e/a", ea, true);

      THEN("Calling the parser without any argument fails")
      {
        const int argc = 1;
        const char *argv [] = {
          "program"
        };

        REQUIRE_THROWS(parser.parse(argc, argv));
      }

      THEN("Calling the parser with only the JSON file works")
      {
        const int argc = 3;
        const char *argv [] = {
          "program",
          "--config",
          jsonPath.c_str()
        };
        REQUIRE_NOTHROW(parser.parse(argc, argv));
        REQUIRE(a == j["a"]);
        REQUIRE(b == j["b"]);
        REQUIRE(c == j["c"]);
        REQUIRE(d == j["d"]);
        REQUIRE(ea == j["e"]["a"]);

      }
      THEN("Calling the parser by specifying the json argument but leaving the file path empty throws an error")
      {
        const int argc = 2;
        const char *argv [] = {
          "program",
          "--config",
        };
        REQUIRE_THROWS(parser.parse(argc, argv));
      }
      THEN("Calling the parser with only the json file but deleting a random field throws an error")
      {
        const int argc = 3;
        for (const auto &jsonElem : j.items()) {
          modifyJson([&jsonElem](json &j) { j.erase(jsonElem.key()); });
          const char *argv [] = {
            "program",
            "--config",
            jsonPath.c_str()
          };
          REQUIRE_THROWS(parser.parse(argc, argv));
        }
      }
      THEN("Calling the parser with only the json file but setting a random field to null throws an error")
      {
        const int argc = 3;
        for (const auto &jsonElem : j.items()) {
          modifyJson([&jsonElem](json &j) { j[jsonElem.key()] = nullptr; });
          const char *argv [] = {
            "program",
            "--config",
            jsonPath.c_str()
          };
          REQUIRE_THROWS(parser.parse(argc, argv));
        }
      }
      THEN("Calling the parser with an invalid json file path throws an error")
      {
        const int argc = 3;
        const char *argv [] = {
          "program",
          "--config",
          "some_invalid_json/file/path.json"
        };
        REQUIRE_THROWS(parser.parse(argc, argv));
      }
      THEN("Calling the parser with only the command line arguments works")
      {
        const int newa = a + 1, newea = ea + 6;
        const double newb = b + 2.0;
        const std::string newc = c + "hello";
        const bool newd = !d;

        const std::string newdstr(newd ? "true" : "false");
        std::vector<std::string> args = {
          "program",
          "a", std::to_string(newa),
          "b", std::to_string(newb),
          "c", newc,
          "d", newdstr,
          "e/a", std::to_string(newea)
        };
        int argc;
        std::vector<char *> argv;
        std::tie(argc, argv) = convertToArgcAndArgv(args);
        REQUIRE_NOTHROW(parser.parse(argc, (const char **)(&argv[0])));
        REQUIRE(a == newa);
        REQUIRE(b == newb);
        REQUIRE(c == newc);
        REQUIRE(d == newd);
        REQUIRE(ea == newea);

      }
      THEN("Calling the parser with JSON and command line argument works")
      {
        const int newa = a + 1;
        const double newb = b + 2.0;
        std::vector<std::string> args = {
          "program",
          "--config", jsonPath,
          "a", std::to_string(newa),
          "b", std::to_string(newb)
        };
        int argc;
        std::vector<char *> argv;
        std::tie(argc, argv) = convertToArgcAndArgv(args);
        REQUIRE_NOTHROW(parser.parse(argc, (const char **)(&argv[0])));
        REQUIRE(a == newa);
        REQUIRE(b == newb);
        REQUIRE(c == j["c"]);
        REQUIRE(d == j["d"]);
        REQUIRE(ea == j["e"]["a"]);

      }
      THEN("Calling the parser with a missing argument value throws an error")
      {

        std::vector<std::string> args = {
          "program",
          "--config", jsonPath,
          "a"
        };
        int argc;
        std::vector<char *> argv;
        std::tie(argc, argv) = convertToArgcAndArgv(args);
        REQUIRE_THROWS(parser.parse(argc, (const char **)(&argv[0])));
      }
    }
  }
  THEN("Declaring a parser with an undefined nesting delimiter fails")
  {
    REQUIRE_THROWS(vpJsonArgumentParser("A program", "--config", ""));
  }
  THEN("Declaring a parser with an invalid JSON file argument fails")
  {
    REQUIRE_THROWS(vpJsonArgumentParser("A program", "", "/"));
  }

  WHEN("Instanciating a parser with some optional fields")
  {
    vpJsonArgumentParser parser("A program", "--config", "/");
    float b = 0.0;
    parser.addArgument("b", b, false);

    THEN("Calling the parser without any argument works and does not modify the default value")
    {
      float bcopy = b;
      const int argc = 1;
      const char *argv [] = {
        "program"
      };

      REQUIRE_NOTHROW(parser.parse(argc, argv));
      REQUIRE(b == bcopy);

    }
  }
  WHEN("Instanciating a parser with nested parameters")
  {
    vpJsonArgumentParser parser("A program", "--config", "/");
    float b = 0.0;
    parser.addArgument("b", b, false);

    THEN("Calling the parser without any argument works and does not modify the default value")
    {
      float bcopy = b;
      const int argc = 1;
      const char *argv [] = {
        "program"
      };

      REQUIRE_NOTHROW(parser.parse(argc, argv));
      REQUIRE(b == bcopy);

    }
  }


  WHEN("Instanciating a parser with some documentation")
  {
    const std::string programString = "ProgramString";
    const std::string firstArg = "FirstArgName", firstArgDescription = "FirstArgDescription";
    const std::string secondArg = "secondArgName", secondArgDescription = "secondArgDescription";
    vpJsonArgumentParser parser(programString, "--config", "/");
    std::string a = "DefaultFirstArg", b = "DefaultSecondArg";
    parser.addArgument(firstArg, a, true, firstArgDescription);
    parser.addArgument(secondArg, b, false, secondArgDescription);
    WHEN("Getting the help string")
    {
      const std::string help = parser.help();
      THEN("Output should contain the basic program description")
      {
        REQUIRE(help.find(programString) < help.size());
      }
      THEN("Output should contain the json argument")
      {
        REQUIRE(help.find("--config") < help.size());
      }
      THEN("Output should contain the arguments, their description and their default value")
      {
        const std::vector<std::string> requireds = { firstArg, secondArg, firstArgDescription, secondArgDescription, a, b };
        for (const auto &required : requireds) {
          REQUIRE(help.find(required) < help.size());
        }
      }
    }


  }
}
int main(int argc, char *argv [])
{
  Catch::Session session; // There must be exactly one instance
  session.applyCommandLine(argc, argv);

  int numFailed = session.run();
  return numFailed;
}

#else

int main()
{
  return EXIT_SUCCESS;
}

#endif