File: messageformat2test_read_json.cpp

package info (click to toggle)
icu 78.2-1
  • links: PTS
  • area: main
  • in suites: experimental
  • size: 123,992 kB
  • sloc: cpp: 527,891; ansic: 112,789; sh: 4,983; makefile: 4,657; perl: 3,199; python: 2,933; xml: 749; sed: 36; lisp: 12
file content (378 lines) | stat: -rw-r--r-- 15,321 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
371
372
373
374
375
376
377
378
// © 2024 and later: Unicode, Inc. and others.
// License & terms of use: https://www.unicode.org/copyright.html

#include "unicode/utypes.h"

#if !UCONFIG_NO_NORMALIZATION

#if !UCONFIG_NO_FORMATTING

#if !UCONFIG_NO_MF2

#include <fstream>
#include <string>

#include "charstr.h"
#include "json-json.hpp"
#include "messageformat2test.h"
#include "messageformat2test_utils.h"

using namespace nlohmann;

using namespace icu::message2;

static UErrorCode getExpectedRuntimeErrorFromString(const std::string& errorName) {
    if (errorName == "syntax-error") {
        return U_MF_SYNTAX_ERROR;
    }
    if (errorName == "variant-key-mismatch") {
        return U_MF_VARIANT_KEY_MISMATCH_ERROR;
    }
    if (errorName == "missing-fallback-variant") {
        return U_MF_NONEXHAUSTIVE_PATTERN_ERROR;
    }
    if (errorName == "missing-selector-annotation") {
        return U_MF_MISSING_SELECTOR_ANNOTATION_ERROR;
    }
    if (errorName == "unresolved-variable") {
        return U_MF_UNRESOLVED_VARIABLE_ERROR;
    }
    if (errorName == "bad-operand") {
        return U_MF_OPERAND_MISMATCH_ERROR;
    }
    if (errorName == "bad-option") {
        return U_MF_BAD_OPTION;
    }
    if (errorName == "unknown-function") {
        return U_MF_UNKNOWN_FUNCTION_ERROR;
    }
    if (errorName == "duplicate-declaration") {
        return U_MF_DUPLICATE_DECLARATION_ERROR;
    }
    if (errorName == "duplicate-option-name") {
        return U_MF_DUPLICATE_OPTION_NAME_ERROR;
    }
    if (errorName == "duplicate-variant") {
        return U_MF_DUPLICATE_VARIANT_ERROR;
    }
    if (errorName == "bad-selector") {
        return U_MF_SELECTOR_ERROR;
    }
// Arbitrary default
    return U_MF_FORMATTING_ERROR;
}

static UnicodeString u_str(std::string s) {
    return UnicodeString::fromUTF8(s);
}

static TestCase::Builder successTest(const std::string& testName,
                                     const std::string& messageText) {
    return TestCase::Builder().setName(u_str(testName))
        .setPattern(u_str(messageText))
        .setExpectSuccess();
}

static void makeTestName(char* buffer, size_t size, std::string fileName, int32_t testNum) {
    snprintf(buffer, size, "test from file: %s[%u]", fileName.c_str(), ++testNum);
}

