conformance_test.cc 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  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/wire_format_lite.h>
  37. using conformance::ConformanceRequest;
  38. using conformance::ConformanceResponse;
  39. using conformance::TestAllTypes;
  40. using google::protobuf::Descriptor;
  41. using google::protobuf::FieldDescriptor;
  42. using google::protobuf::internal::WireFormatLite;
  43. using std::string;
  44. namespace {
  45. /* Routines for building arbitrary protos *************************************/
  46. // We would use CodedOutputStream except that we want more freedom to build
  47. // arbitrary protos (even invalid ones).
  48. const string empty;
  49. string cat(const string& a, const string& b,
  50. const string& c = empty,
  51. const string& d = empty,
  52. const string& e = empty,
  53. const string& f = empty,
  54. const string& g = empty,
  55. const string& h = empty,
  56. const string& i = empty,
  57. const string& j = empty,
  58. const string& k = empty,
  59. const string& l = empty) {
  60. string ret;
  61. ret.reserve(a.size() + b.size() + c.size() + d.size() + e.size() + f.size() +
  62. g.size() + h.size() + i.size() + j.size() + k.size() + l.size());
  63. ret.append(a);
  64. ret.append(b);
  65. ret.append(c);
  66. ret.append(d);
  67. ret.append(e);
  68. ret.append(f);
  69. ret.append(g);
  70. ret.append(h);
  71. ret.append(i);
  72. ret.append(j);
  73. ret.append(k);
  74. ret.append(l);
  75. return ret;
  76. }
  77. // The maximum number of bytes that it takes to encode a 64-bit varint.
  78. #define VARINT_MAX_LEN 10
  79. size_t vencode64(uint64_t val, char *buf) {
  80. if (val == 0) { buf[0] = 0; return 1; }
  81. size_t i = 0;
  82. while (val) {
  83. uint8_t byte = val & 0x7fU;
  84. val >>= 7;
  85. if (val) byte |= 0x80U;
  86. buf[i++] = byte;
  87. }
  88. return i;
  89. }
  90. string varint(uint64_t x) {
  91. char buf[VARINT_MAX_LEN];
  92. size_t len = vencode64(x, buf);
  93. return string(buf, len);
  94. }
  95. // TODO: proper byte-swapping for big-endian machines.
  96. string fixed32(void *data) { return string(static_cast<char*>(data), 4); }
  97. string fixed64(void *data) { return string(static_cast<char*>(data), 8); }
  98. string delim(const string& buf) { return cat(varint(buf.size()), buf); }
  99. string uint32(uint32_t u32) { return fixed32(&u32); }
  100. string uint64(uint64_t u64) { return fixed64(&u64); }
  101. string flt(float f) { return fixed32(&f); }
  102. string dbl(double d) { return fixed64(&d); }
  103. string zz32(int32_t x) { return varint(WireFormatLite::ZigZagEncode32(x)); }
  104. string zz64(int64_t x) { return varint(WireFormatLite::ZigZagEncode64(x)); }
  105. string tag(uint32_t fieldnum, char wire_type) {
  106. return varint((fieldnum << 3) | wire_type);
  107. }
  108. string submsg(uint32_t fn, const string& buf) {
  109. return cat( tag(fn, WireFormatLite::WIRETYPE_LENGTH_DELIMITED), delim(buf) );
  110. }
  111. #define UNKNOWN_FIELD 666
  112. uint32_t GetFieldNumberForType(FieldDescriptor::Type type, bool repeated) {
  113. const Descriptor* d = TestAllTypes().GetDescriptor();
  114. for (int i = 0; i < d->field_count(); i++) {
  115. const FieldDescriptor* f = d->field(i);
  116. if (f->type() == type && f->is_repeated() == repeated) {
  117. return f->number();
  118. }
  119. }
  120. GOOGLE_LOG(FATAL) << "Couldn't find field with type " << (int)type;
  121. return 0;
  122. }
  123. string UpperCase(string str) {
  124. for (int i = 0; i < str.size(); i++) {
  125. str[i] = toupper(str[i]);
  126. }
  127. return str;
  128. }
  129. } // anonymous namespace
  130. namespace google {
  131. namespace protobuf {
  132. void ConformanceTestSuite::ReportSuccess(const string& test_name) {
  133. if (expected_to_fail_.erase(test_name) != 0) {
  134. StringAppendF(&output_,
  135. "ERROR: test %s is in the failure list, but test succeeded. "
  136. "Remove it from the failure list.\n",
  137. test_name.c_str());
  138. unexpected_succeeding_tests_.insert(test_name);
  139. }
  140. successes_++;
  141. }
  142. void ConformanceTestSuite::ReportFailure(const string& test_name,
  143. const char* fmt, ...) {
  144. if (expected_to_fail_.erase(test_name) == 1) {
  145. StringAppendF(&output_, "FAILED AS EXPECTED, test=%s: ", test_name.c_str());
  146. } else {
  147. StringAppendF(&output_, "ERROR, test=%s: ", test_name.c_str());
  148. unexpected_failing_tests_.insert(test_name);
  149. }
  150. va_list args;
  151. va_start(args, fmt);
  152. StringAppendV(&output_, fmt, args);
  153. va_end(args);
  154. failures_++;
  155. }
  156. void ConformanceTestSuite::RunTest(const string& test_name,
  157. const ConformanceRequest& request,
  158. ConformanceResponse* response) {
  159. if (test_names_.insert(test_name).second == false) {
  160. GOOGLE_LOG(FATAL) << "Duplicated test name: " << test_name;
  161. }
  162. string serialized_request;
  163. string serialized_response;
  164. request.SerializeToString(&serialized_request);
  165. runner_->RunTest(serialized_request, &serialized_response);
  166. if (!response->ParseFromString(serialized_response)) {
  167. response->Clear();
  168. response->set_runtime_error("response proto could not be parsed.");
  169. }
  170. if (verbose_) {
  171. StringAppendF(&output_, "conformance test: name=%s, request=%s, response=%s\n",
  172. test_name.c_str(),
  173. request.ShortDebugString().c_str(),
  174. response->ShortDebugString().c_str());
  175. }
  176. }
  177. // Expect that this precise protobuf will cause a parse error.
  178. void ConformanceTestSuite::ExpectParseFailureForProto(
  179. const string& proto, const string& test_name) {
  180. ConformanceRequest request;
  181. ConformanceResponse response;
  182. request.set_protobuf_payload(proto);
  183. // We don't expect output, but if the program erroneously accepts the protobuf
  184. // we let it send its response as this. We must not leave it unspecified.
  185. request.set_requested_output(ConformanceRequest::PROTOBUF);
  186. RunTest(test_name, request, &response);
  187. if (response.result_case() == ConformanceResponse::kParseError) {
  188. ReportSuccess(test_name);
  189. } else {
  190. ReportFailure(test_name,
  191. "Should have failed to parse, but didn't. Request: %s, "
  192. "response: %s\n",
  193. request.ShortDebugString().c_str(),
  194. response.ShortDebugString().c_str());
  195. }
  196. }
  197. // Expect that this protobuf will cause a parse error, even if it is followed
  198. // by valid protobuf data. We can try running this twice: once with this
  199. // data verbatim and once with this data followed by some valid data.
  200. //
  201. // TODO(haberman): implement the second of these.
  202. void ConformanceTestSuite::ExpectHardParseFailureForProto(
  203. const string& proto, const string& test_name) {
  204. return ExpectParseFailureForProto(proto, test_name);
  205. }
  206. void ConformanceTestSuite::TestPrematureEOFForType(FieldDescriptor::Type type) {
  207. // Incomplete values for each wire type.
  208. static const string incompletes[6] = {
  209. string("\x80"), // VARINT
  210. string("abcdefg"), // 64BIT
  211. string("\x80"), // DELIMITED (partial length)
  212. string(), // START_GROUP (no value required)
  213. string(), // END_GROUP (no value required)
  214. string("abc") // 32BIT
  215. };
  216. uint32_t fieldnum = GetFieldNumberForType(type, false);
  217. uint32_t rep_fieldnum = GetFieldNumberForType(type, true);
  218. WireFormatLite::WireType wire_type = WireFormatLite::WireTypeForFieldType(
  219. static_cast<WireFormatLite::FieldType>(type));
  220. const string& incomplete = incompletes[wire_type];
  221. const string type_name =
  222. UpperCase(string(".") + FieldDescriptor::TypeName(type));
  223. ExpectParseFailureForProto(
  224. tag(fieldnum, wire_type),
  225. "PrematureEofBeforeKnownNonRepeatedValue" + type_name);
  226. ExpectParseFailureForProto(
  227. tag(rep_fieldnum, wire_type),
  228. "PrematureEofBeforeKnownRepeatedValue" + type_name);
  229. ExpectParseFailureForProto(
  230. tag(UNKNOWN_FIELD, wire_type),
  231. "PrematureEofBeforeUnknownValue" + type_name);
  232. ExpectParseFailureForProto(
  233. cat( tag(fieldnum, wire_type), incomplete ),
  234. "PrematureEofInsideKnownNonRepeatedValue" + type_name);
  235. ExpectParseFailureForProto(
  236. cat( tag(rep_fieldnum, wire_type), incomplete ),
  237. "PrematureEofInsideKnownRepeatedValue" + type_name);
  238. ExpectParseFailureForProto(
  239. cat( tag(UNKNOWN_FIELD, wire_type), incomplete ),
  240. "PrematureEofInsideUnknownValue" + type_name);
  241. if (wire_type == WireFormatLite::WIRETYPE_LENGTH_DELIMITED) {
  242. ExpectParseFailureForProto(
  243. cat( tag(fieldnum, wire_type), varint(1) ),
  244. "PrematureEofInDelimitedDataForKnownNonRepeatedValue" + type_name);
  245. ExpectParseFailureForProto(
  246. cat( tag(rep_fieldnum, wire_type), varint(1) ),
  247. "PrematureEofInDelimitedDataForKnownRepeatedValue" + type_name);
  248. // EOF in the middle of delimited data for unknown value.
  249. ExpectParseFailureForProto(
  250. cat( tag(UNKNOWN_FIELD, wire_type), varint(1) ),
  251. "PrematureEofInDelimitedDataForUnknownValue" + type_name);
  252. if (type == FieldDescriptor::TYPE_MESSAGE) {
  253. // Submessage ends in the middle of a value.
  254. string incomplete_submsg =
  255. cat( tag(WireFormatLite::TYPE_INT32, WireFormatLite::WIRETYPE_VARINT),
  256. incompletes[WireFormatLite::WIRETYPE_VARINT] );
  257. ExpectHardParseFailureForProto(
  258. cat( tag(fieldnum, WireFormatLite::WIRETYPE_LENGTH_DELIMITED),
  259. varint(incomplete_submsg.size()),
  260. incomplete_submsg ),
  261. "PrematureEofInSubmessageValue" + type_name);
  262. }
  263. } else if (type != FieldDescriptor::TYPE_GROUP) {
  264. // Non-delimited, non-group: eligible for packing.
  265. // Packed region ends in the middle of a value.
  266. ExpectHardParseFailureForProto(
  267. cat( tag(rep_fieldnum, WireFormatLite::WIRETYPE_LENGTH_DELIMITED),
  268. varint(incomplete.size()),
  269. incomplete ),
  270. "PrematureEofInPackedFieldValue" + type_name);
  271. // EOF in the middle of packed region.
  272. ExpectParseFailureForProto(
  273. cat( tag(rep_fieldnum, WireFormatLite::WIRETYPE_LENGTH_DELIMITED),
  274. varint(1) ),
  275. "PrematureEofInPackedField" + type_name);
  276. }
  277. }
  278. void ConformanceTestSuite::SetFailureList(const vector<string>& failure_list) {
  279. expected_to_fail_.clear();
  280. std::copy(failure_list.begin(), failure_list.end(),
  281. std::inserter(expected_to_fail_, expected_to_fail_.end()));
  282. }
  283. bool ConformanceTestSuite::CheckSetEmpty(const set<string>& set_to_check,
  284. const char* msg) {
  285. if (set_to_check.empty()) {
  286. return true;
  287. } else {
  288. StringAppendF(&output_, "\n");
  289. StringAppendF(&output_, "ERROR: %s:\n", msg);
  290. for (set<string>::const_iterator iter = set_to_check.begin();
  291. iter != set_to_check.end(); ++iter) {
  292. StringAppendF(&output_, "%s\n", iter->c_str());
  293. }
  294. return false;
  295. }
  296. }
  297. bool ConformanceTestSuite::RunSuite(ConformanceTestRunner* runner,
  298. std::string* output) {
  299. runner_ = runner;
  300. output_.clear();
  301. successes_ = 0;
  302. failures_ = 0;
  303. test_names_.clear();
  304. unexpected_failing_tests_.clear();
  305. unexpected_succeeding_tests_.clear();
  306. for (int i = 1; i <= FieldDescriptor::MAX_TYPE; i++) {
  307. if (i == FieldDescriptor::TYPE_GROUP) continue;
  308. TestPrematureEOFForType(static_cast<FieldDescriptor::Type>(i));
  309. }
  310. StringAppendF(&output_, "\n");
  311. StringAppendF(&output_,
  312. "CONFORMANCE SUITE FINISHED: completed %d tests, %d successes, "
  313. "%d failures.\n",
  314. successes_ + failures_, successes_, failures_);
  315. bool ok =
  316. CheckSetEmpty(expected_to_fail_,
  317. "These tests were listed in the failure list, but they "
  318. "don't exist. Remove them from the failure list") &&
  319. CheckSetEmpty(unexpected_failing_tests_,
  320. "These tests failed. If they can't be fixed right now, "
  321. "you can add them to the failure list so the overall "
  322. "suite can succeed") &&
  323. CheckSetEmpty(unexpected_succeeding_tests_,
  324. "These tests succeeded, even though they were listed in "
  325. "the failure list. Remove them from the failure list");
  326. output->assign(output_);
  327. return ok;
  328. }
  329. } // namespace protobuf
  330. } // namespace google