~ubuntu-branches/ubuntu/oneiric/mozc/oneiric

« back to all changes in this revision

Viewing changes to protobuf/files/src/google/protobuf/compiler/cpp/cpp_unittest.cc

  • Committer: Bazaar Package Importer
  • Author(s): Nobuhiro Iwamatsu
  • Date: 2010-07-14 03:26:47 UTC
  • mfrom: (1.1.1 upstream)
  • Revision ID: james.westby@ubuntu.com-20100714032647-13qjisj6m8cm8jdx
Tags: 0.12.410.102-1
* New upstream release (Closes: #588971).
  - Add mozc-server, mozc-utils-gui and scim-mozc packages.
* Update debian/rules.
  Add --gypdir option to build_mozc.py.
* Update debian/control.
  - Bumped standards-version to 3.9.0.
  - Update description.
* Add mozc icon (Closes: #588972).
* Add patch which revises issue 18.
  ibus_mozc_issue18.patch
* kFreeBSD build support.
  support_kfreebsd.patch

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
// Protocol Buffers - Google's data interchange format
2
 
// Copyright 2008 Google Inc.  All rights reserved.
3
 
// http://code.google.com/p/protobuf/
4
 
//
5
 
// Redistribution and use in source and binary forms, with or without
6
 
// modification, are permitted provided that the following conditions are
7
 
// met:
8
 
//
9
 
//     * Redistributions of source code must retain the above copyright
10
 
// notice, this list of conditions and the following disclaimer.
11
 
//     * Redistributions in binary form must reproduce the above
12
 
// copyright notice, this list of conditions and the following disclaimer
13
 
// in the documentation and/or other materials provided with the
14
 
// distribution.
15
 
//     * Neither the name of Google Inc. nor the names of its
16
 
// contributors may be used to endorse or promote products derived from
17
 
// this software without specific prior written permission.
18
 
//
19
 
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20
 
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21
 
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22
 
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
23
 
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24
 
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
25
 
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26
 
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27
 
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28
 
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29
 
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30
 
 
31
 
// Author: kenton@google.com (Kenton Varda)
32
 
//  Based on original Protocol Buffers design by
33
 
//  Sanjay Ghemawat, Jeff Dean, and others.
34
 
//
35
 
// To test the code generator, we actually use it to generate code for
36
 
// google/protobuf/unittest.proto, then test that.  This means that we
37
 
// are actually testing the parser and other parts of the system at the same
38
 
// time, and that problems in the generator may show up as compile-time errors
39
 
// rather than unittest failures, which may be surprising.  However, testing
40
 
// the output of the C++ generator directly would be very hard.  We can't very
41
 
// well just check it against golden files since those files would have to be
42
 
// updated for any small change; such a test would be very brittle and probably
43
 
// not very helpful.  What we really want to test is that the code compiles
44
 
// correctly and produces the interfaces we expect, which is why this test
45
 
// is written this way.
46
 
 
47
 
#include <vector>
48
 
 
49
 
#include <google/protobuf/unittest.pb.h>
50
 
#include <google/protobuf/unittest_optimize_for.pb.h>
51
 
#include <google/protobuf/unittest_embed_optimize_for.pb.h>
52
 
#include <google/protobuf/unittest_no_generic_services.pb.h>
53
 
#include <google/protobuf/test_util.h>
54
 
#include <google/protobuf/compiler/cpp/cpp_test_bad_identifiers.pb.h>
55
 
#include <google/protobuf/compiler/importer.h>
56
 
#include <google/protobuf/io/coded_stream.h>
57
 
#include <google/protobuf/io/zero_copy_stream_impl.h>
58
 
#include <google/protobuf/descriptor.h>
59
 
#include <google/protobuf/descriptor.pb.h>
60
 
#include <google/protobuf/dynamic_message.h>
61
 
 
62
 
#include <google/protobuf/stubs/common.h>
63
 
#include <google/protobuf/stubs/strutil.h>
64
 
#include <google/protobuf/stubs/substitute.h>
65
 
#include <google/protobuf/testing/googletest.h>
66
 
#include <gtest/gtest.h>
67
 
#include <google/protobuf/stubs/stl_util-inl.h>
68
 
 
69
 
namespace google {
70
 
namespace protobuf {
71
 
namespace compiler {
72
 
namespace cpp {
73
 
 
74
 
// Can't use an anonymous namespace here due to brokenness of Tru64 compiler.
75
 
namespace cpp_unittest {
76
 
 
77
 
 
78
 
class MockErrorCollector : public MultiFileErrorCollector {
79
 
 public:
80
 
  MockErrorCollector() {}
81
 
  ~MockErrorCollector() {}
82
 
 
83
 
  string text_;
84
 
 
85
 
  // implements ErrorCollector ---------------------------------------
86
 
  void AddError(const string& filename, int line, int column,
87
 
                const string& message) {
88
 
    strings::SubstituteAndAppend(&text_, "$0:$1:$2: $3\n",
89
 
                                 filename, line, column, message);
90
 
  }
91
 
};
92
 
 
93
 
#ifndef PROTOBUF_TEST_NO_DESCRIPTORS
94
 
 
95
 
// Test that generated code has proper descriptors:
96
 
// Parse a descriptor directly (using google::protobuf::compiler::Importer) and
97
 
// compare it to the one that was produced by generated code.
98
 
TEST(GeneratedDescriptorTest, IdenticalDescriptors) {
99
 
  const FileDescriptor* generated_descriptor =
100
 
    unittest::TestAllTypes::descriptor()->file();
101
 
 
102
 
  // Set up the Importer.
103
 
  MockErrorCollector error_collector;
104
 
  DiskSourceTree source_tree;
105
 
  source_tree.MapPath("", TestSourceDir());
106
 
  Importer importer(&source_tree, &error_collector);
107
 
 
108
 
  // Import (parse) unittest.proto.
109
 
  const FileDescriptor* parsed_descriptor =
110
 
    importer.Import("google/protobuf/unittest.proto");
111
 
  EXPECT_EQ("", error_collector.text_);
112
 
  ASSERT_TRUE(parsed_descriptor != NULL);
113
 
 
114
 
  // Test that descriptors are generated correctly by converting them to
115
 
  // FileDescriptorProtos and comparing.
116
 
  FileDescriptorProto generated_decsriptor_proto, parsed_descriptor_proto;
117
 
  generated_descriptor->CopyTo(&generated_decsriptor_proto);
118
 
  parsed_descriptor->CopyTo(&parsed_descriptor_proto);
119
 
 
120
 
  EXPECT_EQ(parsed_descriptor_proto.DebugString(),
121
 
            generated_decsriptor_proto.DebugString());
122
 
}
123
 
 
124
 
#endif  // !PROTOBUF_TEST_NO_DESCRIPTORS
125
 
 
126
 
// ===================================================================
127
 
 
128
 
TEST(GeneratedMessageTest, Defaults) {
129
 
  // Check that all default values are set correctly in the initial message.
130
 
  unittest::TestAllTypes message;
131
 
 
132
 
  TestUtil::ExpectClear(message);
133
 
 
134
 
  // Messages should return pointers to default instances until first use.
135
 
  // (This is not checked by ExpectClear() since it is not actually true after
136
 
  // the fields have been set and then cleared.)
137
 
  EXPECT_EQ(&unittest::TestAllTypes::OptionalGroup::default_instance(),
138
 
            &message.optionalgroup());
139
 
  EXPECT_EQ(&unittest::TestAllTypes::NestedMessage::default_instance(),
140
 
            &message.optional_nested_message());
141
 
  EXPECT_EQ(&unittest::ForeignMessage::default_instance(),
142
 
            &message.optional_foreign_message());
143
 
  EXPECT_EQ(&unittest_import::ImportMessage::default_instance(),
144
 
            &message.optional_import_message());
145
 
}
146
 
 
147
 
TEST(GeneratedMessageTest, FloatingPointDefaults) {
148
 
  const unittest::TestExtremeDefaultValues& extreme_default =
149
 
      unittest::TestExtremeDefaultValues::default_instance();
150
 
 
151
 
  EXPECT_EQ(0.0f, extreme_default.zero_float());
152
 
  EXPECT_EQ(1.0f, extreme_default.one_float());
153
 
  EXPECT_EQ(1.5f, extreme_default.small_float());
154
 
  EXPECT_EQ(-1.0f, extreme_default.negative_one_float());
155
 
  EXPECT_EQ(-1.5f, extreme_default.negative_float());
156
 
  EXPECT_EQ(2.0e8f, extreme_default.large_float());
157
 
  EXPECT_EQ(-8e-28f, extreme_default.small_negative_float());
158
 
  EXPECT_EQ(numeric_limits<double>::infinity(),
159
 
            extreme_default.inf_double());
160
 
  EXPECT_EQ(-numeric_limits<double>::infinity(),
161
 
            extreme_default.neg_inf_double());
162
 
  EXPECT_TRUE(extreme_default.nan_double() != extreme_default.nan_double());
163
 
  EXPECT_EQ(numeric_limits<float>::infinity(),
164
 
            extreme_default.inf_float());
165
 
  EXPECT_EQ(-numeric_limits<float>::infinity(),
166
 
            extreme_default.neg_inf_float());
167
 
  EXPECT_TRUE(extreme_default.nan_float() != extreme_default.nan_float());
168
 
}
169
 
 
170
 
TEST(GeneratedMessageTest, Accessors) {
171
 
  // Set every field to a unique value then go back and check all those
172
 
  // values.
173
 
  unittest::TestAllTypes message;
174
 
 
175
 
  TestUtil::SetAllFields(&message);
176
 
  TestUtil::ExpectAllFieldsSet(message);
177
 
 
178
 
  TestUtil::ModifyRepeatedFields(&message);
179
 
  TestUtil::ExpectRepeatedFieldsModified(message);
180
 
}
181
 
 
182
 
TEST(GeneratedMessageTest, MutableStringDefault) {
183
 
  // mutable_foo() for a string should return a string initialized to its
184
 
  // default value.
185
 
  unittest::TestAllTypes message;
186
 
 
187
 
  EXPECT_EQ("hello", *message.mutable_default_string());
188
 
 
189
 
  // Note that the first time we call mutable_foo(), we get a newly-allocated
190
 
  // string, but if we clear it and call it again, we get the same object again.
191
 
  // We should verify that it has its default value in both cases.
192
 
  message.set_default_string("blah");
193
 
  message.Clear();
194
 
 
195
 
  EXPECT_EQ("hello", *message.mutable_default_string());
196
 
}
197
 
 
198
 
TEST(GeneratedMessageTest, Clear) {
199
 
  // Set every field to a unique value, clear the message, then check that
200
 
  // it is cleared.
201
 
  unittest::TestAllTypes message;
202
 
 
203
 
  TestUtil::SetAllFields(&message);
204
 
  message.Clear();
205
 
  TestUtil::ExpectClear(message);
206
 
 
207
 
  // Unlike with the defaults test, we do NOT expect that requesting embedded
208
 
  // messages will return a pointer to the default instance.  Instead, they
209
 
  // should return the objects that were created when mutable_blah() was
210
 
  // called.
211
 
  EXPECT_NE(&unittest::TestAllTypes::OptionalGroup::default_instance(),
212
 
            &message.optionalgroup());
213
 
  EXPECT_NE(&unittest::TestAllTypes::NestedMessage::default_instance(),
214
 
            &message.optional_nested_message());
215
 
  EXPECT_NE(&unittest::ForeignMessage::default_instance(),
216
 
            &message.optional_foreign_message());
217
 
  EXPECT_NE(&unittest_import::ImportMessage::default_instance(),
218
 
            &message.optional_import_message());
219
 
}
220
 
 
221
 
TEST(GeneratedMessageTest, EmbeddedNullsInBytesCharStar) {
222
 
  unittest::TestAllTypes message;
223
 
 
224
 
  const char* value = "\0lalala\0\0";
225
 
  message.set_optional_bytes(value, 9);
226
 
  ASSERT_EQ(9, message.optional_bytes().size());
227
 
  EXPECT_EQ(0, memcmp(value, message.optional_bytes().data(), 9));
228
 
 
229
 
  message.add_repeated_bytes(value, 9);
230
 
  ASSERT_EQ(9, message.repeated_bytes(0).size());
231
 
  EXPECT_EQ(0, memcmp(value, message.repeated_bytes(0).data(), 9));
232
 
}
233
 
 
234
 
TEST(GeneratedMessageTest, ClearOneField) {
235
 
  // Set every field to a unique value, then clear one value and insure that
236
 
  // only that one value is cleared.
237
 
  unittest::TestAllTypes message;
238
 
 
239
 
  TestUtil::SetAllFields(&message);
240
 
  int64 original_value = message.optional_int64();
241
 
 
242
 
  // Clear the field and make sure it shows up as cleared.
243
 
  message.clear_optional_int64();
244
 
  EXPECT_FALSE(message.has_optional_int64());
245
 
  EXPECT_EQ(0, message.optional_int64());
246
 
 
247
 
  // Other adjacent fields should not be cleared.
248
 
  EXPECT_TRUE(message.has_optional_int32());
249
 
  EXPECT_TRUE(message.has_optional_uint32());
250
 
 
251
 
  // Make sure if we set it again, then all fields are set.
252
 
  message.set_optional_int64(original_value);
253
 
  TestUtil::ExpectAllFieldsSet(message);
254
 
}
255
 
 
256
 
TEST(GeneratedMessageTest, StringCharStarLength) {
257
 
  // Verify that we can use a char*,length to set one of the string fields.
258
 
  unittest::TestAllTypes message;
259
 
  message.set_optional_string("abcdef", 3);
260
 
  EXPECT_EQ("abc", message.optional_string());
261
 
 
262
 
  // Verify that we can use a char*,length to add to a repeated string field.
263
 
  message.add_repeated_string("abcdef", 3);
264
 
  EXPECT_EQ(1, message.repeated_string_size());
265
 
  EXPECT_EQ("abc", message.repeated_string(0));
266
 
 
267
 
  // Verify that we can use a char*,length to set a repeated string field.
268
 
  message.set_repeated_string(0, "wxyz", 2);
269
 
  EXPECT_EQ("wx", message.repeated_string(0));
270
 
}
271
 
 
272
 
 
273
 
TEST(GeneratedMessageTest, CopyFrom) {
274
 
  unittest::TestAllTypes message1, message2;
275
 
 
276
 
  TestUtil::SetAllFields(&message1);
277
 
  message2.CopyFrom(message1);
278
 
  TestUtil::ExpectAllFieldsSet(message2);
279
 
 
280
 
  // Copying from self should be a no-op.
281
 
  message2.CopyFrom(message2);
282
 
  TestUtil::ExpectAllFieldsSet(message2);
283
 
}
284
 
 
285
 
TEST(GeneratedMessageTest, SwapWithEmpty) {
286
 
  unittest::TestAllTypes message1, message2;
287
 
  TestUtil::SetAllFields(&message1);
288
 
 
289
 
  TestUtil::ExpectAllFieldsSet(message1);
290
 
  TestUtil::ExpectClear(message2);
291
 
  message1.Swap(&message2);
292
 
  TestUtil::ExpectAllFieldsSet(message2);
293
 
  TestUtil::ExpectClear(message1);
294
 
}
295
 
 
296
 
TEST(GeneratedMessageTest, SwapWithSelf) {
297
 
  unittest::TestAllTypes message;
298
 
  TestUtil::SetAllFields(&message);
299
 
  TestUtil::ExpectAllFieldsSet(message);
300
 
  message.Swap(&message);
301
 
  TestUtil::ExpectAllFieldsSet(message);
302
 
}
303
 
 
304
 
TEST(GeneratedMessageTest, SwapWithOther) {
305
 
  unittest::TestAllTypes message1, message2;
306
 
 
307
 
  message1.set_optional_int32(123);
308
 
  message1.set_optional_string("abc");
309
 
  message1.mutable_optional_nested_message()->set_bb(1);
310
 
  message1.set_optional_nested_enum(unittest::TestAllTypes::FOO);
311
 
  message1.add_repeated_int32(1);
312
 
  message1.add_repeated_int32(2);
313
 
  message1.add_repeated_string("a");
314
 
  message1.add_repeated_string("b");
315
 
  message1.add_repeated_nested_message()->set_bb(7);
316
 
  message1.add_repeated_nested_message()->set_bb(8);
317
 
  message1.add_repeated_nested_enum(unittest::TestAllTypes::FOO);
318
 
  message1.add_repeated_nested_enum(unittest::TestAllTypes::BAR);
319
 
 
320
 
  message2.set_optional_int32(456);
321
 
  message2.set_optional_string("def");
322
 
  message2.mutable_optional_nested_message()->set_bb(2);
323
 
  message2.set_optional_nested_enum(unittest::TestAllTypes::BAR);
324
 
  message2.add_repeated_int32(3);
325
 
  message2.add_repeated_string("c");
326
 
  message2.add_repeated_nested_message()->set_bb(9);
327
 
  message2.add_repeated_nested_enum(unittest::TestAllTypes::BAZ);
328
 
 
329
 
  message1.Swap(&message2);
330
 
 
331
 
  EXPECT_EQ(456, message1.optional_int32());
332
 
  EXPECT_EQ("def", message1.optional_string());
333
 
  EXPECT_EQ(2, message1.optional_nested_message().bb());
334
 
  EXPECT_EQ(unittest::TestAllTypes::BAR, message1.optional_nested_enum());
335
 
  ASSERT_EQ(1, message1.repeated_int32_size());
336
 
  EXPECT_EQ(3, message1.repeated_int32(0));
337
 
  ASSERT_EQ(1, message1.repeated_string_size());
338
 
  EXPECT_EQ("c", message1.repeated_string(0));
339
 
  ASSERT_EQ(1, message1.repeated_nested_message_size());
340
 
  EXPECT_EQ(9, message1.repeated_nested_message(0).bb());
341
 
  ASSERT_EQ(1, message1.repeated_nested_enum_size());
342
 
  EXPECT_EQ(unittest::TestAllTypes::BAZ, message1.repeated_nested_enum(0));
343
 
 
344
 
  EXPECT_EQ(123, message2.optional_int32());
345
 
  EXPECT_EQ("abc", message2.optional_string());
346
 
  EXPECT_EQ(1, message2.optional_nested_message().bb());
347
 
  EXPECT_EQ(unittest::TestAllTypes::FOO, message2.optional_nested_enum());
348
 
  ASSERT_EQ(2, message2.repeated_int32_size());
349
 
  EXPECT_EQ(1, message2.repeated_int32(0));
350
 
  EXPECT_EQ(2, message2.repeated_int32(1));
351
 
  ASSERT_EQ(2, message2.repeated_string_size());
352
 
  EXPECT_EQ("a", message2.repeated_string(0));
353
 
  EXPECT_EQ("b", message2.repeated_string(1));
354
 
  ASSERT_EQ(2, message2.repeated_nested_message_size());
355
 
  EXPECT_EQ(7, message2.repeated_nested_message(0).bb());
356
 
  EXPECT_EQ(8, message2.repeated_nested_message(1).bb());
357
 
  ASSERT_EQ(2, message2.repeated_nested_enum_size());
358
 
  EXPECT_EQ(unittest::TestAllTypes::FOO, message2.repeated_nested_enum(0));
359
 
  EXPECT_EQ(unittest::TestAllTypes::BAR, message2.repeated_nested_enum(1));
360
 
}
361
 
 
362
 
TEST(GeneratedMessageTest, CopyConstructor) {
363
 
  unittest::TestAllTypes message1;
364
 
  TestUtil::SetAllFields(&message1);
365
 
 
366
 
  unittest::TestAllTypes message2(message1);
367
 
  TestUtil::ExpectAllFieldsSet(message2);
368
 
}
369
 
 
370
 
TEST(GeneratedMessageTest, CopyAssignmentOperator) {
371
 
  unittest::TestAllTypes message1;
372
 
  TestUtil::SetAllFields(&message1);
373
 
 
374
 
  unittest::TestAllTypes message2;
375
 
  message2 = message1;
376
 
  TestUtil::ExpectAllFieldsSet(message2);
377
 
 
378
 
  // Make sure that self-assignment does something sane.
379
 
  message2 = message2;
380
 
  TestUtil::ExpectAllFieldsSet(message2);
381
 
}
382
 
 
383
 
TEST(GeneratedMessageTest, UpcastCopyFrom) {
384
 
  // Test the CopyFrom method that takes in the generic const Message&
385
 
  // parameter.
386
 
  unittest::TestAllTypes message1, message2;
387
 
 
388
 
  TestUtil::SetAllFields(&message1);
389
 
 
390
 
  const Message* source = implicit_cast<const Message*>(&message1);
391
 
  message2.CopyFrom(*source);
392
 
 
393
 
  TestUtil::ExpectAllFieldsSet(message2);
394
 
}
395
 
 
396
 
#ifndef PROTOBUF_TEST_NO_DESCRIPTORS
397
 
 
398
 
TEST(GeneratedMessageTest, DynamicMessageCopyFrom) {
399
 
  // Test copying from a DynamicMessage, which must fall back to using
400
 
  // reflection.
401
 
  unittest::TestAllTypes message2;
402
 
 
403
 
  // Construct a new version of the dynamic message via the factory.
404
 
  DynamicMessageFactory factory;
405
 
  scoped_ptr<Message> message1;
406
 
  message1.reset(factory.GetPrototype(
407
 
                     unittest::TestAllTypes::descriptor())->New());
408
 
 
409
 
  TestUtil::ReflectionTester reflection_tester(
410
 
    unittest::TestAllTypes::descriptor());
411
 
  reflection_tester.SetAllFieldsViaReflection(message1.get());
412
 
 
413
 
  message2.CopyFrom(*message1);
414
 
 
415
 
  TestUtil::ExpectAllFieldsSet(message2);
416
 
}
417
 
 
418
 
#endif  // !PROTOBUF_TEST_NO_DESCRIPTORS
419
 
 
420
 
TEST(GeneratedMessageTest, NonEmptyMergeFrom) {
421
 
  // Test merging with a non-empty message. Code is a modified form
422
 
  // of that found in google/protobuf/reflection_ops_unittest.cc.
423
 
  unittest::TestAllTypes message1, message2;
424
 
 
425
 
  TestUtil::SetAllFields(&message1);
426
 
 
427
 
  // This field will test merging into an empty spot.
428
 
  message2.set_optional_int32(message1.optional_int32());
429
 
  message1.clear_optional_int32();
430
 
 
431
 
  // This tests overwriting.
432
 
  message2.set_optional_string(message1.optional_string());
433
 
  message1.set_optional_string("something else");
434
 
 
435
 
  // This tests concatenating.
436
 
  message2.add_repeated_int32(message1.repeated_int32(1));
437
 
  int32 i = message1.repeated_int32(0);
438
 
  message1.clear_repeated_int32();
439
 
  message1.add_repeated_int32(i);
440
 
 
441
 
  message1.MergeFrom(message2);
442
 
 
443
 
  TestUtil::ExpectAllFieldsSet(message1);
444
 
}
445
 
 
446
 
#ifdef GTEST_HAS_DEATH_TEST
447
 
 
448
 
TEST(GeneratedMessageTest, MergeFromSelf) {
449
 
  unittest::TestAllTypes message;
450
 
  EXPECT_DEATH(message.MergeFrom(message), "&from");
451
 
  EXPECT_DEATH(message.MergeFrom(implicit_cast<const Message&>(message)),
452
 
               "&from");
453
 
}
454
 
 
455
 
#endif  // GTEST_HAS_DEATH_TEST
456
 
 
457
 
// Test the generated SerializeWithCachedSizesToArray(),
458
 
TEST(GeneratedMessageTest, SerializationToArray) {
459
 
  unittest::TestAllTypes message1, message2;
460
 
  string data;
461
 
  TestUtil::SetAllFields(&message1);
462
 
  int size = message1.ByteSize();
463
 
  data.resize(size);
464
 
  uint8* start = reinterpret_cast<uint8*>(string_as_array(&data));
465
 
  uint8* end = message1.SerializeWithCachedSizesToArray(start);
466
 
  EXPECT_EQ(size, end - start);
467
 
  EXPECT_TRUE(message2.ParseFromString(data));
468
 
  TestUtil::ExpectAllFieldsSet(message2);
469
 
 
470
 
}
471
 
 
472
 
TEST(GeneratedMessageTest, PackedFieldsSerializationToArray) {
473
 
  unittest::TestPackedTypes packed_message1, packed_message2;
474
 
  string packed_data;
475
 
  TestUtil::SetPackedFields(&packed_message1);
476
 
  int packed_size = packed_message1.ByteSize();
477
 
  packed_data.resize(packed_size);
478
 
  uint8* start = reinterpret_cast<uint8*>(string_as_array(&packed_data));
479
 
  uint8* end = packed_message1.SerializeWithCachedSizesToArray(start);
480
 
  EXPECT_EQ(packed_size, end - start);
481
 
  EXPECT_TRUE(packed_message2.ParseFromString(packed_data));
482
 
  TestUtil::ExpectPackedFieldsSet(packed_message2);
483
 
}
484
 
 
485
 
// Test the generated SerializeWithCachedSizes() by forcing the buffer to write
486
 
// one byte at a time.
487
 
TEST(GeneratedMessageTest, SerializationToStream) {
488
 
  unittest::TestAllTypes message1, message2;
489
 
  TestUtil::SetAllFields(&message1);
490
 
  int size = message1.ByteSize();
491
 
  string data;
492
 
  data.resize(size);
493
 
  {
494
 
    // Allow the output stream to buffer only one byte at a time.
495
 
    io::ArrayOutputStream array_stream(string_as_array(&data), size, 1);
496
 
    io::CodedOutputStream output_stream(&array_stream);
497
 
    message1.SerializeWithCachedSizes(&output_stream);
498
 
    EXPECT_FALSE(output_stream.HadError());
499
 
    EXPECT_EQ(size, output_stream.ByteCount());
500
 
  }
501
 
  EXPECT_TRUE(message2.ParseFromString(data));
502
 
  TestUtil::ExpectAllFieldsSet(message2);
503
 
 
504
 
}
505
 
 
506
 
TEST(GeneratedMessageTest, PackedFieldsSerializationToStream) {
507
 
  unittest::TestPackedTypes message1, message2;
508
 
  TestUtil::SetPackedFields(&message1);
509
 
  int size = message1.ByteSize();
510
 
  string data;
511
 
  data.resize(size);
512
 
  {
513
 
    // Allow the output stream to buffer only one byte at a time.
514
 
    io::ArrayOutputStream array_stream(string_as_array(&data), size, 1);
515
 
    io::CodedOutputStream output_stream(&array_stream);
516
 
    message1.SerializeWithCachedSizes(&output_stream);
517
 
    EXPECT_FALSE(output_stream.HadError());
518
 
    EXPECT_EQ(size, output_stream.ByteCount());
519
 
  }
520
 
  EXPECT_TRUE(message2.ParseFromString(data));
521
 
  TestUtil::ExpectPackedFieldsSet(message2);
522
 
}
523
 
 
524
 
 
525
 
TEST(GeneratedMessageTest, Required) {
526
 
  // Test that IsInitialized() returns false if required fields are missing.
527
 
  unittest::TestRequired message;
528
 
 
529
 
  EXPECT_FALSE(message.IsInitialized());
530
 
  message.set_a(1);
531
 
  EXPECT_FALSE(message.IsInitialized());
532
 
  message.set_b(2);
533
 
  EXPECT_FALSE(message.IsInitialized());
534
 
  message.set_c(3);
535
 
  EXPECT_TRUE(message.IsInitialized());
536
 
}
537
 
 
538
 
TEST(GeneratedMessageTest, RequiredForeign) {
539
 
  // Test that IsInitialized() returns false if required fields in nested
540
 
  // messages are missing.
541
 
  unittest::TestRequiredForeign message;
542
 
 
543
 
  EXPECT_TRUE(message.IsInitialized());
544
 
 
545
 
  message.mutable_optional_message();
546
 
  EXPECT_FALSE(message.IsInitialized());
547
 
 
548
 
  message.mutable_optional_message()->set_a(1);
549
 
  message.mutable_optional_message()->set_b(2);
550
 
  message.mutable_optional_message()->set_c(3);
551
 
  EXPECT_TRUE(message.IsInitialized());
552
 
 
553
 
  message.add_repeated_message();
554
 
  EXPECT_FALSE(message.IsInitialized());
555
 
 
556
 
  message.mutable_repeated_message(0)->set_a(1);
557
 
  message.mutable_repeated_message(0)->set_b(2);
558
 
  message.mutable_repeated_message(0)->set_c(3);
559
 
  EXPECT_TRUE(message.IsInitialized());
560
 
}
561
 
 
562
 
TEST(GeneratedMessageTest, ForeignNested) {
563
 
  // Test that TestAllTypes::NestedMessage can be embedded directly into
564
 
  // another message.
565
 
  unittest::TestForeignNested message;
566
 
 
567
 
  // If this compiles and runs without crashing, it must work.  We have
568
 
  // nothing more to test.
569
 
  unittest::TestAllTypes::NestedMessage* nested =
570
 
    message.mutable_foreign_nested();
571
 
  nested->set_bb(1);
572
 
}
573
 
 
574
 
TEST(GeneratedMessageTest, ReallyLargeTagNumber) {
575
 
  // Test that really large tag numbers don't break anything.
576
 
  unittest::TestReallyLargeTagNumber message1, message2;
577
 
  string data;
578
 
 
579
 
  // For the most part, if this compiles and runs then we're probably good.
580
 
  // (The most likely cause for failure would be if something were attempting
581
 
  // to allocate a lookup table of some sort using tag numbers as the index.)
582
 
  // We'll try serializing just for fun.
583
 
  message1.set_a(1234);
584
 
  message1.set_bb(5678);
585
 
  message1.SerializeToString(&data);
586
 
  EXPECT_TRUE(message2.ParseFromString(data));
587
 
  EXPECT_EQ(1234, message2.a());
588
 
  EXPECT_EQ(5678, message2.bb());
589
 
}
590
 
 
591
 
TEST(GeneratedMessageTest, MutualRecursion) {
592
 
  // Test that mutually-recursive message types work.
593
 
  unittest::TestMutualRecursionA message;
594
 
  unittest::TestMutualRecursionA* nested = message.mutable_bb()->mutable_a();
595
 
  unittest::TestMutualRecursionA* nested2 = nested->mutable_bb()->mutable_a();
596
 
 
597
 
  // Again, if the above compiles and runs, that's all we really have to
598
 
  // test, but just for run we'll check that the system didn't somehow come
599
 
  // up with a pointer loop...
600
 
  EXPECT_NE(&message, nested);
601
 
  EXPECT_NE(&message, nested2);
602
 
  EXPECT_NE(nested, nested2);
603
 
}
604
 
 
605
 
TEST(GeneratedMessageTest, CamelCaseFieldNames) {
606
 
  // This test is mainly checking that the following compiles, which verifies
607
 
  // that the field names were coerced to lower-case.
608
 
  //
609
 
  // Protocol buffers standard style is to use lowercase-with-underscores for
610
 
  // field names.  Some old proto1 .protos unfortunately used camel-case field
611
 
  // names.  In proto1, these names were forced to lower-case.  So, we do the
612
 
  // same thing in proto2.
613
 
 
614
 
  unittest::TestCamelCaseFieldNames message;
615
 
 
616
 
  message.set_primitivefield(2);
617
 
  message.set_stringfield("foo");
618
 
  message.set_enumfield(unittest::FOREIGN_FOO);
619
 
  message.mutable_messagefield()->set_c(6);
620
 
 
621
 
  message.add_repeatedprimitivefield(8);
622
 
  message.add_repeatedstringfield("qux");
623
 
  message.add_repeatedenumfield(unittest::FOREIGN_BAR);
624
 
  message.add_repeatedmessagefield()->set_c(15);
625
 
 
626
 
  EXPECT_EQ(2, message.primitivefield());
627
 
  EXPECT_EQ("foo", message.stringfield());
628
 
  EXPECT_EQ(unittest::FOREIGN_FOO, message.enumfield());
629
 
  EXPECT_EQ(6, message.messagefield().c());
630
 
 
631
 
  EXPECT_EQ(8, message.repeatedprimitivefield(0));
632
 
  EXPECT_EQ("qux", message.repeatedstringfield(0));
633
 
  EXPECT_EQ(unittest::FOREIGN_BAR, message.repeatedenumfield(0));
634
 
  EXPECT_EQ(15, message.repeatedmessagefield(0).c());
635
 
}
636
 
 
637
 
TEST(GeneratedMessageTest, TestConflictingSymbolNames) {
638
 
  // test_bad_identifiers.proto successfully compiled, then it works.  The
639
 
  // following is just a token usage to insure that the code is, in fact,
640
 
  // being compiled and linked.
641
 
 
642
 
  protobuf_unittest::TestConflictingSymbolNames message;
643
 
  message.set_uint32(1);
644
 
  EXPECT_EQ(3, message.ByteSize());
645
 
 
646
 
  message.set_friend_(5);
647
 
  EXPECT_EQ(5, message.friend_());
648
 
}
649
 
 
650
 
#ifndef PROTOBUF_TEST_NO_DESCRIPTORS
651
 
 
652
 
TEST(GeneratedMessageTest, TestOptimizedForSize) {
653
 
  // We rely on the tests in reflection_ops_unittest and wire_format_unittest
654
 
  // to really test that reflection-based methods work.  Here we are mostly
655
 
  // just making sure that TestOptimizedForSize actually builds and seems to
656
 
  // function.
657
 
 
658
 
  protobuf_unittest::TestOptimizedForSize message, message2;
659
 
  message.set_i(1);
660
 
  message.mutable_msg()->set_c(2);
661
 
  message2.CopyFrom(message);
662
 
  EXPECT_EQ(1, message2.i());
663
 
  EXPECT_EQ(2, message2.msg().c());
664
 
}
665
 
 
666
 
TEST(GeneratedMessageTest, TestEmbedOptimizedForSize) {
667
 
  // Verifies that something optimized for speed can contain something optimized
668
 
  // for size.
669
 
 
670
 
  protobuf_unittest::TestEmbedOptimizedForSize message, message2;
671
 
  message.mutable_optional_message()->set_i(1);
672
 
  message.add_repeated_message()->mutable_msg()->set_c(2);
673
 
  string data;
674
 
  message.SerializeToString(&data);
675
 
  ASSERT_TRUE(message2.ParseFromString(data));
676
 
  EXPECT_EQ(1, message2.optional_message().i());
677
 
  EXPECT_EQ(2, message2.repeated_message(0).msg().c());
678
 
}
679
 
 
680
 
TEST(GeneratedMessageTest, TestSpaceUsed) {
681
 
  unittest::TestAllTypes message1;
682
 
  // sizeof provides a lower bound on SpaceUsed().
683
 
  EXPECT_LE(sizeof(unittest::TestAllTypes), message1.SpaceUsed());
684
 
  const int empty_message_size = message1.SpaceUsed();
685
 
 
686
 
  // Setting primitive types shouldn't affect the space used.
687
 
  message1.set_optional_int32(123);
688
 
  message1.set_optional_int64(12345);
689
 
  message1.set_optional_uint32(123);
690
 
  message1.set_optional_uint64(12345);
691
 
  EXPECT_EQ(empty_message_size, message1.SpaceUsed());
692
 
 
693
 
  // On some STL implementations, setting the string to a small value should
694
 
  // only increase SpaceUsed() by the size of a string object, though this is
695
 
  // not true everywhere.
696
 
  message1.set_optional_string("abc");
697
 
  EXPECT_LE(empty_message_size + sizeof(string), message1.SpaceUsed());
698
 
 
699
 
  // Setting a string to a value larger than the string object itself should
700
 
  // increase SpaceUsed(), because it cannot store the value internally.
701
 
  message1.set_optional_string(string(sizeof(string) + 1, 'x'));
702
 
  int min_expected_increase = message1.optional_string().capacity() +
703
 
      sizeof(string);
704
 
  EXPECT_LE(empty_message_size + min_expected_increase,
705
 
            message1.SpaceUsed());
706
 
 
707
 
  int previous_size = message1.SpaceUsed();
708
 
  // Adding an optional message should increase the size by the size of the
709
 
  // nested message type. NestedMessage is simple enough (1 int field) that it
710
 
  // is equal to sizeof(NestedMessage)
711
 
  message1.mutable_optional_nested_message();
712
 
  ASSERT_EQ(sizeof(unittest::TestAllTypes::NestedMessage),
713
 
            message1.optional_nested_message().SpaceUsed());
714
 
  EXPECT_EQ(previous_size +
715
 
            sizeof(unittest::TestAllTypes::NestedMessage),
716
 
            message1.SpaceUsed());
717
 
}
718
 
 
719
 
#endif  // !PROTOBUF_TEST_NO_DESCRIPTORS
720
 
 
721
 
TEST(GeneratedMessageTest, FieldConstantValues) {
722
 
  unittest::TestRequired message;
723
 
  EXPECT_EQ(unittest::TestAllTypes_NestedMessage::kBbFieldNumber, 1);
724
 
  EXPECT_EQ(unittest::TestAllTypes::kOptionalInt32FieldNumber, 1);
725
 
  EXPECT_EQ(unittest::TestAllTypes::kOptionalgroupFieldNumber, 16);
726
 
  EXPECT_EQ(unittest::TestAllTypes::kOptionalNestedMessageFieldNumber, 18);
727
 
  EXPECT_EQ(unittest::TestAllTypes::kOptionalNestedEnumFieldNumber, 21);
728
 
  EXPECT_EQ(unittest::TestAllTypes::kRepeatedInt32FieldNumber, 31);
729
 
  EXPECT_EQ(unittest::TestAllTypes::kRepeatedgroupFieldNumber, 46);
730
 
  EXPECT_EQ(unittest::TestAllTypes::kRepeatedNestedMessageFieldNumber, 48);
731
 
  EXPECT_EQ(unittest::TestAllTypes::kRepeatedNestedEnumFieldNumber, 51);
732
 
}
733
 
 
734
 
TEST(GeneratedMessageTest, ExtensionConstantValues) {
735
 
  EXPECT_EQ(unittest::TestRequired::kSingleFieldNumber, 1000);
736
 
  EXPECT_EQ(unittest::TestRequired::kMultiFieldNumber, 1001);
737
 
  EXPECT_EQ(unittest::kOptionalInt32ExtensionFieldNumber, 1);
738
 
  EXPECT_EQ(unittest::kOptionalgroupExtensionFieldNumber, 16);
739
 
  EXPECT_EQ(unittest::kOptionalNestedMessageExtensionFieldNumber, 18);
740
 
  EXPECT_EQ(unittest::kOptionalNestedEnumExtensionFieldNumber, 21);
741
 
  EXPECT_EQ(unittest::kRepeatedInt32ExtensionFieldNumber, 31);
742
 
  EXPECT_EQ(unittest::kRepeatedgroupExtensionFieldNumber, 46);
743
 
  EXPECT_EQ(unittest::kRepeatedNestedMessageExtensionFieldNumber, 48);
744
 
  EXPECT_EQ(unittest::kRepeatedNestedEnumExtensionFieldNumber, 51);
745
 
}
746
 
 
747
 
// ===================================================================
748
 
 
749
 
TEST(GeneratedEnumTest, EnumValuesAsSwitchCases) {
750
 
  // Test that our nested enum values can be used as switch cases.  This test
751
 
  // doesn't actually do anything, the proof that it works is that it
752
 
  // compiles.
753
 
  int i =0;
754
 
  unittest::TestAllTypes::NestedEnum a = unittest::TestAllTypes::BAR;
755
 
  switch (a) {
756
 
    case unittest::TestAllTypes::FOO:
757
 
      i = 1;
758
 
      break;
759
 
    case unittest::TestAllTypes::BAR:
760
 
      i = 2;
761
 
      break;
762
 
    case unittest::TestAllTypes::BAZ:
763
 
      i = 3;
764
 
      break;
765
 
    // no default case:  We want to make sure the compiler recognizes that
766
 
    //   all cases are covered.  (GCC warns if you do not cover all cases of
767
 
    //   an enum in a switch.)
768
 
  }
769
 
 
770
 
  // Token check just for fun.
771
 
  EXPECT_EQ(2, i);
772
 
}
773
 
 
774
 
TEST(GeneratedEnumTest, IsValidValue) {
775
 
  // Test enum IsValidValue.
776
 
  EXPECT_TRUE(unittest::TestAllTypes::NestedEnum_IsValid(1));
777
 
  EXPECT_TRUE(unittest::TestAllTypes::NestedEnum_IsValid(2));
778
 
  EXPECT_TRUE(unittest::TestAllTypes::NestedEnum_IsValid(3));
779
 
 
780
 
  EXPECT_FALSE(unittest::TestAllTypes::NestedEnum_IsValid(0));
781
 
  EXPECT_FALSE(unittest::TestAllTypes::NestedEnum_IsValid(4));
782
 
 
783
 
  // Make sure it also works when there are dups.
784
 
  EXPECT_TRUE(unittest::TestEnumWithDupValue_IsValid(1));
785
 
  EXPECT_TRUE(unittest::TestEnumWithDupValue_IsValid(2));
786
 
  EXPECT_TRUE(unittest::TestEnumWithDupValue_IsValid(3));
787
 
 
788
 
  EXPECT_FALSE(unittest::TestEnumWithDupValue_IsValid(0));
789
 
  EXPECT_FALSE(unittest::TestEnumWithDupValue_IsValid(4));
790
 
}
791
 
 
792
 
TEST(GeneratedEnumTest, MinAndMax) {
793
 
  EXPECT_EQ(unittest::TestAllTypes::FOO,
794
 
            unittest::TestAllTypes::NestedEnum_MIN);
795
 
  EXPECT_EQ(unittest::TestAllTypes::BAZ,
796
 
            unittest::TestAllTypes::NestedEnum_MAX);
797
 
  EXPECT_EQ(4, unittest::TestAllTypes::NestedEnum_ARRAYSIZE);
798
 
 
799
 
  EXPECT_EQ(unittest::FOREIGN_FOO, unittest::ForeignEnum_MIN);
800
 
  EXPECT_EQ(unittest::FOREIGN_BAZ, unittest::ForeignEnum_MAX);
801
 
  EXPECT_EQ(7, unittest::ForeignEnum_ARRAYSIZE);
802
 
 
803
 
  EXPECT_EQ(1, unittest::TestEnumWithDupValue_MIN);
804
 
  EXPECT_EQ(3, unittest::TestEnumWithDupValue_MAX);
805
 
  EXPECT_EQ(4, unittest::TestEnumWithDupValue_ARRAYSIZE);
806
 
 
807
 
  EXPECT_EQ(unittest::SPARSE_E, unittest::TestSparseEnum_MIN);
808
 
  EXPECT_EQ(unittest::SPARSE_C, unittest::TestSparseEnum_MAX);
809
 
  EXPECT_EQ(12589235, unittest::TestSparseEnum_ARRAYSIZE);
810
 
 
811
 
  // Make sure we can take the address of _MIN, _MAX and _ARRAYSIZE.
812
 
  void* nullptr = 0;  // NULL may be integer-type, not pointer-type.
813
 
  EXPECT_NE(nullptr, &unittest::TestAllTypes::NestedEnum_MIN);
814
 
  EXPECT_NE(nullptr, &unittest::TestAllTypes::NestedEnum_MAX);
815
 
  EXPECT_NE(nullptr, &unittest::TestAllTypes::NestedEnum_ARRAYSIZE);
816
 
 
817
 
  EXPECT_NE(nullptr, &unittest::ForeignEnum_MIN);
818
 
  EXPECT_NE(nullptr, &unittest::ForeignEnum_MAX);
819
 
  EXPECT_NE(nullptr, &unittest::ForeignEnum_ARRAYSIZE);
820
 
 
821
 
  // Make sure we can use _MIN, _MAX and _ARRAYSIZE as switch cases.
822
 
  switch (unittest::SPARSE_A) {
823
 
    case unittest::TestSparseEnum_MIN:
824
 
    case unittest::TestSparseEnum_MAX:
825
 
    case unittest::TestSparseEnum_ARRAYSIZE:
826
 
      break;
827
 
    default:
828
 
      break;
829
 
  }
830
 
}
831
 
 
832
 
#ifndef PROTOBUF_TEST_NO_DESCRIPTORS
833
 
 
834
 
TEST(GeneratedEnumTest, Name) {
835
 
  // "Names" in the presence of dup values are a bit arbitrary.
836
 
  EXPECT_EQ("FOO1", unittest::TestEnumWithDupValue_Name(unittest::FOO1));
837
 
  EXPECT_EQ("FOO1", unittest::TestEnumWithDupValue_Name(unittest::FOO2));
838
 
 
839
 
  EXPECT_EQ("SPARSE_A", unittest::TestSparseEnum_Name(unittest::SPARSE_A));
840
 
  EXPECT_EQ("SPARSE_B", unittest::TestSparseEnum_Name(unittest::SPARSE_B));
841
 
  EXPECT_EQ("SPARSE_C", unittest::TestSparseEnum_Name(unittest::SPARSE_C));
842
 
  EXPECT_EQ("SPARSE_D", unittest::TestSparseEnum_Name(unittest::SPARSE_D));
843
 
  EXPECT_EQ("SPARSE_E", unittest::TestSparseEnum_Name(unittest::SPARSE_E));
844
 
  EXPECT_EQ("SPARSE_F", unittest::TestSparseEnum_Name(unittest::SPARSE_F));
845
 
  EXPECT_EQ("SPARSE_G", unittest::TestSparseEnum_Name(unittest::SPARSE_G));
846
 
}
847
 
 
848
 
TEST(GeneratedEnumTest, Parse) {
849
 
  unittest::TestEnumWithDupValue dup_value = unittest::FOO1;
850
 
  EXPECT_TRUE(unittest::TestEnumWithDupValue_Parse("FOO1", &dup_value));
851
 
  EXPECT_EQ(unittest::FOO1, dup_value);
852
 
  EXPECT_TRUE(unittest::TestEnumWithDupValue_Parse("FOO2", &dup_value));
853
 
  EXPECT_EQ(unittest::FOO2, dup_value);
854
 
  EXPECT_FALSE(unittest::TestEnumWithDupValue_Parse("FOO", &dup_value));
855
 
}
856
 
 
857
 
TEST(GeneratedEnumTest, GetEnumDescriptor) {
858
 
  EXPECT_EQ(unittest::TestAllTypes::NestedEnum_descriptor(),
859
 
            GetEnumDescriptor<unittest::TestAllTypes::NestedEnum>());
860
 
  EXPECT_EQ(unittest::ForeignEnum_descriptor(),
861
 
            GetEnumDescriptor<unittest::ForeignEnum>());
862
 
  EXPECT_EQ(unittest::TestEnumWithDupValue_descriptor(),
863
 
            GetEnumDescriptor<unittest::TestEnumWithDupValue>());
864
 
  EXPECT_EQ(unittest::TestSparseEnum_descriptor(),
865
 
            GetEnumDescriptor<unittest::TestSparseEnum>());
866
 
}
867
 
 
868
 
#endif  // PROTOBUF_TEST_NO_DESCRIPTORS
869
 
 
870
 
// ===================================================================
871
 
 
872
 
#ifndef PROTOBUF_TEST_NO_DESCRIPTORS
873
 
 
874
 
// Support code for testing services.
875
 
class GeneratedServiceTest : public testing::Test {
876
 
 protected:
877
 
  class MockTestService : public unittest::TestService {
878
 
   public:
879
 
    MockTestService()
880
 
      : called_(false),
881
 
        method_(""),
882
 
        controller_(NULL),
883
 
        request_(NULL),
884
 
        response_(NULL),
885
 
        done_(NULL) {}
886
 
 
887
 
    ~MockTestService() {}
888
 
 
889
 
    void Reset() { called_ = false; }
890
 
 
891
 
    // implements TestService ----------------------------------------
892
 
 
893
 
    void Foo(RpcController* controller,
894
 
             const unittest::FooRequest* request,
895
 
             unittest::FooResponse* response,
896
 
             Closure* done) {
897
 
      ASSERT_FALSE(called_);
898
 
      called_ = true;
899
 
      method_ = "Foo";
900
 
      controller_ = controller;
901
 
      request_ = request;
902
 
      response_ = response;
903
 
      done_ = done;
904
 
    }
905
 
 
906
 
    void Bar(RpcController* controller,
907
 
             const unittest::BarRequest* request,
908
 
             unittest::BarResponse* response,
909
 
             Closure* done) {
910
 
      ASSERT_FALSE(called_);
911
 
      called_ = true;
912
 
      method_ = "Bar";
913
 
      controller_ = controller;
914
 
      request_ = request;
915
 
      response_ = response;
916
 
      done_ = done;
917
 
    }
918
 
 
919
 
    // ---------------------------------------------------------------
920
 
 
921
 
    bool called_;
922
 
    string method_;
923
 
    RpcController* controller_;
924
 
    const Message* request_;
925
 
    Message* response_;
926
 
    Closure* done_;
927
 
  };
928
 
 
929
 
  class MockRpcChannel : public RpcChannel {
930
 
   public:
931
 
    MockRpcChannel()
932
 
      : called_(false),
933
 
        method_(NULL),
934
 
        controller_(NULL),
935
 
        request_(NULL),
936
 
        response_(NULL),
937
 
        done_(NULL),
938
 
        destroyed_(NULL) {}
939
 
 
940
 
    ~MockRpcChannel() {
941
 
      if (destroyed_ != NULL) *destroyed_ = true;
942
 
    }
943
 
 
944
 
    void Reset() { called_ = false; }
945
 
 
946
 
    // implements TestService ----------------------------------------
947
 
 
948
 
    void CallMethod(const MethodDescriptor* method,
949
 
                    RpcController* controller,
950
 
                    const Message* request,
951
 
                    Message* response,
952
 
                    Closure* done) {
953
 
      ASSERT_FALSE(called_);
954
 
      called_ = true;
955
 
      method_ = method;
956
 
      controller_ = controller;
957
 
      request_ = request;
958
 
      response_ = response;
959
 
      done_ = done;
960
 
    }
961
 
 
962
 
    // ---------------------------------------------------------------
963
 
 
964
 
    bool called_;
965
 
    const MethodDescriptor* method_;
966
 
    RpcController* controller_;
967
 
    const Message* request_;
968
 
    Message* response_;
969
 
    Closure* done_;
970
 
    bool* destroyed_;
971
 
  };
972
 
 
973
 
  class MockController : public RpcController {
974
 
   public:
975
 
    void Reset() {
976
 
      ADD_FAILURE() << "Reset() not expected during this test.";
977
 
    }
978
 
    bool Failed() const {
979
 
      ADD_FAILURE() << "Failed() not expected during this test.";
980
 
      return false;
981
 
    }
982
 
    string ErrorText() const {
983
 
      ADD_FAILURE() << "ErrorText() not expected during this test.";
984
 
      return "";
985
 
    }
986
 
    void StartCancel() {
987
 
      ADD_FAILURE() << "StartCancel() not expected during this test.";
988
 
    }
989
 
    void SetFailed(const string& reason) {
990
 
      ADD_FAILURE() << "SetFailed() not expected during this test.";
991
 
    }
992
 
    bool IsCanceled() const {
993
 
      ADD_FAILURE() << "IsCanceled() not expected during this test.";
994
 
      return false;
995
 
    }
996
 
    void NotifyOnCancel(Closure* callback) {
997
 
      ADD_FAILURE() << "NotifyOnCancel() not expected during this test.";
998
 
    }
999
 
  };
1000
 
 
1001
 
  GeneratedServiceTest()
1002
 
    : descriptor_(unittest::TestService::descriptor()),
1003
 
      foo_(descriptor_->FindMethodByName("Foo")),
1004
 
      bar_(descriptor_->FindMethodByName("Bar")),
1005
 
      stub_(&mock_channel_),
1006
 
      done_(NewPermanentCallback(&DoNothing)) {}
1007
 
 
1008
 
  virtual void SetUp() {
1009
 
    ASSERT_TRUE(foo_ != NULL);
1010
 
    ASSERT_TRUE(bar_ != NULL);
1011
 
  }
1012
 
 
1013
 
  const ServiceDescriptor* descriptor_;
1014
 
  const MethodDescriptor* foo_;
1015
 
  const MethodDescriptor* bar_;
1016
 
 
1017
 
  MockTestService mock_service_;
1018
 
  MockController mock_controller_;
1019
 
 
1020
 
  MockRpcChannel mock_channel_;
1021
 
  unittest::TestService::Stub stub_;
1022
 
 
1023
 
  // Just so we don't have to re-define these with every test.
1024
 
  unittest::FooRequest foo_request_;
1025
 
  unittest::FooResponse foo_response_;
1026
 
  unittest::BarRequest bar_request_;
1027
 
  unittest::BarResponse bar_response_;
1028
 
  scoped_ptr<Closure> done_;
1029
 
};
1030
 
 
1031
 
TEST_F(GeneratedServiceTest, GetDescriptor) {
1032
 
  // Test that GetDescriptor() works.
1033
 
 
1034
 
  EXPECT_EQ(descriptor_, mock_service_.GetDescriptor());
1035
 
}
1036
 
 
1037
 
TEST_F(GeneratedServiceTest, GetChannel) {
1038
 
  EXPECT_EQ(&mock_channel_, stub_.channel());
1039
 
}
1040
 
 
1041
 
TEST_F(GeneratedServiceTest, OwnsChannel) {
1042
 
  MockRpcChannel* channel = new MockRpcChannel;
1043
 
  bool destroyed = false;
1044
 
  channel->destroyed_ = &destroyed;
1045
 
 
1046
 
  {
1047
 
    unittest::TestService::Stub owning_stub(channel,
1048
 
                                            Service::STUB_OWNS_CHANNEL);
1049
 
    EXPECT_FALSE(destroyed);
1050
 
  }
1051
 
 
1052
 
  EXPECT_TRUE(destroyed);
1053
 
}
1054
 
 
1055
 
TEST_F(GeneratedServiceTest, CallMethod) {
1056
 
  // Test that CallMethod() works.
1057
 
 
1058
 
  // Call Foo() via CallMethod().
1059
 
  mock_service_.CallMethod(foo_, &mock_controller_,
1060
 
                           &foo_request_, &foo_response_, done_.get());
1061
 
 
1062
 
  ASSERT_TRUE(mock_service_.called_);
1063
 
 
1064
 
  EXPECT_EQ("Foo"            , mock_service_.method_    );
1065
 
  EXPECT_EQ(&mock_controller_, mock_service_.controller_);
1066
 
  EXPECT_EQ(&foo_request_    , mock_service_.request_   );
1067
 
  EXPECT_EQ(&foo_response_   , mock_service_.response_  );
1068
 
  EXPECT_EQ(done_.get()      , mock_service_.done_      );
1069
 
 
1070
 
  // Try again, but call Bar() instead.
1071
 
  mock_service_.Reset();
1072
 
  mock_service_.CallMethod(bar_, &mock_controller_,
1073
 
                           &bar_request_, &bar_response_, done_.get());
1074
 
 
1075
 
  ASSERT_TRUE(mock_service_.called_);
1076
 
  EXPECT_EQ("Bar", mock_service_.method_);
1077
 
}
1078
 
 
1079
 
TEST_F(GeneratedServiceTest, CallMethodTypeFailure) {
1080
 
  // Verify death if we call Foo() with Bar's message types.
1081
 
 
1082
 
#ifdef GTEST_HAS_DEATH_TEST  // death tests do not work on Windows yet
1083
 
  EXPECT_DEBUG_DEATH(
1084
 
    mock_service_.CallMethod(foo_, &mock_controller_,
1085
 
                             &foo_request_, &bar_response_, done_.get()),
1086
 
    "dynamic_cast");
1087
 
 
1088
 
  mock_service_.Reset();
1089
 
  EXPECT_DEBUG_DEATH(
1090
 
    mock_service_.CallMethod(foo_, &mock_controller_,
1091
 
                             &bar_request_, &foo_response_, done_.get()),
1092
 
    "dynamic_cast");
1093
 
#endif  // GTEST_HAS_DEATH_TEST
1094
 
}
1095
 
 
1096
 
TEST_F(GeneratedServiceTest, GetPrototypes) {
1097
 
  // Test Get{Request,Response}Prototype() methods.
1098
 
 
1099
 
  EXPECT_EQ(&unittest::FooRequest::default_instance(),
1100
 
            &mock_service_.GetRequestPrototype(foo_));
1101
 
  EXPECT_EQ(&unittest::BarRequest::default_instance(),
1102
 
            &mock_service_.GetRequestPrototype(bar_));
1103
 
 
1104
 
  EXPECT_EQ(&unittest::FooResponse::default_instance(),
1105
 
            &mock_service_.GetResponsePrototype(foo_));
1106
 
  EXPECT_EQ(&unittest::BarResponse::default_instance(),
1107
 
            &mock_service_.GetResponsePrototype(bar_));
1108
 
}
1109
 
 
1110
 
TEST_F(GeneratedServiceTest, Stub) {
1111
 
  // Test that the stub class works.
1112
 
 
1113
 
  // Call Foo() via the stub.
1114
 
  stub_.Foo(&mock_controller_, &foo_request_, &foo_response_, done_.get());
1115
 
 
1116
 
  ASSERT_TRUE(mock_channel_.called_);
1117
 
 
1118
 
  EXPECT_EQ(foo_             , mock_channel_.method_    );
1119
 
  EXPECT_EQ(&mock_controller_, mock_channel_.controller_);
1120
 
  EXPECT_EQ(&foo_request_    , mock_channel_.request_   );
1121
 
  EXPECT_EQ(&foo_response_   , mock_channel_.response_  );
1122
 
  EXPECT_EQ(done_.get()      , mock_channel_.done_      );
1123
 
 
1124
 
  // Call Bar() via the stub.
1125
 
  mock_channel_.Reset();
1126
 
  stub_.Bar(&mock_controller_, &bar_request_, &bar_response_, done_.get());
1127
 
 
1128
 
  ASSERT_TRUE(mock_channel_.called_);
1129
 
  EXPECT_EQ(bar_, mock_channel_.method_);
1130
 
}
1131
 
 
1132
 
TEST_F(GeneratedServiceTest, NotImplemented) {
1133
 
  // Test that failing to implement a method of a service causes it to fail
1134
 
  // with a "not implemented" error message.
1135
 
 
1136
 
  // A service which doesn't implement any methods.
1137
 
  class UnimplementedService : public unittest::TestService {
1138
 
   public:
1139
 
    UnimplementedService() {}
1140
 
  };
1141
 
 
1142
 
  UnimplementedService unimplemented_service;
1143
 
 
1144
 
  // And a controller which expects to get a "not implemented" error.
1145
 
  class ExpectUnimplementedController : public MockController {
1146
 
   public:
1147
 
    ExpectUnimplementedController() : called_(false) {}
1148
 
 
1149
 
    void SetFailed(const string& reason) {
1150
 
      EXPECT_FALSE(called_);
1151
 
      called_ = true;
1152
 
      EXPECT_EQ("Method Foo() not implemented.", reason);
1153
 
    }
1154
 
 
1155
 
    bool called_;
1156
 
  };
1157
 
 
1158
 
  ExpectUnimplementedController controller;
1159
 
 
1160
 
  // Call Foo.
1161
 
  unimplemented_service.Foo(&controller, &foo_request_, &foo_response_,
1162
 
                            done_.get());
1163
 
 
1164
 
  EXPECT_TRUE(controller.called_);
1165
 
}
1166
 
 
1167
 
}  // namespace cpp_unittest
1168
 
}  // namespace cpp
1169
 
}  // namespace compiler
1170
 
 
1171
 
namespace no_generic_services_test {
1172
 
  // Verify that no class called "TestService" was defined in
1173
 
  // unittest_no_generic_services.pb.h by defining a different type by the same
1174
 
  // name.  If such a service was generated, this will not compile.
1175
 
  struct TestService {
1176
 
    int i;
1177
 
  };
1178
 
}
1179
 
 
1180
 
namespace compiler {
1181
 
namespace cpp {
1182
 
namespace cpp_unittest {
1183
 
 
1184
 
TEST_F(GeneratedServiceTest, NoGenericServices) {
1185
 
  // Verify that non-services in unittest_no_generic_services.proto were
1186
 
  // generated.
1187
 
  no_generic_services_test::TestMessage message;
1188
 
  message.set_a(1);
1189
 
  message.SetExtension(no_generic_services_test::test_extension, 123);
1190
 
  no_generic_services_test::TestEnum e = no_generic_services_test::FOO;
1191
 
  EXPECT_EQ(e, 1);
1192
 
 
1193
 
  // Verify that a ServiceDescriptor is generated for the service even if the
1194
 
  // class itself is not.
1195
 
  const FileDescriptor* file =
1196
 
      no_generic_services_test::TestMessage::descriptor()->file();
1197
 
 
1198
 
  ASSERT_EQ(1, file->service_count());
1199
 
  EXPECT_EQ("TestService", file->service(0)->name());
1200
 
  ASSERT_EQ(1, file->service(0)->method_count());
1201
 
  EXPECT_EQ("Foo", file->service(0)->method(0)->name());
1202
 
}
1203
 
 
1204
 
#endif  // !PROTOBUF_TEST_NO_DESCRIPTORS
1205
 
 
1206
 
// ===================================================================
1207
 
 
1208
 
// This test must run last.  It verifies that descriptors were or were not
1209
 
// initialized depending on whether PROTOBUF_TEST_NO_DESCRIPTORS was defined.
1210
 
// When this is defined, we skip all tests which are expected to trigger
1211
 
// descriptor initialization.  This verifies that everything else still works
1212
 
// if descriptors are not initialized.
1213
 
TEST(DescriptorInitializationTest, Initialized) {
1214
 
#ifdef PROTOBUF_TEST_NO_DESCRIPTORS
1215
 
  bool should_have_descriptors = false;
1216
 
#else
1217
 
  bool should_have_descriptors = true;
1218
 
#endif
1219
 
 
1220
 
  EXPECT_EQ(should_have_descriptors,
1221
 
    DescriptorPool::generated_pool()->InternalIsFileLoaded(
1222
 
      "google/protobuf/unittest.proto"));
1223
 
}
1224
 
 
1225
 
}  // namespace cpp_unittest
1226
 
 
1227
 
}  // namespace cpp
1228
 
}  // namespace compiler
1229
 
}  // namespace protobuf
1230
 
}  // namespace google