static bool setArguments(TestMessageFormat2& t,
                         TestCase::Builder& test,
                         const std::vector<json>& params,
                         UErrorCode& errorCode) {
    if (U_FAILURE(errorCode)) {
        return true;
    }
    bool schemaError = false;
    for (auto argsIter = params.begin(); argsIter != params.end(); ++argsIter) {
        auto j_object = argsIter->template get<json::object_t>();
        if (!j_object["name"].is_null()) {
            const UnicodeString argName = u_str(j_object["name"].template get<std::string>());
            if (!j_object["value"].is_null()) {
                json val = j_object["value"];
                // Determine type of value
                if (val.is_number()) {
                    test.setArgument(argName,
                                     val.template get<double>());
                } else if (val.is_string()) {
                    test.setArgument(argName,
                                     u_str(val.template get<std::string>()));
                } else if (val.is_object()) {
                    // Dates: represent in tests as { "date" : timestamp }, to distinguish
                    // from number values
                    auto obj = val.template get<json::object_t>();
                    if (obj["date"].is_number()) {
                        test.setDateArgument(argName, val["date"]);
                    } else if (obj["decimal"].is_string()) {
                        // Decimal strings: represent in tests as { "decimal" : string },
                        // to distinguish from string values
                        test.setDecimalArgument(argName, obj["decimal"].template get<std::string>(), errorCode);
                    }
                } else if (val.is_boolean() || val.is_null()) {
                    return false; // For now, boolean and null arguments are unsupported
                }
            } else {
                // Null argument -- not supported
                return false;
            }
        } else {
            t.logln("name is null");
            schemaError = true;
            break;
        }
    }
    if (schemaError) {
        t.logln("Warning: test with missing 'name' or 'value' in params");
        if (U_SUCCESS(errorCode)) {
            errorCode = U_ILLEGAL_ARGUMENT_ERROR;
        }
    }
    return true;
}


/*
  Test files are expected to follow the schema in:
  https://github.com/unicode-org/conformance/blob/main/schema/message_fmt2/testgen_schema.json
  as of https://github.com/unicode-org/conformance/pull/255
*/
static void runValidTest(TestMessageFormat2& icuTest,
                         const std::string& testName,
                         const std::string& defaultError,
                         bool anyError,
                         const json& j,
                         IcuTestErrorCode& errorCode) {
    auto j_object = j.template get<json::object_t>();
    std::string messageText;

    // src can be a single string or an array of strings
    if (!j_object["src"].is_null()) {
        if (j_object["src"].is_string()) {
            messageText = j_object["src"].template get<std::string>();
        } else {
            auto strings = j_object["src"].template get<std::vector<std::string>>();
            for (const auto &piece : strings) {
                messageText += piece;
            }
        }
    }
    // Otherwise, it should probably be an error, but we just
    // treat this as the empty string

    TestCase::Builder test = successTest(testName, messageText);

    // Certain ICU4J tests don't work yet in ICU4C.
    // See ICU-22754
    // ignoreCpp => only works in Java
    if (!j_object["ignoreCpp"].is_null()) {
        return;
    }

    if (!j_object["exp"].is_null()) {
        // Set expected result if it's present
        std::string expectedOutput = j["exp"].template get<std::string>();
        test.setExpected(u_str(expectedOutput));
    }

    if (!j_object["locale"].is_null()) {
        std::string localeStr = j_object["locale"].template get<std::string>();
        test.setLocale(Locale(localeStr.c_str()));
    }

    if (!j_object["params"].is_null()) {
        // `params` is an array of objects
        auto params = j_object["params"].template get<std::vector<json>>();
        if (!setArguments(icuTest, test, params, errorCode)) {
            return; // Skip tests with unsupported arguments
        }
    }

    bool expectedError = false;
    if (!j_object["expErrors"].is_null()) {
        // Map from string to string
        auto errors = j_object["expErrors"].template get<std::vector<std::map<std::string, std::string>>>();
        // We only emit the first error, so we just hope the first error
        // in the list in the test is also the error we emit
        U_ASSERT(errors.size() > 0);
        std::string errorType = errors[0]["type"];
        if (errorType.length() <= 0) {
            errorType = errors[0]["name"];
        }
//        // See TODO(options); ignore these tests for now
//        if (errorType == "bad-option") {
//            return;
//        }
        test.setExpectedError(getExpectedRuntimeErrorFromString(errorType));
        expectedError = true;
    } else if (defaultError.length() > 0) {
        test.setExpectedError(getExpectedRuntimeErrorFromString(defaultError));
        expectedError = true;
    } else if (anyError) {
        test.setExpectedAnyError();
        expectedError = true;
    }

    // If no expected result and no error, then set the test builder to expect success
    if (j_object["exp"].is_null() && !expectedError) {
        test.setNoSyntaxError();
    }

    // Check for expected diagnostic values
    int32_t lineNumber = 0;
    int32_t offset = -1;
    if (!j_object["char"].is_null()) {
        offset = j_object["char"].template get<int32_t>();
    }
    if (!j_object["line"].is_null()) {
        lineNumber = j_object["line"].template get<int32_t>();
    }
    if (offset != -1) {
        test.setExpectedLineNumberAndOffset(lineNumber, offset);
    }


    TestCase t = test.build();
    TestUtils::runTestCase(icuTest, t, errorCode);
}

