Consolix
Loading...
Searching...
No Matches
test_strip_json_comments.cpp
Go to the documentation of this file.
1#include <array>
2#include <fstream>
3#include <iostream>
4#include <stdexcept>
5#include <string>
6
8
9#ifndef CONSOLIX_TEST_DATA_DIR
10#error "CONSOLIX_TEST_DATA_DIR must point to the test fixture directory."
11#endif
12
13std::string read_file(const std::string& file_path) {
14 std::ifstream file(file_path);
15 if (!file.is_open()) {
16 throw std::runtime_error("Failed to open file: " + file_path);
17 }
18
19 return std::string(
20 (std::istreambuf_iterator<char>(file)),
21 std::istreambuf_iterator<char>());
22}
23
24std::string fixture_path(const char* file_name) {
25 return std::string(CONSOLIX_TEST_DATA_DIR) + "/" + file_name;
26}
27
28int main() {
29 try {
30 const std::string input_file = fixture_path("test_input.json");
31 const std::string json_string = read_file(input_file);
32
33 struct TestCase {
34 bool with_whitespace;
35 bool preserve_newlines;
36 const char* expected_file;
37 };
38
39 const std::array<TestCase, 4> test_cases{{
40 {false, false, "test_output_no_whitespace_no_newlines.json"},
41 {false, true, "test_output_no_whitespace_preserve_newlines.json"},
42 {true, false, "test_output_whitespace_no_newlines.json"},
43 {true, true, "test_output_whitespace_preserve_newlines.json"}
44 }};
45
46 for (const TestCase& test_case : test_cases) {
47 const std::string actual = consolix::strip_json_comments(
48 json_string,
49 test_case.with_whitespace,
50 test_case.preserve_newlines);
51
52 const std::string expected_path = fixture_path(test_case.expected_file);
53 const std::string expected = read_file(expected_path);
54
55 if (actual != expected) {
56 std::cerr
57 << "Mismatch for case "
58 << "with_whitespace=" << test_case.with_whitespace << ", "
59 << "preserve_newlines=" << test_case.preserve_newlines << ", "
60 << "expected_file=" << expected_path
61 << std::endl;
62 return 1;
63 }
64 }
65
66 std::cout << "All JSON comment stripping checks passed." << std::endl;
67 return 0;
68 } catch (const std::exception& e) {
69 std::cerr << "Error: " << e.what() << std::endl;
70 return 1;
71 }
72}
Utilities for working with JSON strings, including removing comments.
std::string strip_json_comments(const std::string &json_string, bool with_whitespace=false, bool preserve_newlines=true)
Removes comments from a JSON string.
std::string read_file(const std::string &file_path)
std::string fixture_path(const char *file_name)