Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Latest commit

 

History

History
History
393 lines (328 loc) · 13.8 KB

File metadata and controls

393 lines (328 loc) · 13.8 KB
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
/**
* JSONata C++ Test Generator
*
* Ports the Java Generate.java functionality to C++
* Reads JSONata test cases from jsonata/test/test-suite/groups and generates
* individual C++ Google Test files in test/gen/
*/
#include <iostream>
#include <fstream>
#include <filesystem>
#include <string>
#include <vector>
#include <algorithm>
#include <sstream>
#include <nlohmann/json.hpp>
using nlohmann::ordered_json;
namespace fs = std::filesystem;
class JsonataTestGenerator {
public:
// Helper function to sanitize names for C++ identifiers
static std::string sanitizeName(const std::string& name) {
std::string result = name;
std::replace(result.begin(), result.end(), '-', '_');
std::replace(result.begin(), result.end(), '.', '_');
return result;
}
// Helper function to read JSON file content
static std::string readFileContent(const std::string& filePath) {
std::ifstream file(filePath);
if (!file.is_open()) {
throw std::runtime_error("Cannot open file: " + filePath);
}
std::stringstream buffer;
buffer << file.rdbuf();
return buffer.str();
}
// Helper function to preprocess JSON content to fix common issues
static std::string preprocessJsonContent(const std::string& content) {
std::string result = content;
// Replace unescaped control characters in strings
// This is a simple approach - replace unescaped newlines, tabs, etc.
bool inString = false;
bool escaped = false;
for (size_t i = 0; i < result.length(); ++i) {
char c = result[i];
if (escaped) {
escaped = false;
continue;
}
if (c == '\\' && inString) {
escaped = true;
continue;
}
if (c == '"') {
inString = !inString;
continue;
}
// If we're in a string and encounter control characters, escape them
if (inString && c < 0x20) {
switch (c) {
case '\n':
result[i] = 'n';
result.insert(i, "\\");
i++; // Skip the inserted backslash
break;
case '\r':
result[i] = 'r';
result.insert(i, "\\");
i++;
break;
case '\t':
result[i] = 't';
result.insert(i, "\\");
i++;
break;
default:
result[i] = ' '; // Replace with space
break;
}
}
}
return result;
}
// Helper function to escape strings for C++ literals
static std::string escapeString(const std::string& str) {
std::string result;
for (char c : str) {
switch (c) {
case '\n': result += ' '; break; // Replace newlines with spaces like Java
case '"': result += "\\\""; break;
case '\\': result += "\\\\"; break;
case '\r': result += "\\r"; break;
case '\t': result += "\\t"; break;
default: result += c; break;
}
}
return result;
}
// Extract expression from test case for comment
static std::string getExpressionComment(const ordered_json& testCase) {
if (testCase.is_object() && testCase.contains("expr") && testCase["expr"].is_string())
return escapeString(testCase["expr"].get<std::string>());
return "";
}
// Extract expression from std::any that contains JsonObject
static std::string getExpressionCommentFromAny(const std::any&) { return ""; }
// Generate test method for a single test case
static void generateTestMethod(std::stringstream& output,
const std::string& suiteName,
const std::string& caseName,
int caseIndex,
const std::string& expr) {
std::string methodName;
if (caseIndex >= 0) {
methodName = sanitizeName(caseName) + "_case_" + std::to_string(caseIndex);
} else {
methodName = sanitizeName(caseName);
}
output << "// " << expr << "\n";
output << "TEST_F(" << sanitizeName(suiteName) << "Test, " << methodName << ") {\n";
if (caseIndex >= 0) {
output << " EXPECT_NO_THROW(runSubCase(\"jsonata/test/test-suite/groups/" << suiteName
<< "/" << caseName << ".json\", " << caseIndex << "));\n";
} else {
output << " EXPECT_NO_THROW(runCase(\"jsonata/test/test-suite/groups/" << suiteName
<< "/" << caseName << ".json\"));\n";
}
output << "}\n\n";
}
// Extract expression from content using simple string parsing as fallback
static std::string extractExpressionFallback(const std::string& content) {
// Find the "expr" field manually
size_t exprPos = content.find("\"expr\"");
if (exprPos == std::string::npos) return "";
size_t colonPos = content.find(":", exprPos);
if (colonPos == std::string::npos) return "";
size_t quoteStart = content.find("\"", colonPos);
if (quoteStart == std::string::npos) return "";
size_t quoteEnd = quoteStart + 1;
int escapeCount = 0;
while (quoteEnd < content.size()) {
if (content[quoteEnd] == '\\') {
escapeCount++;
} else if (content[quoteEnd] == '"' && escapeCount % 2 == 0) {
break;
} else if (content[quoteEnd] != '\\') {
escapeCount = 0;
}
quoteEnd++;
}
if (quoteEnd >= content.size()) return "";
std::string expr = content.substr(quoteStart + 1, quoteEnd - quoteStart - 1);
return escapeString(expr);
}
// Determine if content is an array by checking if it starts with '['
static bool isJsonArray(const std::string& content) {
for (char c : content) {
if (std::isspace(c)) continue;
return c == '[';
}
return false;
}
// Count test cases in an array by counting objects
static int countArrayTestCases(const std::string& content) {
int count = 0;
bool inString = false;
bool escaped = false;
int braceLevel = 0;
for (size_t i = 0; i < content.size(); ++i) {
char c = content[i];
if (escaped) {
escaped = false;
continue;
}
if (c == '\\' && inString) {
escaped = true;
continue;
}
if (c == '"') {
inString = !inString;
continue;
}
if (inString) continue;
if (c == '{') {
if (braceLevel == 0) count++;
braceLevel++;
} else if (c == '}') {
braceLevel--;
}
}
return count;
}
// Process a single test case file
static int processTestFile(std::stringstream& output,
const std::string& suiteName,
const std::string& filePath) {
std::string fileName = fs::path(filePath).stem().string();
std::string content = readFileContent(filePath);
try {
// First try parsing the content as-is
auto jsonValue = ordered_json::parse(content);
int testCount = 0;
if (jsonValue.is_array()) {
for (size_t i = 0; i < jsonValue.size(); ++i) {
std::string expr = getExpressionComment(jsonValue[i]);
generateTestMethod(output, suiteName, fileName, static_cast<int>(i), expr);
testCount++;
}
} else {
std::string expr = getExpressionComment(jsonValue);
generateTestMethod(output, suiteName, fileName, -1, expr);
testCount++;
}
return testCount;
} catch (const std::exception& e) {
// Parsing failed - try preprocessing the content first
std::cerr << "JSON parsing failed for " << filePath << ": " << e.what() << std::endl;
std::cerr << "Trying with preprocessed content..." << std::endl;
try {
std::string processedContent = preprocessJsonContent(content);
auto jsonValue = ordered_json::parse(processedContent);
int testCount = 0;
if (jsonValue.is_array()) {
for (size_t i = 0; i < jsonValue.size(); ++i) {
std::string expr = getExpressionComment(jsonValue[i]);
generateTestMethod(output, suiteName, fileName, static_cast<int>(i), expr);
testCount++;
}
} else {
std::string expr = getExpressionComment(jsonValue);
generateTestMethod(output, suiteName, fileName, -1, expr);
testCount++;
}
return testCount;
} catch (const std::exception& e2) {
std::cerr << "Preprocessing also failed: " << e2.what() << std::endl;
}
// Both attempts failed - use fallback method to still generate tests
std::cerr << "File content preview (first 200 chars): " << content.substr(0, 200) << "..." << std::endl;
std::cerr << "Using fallback method to generate tests..." << std::endl;
int testCount = 0;
std::string expr = extractExpressionFallback(content);
if (isJsonArray(content)) {
// Multiple test cases in array
int arrayCount = countArrayTestCases(content);
for (int i = 0; i < arrayCount; ++i) {
generateTestMethod(output, suiteName, fileName, i, expr);
testCount++;
}
} else {
// Single test case
generateTestMethod(output, suiteName, fileName, -1, expr);
testCount++;
}
return testCount;
}
}
public:
static void generateTests(bool verbose = false) {
// Create output directory
fs::create_directories("test/gen");
std::string suitesPath = "jsonata/test/test-suite/groups";
if (!fs::exists(suitesPath)) {
std::cerr << "Error: Test suite directory not found: " << suitesPath << std::endl;
return;
}
int totalTests = 0;
int totalSuites = 0;
// Get all suite directories and sort them
std::vector<fs::path> suiteDirs;
for (const auto& entry : fs::directory_iterator(suitesPath)) {
if (entry.is_directory()) {
suiteDirs.push_back(entry.path());
}
}
std::sort(suiteDirs.begin(), suiteDirs.end());
for (const auto& suiteDir : suiteDirs) {
std::string suiteName = suiteDir.filename().string();
std::stringstream output;
// Generate file header
output << "#include <gtest/gtest.h>\n";
output << "#include \"JsonataTest.h\"\n\n";
output << "using namespace jsonata;\n\n";
// Generate test class inheriting from JsonataTest
output << "class " << sanitizeName(suiteName) << "Test : public JsonataTest {\n";
output << "};\n\n";
// Process all JSON files in the suite directory
int suiteTestCount = 0;
std::vector<fs::path> testFiles;
for (const auto& entry : fs::directory_iterator(suiteDir)) {
if (entry.is_regular_file() && entry.path().extension() == ".json") {
testFiles.push_back(entry.path());
}
}
std::sort(testFiles.begin(), testFiles.end());
for (const auto& testFile : testFiles) {
int count = processTestFile(output, suiteName, testFile.string());
suiteTestCount += count;
}
totalTests += suiteTestCount;
totalSuites++;
// Write the generated test file
std::string outputFileName = "test/gen/" + sanitizeName(suiteName) + "Test.cpp";
std::ofstream outFile(outputFileName);
if (outFile.is_open()) {
outFile << output.str();
outFile.close();
if (verbose) {
std::cout << output.str() << std::endl;
}
std::cout << "Generated suite '" << suiteName << "' tests=" << suiteTestCount << std::endl;
} else {
std::cerr << "Error: Could not write to " << outputFileName << std::endl;
}
}
std::cout << "Generated SUITES=" << totalSuites << " TOTAL=" << totalTests << std::endl;
}
};
int main(int argc, char* argv[]) {
bool verbose = (argc > 1) && (std::string(argv[1]).find("-v") == 0);
try {
JsonataTestGenerator::generateTests(verbose);
return 0;
} catch (const std::exception& e) {
std::cerr << "Error: " << e.what() << std::endl;
return 1;
}
}
Morty Proxy This is a proxified and sanitized view of the page, visit original site.