// File name is relative to message2/ in the test data directory
static void runTestsFromJsonFile(TestMessageFormat2& t,
                                      const std::string& fileName,
                                      IcuTestErrorCode& errorCode) {
    const char* testDataDirectory = IntlTest::getSharedTestData(errorCode);
    CHECK_ERROR(errorCode);

    std::string testFileName(testDataDirectory);
    testFileName.append("message2/");
    testFileName.append(fileName);
    std::ifstream testFile(testFileName);
    json data = json::parse(testFile);

    int32_t testNum = 0;
    char testName[100];

    auto j_object = data.template get<json::object_t>();

    // Some files have an expected error
    std::string defaultError;
    bool anyError = false;
    if (!j_object["defaultTestProperties"].is_null()
        && !j_object["defaultTestProperties"]["expErrors"].is_null()) {
        auto expErrors = j_object["defaultTestProperties"]["expErrors"];
        // If expErrors is a boolean "true", that means we expect all tests
        // to emit errors but we don't care which ones.
        anyError = expErrors.is_boolean() && expErrors.template get<bool>();
        // expErrors might also be a boolean, in which case we ignore it --
        // so we have to check if it's an array
        if (expErrors.is_array()) {
            auto expErrorsObj = expErrors.template get<std::vector<json>>();
            if (expErrorsObj.size() > 0) {
                if (!expErrorsObj[0]["type"].is_null()) {
                    defaultError = expErrorsObj[0]["type"].template get<std::string>();
                }
            }
        }
    }

    if (!j_object["tests"].is_null()) {
        auto tests = j_object["tests"].template get<std::vector<json>>();
        for (auto iter = tests.begin(); iter != tests.end(); ++iter) {
            makeTestName(testName, sizeof(testName), fileName, ++testNum);
            t.logln(testName);
            // Use error_handler_t::ignore because of the patch to allow lone surrogates
            t.logln(u_str(iter->dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore)));

            runValidTest(t, testName, defaultError, anyError, *iter, errorCode);
        }
    } else {
        // Test doesn't follow schema -- probably an error
        t.logln("Warning: no tests in filename: ");
        t.logln(u_str(fileName));
        (UErrorCode&) errorCode = U_ILLEGAL_ARGUMENT_ERROR;
    }
}

