blob: 41ba5e43c31b0a66e85d7019df859f7322cba51d [file] [log] [blame]
temporal40ee5512008-07-10 02:12:20 +00001// Protocol Buffers - Google's data interchange format
kenton@google.com24bf56f2008-09-24 20:31:01 +00002// Copyright 2008 Google Inc. All rights reserved.
temporal40ee5512008-07-10 02:12:20 +00003// http://code.google.com/p/protobuf/
4//
kenton@google.com24bf56f2008-09-24 20:31:01 +00005// Redistribution and use in source and binary forms, with or without
6// modification, are permitted provided that the following conditions are
7// met:
temporal40ee5512008-07-10 02:12:20 +00008//
kenton@google.com24bf56f2008-09-24 20:31:01 +00009// * 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.
temporal40ee5512008-07-10 02:12:20 +000018//
kenton@google.com24bf56f2008-09-24 20:31:01 +000019// 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.
temporal40ee5512008-07-10 02:12:20 +000030
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>
kenton@google.comfccb1462009-12-18 02:11:36 +000052#include <google/protobuf/unittest_no_generic_services.pb.h>
temporal40ee5512008-07-10 02:12:20 +000053#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>
kenton@google.comd37d46d2009-04-25 02:53:47 +000056#include <google/protobuf/io/coded_stream.h>
57#include <google/protobuf/io/zero_copy_stream_impl.h>
temporal40ee5512008-07-10 02:12:20 +000058#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>
kenton@google.comd37d46d2009-04-25 02:53:47 +000067#include <google/protobuf/stubs/stl_util-inl.h>
temporal40ee5512008-07-10 02:12:20 +000068
69namespace google {
70namespace protobuf {
71namespace compiler {
72namespace cpp {
73
kenton@google.coma2a32c22008-11-14 17:29:32 +000074// Can't use an anonymous namespace here due to brokenness of Tru64 compiler.
75namespace cpp_unittest {
temporal40ee5512008-07-10 02:12:20 +000076
77
78class 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
kenton@google.comd37d46d2009-04-25 02:53:47 +000093#ifndef PROTOBUF_TEST_NO_DESCRIPTORS
94
temporal40ee5512008-07-10 02:12:20 +000095// 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.
98TEST(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
kenton@google.comd37d46d2009-04-25 02:53:47 +0000124#endif // !PROTOBUF_TEST_NO_DESCRIPTORS
125
temporal40ee5512008-07-10 02:12:20 +0000126// ===================================================================
127
128TEST(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
kenton@google.com80b1d622009-07-29 01:13:20 +0000147TEST(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());
kenton@google.comfccb1462009-12-18 02:11:36 +0000158 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());
kenton@google.com80b1d622009-07-29 01:13:20 +0000168}
169
temporal40ee5512008-07-10 02:12:20 +0000170TEST(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
182TEST(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
liujisi@google.com33165fe2010-11-02 13:14:58 +0000198TEST(GeneratedMessageTest, ReleaseString) {
199 // Check that release_foo() starts out NULL, and gives us a value
200 // that we can delete after it's been set.
201 unittest::TestAllTypes message;
202
203 EXPECT_EQ(NULL, message.release_default_string());
204 EXPECT_FALSE(message.has_default_string());
205 EXPECT_EQ("hello", message.default_string());
206
207 message.set_default_string("blah");
208 EXPECT_TRUE(message.has_default_string());
209 string* str = message.release_default_string();
210 EXPECT_FALSE(message.has_default_string());
211 ASSERT_TRUE(str != NULL);
212 EXPECT_EQ("blah", *str);
213 delete str;
214
215 EXPECT_EQ(NULL, message.release_default_string());
216 EXPECT_FALSE(message.has_default_string());
217 EXPECT_EQ("hello", message.default_string());
218}
219
220TEST(GeneratedMessageTest, ReleaseMessage) {
221 // Check that release_foo() starts out NULL, and gives us a value
222 // that we can delete after it's been set.
223 unittest::TestAllTypes message;
224
225 EXPECT_EQ(NULL, message.release_optional_nested_message());
226 EXPECT_FALSE(message.has_optional_nested_message());
227
228 message.mutable_optional_nested_message()->set_bb(1);
229 unittest::TestAllTypes::NestedMessage* nest =
230 message.release_optional_nested_message();
231 EXPECT_FALSE(message.has_optional_nested_message());
232 ASSERT_TRUE(nest != NULL);
233 EXPECT_EQ(1, nest->bb());
234 delete nest;
235
236 EXPECT_EQ(NULL, message.release_optional_nested_message());
237 EXPECT_FALSE(message.has_optional_nested_message());
238}
239
temporal40ee5512008-07-10 02:12:20 +0000240TEST(GeneratedMessageTest, Clear) {
241 // Set every field to a unique value, clear the message, then check that
242 // it is cleared.
243 unittest::TestAllTypes message;
244
245 TestUtil::SetAllFields(&message);
246 message.Clear();
247 TestUtil::ExpectClear(message);
248
249 // Unlike with the defaults test, we do NOT expect that requesting embedded
250 // messages will return a pointer to the default instance. Instead, they
251 // should return the objects that were created when mutable_blah() was
252 // called.
253 EXPECT_NE(&unittest::TestAllTypes::OptionalGroup::default_instance(),
254 &message.optionalgroup());
255 EXPECT_NE(&unittest::TestAllTypes::NestedMessage::default_instance(),
256 &message.optional_nested_message());
257 EXPECT_NE(&unittest::ForeignMessage::default_instance(),
258 &message.optional_foreign_message());
259 EXPECT_NE(&unittest_import::ImportMessage::default_instance(),
260 &message.optional_import_message());
261}
262
temporal928ebb62008-07-16 02:00:27 +0000263TEST(GeneratedMessageTest, EmbeddedNullsInBytesCharStar) {
264 unittest::TestAllTypes message;
265
266 const char* value = "\0lalala\0\0";
267 message.set_optional_bytes(value, 9);
268 ASSERT_EQ(9, message.optional_bytes().size());
269 EXPECT_EQ(0, memcmp(value, message.optional_bytes().data(), 9));
270
271 message.add_repeated_bytes(value, 9);
272 ASSERT_EQ(9, message.repeated_bytes(0).size());
273 EXPECT_EQ(0, memcmp(value, message.repeated_bytes(0).data(), 9));
274}
275
temporal40ee5512008-07-10 02:12:20 +0000276TEST(GeneratedMessageTest, ClearOneField) {
277 // Set every field to a unique value, then clear one value and insure that
278 // only that one value is cleared.
279 unittest::TestAllTypes message;
280
281 TestUtil::SetAllFields(&message);
282 int64 original_value = message.optional_int64();
283
284 // Clear the field and make sure it shows up as cleared.
285 message.clear_optional_int64();
286 EXPECT_FALSE(message.has_optional_int64());
287 EXPECT_EQ(0, message.optional_int64());
288
289 // Other adjacent fields should not be cleared.
290 EXPECT_TRUE(message.has_optional_int32());
291 EXPECT_TRUE(message.has_optional_uint32());
292
293 // Make sure if we set it again, then all fields are set.
294 message.set_optional_int64(original_value);
295 TestUtil::ExpectAllFieldsSet(message);
296}
297
kenton@google.comd37d46d2009-04-25 02:53:47 +0000298TEST(GeneratedMessageTest, StringCharStarLength) {
299 // Verify that we can use a char*,length to set one of the string fields.
300 unittest::TestAllTypes message;
301 message.set_optional_string("abcdef", 3);
302 EXPECT_EQ("abc", message.optional_string());
303
304 // Verify that we can use a char*,length to add to a repeated string field.
305 message.add_repeated_string("abcdef", 3);
306 EXPECT_EQ(1, message.repeated_string_size());
307 EXPECT_EQ("abc", message.repeated_string(0));
308
309 // Verify that we can use a char*,length to set a repeated string field.
310 message.set_repeated_string(0, "wxyz", 2);
311 EXPECT_EQ("wx", message.repeated_string(0));
312}
313
temporal40ee5512008-07-10 02:12:20 +0000314
315TEST(GeneratedMessageTest, CopyFrom) {
316 unittest::TestAllTypes message1, message2;
temporal40ee5512008-07-10 02:12:20 +0000317
318 TestUtil::SetAllFields(&message1);
319 message2.CopyFrom(message1);
320 TestUtil::ExpectAllFieldsSet(message2);
321
322 // Copying from self should be a no-op.
323 message2.CopyFrom(message2);
324 TestUtil::ExpectAllFieldsSet(message2);
325}
326
liujisi@google.com33165fe2010-11-02 13:14:58 +0000327
kenton@google.com26bd9ee2008-11-21 00:06:27 +0000328TEST(GeneratedMessageTest, SwapWithEmpty) {
329 unittest::TestAllTypes message1, message2;
330 TestUtil::SetAllFields(&message1);
331
332 TestUtil::ExpectAllFieldsSet(message1);
333 TestUtil::ExpectClear(message2);
334 message1.Swap(&message2);
335 TestUtil::ExpectAllFieldsSet(message2);
336 TestUtil::ExpectClear(message1);
337}
338
339TEST(GeneratedMessageTest, SwapWithSelf) {
340 unittest::TestAllTypes message;
341 TestUtil::SetAllFields(&message);
342 TestUtil::ExpectAllFieldsSet(message);
343 message.Swap(&message);
344 TestUtil::ExpectAllFieldsSet(message);
345}
346
347TEST(GeneratedMessageTest, SwapWithOther) {
348 unittest::TestAllTypes message1, message2;
349
350 message1.set_optional_int32(123);
351 message1.set_optional_string("abc");
352 message1.mutable_optional_nested_message()->set_bb(1);
353 message1.set_optional_nested_enum(unittest::TestAllTypes::FOO);
354 message1.add_repeated_int32(1);
355 message1.add_repeated_int32(2);
356 message1.add_repeated_string("a");
357 message1.add_repeated_string("b");
358 message1.add_repeated_nested_message()->set_bb(7);
359 message1.add_repeated_nested_message()->set_bb(8);
360 message1.add_repeated_nested_enum(unittest::TestAllTypes::FOO);
361 message1.add_repeated_nested_enum(unittest::TestAllTypes::BAR);
362
363 message2.set_optional_int32(456);
364 message2.set_optional_string("def");
365 message2.mutable_optional_nested_message()->set_bb(2);
366 message2.set_optional_nested_enum(unittest::TestAllTypes::BAR);
367 message2.add_repeated_int32(3);
368 message2.add_repeated_string("c");
369 message2.add_repeated_nested_message()->set_bb(9);
370 message2.add_repeated_nested_enum(unittest::TestAllTypes::BAZ);
371
372 message1.Swap(&message2);
373
374 EXPECT_EQ(456, message1.optional_int32());
375 EXPECT_EQ("def", message1.optional_string());
376 EXPECT_EQ(2, message1.optional_nested_message().bb());
377 EXPECT_EQ(unittest::TestAllTypes::BAR, message1.optional_nested_enum());
378 ASSERT_EQ(1, message1.repeated_int32_size());
379 EXPECT_EQ(3, message1.repeated_int32(0));
380 ASSERT_EQ(1, message1.repeated_string_size());
381 EXPECT_EQ("c", message1.repeated_string(0));
382 ASSERT_EQ(1, message1.repeated_nested_message_size());
383 EXPECT_EQ(9, message1.repeated_nested_message(0).bb());
384 ASSERT_EQ(1, message1.repeated_nested_enum_size());
385 EXPECT_EQ(unittest::TestAllTypes::BAZ, message1.repeated_nested_enum(0));
386
387 EXPECT_EQ(123, message2.optional_int32());
388 EXPECT_EQ("abc", message2.optional_string());
389 EXPECT_EQ(1, message2.optional_nested_message().bb());
390 EXPECT_EQ(unittest::TestAllTypes::FOO, message2.optional_nested_enum());
391 ASSERT_EQ(2, message2.repeated_int32_size());
392 EXPECT_EQ(1, message2.repeated_int32(0));
393 EXPECT_EQ(2, message2.repeated_int32(1));
394 ASSERT_EQ(2, message2.repeated_string_size());
395 EXPECT_EQ("a", message2.repeated_string(0));
396 EXPECT_EQ("b", message2.repeated_string(1));
397 ASSERT_EQ(2, message2.repeated_nested_message_size());
398 EXPECT_EQ(7, message2.repeated_nested_message(0).bb());
399 EXPECT_EQ(8, message2.repeated_nested_message(1).bb());
400 ASSERT_EQ(2, message2.repeated_nested_enum_size());
401 EXPECT_EQ(unittest::TestAllTypes::FOO, message2.repeated_nested_enum(0));
402 EXPECT_EQ(unittest::TestAllTypes::BAR, message2.repeated_nested_enum(1));
403}
404
temporal40ee5512008-07-10 02:12:20 +0000405TEST(GeneratedMessageTest, CopyConstructor) {
406 unittest::TestAllTypes message1;
407 TestUtil::SetAllFields(&message1);
408
409 unittest::TestAllTypes message2(message1);
410 TestUtil::ExpectAllFieldsSet(message2);
411}
412
413TEST(GeneratedMessageTest, CopyAssignmentOperator) {
414 unittest::TestAllTypes message1;
415 TestUtil::SetAllFields(&message1);
416
417 unittest::TestAllTypes message2;
418 message2 = message1;
419 TestUtil::ExpectAllFieldsSet(message2);
420
421 // Make sure that self-assignment does something sane.
liujisi@google.com33165fe2010-11-02 13:14:58 +0000422 message2.operator=(message2);
temporal40ee5512008-07-10 02:12:20 +0000423 TestUtil::ExpectAllFieldsSet(message2);
424}
425
426TEST(GeneratedMessageTest, UpcastCopyFrom) {
427 // Test the CopyFrom method that takes in the generic const Message&
428 // parameter.
429 unittest::TestAllTypes message1, message2;
430
431 TestUtil::SetAllFields(&message1);
432
433 const Message* source = implicit_cast<const Message*>(&message1);
434 message2.CopyFrom(*source);
435
436 TestUtil::ExpectAllFieldsSet(message2);
437}
438
kenton@google.comd37d46d2009-04-25 02:53:47 +0000439#ifndef PROTOBUF_TEST_NO_DESCRIPTORS
440
temporal40ee5512008-07-10 02:12:20 +0000441TEST(GeneratedMessageTest, DynamicMessageCopyFrom) {
442 // Test copying from a DynamicMessage, which must fall back to using
443 // reflection.
444 unittest::TestAllTypes message2;
445
446 // Construct a new version of the dynamic message via the factory.
447 DynamicMessageFactory factory;
448 scoped_ptr<Message> message1;
449 message1.reset(factory.GetPrototype(
450 unittest::TestAllTypes::descriptor())->New());
451
452 TestUtil::ReflectionTester reflection_tester(
453 unittest::TestAllTypes::descriptor());
temporal779f61c2008-08-13 03:15:00 +0000454 reflection_tester.SetAllFieldsViaReflection(message1.get());
temporal40ee5512008-07-10 02:12:20 +0000455
456 message2.CopyFrom(*message1);
457
458 TestUtil::ExpectAllFieldsSet(message2);
459}
460
kenton@google.comd37d46d2009-04-25 02:53:47 +0000461#endif // !PROTOBUF_TEST_NO_DESCRIPTORS
462
temporal40ee5512008-07-10 02:12:20 +0000463TEST(GeneratedMessageTest, NonEmptyMergeFrom) {
464 // Test merging with a non-empty message. Code is a modified form
465 // of that found in google/protobuf/reflection_ops_unittest.cc.
466 unittest::TestAllTypes message1, message2;
467
468 TestUtil::SetAllFields(&message1);
469
470 // This field will test merging into an empty spot.
471 message2.set_optional_int32(message1.optional_int32());
472 message1.clear_optional_int32();
473
474 // This tests overwriting.
475 message2.set_optional_string(message1.optional_string());
476 message1.set_optional_string("something else");
477
478 // This tests concatenating.
479 message2.add_repeated_int32(message1.repeated_int32(1));
480 int32 i = message1.repeated_int32(0);
481 message1.clear_repeated_int32();
482 message1.add_repeated_int32(i);
483
484 message1.MergeFrom(message2);
485
486 TestUtil::ExpectAllFieldsSet(message1);
487}
488
489#ifdef GTEST_HAS_DEATH_TEST
490
491TEST(GeneratedMessageTest, MergeFromSelf) {
492 unittest::TestAllTypes message;
493 EXPECT_DEATH(message.MergeFrom(message), "&from");
494 EXPECT_DEATH(message.MergeFrom(implicit_cast<const Message&>(message)),
495 "&from");
496}
497
498#endif // GTEST_HAS_DEATH_TEST
499
kenton@google.comd37d46d2009-04-25 02:53:47 +0000500// Test the generated SerializeWithCachedSizesToArray(),
501TEST(GeneratedMessageTest, SerializationToArray) {
temporal40ee5512008-07-10 02:12:20 +0000502 unittest::TestAllTypes message1, message2;
503 string data;
temporal40ee5512008-07-10 02:12:20 +0000504 TestUtil::SetAllFields(&message1);
kenton@google.comd37d46d2009-04-25 02:53:47 +0000505 int size = message1.ByteSize();
506 data.resize(size);
507 uint8* start = reinterpret_cast<uint8*>(string_as_array(&data));
kenton@google.com09b9e992009-08-10 20:23:41 +0000508 uint8* end = message1.SerializeWithCachedSizesToArray(start);
kenton@google.comd37d46d2009-04-25 02:53:47 +0000509 EXPECT_EQ(size, end - start);
temporal40ee5512008-07-10 02:12:20 +0000510 EXPECT_TRUE(message2.ParseFromString(data));
511 TestUtil::ExpectAllFieldsSet(message2);
512
kenton@google.comd37d46d2009-04-25 02:53:47 +0000513}
kenton@google.com2d6daa72009-01-22 01:27:00 +0000514
kenton@google.comd37d46d2009-04-25 02:53:47 +0000515TEST(GeneratedMessageTest, PackedFieldsSerializationToArray) {
kenton@google.com2d6daa72009-01-22 01:27:00 +0000516 unittest::TestPackedTypes packed_message1, packed_message2;
517 string packed_data;
518 TestUtil::SetPackedFields(&packed_message1);
kenton@google.comd37d46d2009-04-25 02:53:47 +0000519 int packed_size = packed_message1.ByteSize();
520 packed_data.resize(packed_size);
521 uint8* start = reinterpret_cast<uint8*>(string_as_array(&packed_data));
kenton@google.com09b9e992009-08-10 20:23:41 +0000522 uint8* end = packed_message1.SerializeWithCachedSizesToArray(start);
kenton@google.comd37d46d2009-04-25 02:53:47 +0000523 EXPECT_EQ(packed_size, end - start);
kenton@google.com2d6daa72009-01-22 01:27:00 +0000524 EXPECT_TRUE(packed_message2.ParseFromString(packed_data));
525 TestUtil::ExpectPackedFieldsSet(packed_message2);
temporal40ee5512008-07-10 02:12:20 +0000526}
527
kenton@google.comd37d46d2009-04-25 02:53:47 +0000528// Test the generated SerializeWithCachedSizes() by forcing the buffer to write
529// one byte at a time.
530TEST(GeneratedMessageTest, SerializationToStream) {
531 unittest::TestAllTypes message1, message2;
532 TestUtil::SetAllFields(&message1);
533 int size = message1.ByteSize();
534 string data;
535 data.resize(size);
536 {
537 // Allow the output stream to buffer only one byte at a time.
538 io::ArrayOutputStream array_stream(string_as_array(&data), size, 1);
539 io::CodedOutputStream output_stream(&array_stream);
kenton@google.com09b9e992009-08-10 20:23:41 +0000540 message1.SerializeWithCachedSizes(&output_stream);
kenton@google.comd37d46d2009-04-25 02:53:47 +0000541 EXPECT_FALSE(output_stream.HadError());
542 EXPECT_EQ(size, output_stream.ByteCount());
543 }
544 EXPECT_TRUE(message2.ParseFromString(data));
545 TestUtil::ExpectAllFieldsSet(message2);
546
547}
548
549TEST(GeneratedMessageTest, PackedFieldsSerializationToStream) {
550 unittest::TestPackedTypes message1, message2;
551 TestUtil::SetPackedFields(&message1);
552 int size = message1.ByteSize();
553 string data;
554 data.resize(size);
555 {
556 // Allow the output stream to buffer only one byte at a time.
557 io::ArrayOutputStream array_stream(string_as_array(&data), size, 1);
558 io::CodedOutputStream output_stream(&array_stream);
kenton@google.com09b9e992009-08-10 20:23:41 +0000559 message1.SerializeWithCachedSizes(&output_stream);
kenton@google.comd37d46d2009-04-25 02:53:47 +0000560 EXPECT_FALSE(output_stream.HadError());
561 EXPECT_EQ(size, output_stream.ByteCount());
562 }
563 EXPECT_TRUE(message2.ParseFromString(data));
564 TestUtil::ExpectPackedFieldsSet(message2);
565}
566
temporal40ee5512008-07-10 02:12:20 +0000567
568TEST(GeneratedMessageTest, Required) {
569 // Test that IsInitialized() returns false if required fields are missing.
570 unittest::TestRequired message;
571
572 EXPECT_FALSE(message.IsInitialized());
573 message.set_a(1);
574 EXPECT_FALSE(message.IsInitialized());
575 message.set_b(2);
576 EXPECT_FALSE(message.IsInitialized());
577 message.set_c(3);
578 EXPECT_TRUE(message.IsInitialized());
579}
580
581TEST(GeneratedMessageTest, RequiredForeign) {
582 // Test that IsInitialized() returns false if required fields in nested
583 // messages are missing.
584 unittest::TestRequiredForeign message;
585
586 EXPECT_TRUE(message.IsInitialized());
587
588 message.mutable_optional_message();
589 EXPECT_FALSE(message.IsInitialized());
590
591 message.mutable_optional_message()->set_a(1);
592 message.mutable_optional_message()->set_b(2);
593 message.mutable_optional_message()->set_c(3);
594 EXPECT_TRUE(message.IsInitialized());
595
596 message.add_repeated_message();
597 EXPECT_FALSE(message.IsInitialized());
598
599 message.mutable_repeated_message(0)->set_a(1);
600 message.mutable_repeated_message(0)->set_b(2);
601 message.mutable_repeated_message(0)->set_c(3);
602 EXPECT_TRUE(message.IsInitialized());
603}
604
605TEST(GeneratedMessageTest, ForeignNested) {
606 // Test that TestAllTypes::NestedMessage can be embedded directly into
607 // another message.
608 unittest::TestForeignNested message;
609
610 // If this compiles and runs without crashing, it must work. We have
611 // nothing more to test.
612 unittest::TestAllTypes::NestedMessage* nested =
613 message.mutable_foreign_nested();
614 nested->set_bb(1);
615}
616
617TEST(GeneratedMessageTest, ReallyLargeTagNumber) {
618 // Test that really large tag numbers don't break anything.
619 unittest::TestReallyLargeTagNumber message1, message2;
620 string data;
621
622 // For the most part, if this compiles and runs then we're probably good.
623 // (The most likely cause for failure would be if something were attempting
624 // to allocate a lookup table of some sort using tag numbers as the index.)
625 // We'll try serializing just for fun.
626 message1.set_a(1234);
627 message1.set_bb(5678);
628 message1.SerializeToString(&data);
629 EXPECT_TRUE(message2.ParseFromString(data));
630 EXPECT_EQ(1234, message2.a());
631 EXPECT_EQ(5678, message2.bb());
632}
633
634TEST(GeneratedMessageTest, MutualRecursion) {
635 // Test that mutually-recursive message types work.
636 unittest::TestMutualRecursionA message;
637 unittest::TestMutualRecursionA* nested = message.mutable_bb()->mutable_a();
638 unittest::TestMutualRecursionA* nested2 = nested->mutable_bb()->mutable_a();
639
640 // Again, if the above compiles and runs, that's all we really have to
641 // test, but just for run we'll check that the system didn't somehow come
642 // up with a pointer loop...
643 EXPECT_NE(&message, nested);
644 EXPECT_NE(&message, nested2);
645 EXPECT_NE(nested, nested2);
646}
647
648TEST(GeneratedMessageTest, CamelCaseFieldNames) {
649 // This test is mainly checking that the following compiles, which verifies
650 // that the field names were coerced to lower-case.
651 //
652 // Protocol buffers standard style is to use lowercase-with-underscores for
653 // field names. Some old proto1 .protos unfortunately used camel-case field
654 // names. In proto1, these names were forced to lower-case. So, we do the
655 // same thing in proto2.
656
657 unittest::TestCamelCaseFieldNames message;
658
659 message.set_primitivefield(2);
660 message.set_stringfield("foo");
661 message.set_enumfield(unittest::FOREIGN_FOO);
662 message.mutable_messagefield()->set_c(6);
663
664 message.add_repeatedprimitivefield(8);
665 message.add_repeatedstringfield("qux");
666 message.add_repeatedenumfield(unittest::FOREIGN_BAR);
667 message.add_repeatedmessagefield()->set_c(15);
668
669 EXPECT_EQ(2, message.primitivefield());
670 EXPECT_EQ("foo", message.stringfield());
671 EXPECT_EQ(unittest::FOREIGN_FOO, message.enumfield());
672 EXPECT_EQ(6, message.messagefield().c());
673
674 EXPECT_EQ(8, message.repeatedprimitivefield(0));
675 EXPECT_EQ("qux", message.repeatedstringfield(0));
676 EXPECT_EQ(unittest::FOREIGN_BAR, message.repeatedenumfield(0));
677 EXPECT_EQ(15, message.repeatedmessagefield(0).c());
678}
679
680TEST(GeneratedMessageTest, TestConflictingSymbolNames) {
681 // test_bad_identifiers.proto successfully compiled, then it works. The
682 // following is just a token usage to insure that the code is, in fact,
683 // being compiled and linked.
684
685 protobuf_unittest::TestConflictingSymbolNames message;
686 message.set_uint32(1);
687 EXPECT_EQ(3, message.ByteSize());
688
689 message.set_friend_(5);
690 EXPECT_EQ(5, message.friend_());
691}
692
kenton@google.comd37d46d2009-04-25 02:53:47 +0000693#ifndef PROTOBUF_TEST_NO_DESCRIPTORS
694
temporal40ee5512008-07-10 02:12:20 +0000695TEST(GeneratedMessageTest, TestOptimizedForSize) {
696 // We rely on the tests in reflection_ops_unittest and wire_format_unittest
697 // to really test that reflection-based methods work. Here we are mostly
698 // just making sure that TestOptimizedForSize actually builds and seems to
699 // function.
700
701 protobuf_unittest::TestOptimizedForSize message, message2;
702 message.set_i(1);
703 message.mutable_msg()->set_c(2);
704 message2.CopyFrom(message);
705 EXPECT_EQ(1, message2.i());
706 EXPECT_EQ(2, message2.msg().c());
707}
708
709TEST(GeneratedMessageTest, TestEmbedOptimizedForSize) {
710 // Verifies that something optimized for speed can contain something optimized
711 // for size.
712
713 protobuf_unittest::TestEmbedOptimizedForSize message, message2;
714 message.mutable_optional_message()->set_i(1);
715 message.add_repeated_message()->mutable_msg()->set_c(2);
716 string data;
717 message.SerializeToString(&data);
718 ASSERT_TRUE(message2.ParseFromString(data));
719 EXPECT_EQ(1, message2.optional_message().i());
720 EXPECT_EQ(2, message2.repeated_message(0).msg().c());
721}
722
kenton@google.com26bd9ee2008-11-21 00:06:27 +0000723TEST(GeneratedMessageTest, TestSpaceUsed) {
724 unittest::TestAllTypes message1;
725 // sizeof provides a lower bound on SpaceUsed().
726 EXPECT_LE(sizeof(unittest::TestAllTypes), message1.SpaceUsed());
727 const int empty_message_size = message1.SpaceUsed();
728
729 // Setting primitive types shouldn't affect the space used.
730 message1.set_optional_int32(123);
731 message1.set_optional_int64(12345);
732 message1.set_optional_uint32(123);
733 message1.set_optional_uint64(12345);
734 EXPECT_EQ(empty_message_size, message1.SpaceUsed());
735
736 // On some STL implementations, setting the string to a small value should
737 // only increase SpaceUsed() by the size of a string object, though this is
738 // not true everywhere.
739 message1.set_optional_string("abc");
740 EXPECT_LE(empty_message_size + sizeof(string), message1.SpaceUsed());
741
742 // Setting a string to a value larger than the string object itself should
743 // increase SpaceUsed(), because it cannot store the value internally.
744 message1.set_optional_string(string(sizeof(string) + 1, 'x'));
745 int min_expected_increase = message1.optional_string().capacity() +
746 sizeof(string);
747 EXPECT_LE(empty_message_size + min_expected_increase,
748 message1.SpaceUsed());
749
750 int previous_size = message1.SpaceUsed();
751 // Adding an optional message should increase the size by the size of the
752 // nested message type. NestedMessage is simple enough (1 int field) that it
753 // is equal to sizeof(NestedMessage)
754 message1.mutable_optional_nested_message();
755 ASSERT_EQ(sizeof(unittest::TestAllTypes::NestedMessage),
756 message1.optional_nested_message().SpaceUsed());
757 EXPECT_EQ(previous_size +
758 sizeof(unittest::TestAllTypes::NestedMessage),
759 message1.SpaceUsed());
760}
761
kenton@google.comd37d46d2009-04-25 02:53:47 +0000762#endif // !PROTOBUF_TEST_NO_DESCRIPTORS
763
liujisi@google.com33165fe2010-11-02 13:14:58 +0000764
kenton@google.com80b1d622009-07-29 01:13:20 +0000765TEST(GeneratedMessageTest, FieldConstantValues) {
766 unittest::TestRequired message;
767 EXPECT_EQ(unittest::TestAllTypes_NestedMessage::kBbFieldNumber, 1);
768 EXPECT_EQ(unittest::TestAllTypes::kOptionalInt32FieldNumber, 1);
769 EXPECT_EQ(unittest::TestAllTypes::kOptionalgroupFieldNumber, 16);
770 EXPECT_EQ(unittest::TestAllTypes::kOptionalNestedMessageFieldNumber, 18);
771 EXPECT_EQ(unittest::TestAllTypes::kOptionalNestedEnumFieldNumber, 21);
772 EXPECT_EQ(unittest::TestAllTypes::kRepeatedInt32FieldNumber, 31);
773 EXPECT_EQ(unittest::TestAllTypes::kRepeatedgroupFieldNumber, 46);
774 EXPECT_EQ(unittest::TestAllTypes::kRepeatedNestedMessageFieldNumber, 48);
775 EXPECT_EQ(unittest::TestAllTypes::kRepeatedNestedEnumFieldNumber, 51);
776}
777
778TEST(GeneratedMessageTest, ExtensionConstantValues) {
779 EXPECT_EQ(unittest::TestRequired::kSingleFieldNumber, 1000);
780 EXPECT_EQ(unittest::TestRequired::kMultiFieldNumber, 1001);
781 EXPECT_EQ(unittest::kOptionalInt32ExtensionFieldNumber, 1);
782 EXPECT_EQ(unittest::kOptionalgroupExtensionFieldNumber, 16);
783 EXPECT_EQ(unittest::kOptionalNestedMessageExtensionFieldNumber, 18);
784 EXPECT_EQ(unittest::kOptionalNestedEnumExtensionFieldNumber, 21);
785 EXPECT_EQ(unittest::kRepeatedInt32ExtensionFieldNumber, 31);
786 EXPECT_EQ(unittest::kRepeatedgroupExtensionFieldNumber, 46);
787 EXPECT_EQ(unittest::kRepeatedNestedMessageExtensionFieldNumber, 48);
788 EXPECT_EQ(unittest::kRepeatedNestedEnumExtensionFieldNumber, 51);
789}
790
temporal40ee5512008-07-10 02:12:20 +0000791// ===================================================================
792
793TEST(GeneratedEnumTest, EnumValuesAsSwitchCases) {
794 // Test that our nested enum values can be used as switch cases. This test
795 // doesn't actually do anything, the proof that it works is that it
796 // compiles.
797 int i =0;
798 unittest::TestAllTypes::NestedEnum a = unittest::TestAllTypes::BAR;
799 switch (a) {
800 case unittest::TestAllTypes::FOO:
801 i = 1;
802 break;
803 case unittest::TestAllTypes::BAR:
804 i = 2;
805 break;
806 case unittest::TestAllTypes::BAZ:
807 i = 3;
808 break;
809 // no default case: We want to make sure the compiler recognizes that
810 // all cases are covered. (GCC warns if you do not cover all cases of
811 // an enum in a switch.)
812 }
813
814 // Token check just for fun.
815 EXPECT_EQ(2, i);
816}
817
818TEST(GeneratedEnumTest, IsValidValue) {
819 // Test enum IsValidValue.
820 EXPECT_TRUE(unittest::TestAllTypes::NestedEnum_IsValid(1));
821 EXPECT_TRUE(unittest::TestAllTypes::NestedEnum_IsValid(2));
822 EXPECT_TRUE(unittest::TestAllTypes::NestedEnum_IsValid(3));
823
824 EXPECT_FALSE(unittest::TestAllTypes::NestedEnum_IsValid(0));
825 EXPECT_FALSE(unittest::TestAllTypes::NestedEnum_IsValid(4));
826
827 // Make sure it also works when there are dups.
828 EXPECT_TRUE(unittest::TestEnumWithDupValue_IsValid(1));
829 EXPECT_TRUE(unittest::TestEnumWithDupValue_IsValid(2));
830 EXPECT_TRUE(unittest::TestEnumWithDupValue_IsValid(3));
831
832 EXPECT_FALSE(unittest::TestEnumWithDupValue_IsValid(0));
833 EXPECT_FALSE(unittest::TestEnumWithDupValue_IsValid(4));
834}
835
836TEST(GeneratedEnumTest, MinAndMax) {
kenton@google.comfccb1462009-12-18 02:11:36 +0000837 EXPECT_EQ(unittest::TestAllTypes::FOO,
838 unittest::TestAllTypes::NestedEnum_MIN);
839 EXPECT_EQ(unittest::TestAllTypes::BAZ,
840 unittest::TestAllTypes::NestedEnum_MAX);
841 EXPECT_EQ(4, unittest::TestAllTypes::NestedEnum_ARRAYSIZE);
temporal40ee5512008-07-10 02:12:20 +0000842
843 EXPECT_EQ(unittest::FOREIGN_FOO, unittest::ForeignEnum_MIN);
844 EXPECT_EQ(unittest::FOREIGN_BAZ, unittest::ForeignEnum_MAX);
kenton@google.comfccb1462009-12-18 02:11:36 +0000845 EXPECT_EQ(7, unittest::ForeignEnum_ARRAYSIZE);
temporal40ee5512008-07-10 02:12:20 +0000846
847 EXPECT_EQ(1, unittest::TestEnumWithDupValue_MIN);
848 EXPECT_EQ(3, unittest::TestEnumWithDupValue_MAX);
kenton@google.comfccb1462009-12-18 02:11:36 +0000849 EXPECT_EQ(4, unittest::TestEnumWithDupValue_ARRAYSIZE);
temporal40ee5512008-07-10 02:12:20 +0000850
851 EXPECT_EQ(unittest::SPARSE_E, unittest::TestSparseEnum_MIN);
852 EXPECT_EQ(unittest::SPARSE_C, unittest::TestSparseEnum_MAX);
kenton@google.comfccb1462009-12-18 02:11:36 +0000853 EXPECT_EQ(12589235, unittest::TestSparseEnum_ARRAYSIZE);
temporal40ee5512008-07-10 02:12:20 +0000854
kenton@google.comfccb1462009-12-18 02:11:36 +0000855 // Make sure we can take the address of _MIN, _MAX and _ARRAYSIZE.
856 void* nullptr = 0; // NULL may be integer-type, not pointer-type.
857 EXPECT_NE(nullptr, &unittest::TestAllTypes::NestedEnum_MIN);
858 EXPECT_NE(nullptr, &unittest::TestAllTypes::NestedEnum_MAX);
859 EXPECT_NE(nullptr, &unittest::TestAllTypes::NestedEnum_ARRAYSIZE);
860
861 EXPECT_NE(nullptr, &unittest::ForeignEnum_MIN);
862 EXPECT_NE(nullptr, &unittest::ForeignEnum_MAX);
863 EXPECT_NE(nullptr, &unittest::ForeignEnum_ARRAYSIZE);
864
865 // Make sure we can use _MIN, _MAX and _ARRAYSIZE as switch cases.
866 switch (unittest::SPARSE_A) {
temporal40ee5512008-07-10 02:12:20 +0000867 case unittest::TestSparseEnum_MIN:
868 case unittest::TestSparseEnum_MAX:
kenton@google.comfccb1462009-12-18 02:11:36 +0000869 case unittest::TestSparseEnum_ARRAYSIZE:
temporal40ee5512008-07-10 02:12:20 +0000870 break;
871 default:
872 break;
873 }
874}
875
kenton@google.comd37d46d2009-04-25 02:53:47 +0000876#ifndef PROTOBUF_TEST_NO_DESCRIPTORS
877
878TEST(GeneratedEnumTest, Name) {
879 // "Names" in the presence of dup values are a bit arbitrary.
880 EXPECT_EQ("FOO1", unittest::TestEnumWithDupValue_Name(unittest::FOO1));
881 EXPECT_EQ("FOO1", unittest::TestEnumWithDupValue_Name(unittest::FOO2));
882
883 EXPECT_EQ("SPARSE_A", unittest::TestSparseEnum_Name(unittest::SPARSE_A));
884 EXPECT_EQ("SPARSE_B", unittest::TestSparseEnum_Name(unittest::SPARSE_B));
885 EXPECT_EQ("SPARSE_C", unittest::TestSparseEnum_Name(unittest::SPARSE_C));
886 EXPECT_EQ("SPARSE_D", unittest::TestSparseEnum_Name(unittest::SPARSE_D));
887 EXPECT_EQ("SPARSE_E", unittest::TestSparseEnum_Name(unittest::SPARSE_E));
888 EXPECT_EQ("SPARSE_F", unittest::TestSparseEnum_Name(unittest::SPARSE_F));
889 EXPECT_EQ("SPARSE_G", unittest::TestSparseEnum_Name(unittest::SPARSE_G));
890}
891
892TEST(GeneratedEnumTest, Parse) {
893 unittest::TestEnumWithDupValue dup_value = unittest::FOO1;
894 EXPECT_TRUE(unittest::TestEnumWithDupValue_Parse("FOO1", &dup_value));
895 EXPECT_EQ(unittest::FOO1, dup_value);
896 EXPECT_TRUE(unittest::TestEnumWithDupValue_Parse("FOO2", &dup_value));
897 EXPECT_EQ(unittest::FOO2, dup_value);
898 EXPECT_FALSE(unittest::TestEnumWithDupValue_Parse("FOO", &dup_value));
899}
900
kenton@google.com80b1d622009-07-29 01:13:20 +0000901TEST(GeneratedEnumTest, GetEnumDescriptor) {
902 EXPECT_EQ(unittest::TestAllTypes::NestedEnum_descriptor(),
903 GetEnumDescriptor<unittest::TestAllTypes::NestedEnum>());
904 EXPECT_EQ(unittest::ForeignEnum_descriptor(),
905 GetEnumDescriptor<unittest::ForeignEnum>());
906 EXPECT_EQ(unittest::TestEnumWithDupValue_descriptor(),
907 GetEnumDescriptor<unittest::TestEnumWithDupValue>());
908 EXPECT_EQ(unittest::TestSparseEnum_descriptor(),
909 GetEnumDescriptor<unittest::TestSparseEnum>());
910}
911
kenton@google.comd37d46d2009-04-25 02:53:47 +0000912#endif // PROTOBUF_TEST_NO_DESCRIPTORS
913
temporal40ee5512008-07-10 02:12:20 +0000914// ===================================================================
915
kenton@google.comd37d46d2009-04-25 02:53:47 +0000916#ifndef PROTOBUF_TEST_NO_DESCRIPTORS
917
temporal40ee5512008-07-10 02:12:20 +0000918// Support code for testing services.
919class GeneratedServiceTest : public testing::Test {
920 protected:
921 class MockTestService : public unittest::TestService {
922 public:
923 MockTestService()
924 : called_(false),
925 method_(""),
926 controller_(NULL),
927 request_(NULL),
928 response_(NULL),
929 done_(NULL) {}
930
931 ~MockTestService() {}
932
933 void Reset() { called_ = false; }
934
935 // implements TestService ----------------------------------------
936
937 void Foo(RpcController* controller,
938 const unittest::FooRequest* request,
939 unittest::FooResponse* response,
940 Closure* done) {
941 ASSERT_FALSE(called_);
942 called_ = true;
943 method_ = "Foo";
944 controller_ = controller;
945 request_ = request;
946 response_ = response;
947 done_ = done;
948 }
949
950 void Bar(RpcController* controller,
951 const unittest::BarRequest* request,
952 unittest::BarResponse* response,
953 Closure* done) {
954 ASSERT_FALSE(called_);
955 called_ = true;
956 method_ = "Bar";
957 controller_ = controller;
958 request_ = request;
959 response_ = response;
960 done_ = done;
961 }
962
963 // ---------------------------------------------------------------
964
965 bool called_;
966 string method_;
967 RpcController* controller_;
968 const Message* request_;
969 Message* response_;
970 Closure* done_;
971 };
972
973 class MockRpcChannel : public RpcChannel {
974 public:
975 MockRpcChannel()
976 : called_(false),
977 method_(NULL),
978 controller_(NULL),
979 request_(NULL),
980 response_(NULL),
981 done_(NULL),
982 destroyed_(NULL) {}
983
984 ~MockRpcChannel() {
985 if (destroyed_ != NULL) *destroyed_ = true;
986 }
987
988 void Reset() { called_ = false; }
989
990 // implements TestService ----------------------------------------
991
992 void CallMethod(const MethodDescriptor* method,
993 RpcController* controller,
994 const Message* request,
995 Message* response,
996 Closure* done) {
997 ASSERT_FALSE(called_);
998 called_ = true;
999 method_ = method;
1000 controller_ = controller;
1001 request_ = request;
1002 response_ = response;
1003 done_ = done;
1004 }
1005
1006 // ---------------------------------------------------------------
1007
1008 bool called_;
1009 const MethodDescriptor* method_;
1010 RpcController* controller_;
1011 const Message* request_;
1012 Message* response_;
1013 Closure* done_;
1014 bool* destroyed_;
1015 };
1016
1017 class MockController : public RpcController {
1018 public:
1019 void Reset() {
1020 ADD_FAILURE() << "Reset() not expected during this test.";
1021 }
1022 bool Failed() const {
1023 ADD_FAILURE() << "Failed() not expected during this test.";
1024 return false;
1025 }
1026 string ErrorText() const {
1027 ADD_FAILURE() << "ErrorText() not expected during this test.";
1028 return "";
1029 }
1030 void StartCancel() {
1031 ADD_FAILURE() << "StartCancel() not expected during this test.";
1032 }
1033 void SetFailed(const string& reason) {
1034 ADD_FAILURE() << "SetFailed() not expected during this test.";
1035 }
1036 bool IsCanceled() const {
1037 ADD_FAILURE() << "IsCanceled() not expected during this test.";
1038 return false;
1039 }
1040 void NotifyOnCancel(Closure* callback) {
1041 ADD_FAILURE() << "NotifyOnCancel() not expected during this test.";
1042 }
1043 };
1044
1045 GeneratedServiceTest()
1046 : descriptor_(unittest::TestService::descriptor()),
1047 foo_(descriptor_->FindMethodByName("Foo")),
1048 bar_(descriptor_->FindMethodByName("Bar")),
1049 stub_(&mock_channel_),
1050 done_(NewPermanentCallback(&DoNothing)) {}
1051
1052 virtual void SetUp() {
1053 ASSERT_TRUE(foo_ != NULL);
1054 ASSERT_TRUE(bar_ != NULL);
1055 }
1056
1057 const ServiceDescriptor* descriptor_;
1058 const MethodDescriptor* foo_;
1059 const MethodDescriptor* bar_;
1060
1061 MockTestService mock_service_;
1062 MockController mock_controller_;
1063
1064 MockRpcChannel mock_channel_;
1065 unittest::TestService::Stub stub_;
1066
1067 // Just so we don't have to re-define these with every test.
1068 unittest::FooRequest foo_request_;
1069 unittest::FooResponse foo_response_;
1070 unittest::BarRequest bar_request_;
1071 unittest::BarResponse bar_response_;
1072 scoped_ptr<Closure> done_;
1073};
1074
1075TEST_F(GeneratedServiceTest, GetDescriptor) {
1076 // Test that GetDescriptor() works.
1077
1078 EXPECT_EQ(descriptor_, mock_service_.GetDescriptor());
1079}
1080
1081TEST_F(GeneratedServiceTest, GetChannel) {
1082 EXPECT_EQ(&mock_channel_, stub_.channel());
1083}
1084
1085TEST_F(GeneratedServiceTest, OwnsChannel) {
1086 MockRpcChannel* channel = new MockRpcChannel;
1087 bool destroyed = false;
1088 channel->destroyed_ = &destroyed;
1089
1090 {
1091 unittest::TestService::Stub owning_stub(channel,
1092 Service::STUB_OWNS_CHANNEL);
1093 EXPECT_FALSE(destroyed);
1094 }
1095
1096 EXPECT_TRUE(destroyed);
1097}
1098
1099TEST_F(GeneratedServiceTest, CallMethod) {
1100 // Test that CallMethod() works.
1101
1102 // Call Foo() via CallMethod().
1103 mock_service_.CallMethod(foo_, &mock_controller_,
1104 &foo_request_, &foo_response_, done_.get());
1105
1106 ASSERT_TRUE(mock_service_.called_);
1107
1108 EXPECT_EQ("Foo" , mock_service_.method_ );
1109 EXPECT_EQ(&mock_controller_, mock_service_.controller_);
1110 EXPECT_EQ(&foo_request_ , mock_service_.request_ );
1111 EXPECT_EQ(&foo_response_ , mock_service_.response_ );
1112 EXPECT_EQ(done_.get() , mock_service_.done_ );
1113
1114 // Try again, but call Bar() instead.
1115 mock_service_.Reset();
1116 mock_service_.CallMethod(bar_, &mock_controller_,
1117 &bar_request_, &bar_response_, done_.get());
1118
1119 ASSERT_TRUE(mock_service_.called_);
1120 EXPECT_EQ("Bar", mock_service_.method_);
1121}
1122
1123TEST_F(GeneratedServiceTest, CallMethodTypeFailure) {
1124 // Verify death if we call Foo() with Bar's message types.
1125
1126#ifdef GTEST_HAS_DEATH_TEST // death tests do not work on Windows yet
1127 EXPECT_DEBUG_DEATH(
1128 mock_service_.CallMethod(foo_, &mock_controller_,
1129 &foo_request_, &bar_response_, done_.get()),
1130 "dynamic_cast");
1131
1132 mock_service_.Reset();
1133 EXPECT_DEBUG_DEATH(
1134 mock_service_.CallMethod(foo_, &mock_controller_,
1135 &bar_request_, &foo_response_, done_.get()),
1136 "dynamic_cast");
1137#endif // GTEST_HAS_DEATH_TEST
1138}
1139
1140TEST_F(GeneratedServiceTest, GetPrototypes) {
1141 // Test Get{Request,Response}Prototype() methods.
1142
1143 EXPECT_EQ(&unittest::FooRequest::default_instance(),
1144 &mock_service_.GetRequestPrototype(foo_));
1145 EXPECT_EQ(&unittest::BarRequest::default_instance(),
1146 &mock_service_.GetRequestPrototype(bar_));
1147
1148 EXPECT_EQ(&unittest::FooResponse::default_instance(),
1149 &mock_service_.GetResponsePrototype(foo_));
1150 EXPECT_EQ(&unittest::BarResponse::default_instance(),
1151 &mock_service_.GetResponsePrototype(bar_));
1152}
1153
1154TEST_F(GeneratedServiceTest, Stub) {
1155 // Test that the stub class works.
1156
1157 // Call Foo() via the stub.
1158 stub_.Foo(&mock_controller_, &foo_request_, &foo_response_, done_.get());
1159
1160 ASSERT_TRUE(mock_channel_.called_);
1161
1162 EXPECT_EQ(foo_ , mock_channel_.method_ );
1163 EXPECT_EQ(&mock_controller_, mock_channel_.controller_);
1164 EXPECT_EQ(&foo_request_ , mock_channel_.request_ );
1165 EXPECT_EQ(&foo_response_ , mock_channel_.response_ );
1166 EXPECT_EQ(done_.get() , mock_channel_.done_ );
1167
1168 // Call Bar() via the stub.
1169 mock_channel_.Reset();
1170 stub_.Bar(&mock_controller_, &bar_request_, &bar_response_, done_.get());
1171
1172 ASSERT_TRUE(mock_channel_.called_);
1173 EXPECT_EQ(bar_, mock_channel_.method_);
1174}
1175
1176TEST_F(GeneratedServiceTest, NotImplemented) {
1177 // Test that failing to implement a method of a service causes it to fail
1178 // with a "not implemented" error message.
1179
1180 // A service which doesn't implement any methods.
1181 class UnimplementedService : public unittest::TestService {
1182 public:
1183 UnimplementedService() {}
1184 };
1185
1186 UnimplementedService unimplemented_service;
1187
1188 // And a controller which expects to get a "not implemented" error.
1189 class ExpectUnimplementedController : public MockController {
1190 public:
1191 ExpectUnimplementedController() : called_(false) {}
1192
1193 void SetFailed(const string& reason) {
1194 EXPECT_FALSE(called_);
1195 called_ = true;
1196 EXPECT_EQ("Method Foo() not implemented.", reason);
1197 }
1198
1199 bool called_;
1200 };
1201
1202 ExpectUnimplementedController controller;
1203
1204 // Call Foo.
1205 unimplemented_service.Foo(&controller, &foo_request_, &foo_response_,
1206 done_.get());
1207
1208 EXPECT_TRUE(controller.called_);
1209}
1210
kenton@google.comfccb1462009-12-18 02:11:36 +00001211} // namespace cpp_unittest
1212} // namespace cpp
1213} // namespace compiler
1214
1215namespace no_generic_services_test {
1216 // Verify that no class called "TestService" was defined in
1217 // unittest_no_generic_services.pb.h by defining a different type by the same
1218 // name. If such a service was generated, this will not compile.
1219 struct TestService {
1220 int i;
1221 };
1222}
1223
1224namespace compiler {
1225namespace cpp {
1226namespace cpp_unittest {
1227
1228TEST_F(GeneratedServiceTest, NoGenericServices) {
1229 // Verify that non-services in unittest_no_generic_services.proto were
1230 // generated.
1231 no_generic_services_test::TestMessage message;
1232 message.set_a(1);
1233 message.SetExtension(no_generic_services_test::test_extension, 123);
1234 no_generic_services_test::TestEnum e = no_generic_services_test::FOO;
1235 EXPECT_EQ(e, 1);
1236
1237 // Verify that a ServiceDescriptor is generated for the service even if the
1238 // class itself is not.
1239 const FileDescriptor* file =
1240 no_generic_services_test::TestMessage::descriptor()->file();
1241
1242 ASSERT_EQ(1, file->service_count());
1243 EXPECT_EQ("TestService", file->service(0)->name());
1244 ASSERT_EQ(1, file->service(0)->method_count());
1245 EXPECT_EQ("Foo", file->service(0)->method(0)->name());
1246}
1247
kenton@google.comd37d46d2009-04-25 02:53:47 +00001248#endif // !PROTOBUF_TEST_NO_DESCRIPTORS
1249
1250// ===================================================================
1251
1252// This test must run last. It verifies that descriptors were or were not
1253// initialized depending on whether PROTOBUF_TEST_NO_DESCRIPTORS was defined.
1254// When this is defined, we skip all tests which are expected to trigger
1255// descriptor initialization. This verifies that everything else still works
1256// if descriptors are not initialized.
1257TEST(DescriptorInitializationTest, Initialized) {
1258#ifdef PROTOBUF_TEST_NO_DESCRIPTORS
1259 bool should_have_descriptors = false;
1260#else
1261 bool should_have_descriptors = true;
1262#endif
1263
1264 EXPECT_EQ(should_have_descriptors,
1265 DescriptorPool::generated_pool()->InternalIsFileLoaded(
1266 "google/protobuf/unittest.proto"));
1267}
1268
kenton@google.coma2a32c22008-11-14 17:29:32 +00001269} // namespace cpp_unittest
temporal40ee5512008-07-10 02:12:20 +00001270
1271} // namespace cpp
1272} // namespace compiler
1273} // namespace protobuf
1274} // namespace google