User Guide
printer.cpp
Go to the documentation of this file.
1 /*
2  * Copyright 2023 Blue Brain Project, EPFL.
3  * See the top-level LICENSE file for details.
4  *
5  * SPDX-License-Identifier: Apache-2.0
6  */
7 
8 #include <sstream>
9 #include <string>
10 
11 #include <catch2/catch_test_macros.hpp>
12 
13 #include "printer/json_printer.hpp"
14 
16 
17 TEST_CASE("JSON printer converting object to string form", "[printer][json]") {
18  SECTION("Stringstream test 1") {
19  std::stringstream ss;
20  JSONPrinter p(ss);
21  p.compact_json(true);
22 
23  p.push_block("A");
24  p.add_node("B");
25  p.pop_block();
26  p.flush();
27 
28  auto result = R"({"A":[{"name":"B"}]})";
29  REQUIRE(ss.str() == result);
30  }
31 
32  SECTION("Stringstream test 2") {
33  std::stringstream ss;
34  JSONPrinter p(ss);
35  p.compact_json(true);
36 
37  p.push_block("A");
38  p.add_node("B");
39  p.add_node("C");
40  p.push_block("D");
41  p.add_node("E");
42  p.pop_block();
43  p.pop_block();
44  p.flush();
45 
46  auto result = R"({"A":[{"name":"B"},{"name":"C"},{"D":[{"name":"E"}]}]})";
47  REQUIRE(ss.str() == result);
48  }
49 
50  SECTION("Test with nodes as separate tags") {
51  std::stringstream ss;
52  JSONPrinter p(ss);
53  p.compact_json(true);
54  p.expand_keys(true);
55 
56  p.push_block("A");
57  p.add_node("B");
58  p.push_block("D");
59  p.add_node("E");
60  p.pop_block();
61  p.flush();
62 
63  auto result =
64  R"({"children":[{"name":"B"},{"children":[{"name":"E"}],"name":"D"}],"name":"A"})";
65  REQUIRE(ss.str() == result);
66  }
67 }
json_printer.hpp
Helper class for printing AST in JSON form.
nmodl::printer::JSONPrinter::add_node
void add_node(std::string value, const std::string &key="name")
Add node to json (typically basic type)
Definition: json_printer.cpp:34
nmodl::printer::JSONPrinter
Helper class for printing AST in JSON form.
Definition: json_printer.hpp:46
nmodl::printer::JSONPrinter::compact_json
void compact_json(bool flag)
print json in compact mode
Definition: json_printer.hpp:92
nmodl::printer::JSONPrinter::push_block
void push_block(const std::string &value, const std::string &key="name")
Add new json object (typically start of new block) name here is type of new block encountered.
Definition: json_printer.cpp:55
nmodl::printer::JSONPrinter::pop_block
void pop_block()
We finished processing a block, add processed block to it's parent block.
Definition: json_printer.cpp:71
nmodl::printer::JSONPrinter::flush
void flush()
Dump json object to stream (typically at the end) nspaces is number of spaces used for indentation.
Definition: json_printer.cpp:82
nmodl::printer::JSONPrinter::expand_keys
void expand_keys(bool flag)
Definition: json_printer.hpp:96
TEST_CASE
TEST_CASE("JSON printer converting object to string form", "[printer][json]")
Definition: printer.cpp:17