void TestMessageFormat2::jsonTestsFromFiles(IcuTestErrorCode& errorCode) {
    // Spec tests are fairly limited as the spec doesn't dictate formatter
    // output. Tests under testdata/message2/spec are taken from
    // https://github.com/unicode-org/message-format-wg/tree/main/test .
    // Tests directly under testdata/message2 are specific to ICU4C.

    // Do spec tests for syntax errors
    runTestsFromJsonFile(*this, "spec/syntax-errors.json", errorCode);
    runTestsFromJsonFile(*this, "unsupported-expressions.json", errorCode);
    runTestsFromJsonFile(*this, "unsupported-statements.json", errorCode);
    runTestsFromJsonFile(*this, "syntax-errors-reserved.json", errorCode);

    // Do tests for data model errors
    runTestsFromJsonFile(*this, "spec/data-model-errors.json", errorCode);
    runTestsFromJsonFile(*this, "more-data-model-errors.json", errorCode);

    // Do valid spec tests
    runTestsFromJsonFile(*this, "spec/syntax.json", errorCode);
    runTestsFromJsonFile(*this, "spec/fallback.json", errorCode);

    // Uncomment when test functions are implemented in the registry
    // See https://unicode-org.atlassian.net/browse/ICU-22907
    // runTestsFromJsonFile(*this, "spec/pattern-selection.json", errorCode);

    // Do valid function tests
    runTestsFromJsonFile(*this, "spec/functions/date.json", errorCode);
    runTestsFromJsonFile(*this, "spec/functions/datetime.json", errorCode);
    runTestsFromJsonFile(*this, "spec/functions/integer.json", errorCode);
    runTestsFromJsonFile(*this, "spec/functions/number.json", errorCode);
    runTestsFromJsonFile(*this, "spec/functions/string.json", errorCode);
    runTestsFromJsonFile(*this, "spec/functions/time.json", errorCode);

    // Other tests (non-spec)
    // TODO: https://github.com/unicode-org/message-format-wg/pull/902 will
    // move the bidi tests into the spec
    runTestsFromJsonFile(*this, "bidi.json", errorCode);
    runTestsFromJsonFile(*this, "more-functions.json", errorCode);
    runTestsFromJsonFile(*this, "valid-tests.json", errorCode);
    runTestsFromJsonFile(*this, "resolution-errors.json", errorCode);
    runTestsFromJsonFile(*this, "matches-whitespace.json", errorCode);
    runTestsFromJsonFile(*this, "alias-selector-annotations.json", errorCode);
    runTestsFromJsonFile(*this, "runtime-errors.json", errorCode);
    runTestsFromJsonFile(*this, "more-syntax-errors.json", errorCode);

    // Re: the expected output for the first test in this file:
    // Note: the more "correct" fallback output seems like it should be "1.000 3" (ignoring the
    // overriding .input binding of $var2) but that's hard to achieve
    // as so-called "implicit declarations" can only be detected after parsing, at which
    // point the data model can't be modified.
    // Probably this is going to change anyway so that any data model error gets replaced
    // with a fallback for the whole message.
    // The second test has a similar issue with the output.
    runTestsFromJsonFile(*this, "tricky-declarations.json", errorCode);

    // Markup is ignored when formatting to string
    runTestsFromJsonFile(*this, "markup.json", errorCode);

    // TODO(duplicates): currently the expected output is based on using
    // the last definition of the duplicate-declared variable;
    // perhaps it's better to remove all declarations for $foo before formatting.
    // however if https://github.com/unicode-org/message-format-wg/pull/704 lands,
    // it'll be a moot point since the output will be expected to be the fallback string
    // (This applies to the expected output for all the U_DUPLICATE_DECLARATION_ERROR tests)
    runTestsFromJsonFile(*this, "duplicate-declarations.json", errorCode);

    runTestsFromJsonFile(*this, "invalid-options.json", errorCode);

    runTestsFromJsonFile(*this, "syntax-errors-end-of-input.json", errorCode);
    runTestsFromJsonFile(*this, "syntax-errors-diagnostics.json", errorCode);
    runTestsFromJsonFile(*this, "syntax-errors-diagnostics-multiline.json", errorCode);

    // ICU4J tests
    runTestsFromJsonFile(*this, "icu-test-functions.json", errorCode);
    runTestsFromJsonFile(*this, "icu-parser-tests.json", errorCode);
    runTestsFromJsonFile(*this, "icu-test-selectors.json", errorCode);
    runTestsFromJsonFile(*this, "icu-test-previous-release.json", errorCode);
}

#endif /* #if !UCONFIG_NO_MF2 */

#endif /* #if !UCONFIG_NO_FORMATTING */

#endif /* #if !UCONFIG_NO_NORMALIZATION */