load_node_test.cpp 11.4 KB
Newer Older
Jesse Beder's avatar
Jesse Beder committed
1
2
3
4
5
6
7
#include "yaml-cpp/yaml.h"  // IWYU pragma: keep

#include "gtest/gtest.h"

namespace YAML {
namespace {
TEST(LoadNodeTest, Reassign) {
8
9
  Node node = Load("foo");
  node = Node();
10
  EXPECT_TRUE(node.IsNull());
Jesse Beder's avatar
Jesse Beder committed
11
12
13
}

TEST(LoadNodeTest, FallbackValues) {
14
  Node node = Load("foo: bar\nx: 2");
Jesse Beder's avatar
Jesse Beder committed
15
16
17
18
19
20
21
22
23
  EXPECT_EQ("bar", node["foo"].as<std::string>());
  EXPECT_EQ("bar", node["foo"].as<std::string>("hello"));
  EXPECT_EQ("hello", node["baz"].as<std::string>("hello"));
  EXPECT_EQ(2, node["x"].as<int>());
  EXPECT_EQ(2, node["x"].as<int>(5));
  EXPECT_EQ(5, node["y"].as<int>(5));
}

TEST(LoadNodeTest, NumericConversion) {
Chen's avatar
Chen committed
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
  EXPECT_EQ(1.5f, Load("1.5").as<float>());
  EXPECT_EQ(1.5, Load("1.5").as<double>());
  EXPECT_THROW(Load("1.5").as<int>(), TypedBadConversion<int>);
  EXPECT_EQ(1, Load("1").as<int>());
  EXPECT_EQ(1.0f, Load("1").as<float>());
  EXPECT_NE(Load(".nan").as<float>(), Load(".nan").as<float>());
  EXPECT_EQ(std::numeric_limits<float>::infinity(), Load(".inf").as<float>());
  EXPECT_EQ(-std::numeric_limits<float>::infinity(), Load("-.inf").as<float>());
  EXPECT_EQ(21, Load("0x15").as<int>());
  EXPECT_EQ(13, Load("015").as<int>());
  EXPECT_EQ(-128, +Load("-128").as<int8_t>());
  EXPECT_EQ(127, +Load("127").as<int8_t>());
  EXPECT_THROW(Load("128").as<int8_t>(), TypedBadConversion<signed char>);
  EXPECT_EQ(255, +Load("255").as<uint8_t>());
  EXPECT_THROW(Load("256").as<uint8_t>(), TypedBadConversion<unsigned char>);
  // test as<char>/as<uint8_t> with ‘a’,"ab",'1',"127"
  EXPECT_EQ('a', Load("a").as<char>());
  EXPECT_THROW(Load("ab").as<char>(), TypedBadConversion<char>);
  EXPECT_EQ('1', Load("1").as<char>());
  EXPECT_THROW(Load("127").as<char>(), TypedBadConversion<char>);
  EXPECT_THROW(Load("a").as<uint8_t>(), TypedBadConversion<unsigned char>);
  EXPECT_THROW(Load("ab").as<uint8_t>(), TypedBadConversion<unsigned char>);
  EXPECT_EQ(1, +Load("1").as<uint8_t>());
47
  // Throw exception: convert a negative number to an unsigned number.
Chen's avatar
Chen committed
48
49
50
51
52
  EXPECT_THROW(Load("-128").as<unsigned>(), TypedBadConversion<unsigned int>);
  EXPECT_THROW(Load("-128").as<unsigned short>(), TypedBadConversion<unsigned short>);
  EXPECT_THROW(Load("-128").as<unsigned long>(), TypedBadConversion<unsigned long>);
  EXPECT_THROW(Load("-128").as<unsigned long long>(), TypedBadConversion<unsigned long long>);
  EXPECT_THROW(Load("-128").as<uint8_t>(), TypedBadConversion<unsigned char>);
Jesse Beder's avatar
Jesse Beder committed
53
54
55
}

TEST(LoadNodeTest, Binary) {
56
  Node node = Load(
Jesse Beder's avatar
Jesse Beder committed
57
58
59
60
61
62
63
      "[!!binary \"SGVsbG8sIFdvcmxkIQ==\", !!binary "
      "\"TWFuIGlzIGRpc3Rpbmd1aXNoZWQsIG5vdCBvbmx5IGJ5IGhpcyByZWFzb24sIGJ1dCBieS"
      "B0aGlzIHNpbmd1bGFyIHBhc3Npb24gZnJvbSBvdGhlciBhbmltYWxzLCB3aGljaCBpcyBhIG"
      "x1c3Qgb2YgdGhlIG1pbmQsIHRoYXQgYnkgYSBwZXJzZXZlcmFuY2Ugb2YgZGVsaWdodCBpbi"
      "B0aGUgY29udGludWVkIGFuZCBpbmRlZmF0aWdhYmxlIGdlbmVyYXRpb24gb2Yga25vd2xlZG"
      "dlLCBleGNlZWRzIHRoZSBzaG9ydCB2ZWhlbWVuY2Ugb2YgYW55IGNhcm5hbCBwbGVhc3VyZS"
      "4K\"]");
64
65
66
67
68
69
70
71
72
73
74
  EXPECT_EQ(Binary(reinterpret_cast<const unsigned char*>("Hello, World!"), 13),
            node[0].as<Binary>());
  EXPECT_EQ(Binary(reinterpret_cast<const unsigned char*>(
                       "Man is distinguished, not only by his reason, "
                       "but by this singular passion from other "
                       "animals, which is a lust of the mind, that by "
                       "a perseverance of delight in the continued and "
                       "indefatigable generation of knowledge, exceeds "
                       "the short vehemence of any carnal pleasure.\n"),
                   270),
            node[1].as<Binary>());
Jesse Beder's avatar
Jesse Beder committed
75
76
}

77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
TEST(LoadNodeTest, BinaryWithWhitespaces) {
  Node node = Load(
      "binaryText: !binary |-\n"
      "  TWFuIGlzIGRpc3Rpbmd1aXNoZWQsIG5vdCBvbmx5IGJ5IGhpcyByZWFzb24sIGJ1dCBieS\n"
      "  B0aGlzIHNpbmd1bGFyIHBhc3Npb24gZnJvbSBvdGhlciBhbmltYWxzLCB3aGljaCBpcyBhIG\n"
      "  x1c3Qgb2YgdGhlIG1pbmQsIHRoYXQgYnkgYSBwZXJzZXZlcmFuY2Ugb2YgZGVsaWdodCBpbi\n"
      "  B0aGUgY29udGludWVkIGFuZCBpbmRlZmF0aWdhYmxlIGdlbmVyYXRpb24gb2Yga25vd2xlZG\n"
      "  dlLCBleGNlZWRzIHRoZSBzaG9ydCB2ZWhlbWVuY2Ugb2YgYW55IGNhcm5hbCBwbGVhc3VyZS\n"
      "  4K");
  EXPECT_EQ(Binary(reinterpret_cast<const unsigned char*>(
                       "Man is distinguished, not only by his reason, "
                       "but by this singular passion from other "
                       "animals, which is a lust of the mind, that by "
                       "a perseverance of delight in the continued and "
                       "indefatigable generation of knowledge, exceeds "
                       "the short vehemence of any carnal pleasure.\n"),
                   270),
            node["binaryText"].as<Binary>());
}

Jesse Beder's avatar
Jesse Beder committed
97
TEST(LoadNodeTest, IterateSequence) {
98
  Node node = Load("[1, 3, 5, 7]");
Jesse Beder's avatar
Jesse Beder committed
99
100
  int seq[] = {1, 3, 5, 7};
  int i = 0;
101
  for (const_iterator it = node.begin(); it != node.end(); ++it) {
Jesse Beder's avatar
Jesse Beder committed
102
103
104
105
106
107
108
109
    EXPECT_TRUE(i < 4);
    int x = seq[i++];
    EXPECT_EQ(x, it->as<int>());
  }
  EXPECT_EQ(4, i);
}

TEST(LoadNodeTest, IterateMap) {
110
  Node node = Load("{a: A, b: B, c: C}");
Jesse Beder's avatar
Jesse Beder committed
111
  int i = 0;
112
  for (const_iterator it = node.begin(); it != node.end(); ++it) {
Jesse Beder's avatar
Jesse Beder committed
113
114
115
116
117
118
119
120
121
    EXPECT_TRUE(i < 3);
    i++;
    EXPECT_EQ(it->second.as<char>(), it->first.as<char>() + 'A' - 'a');
  }
  EXPECT_EQ(3, i);
}

#ifdef BOOST_FOREACH
TEST(LoadNodeTest, ForEach) {
122
  Node node = Load("[1, 3, 5, 7]");
Jesse Beder's avatar
Jesse Beder committed
123
124
  int seq[] = {1, 3, 5, 7};
  int i = 0;
125
  BOOST_FOREACH (const Node& item, node) {
Jesse Beder's avatar
Jesse Beder committed
126
127
128
129
130
131
    int x = seq[i++];
    EXPECT_EQ(x, item.as<int>());
  }
}

TEST(LoadNodeTest, ForEachMap) {
132
133
  Node node = Load("{a: A, b: B, c: C}");
  BOOST_FOREACH (const const_iterator::value_type& p, node) {
Jesse Beder's avatar
Jesse Beder committed
134
135
136
137
138
139
    EXPECT_EQ(p.second.as<char>(), p.first.as<char>() + 'A' - 'a');
  }
}
#endif

TEST(LoadNodeTest, CloneScalar) {
140
141
  Node node = Load("!foo monkey");
  Node clone = Clone(node);
Jesse Beder's avatar
Jesse Beder committed
142
143
144
145
146
147
  EXPECT_FALSE(clone == node);
  EXPECT_EQ(clone.as<std::string>(), node.as<std::string>());
  EXPECT_EQ(clone.Tag(), node.Tag());
}

TEST(LoadNodeTest, CloneSeq) {
148
149
  Node node = Load("[1, 3, 5, 7]");
  Node clone = Clone(node);
Jesse Beder's avatar
Jesse Beder committed
150
  EXPECT_FALSE(clone == node);
151
  EXPECT_EQ(NodeType::Sequence, clone.Type());
Jesse Beder's avatar
Jesse Beder committed
152
153
154
155
156
157
158
  EXPECT_EQ(clone.size(), node.size());
  for (std::size_t i = 0; i < node.size(); i++) {
    EXPECT_EQ(clone[i].as<int>(), node[i].as<int>());
  }
}

TEST(LoadNodeTest, CloneMap) {
159
160
  Node node = Load("{foo: bar}");
  Node clone = Clone(node);
Jesse Beder's avatar
Jesse Beder committed
161
  EXPECT_FALSE(clone == node);
162
  EXPECT_EQ(NodeType::Map, clone.Type());
Jesse Beder's avatar
Jesse Beder committed
163
164
165
166
167
  EXPECT_EQ(clone.size(), node.size());
  EXPECT_EQ(clone["foo"].as<std::string>(), node["foo"].as<std::string>());
}

TEST(LoadNodeTest, CloneAlias) {
168
169
  Node node = Load("&foo [*foo]");
  Node clone = Clone(node);
Jesse Beder's avatar
Jesse Beder committed
170
  EXPECT_FALSE(clone == node);
171
  EXPECT_EQ(NodeType::Sequence, clone.Type());
Jesse Beder's avatar
Jesse Beder committed
172
173
174
175
176
  EXPECT_EQ(clone.size(), node.size());
  EXPECT_EQ(clone[0], clone);
}

TEST(LoadNodeTest, ForceInsertIntoMap) {
177
  Node node;
Jesse Beder's avatar
Jesse Beder committed
178
179
180
181
  node["a"] = "b";
  node.force_insert("x", "y");
  node.force_insert("a", 5);
  EXPECT_EQ(3, node.size());
182
  EXPECT_EQ(NodeType::Map, node.Type());
Jesse Beder's avatar
Jesse Beder committed
183
184
185
  bool ab = false;
  bool a5 = false;
  bool xy = false;
186
  for (const_iterator it = node.begin(); it != node.end(); ++it) {
Jesse Beder's avatar
Jesse Beder committed
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
    if (it->first.as<std::string>() == "a") {
      if (it->second.as<std::string>() == "b")
        ab = true;
      else if (it->second.as<std::string>() == "5")
        a5 = true;
    } else if (it->first.as<std::string>() == "x" &&
               it->second.as<std::string>() == "y")
      xy = true;
  }
  EXPECT_TRUE(ab);
  EXPECT_TRUE(a5);
  EXPECT_TRUE(xy);
}

TEST(LoadNodeTest, ResetNode) {
202
  Node node = Load("[1, 2, 3]");
Jesse Beder's avatar
Jesse Beder committed
203
  EXPECT_TRUE(!node.IsNull());
204
  Node other = node;
Jesse Beder's avatar
Jesse Beder committed
205
206
207
208
209
210
211
212
  node.reset();
  EXPECT_TRUE(node.IsNull());
  EXPECT_TRUE(!other.IsNull());
  node.reset(other);
  EXPECT_TRUE(!node.IsNull());
  EXPECT_EQ(node, other);
}

213
214
215
216
217
TEST(LoadNodeTest, EmptyString) {
  Node node = Load("\"\"");
  EXPECT_TRUE(!node.IsNull());
}

Jesse Beder's avatar
Jesse Beder committed
218
TEST(LoadNodeTest, DereferenceIteratorError) {
219
220
  Node node = Load("[{a: b}, 1, 2]");
  EXPECT_THROW(node.begin()->first.as<int>(), InvalidNode);
Jesse Beder's avatar
Jesse Beder committed
221
222
  EXPECT_EQ(true, (*node.begin()).IsMap());
  EXPECT_EQ(true, node.begin()->IsMap());
223
224
  EXPECT_THROW((*node.begin()->begin()).Type(), InvalidNode);
  EXPECT_THROW(node.begin()->begin()->Type(), InvalidNode);
Jesse Beder's avatar
Jesse Beder committed
225
226
227
}

TEST(NodeTest, EmitEmptyNode) {
228
229
  Node node;
  Emitter emitter;
Jesse Beder's avatar
Jesse Beder committed
230
231
232
  emitter << node;
  EXPECT_EQ("", std::string(emitter.c_str()));
}
233
234
235
236
237
238
239

TEST(NodeTest, ParseNodeStyle) {
  EXPECT_EQ(EmitterStyle::Flow, Load("[1, 2, 3]").Style());
  EXPECT_EQ(EmitterStyle::Flow, Load("{foo: bar}").Style());
  EXPECT_EQ(EmitterStyle::Block, Load("- foo\n- bar").Style());
  EXPECT_EQ(EmitterStyle::Block, Load("foo: bar").Style());
}
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256

struct ParserExceptionTestCase {
  std::string name;
  std::string input;
  std::string expected_exception;
};

TEST(NodeTest, IncompleteJson) {
  std::vector<ParserExceptionTestCase> tests = {
      {"JSON map without value", "{\"access\"", ErrorMsg::END_OF_MAP_FLOW},
      {"JSON map with colon but no value", "{\"access\":",
       ErrorMsg::END_OF_MAP_FLOW},
      {"JSON map with unclosed value quote", "{\"access\":\"",
       ErrorMsg::END_OF_MAP_FLOW},
      {"JSON map without end brace", "{\"access\":\"abc\"",
       ErrorMsg::END_OF_MAP_FLOW},
  };
257
  for (const ParserExceptionTestCase& test : tests) {
258
259
260
261
262
263
264
265
    try {
      Load(test.input);
      FAIL() << "Expected exception " << test.expected_exception << " for "
             << test.name << ", input: " << test.input;
    } catch (const ParserException& e) {
      EXPECT_EQ(test.expected_exception, e.msg);
    }
  }
Jesse Beder's avatar
Jesse Beder committed
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
struct SingleNodeTestCase {
  std::string input;
  NodeType::value nodeType;
  int nodeSize;
  std::string expected_content;
};

TEST(NodeTest, SpecialFlow) {
  std::vector<SingleNodeTestCase> tests = {
      {"[:]", NodeType::Sequence, 1, "[{~: ~}]"},
      {"[a:]", NodeType::Sequence, 1, "[{a: ~}]"},
      {"[:a]", NodeType::Sequence, 1, "[:a]"},
      {"[,]", NodeType::Sequence, 1, "[~]"},
      {"[a:,]", NodeType::Sequence, 1, "[{a: ~}]"},
      {"{:}", NodeType::Map, 1, "{~: ~}"},
      {"{a:}", NodeType::Map, 1, "{a: ~}"},
      {"{:a}", NodeType::Map, 1, "{:a: ~}"},
      {"{,}", NodeType::Map, 1, "{~: ~}"},
      {"{a:,}", NodeType::Map, 1, "{a: ~}"},
  };
  for (const SingleNodeTestCase& test : tests) {
    Node node = Load(test.input);
    Emitter emitter;
    emitter << node;
    EXPECT_EQ(test.nodeType, node.Type());
    EXPECT_EQ(test.nodeSize, node.size());
    EXPECT_EQ(test.expected_content, std::string(emitter.c_str()));
  }
}

TEST(NodeTest, IncorrectFlow) {
  std::vector<ParserExceptionTestCase> tests = {
    {"Incorrect yaml: \"{:]\"", "{:]", ErrorMsg::FLOW_END},
    {"Incorrect yaml: \"[:}\"", "[:}", ErrorMsg::FLOW_END},
  };
  for (const ParserExceptionTestCase test : tests) {
    try {
      Load(test.input);
      FAIL() << "Expected exception " << test.expected_exception << " for "
             << test.name << ", input: " << test.input;
    } catch (const ParserException& e) {
      EXPECT_EQ(test.expected_exception, e.msg);
    }
  }
}

314
315
316
317
TEST(NodeTest, LoadTildeAsNull) {
  Node node = Load("~");
  ASSERT_TRUE(node.IsNull());
}
Chen's avatar
Chen committed
318
319
320
321
322
323
324
325
326
327
328
329

TEST(NodeTest, LoadNullWithStrTag) {
  Node node = Load("!!str null");
  EXPECT_EQ(node.Tag(), "tag:yaml.org,2002:str");
  EXPECT_EQ(node.as<std::string>(), "null");
}

TEST(NodeTest, LoadQuotedNull) {
  Node node = Load("\"null\"");
  EXPECT_EQ(node.as<std::string>(), "null");
}

330
331
332
333
334
TEST(NodeTest, LoadTagWithParenthesis) {
    Node node = Load("!Complex(Tag) foo");
    EXPECT_EQ(node.Tag(), "!Complex(Tag)");
    EXPECT_EQ(node.as<std::string>(), "foo");
}
335

336
337
338
339
340
TEST(NodeTest, LoadTagWithNullScalar) {
  Node node = Load("!2");
  EXPECT_TRUE(node.IsNull());
}

341
342
}  // namespace
}  // namespace YAML