conformance_test.cc 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534
  1. // Protocol Buffers - Google's data interchange format
  2. // Copyright 2008 Google Inc. All rights reserved.
  3. // https://developers.google.com/protocol-buffers/
  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. #include <stdarg.h>
  31. #include <string>
  32. #include "conformance.pb.h"
  33. #include "conformance_test.h"
  34. #include <google/protobuf/stubs/common.h>
  35. #include <google/protobuf/stubs/stringprintf.h>
  36. #include <google/protobuf/text_format.h>
  37. #include <google/protobuf/util/json_util.h>
  38. #include <google/protobuf/util/message_differencer.h>
  39. #include <google/protobuf/util/type_resolver_util.h>
  40. #include <google/protobuf/wire_format_lite.h>
  41. using conformance::ConformanceRequest;
  42. using conformance::ConformanceResponse;
  43. using conformance::TestAllTypes;
  44. using conformance::WireFormat;
  45. using google::protobuf::Descriptor;
  46. using google::protobuf::FieldDescriptor;
  47. using google::protobuf::internal::WireFormatLite;
  48. using google::protobuf::TextFormat;
  49. using google::protobuf::util::JsonToBinaryString;
  50. using google::protobuf::util::MessageDifferencer;
  51. using google::protobuf::util::NewTypeResolverForDescriptorPool;
  52. using google::protobuf::util::Status;
  53. using std::string;
  54. namespace {
  55. static const char kTypeUrlPrefix[] = "type.googleapis.com";
  56. static string GetTypeUrl(const Descriptor* message) {
  57. return string(kTypeUrlPrefix) + "/" + message->full_name();
  58. }
  59. /* Routines for building arbitrary protos *************************************/
  60. // We would use CodedOutputStream except that we want more freedom to build
  61. // arbitrary protos (even invalid ones).
  62. const string empty;
  63. string cat(const string& a, const string& b,
  64. const string& c = empty,
  65. const string& d = empty,
  66. const string& e = empty,
  67. const string& f = empty,
  68. const string& g = empty,
  69. const string& h = empty,
  70. const string& i = empty,
  71. const string& j = empty,
  72. const string& k = empty,
  73. const string& l = empty) {
  74. string ret;
  75. ret.reserve(a.size() + b.size() + c.size() + d.size() + e.size() + f.size() +
  76. g.size() + h.size() + i.size() + j.size() + k.size() + l.size());
  77. ret.append(a);
  78. ret.append(b);
  79. ret.append(c);
  80. ret.append(d);
  81. ret.append(e);
  82. ret.append(f);
  83. ret.append(g);
  84. ret.append(h);
  85. ret.append(i);
  86. ret.append(j);
  87. ret.append(k);
  88. ret.append(l);
  89. return ret;
  90. }
  91. // The maximum number of bytes that it takes to encode a 64-bit varint.
  92. #define VARINT_MAX_LEN 10
  93. size_t vencode64(uint64_t val, char *buf) {
  94. if (val == 0) { buf[0] = 0; return 1; }
  95. size_t i = 0;
  96. while (val) {
  97. uint8_t byte = val & 0x7fU;
  98. val >>= 7;
  99. if (val) byte |= 0x80U;
  100. buf[i++] = byte;
  101. }
  102. return i;
  103. }
  104. string varint(uint64_t x) {
  105. char buf[VARINT_MAX_LEN];
  106. size_t len = vencode64(x, buf);
  107. return string(buf, len);
  108. }
  109. // TODO: proper byte-swapping for big-endian machines.
  110. string fixed32(void *data) { return string(static_cast<char*>(data), 4); }
  111. string fixed64(void *data) { return string(static_cast<char*>(data), 8); }
  112. string delim(const string& buf) { return cat(varint(buf.size()), buf); }
  113. string uint32(uint32_t u32) { return fixed32(&u32); }
  114. string uint64(uint64_t u64) { return fixed64(&u64); }
  115. string flt(float f) { return fixed32(&f); }
  116. string dbl(double d) { return fixed64(&d); }
  117. string zz32(int32_t x) { return varint(WireFormatLite::ZigZagEncode32(x)); }
  118. string zz64(int64_t x) { return varint(WireFormatLite::ZigZagEncode64(x)); }
  119. string tag(uint32_t fieldnum, char wire_type) {
  120. return varint((fieldnum << 3) | wire_type);
  121. }
  122. string submsg(uint32_t fn, const string& buf) {
  123. return cat( tag(fn, WireFormatLite::WIRETYPE_LENGTH_DELIMITED), delim(buf) );
  124. }
  125. #define UNKNOWN_FIELD 666
  126. uint32_t GetFieldNumberForType(FieldDescriptor::Type type, bool repeated) {
  127. const Descriptor* d = TestAllTypes().GetDescriptor();
  128. for (int i = 0; i < d->field_count(); i++) {
  129. const FieldDescriptor* f = d->field(i);
  130. if (f->type() == type && f->is_repeated() == repeated) {
  131. return f->number();
  132. }
  133. }
  134. GOOGLE_LOG(FATAL) << "Couldn't find field with type " << (int)type;
  135. return 0;
  136. }
  137. string UpperCase(string str) {
  138. for (int i = 0; i < str.size(); i++) {
  139. str[i] = toupper(str[i]);
  140. }
  141. return str;
  142. }
  143. } // anonymous namespace
  144. namespace google {
  145. namespace protobuf {
  146. void ConformanceTestSuite::ReportSuccess(const string& test_name) {
  147. if (expected_to_fail_.erase(test_name) != 0) {
  148. StringAppendF(&output_,
  149. "ERROR: test %s is in the failure list, but test succeeded. "
  150. "Remove it from the failure list.\n",
  151. test_name.c_str());
  152. unexpected_succeeding_tests_.insert(test_name);
  153. }
  154. successes_++;
  155. }
  156. void ConformanceTestSuite::ReportFailure(const string& test_name,
  157. const ConformanceRequest& request,
  158. const ConformanceResponse& response,
  159. const char* fmt, ...) {
  160. if (expected_to_fail_.erase(test_name) == 1) {
  161. expected_failures_++;
  162. if (!verbose_)
  163. return;
  164. } else {
  165. StringAppendF(&output_, "ERROR, test=%s: ", test_name.c_str());
  166. unexpected_failing_tests_.insert(test_name);
  167. }
  168. va_list args;
  169. va_start(args, fmt);
  170. StringAppendV(&output_, fmt, args);
  171. va_end(args);
  172. StringAppendF(&output_, " request=%s, response=%s\n",
  173. request.ShortDebugString().c_str(),
  174. response.ShortDebugString().c_str());
  175. }
  176. void ConformanceTestSuite::ReportSkip(const string& test_name,
  177. const ConformanceRequest& request,
  178. const ConformanceResponse& response) {
  179. if (verbose_) {
  180. StringAppendF(&output_, "SKIPPED, test=%s request=%s, response=%s\n",
  181. test_name.c_str(), request.ShortDebugString().c_str(),
  182. response.ShortDebugString().c_str());
  183. }
  184. skipped_.insert(test_name);
  185. }
  186. void ConformanceTestSuite::RunTest(const string& test_name,
  187. const ConformanceRequest& request,
  188. ConformanceResponse* response) {
  189. if (test_names_.insert(test_name).second == false) {
  190. GOOGLE_LOG(FATAL) << "Duplicated test name: " << test_name;
  191. }
  192. string serialized_request;
  193. string serialized_response;
  194. request.SerializeToString(&serialized_request);
  195. runner_->RunTest(serialized_request, &serialized_response);
  196. if (!response->ParseFromString(serialized_response)) {
  197. response->Clear();
  198. response->set_runtime_error("response proto could not be parsed.");
  199. }
  200. if (verbose_) {
  201. StringAppendF(&output_, "conformance test: name=%s, request=%s, response=%s\n",
  202. test_name.c_str(),
  203. request.ShortDebugString().c_str(),
  204. response->ShortDebugString().c_str());
  205. }
  206. }
  207. void ConformanceTestSuite::RunValidInputTest(
  208. const string& test_name, const string& input, WireFormat input_format,
  209. const string& equivalent_text_format, WireFormat requested_output) {
  210. TestAllTypes reference_message;
  211. GOOGLE_CHECK(
  212. TextFormat::ParseFromString(equivalent_text_format, &reference_message));
  213. ConformanceRequest request;
  214. ConformanceResponse response;
  215. switch (input_format) {
  216. case conformance::PROTOBUF:
  217. request.set_protobuf_payload(input);
  218. break;
  219. case conformance::JSON:
  220. request.set_json_payload(input);
  221. break;
  222. case conformance::UNSPECIFIED:
  223. GOOGLE_LOG(FATAL) << "Unspecified input format";
  224. }
  225. request.set_requested_output_format(requested_output);
  226. RunTest(test_name, request, &response);
  227. TestAllTypes test_message;
  228. switch (response.result_case()) {
  229. case ConformanceResponse::kParseError:
  230. case ConformanceResponse::kRuntimeError:
  231. ReportFailure(test_name, request, response,
  232. "Failed to parse valid JSON input.");
  233. return;
  234. case ConformanceResponse::kSkipped:
  235. ReportSkip(test_name, request, response);
  236. return;
  237. case ConformanceResponse::kJsonPayload: {
  238. if (requested_output != conformance::JSON) {
  239. ReportFailure(
  240. test_name, request, response,
  241. "Test was asked for protobuf output but provided JSON instead.");
  242. return;
  243. }
  244. string binary_protobuf;
  245. Status status =
  246. JsonToBinaryString(type_resolver_.get(), type_url_,
  247. response.json_payload(), &binary_protobuf);
  248. if (!status.ok()) {
  249. ReportFailure(test_name, request, response,
  250. "JSON output we received from test was unparseable.");
  251. return;
  252. }
  253. GOOGLE_CHECK(test_message.ParseFromString(binary_protobuf));
  254. break;
  255. }
  256. case ConformanceResponse::kProtobufPayload: {
  257. if (requested_output != conformance::PROTOBUF) {
  258. ReportFailure(
  259. test_name, request, response,
  260. "Test was asked for JSON output but provided protobuf instead.");
  261. return;
  262. }
  263. if (!test_message.ParseFromString(response.protobuf_payload())) {
  264. ReportFailure(test_name, request, response,
  265. "Protobuf output we received from test was unparseable.");
  266. return;
  267. }
  268. break;
  269. }
  270. }
  271. MessageDifferencer differencer;
  272. string differences;
  273. differencer.ReportDifferencesToString(&differences);
  274. if (differencer.Equals(reference_message, test_message)) {
  275. ReportSuccess(test_name);
  276. } else {
  277. ReportFailure(test_name, request, response,
  278. "Output was not equivalent to reference message: %s.",
  279. differences.c_str());
  280. }
  281. }
  282. // Expect that this precise protobuf will cause a parse error.
  283. void ConformanceTestSuite::ExpectParseFailureForProto(
  284. const string& proto, const string& test_name) {
  285. ConformanceRequest request;
  286. ConformanceResponse response;
  287. request.set_protobuf_payload(proto);
  288. string effective_test_name = "ProtobufInput." + test_name;
  289. // We don't expect output, but if the program erroneously accepts the protobuf
  290. // we let it send its response as this. We must not leave it unspecified.
  291. request.set_requested_output_format(conformance::PROTOBUF);
  292. RunTest(effective_test_name, request, &response);
  293. if (response.result_case() == ConformanceResponse::kParseError) {
  294. ReportSuccess(effective_test_name);
  295. } else {
  296. ReportFailure(effective_test_name, request, response,
  297. "Should have failed to parse, but didn't.");
  298. }
  299. }
  300. // Expect that this protobuf will cause a parse error, even if it is followed
  301. // by valid protobuf data. We can try running this twice: once with this
  302. // data verbatim and once with this data followed by some valid data.
  303. //
  304. // TODO(haberman): implement the second of these.
  305. void ConformanceTestSuite::ExpectHardParseFailureForProto(
  306. const string& proto, const string& test_name) {
  307. return ExpectParseFailureForProto(proto, test_name);
  308. }
  309. void ConformanceTestSuite::RunValidJsonTest(
  310. const string& test_name, const string& input_json,
  311. const string& equivalent_text_format) {
  312. RunValidInputTest("JsonInput." + test_name + ".JsonOutput", input_json,
  313. conformance::JSON, equivalent_text_format,
  314. conformance::PROTOBUF);
  315. RunValidInputTest("JsonInput." + test_name + ".ProtobufOutput", input_json, conformance::JSON,
  316. equivalent_text_format, conformance::JSON);
  317. }
  318. void ConformanceTestSuite::TestPrematureEOFForType(FieldDescriptor::Type type) {
  319. // Incomplete values for each wire type.
  320. static const string incompletes[6] = {
  321. string("\x80"), // VARINT
  322. string("abcdefg"), // 64BIT
  323. string("\x80"), // DELIMITED (partial length)
  324. string(), // START_GROUP (no value required)
  325. string(), // END_GROUP (no value required)
  326. string("abc") // 32BIT
  327. };
  328. uint32_t fieldnum = GetFieldNumberForType(type, false);
  329. uint32_t rep_fieldnum = GetFieldNumberForType(type, true);
  330. WireFormatLite::WireType wire_type = WireFormatLite::WireTypeForFieldType(
  331. static_cast<WireFormatLite::FieldType>(type));
  332. const string& incomplete = incompletes[wire_type];
  333. const string type_name =
  334. UpperCase(string(".") + FieldDescriptor::TypeName(type));
  335. ExpectParseFailureForProto(
  336. tag(fieldnum, wire_type),
  337. "PrematureEofBeforeKnownNonRepeatedValue" + type_name);
  338. ExpectParseFailureForProto(
  339. tag(rep_fieldnum, wire_type),
  340. "PrematureEofBeforeKnownRepeatedValue" + type_name);
  341. ExpectParseFailureForProto(
  342. tag(UNKNOWN_FIELD, wire_type),
  343. "PrematureEofBeforeUnknownValue" + type_name);
  344. ExpectParseFailureForProto(
  345. cat( tag(fieldnum, wire_type), incomplete ),
  346. "PrematureEofInsideKnownNonRepeatedValue" + type_name);
  347. ExpectParseFailureForProto(
  348. cat( tag(rep_fieldnum, wire_type), incomplete ),
  349. "PrematureEofInsideKnownRepeatedValue" + type_name);
  350. ExpectParseFailureForProto(
  351. cat( tag(UNKNOWN_FIELD, wire_type), incomplete ),
  352. "PrematureEofInsideUnknownValue" + type_name);
  353. if (wire_type == WireFormatLite::WIRETYPE_LENGTH_DELIMITED) {
  354. ExpectParseFailureForProto(
  355. cat( tag(fieldnum, wire_type), varint(1) ),
  356. "PrematureEofInDelimitedDataForKnownNonRepeatedValue" + type_name);
  357. ExpectParseFailureForProto(
  358. cat( tag(rep_fieldnum, wire_type), varint(1) ),
  359. "PrematureEofInDelimitedDataForKnownRepeatedValue" + type_name);
  360. // EOF in the middle of delimited data for unknown value.
  361. ExpectParseFailureForProto(
  362. cat( tag(UNKNOWN_FIELD, wire_type), varint(1) ),
  363. "PrematureEofInDelimitedDataForUnknownValue" + type_name);
  364. if (type == FieldDescriptor::TYPE_MESSAGE) {
  365. // Submessage ends in the middle of a value.
  366. string incomplete_submsg =
  367. cat( tag(WireFormatLite::TYPE_INT32, WireFormatLite::WIRETYPE_VARINT),
  368. incompletes[WireFormatLite::WIRETYPE_VARINT] );
  369. ExpectHardParseFailureForProto(
  370. cat( tag(fieldnum, WireFormatLite::WIRETYPE_LENGTH_DELIMITED),
  371. varint(incomplete_submsg.size()),
  372. incomplete_submsg ),
  373. "PrematureEofInSubmessageValue" + type_name);
  374. }
  375. } else if (type != FieldDescriptor::TYPE_GROUP) {
  376. // Non-delimited, non-group: eligible for packing.
  377. // Packed region ends in the middle of a value.
  378. ExpectHardParseFailureForProto(
  379. cat( tag(rep_fieldnum, WireFormatLite::WIRETYPE_LENGTH_DELIMITED),
  380. varint(incomplete.size()),
  381. incomplete ),
  382. "PrematureEofInPackedFieldValue" + type_name);
  383. // EOF in the middle of packed region.
  384. ExpectParseFailureForProto(
  385. cat( tag(rep_fieldnum, WireFormatLite::WIRETYPE_LENGTH_DELIMITED),
  386. varint(1) ),
  387. "PrematureEofInPackedField" + type_name);
  388. }
  389. }
  390. void ConformanceTestSuite::SetFailureList(const vector<string>& failure_list) {
  391. expected_to_fail_.clear();
  392. std::copy(failure_list.begin(), failure_list.end(),
  393. std::inserter(expected_to_fail_, expected_to_fail_.end()));
  394. }
  395. bool ConformanceTestSuite::CheckSetEmpty(const set<string>& set_to_check,
  396. const char* msg) {
  397. if (set_to_check.empty()) {
  398. return true;
  399. } else {
  400. StringAppendF(&output_, "\n");
  401. StringAppendF(&output_, "%s:\n", msg);
  402. for (set<string>::const_iterator iter = set_to_check.begin();
  403. iter != set_to_check.end(); ++iter) {
  404. StringAppendF(&output_, " %s\n", iter->c_str());
  405. }
  406. StringAppendF(&output_, "\n");
  407. return false;
  408. }
  409. }
  410. bool ConformanceTestSuite::RunSuite(ConformanceTestRunner* runner,
  411. std::string* output) {
  412. runner_ = runner;
  413. successes_ = 0;
  414. expected_failures_ = 0;
  415. skipped_.clear();
  416. test_names_.clear();
  417. unexpected_failing_tests_.clear();
  418. unexpected_succeeding_tests_.clear();
  419. type_resolver_.reset(NewTypeResolverForDescriptorPool(
  420. kTypeUrlPrefix, DescriptorPool::generated_pool()));
  421. type_url_ = GetTypeUrl(TestAllTypes::descriptor());
  422. output_ = "\nCONFORMANCE TEST BEGIN ====================================\n\n";
  423. for (int i = 1; i <= FieldDescriptor::MAX_TYPE; i++) {
  424. if (i == FieldDescriptor::TYPE_GROUP) continue;
  425. TestPrematureEOFForType(static_cast<FieldDescriptor::Type>(i));
  426. }
  427. RunValidJsonTest("HelloWorld", "{\"optionalString\":\"Hello, World!\"}",
  428. "optional_string: 'Hello, World!'");
  429. bool ok =
  430. CheckSetEmpty(expected_to_fail_,
  431. "These tests were listed in the failure list, but they "
  432. "don't exist. Remove them from the failure list") &&
  433. CheckSetEmpty(unexpected_failing_tests_,
  434. "These tests failed. If they can't be fixed right now, "
  435. "you can add them to the failure list so the overall "
  436. "suite can succeed") &&
  437. CheckSetEmpty(unexpected_succeeding_tests_,
  438. "These tests succeeded, even though they were listed in "
  439. "the failure list. Remove them from the failure list");
  440. CheckSetEmpty(skipped_,
  441. "These tests were skipped (probably because support for some "
  442. "features is not implemented)");
  443. StringAppendF(&output_,
  444. "CONFORMANCE SUITE %s: %d successes, %d skipped, "
  445. "%d expected failures, %d unexpected failures.\n",
  446. ok ? "PASSED" : "FAILED", successes_, skipped_.size(),
  447. expected_failures_, unexpected_failing_tests_.size());
  448. StringAppendF(&output_, "\n");
  449. output->assign(output_);
  450. return ok;
  451. }
  452. } // namespace protobuf
  453. } // namespace google