conformance_test.cc 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  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 "conformance_test.h"
  31. #include <stdarg.h>
  32. #include <fstream>
  33. #include <set>
  34. #include <string>
  35. #include <google/protobuf/stubs/stringprintf.h>
  36. #include <google/protobuf/message.h>
  37. #include <google/protobuf/text_format.h>
  38. #include <google/protobuf/util/field_comparator.h>
  39. #include <google/protobuf/util/json_util.h>
  40. #include <google/protobuf/util/message_differencer.h>
  41. #include "conformance.pb.h"
  42. using conformance::ConformanceRequest;
  43. using conformance::ConformanceResponse;
  44. using conformance::WireFormat;
  45. using google::protobuf::TextFormat;
  46. using google::protobuf::util::DefaultFieldComparator;
  47. using google::protobuf::util::MessageDifferencer;
  48. using std::string;
  49. namespace {
  50. static string ToOctString(const string& binary_string) {
  51. string oct_string;
  52. for (size_t i = 0; i < binary_string.size(); i++) {
  53. uint8_t c = binary_string.at(i);
  54. uint8_t high = c / 64;
  55. uint8_t mid = (c % 64) / 8;
  56. uint8_t low = c % 8;
  57. oct_string.push_back('\\');
  58. oct_string.push_back('0' + high);
  59. oct_string.push_back('0' + mid);
  60. oct_string.push_back('0' + low);
  61. }
  62. return oct_string;
  63. }
  64. } // namespace
  65. namespace google {
  66. namespace protobuf {
  67. ConformanceTestSuite::ConformanceRequestSetting::ConformanceRequestSetting(
  68. ConformanceLevel level,
  69. conformance::WireFormat input_format,
  70. conformance::WireFormat output_format,
  71. conformance::TestCategory test_category,
  72. const Message& prototype_message,
  73. const string& test_name, const string& input)
  74. : level_(level),
  75. input_format_(input_format),
  76. output_format_(output_format),
  77. prototype_message_(prototype_message),
  78. prototype_message_for_compare_(prototype_message.New()),
  79. test_name_(test_name) {
  80. switch (input_format) {
  81. case conformance::PROTOBUF: {
  82. request_.set_protobuf_payload(input);
  83. break;
  84. }
  85. case conformance::JSON: {
  86. request_.set_json_payload(input);
  87. break;
  88. }
  89. case conformance::JSPB: {
  90. request_.set_jspb_payload(input);
  91. break;
  92. }
  93. case conformance::TEXT_FORMAT: {
  94. request_.set_text_payload(input);
  95. break;
  96. }
  97. default:
  98. GOOGLE_LOG(FATAL) << "Unspecified input format";
  99. }
  100. request_.set_test_category(test_category);
  101. request_.set_message_type(prototype_message.GetDescriptor()->full_name());
  102. request_.set_requested_output_format(output_format);
  103. }
  104. std::unique_ptr<Message>
  105. ConformanceTestSuite::ConformanceRequestSetting::NewTestMessage() const {
  106. return std::unique_ptr<Message>(prototype_message_for_compare_->New());
  107. }
  108. string ConformanceTestSuite::ConformanceRequestSetting::
  109. GetTestName() const {
  110. string rname =
  111. prototype_message_.GetDescriptor()->file()->syntax() ==
  112. FileDescriptor::SYNTAX_PROTO3 ? "Proto3" : "Proto2";
  113. return StrCat(ConformanceLevelToString(level_), ".", rname, ".",
  114. InputFormatString(input_format_), ".", test_name_, ".",
  115. OutputFormatString(output_format_));
  116. }
  117. string ConformanceTestSuite::ConformanceRequestSetting::
  118. ConformanceLevelToString(
  119. ConformanceLevel level) const {
  120. switch (level) {
  121. case REQUIRED: return "Required";
  122. case RECOMMENDED: return "Recommended";
  123. }
  124. GOOGLE_LOG(FATAL) << "Unknown value: " << level;
  125. return "";
  126. }
  127. string ConformanceTestSuite::ConformanceRequestSetting::
  128. InputFormatString(conformance::WireFormat format) const {
  129. switch (format) {
  130. case conformance::PROTOBUF:
  131. return "ProtobufInput";
  132. case conformance::JSON:
  133. return "JsonInput";
  134. case conformance::TEXT_FORMAT:
  135. return "TextFormatInput";
  136. default:
  137. GOOGLE_LOG(FATAL) << "Unspecified output format";
  138. }
  139. return "";
  140. }
  141. string ConformanceTestSuite::ConformanceRequestSetting::
  142. OutputFormatString(conformance::WireFormat format) const {
  143. switch (format) {
  144. case conformance::PROTOBUF:
  145. return "ProtobufOutput";
  146. case conformance::JSON:
  147. return "JsonOutput";
  148. case conformance::TEXT_FORMAT:
  149. return "TextFormatOutput";
  150. default:
  151. GOOGLE_LOG(FATAL) << "Unspecified output format";
  152. }
  153. return "";
  154. }
  155. void ConformanceTestSuite::ReportSuccess(const string& test_name) {
  156. if (expected_to_fail_.erase(test_name) != 0) {
  157. StringAppendF(&output_,
  158. "ERROR: test %s is in the failure list, but test succeeded. "
  159. "Remove it from the failure list.\n",
  160. test_name.c_str());
  161. unexpected_succeeding_tests_.insert(test_name);
  162. }
  163. successes_++;
  164. }
  165. void ConformanceTestSuite::ReportFailure(const string& test_name,
  166. ConformanceLevel level,
  167. const ConformanceRequest& request,
  168. const ConformanceResponse& response,
  169. const char* fmt, ...) {
  170. if (expected_to_fail_.erase(test_name) == 1) {
  171. expected_failures_++;
  172. if (!verbose_)
  173. return;
  174. } else if (level == RECOMMENDED && !enforce_recommended_) {
  175. StringAppendF(&output_, "WARNING, test=%s: ", test_name.c_str());
  176. } else {
  177. StringAppendF(&output_, "ERROR, test=%s: ", test_name.c_str());
  178. unexpected_failing_tests_.insert(test_name);
  179. }
  180. va_list args;
  181. va_start(args, fmt);
  182. StringAppendV(&output_, fmt, args);
  183. va_end(args);
  184. StringAppendF(&output_, " request=%s, response=%s\n",
  185. request.ShortDebugString().c_str(),
  186. response.ShortDebugString().c_str());
  187. }
  188. void ConformanceTestSuite::ReportSkip(const string& test_name,
  189. const ConformanceRequest& request,
  190. const ConformanceResponse& response) {
  191. if (verbose_) {
  192. StringAppendF(&output_, "SKIPPED, test=%s request=%s, response=%s\n",
  193. test_name.c_str(), request.ShortDebugString().c_str(),
  194. response.ShortDebugString().c_str());
  195. }
  196. skipped_.insert(test_name);
  197. }
  198. void ConformanceTestSuite::RunValidInputTest(
  199. const ConformanceRequestSetting& setting,
  200. const string& equivalent_text_format) {
  201. std::unique_ptr<Message> reference_message(setting.NewTestMessage());
  202. GOOGLE_CHECK(TextFormat::ParseFromString(equivalent_text_format,
  203. reference_message.get()))
  204. << "Failed to parse data for test case: " << setting.GetTestName()
  205. << ", data: " << equivalent_text_format;
  206. const string equivalent_wire_format = reference_message->SerializeAsString();
  207. RunValidBinaryInputTest(setting, equivalent_wire_format);
  208. }
  209. void ConformanceTestSuite::RunValidBinaryInputTest(
  210. const ConformanceRequestSetting& setting,
  211. const string& equivalent_wire_format, bool require_same_wire_format) {
  212. const ConformanceRequest& request = setting.GetRequest();
  213. ConformanceResponse response;
  214. RunTest(setting.GetTestName(), request, &response);
  215. VerifyResponse(setting, equivalent_wire_format, response, true,
  216. require_same_wire_format);
  217. }
  218. void ConformanceTestSuite::VerifyResponse(
  219. const ConformanceRequestSetting& setting,
  220. const string& equivalent_wire_format, const ConformanceResponse& response,
  221. bool need_report_success, bool require_same_wire_format) {
  222. std::unique_ptr<Message> test_message(setting.NewTestMessage());
  223. const ConformanceRequest& request = setting.GetRequest();
  224. const string& test_name = setting.GetTestName();
  225. ConformanceLevel level = setting.GetLevel();
  226. std::unique_ptr<Message> reference_message = setting.NewTestMessage();
  227. GOOGLE_CHECK(reference_message->ParseFromString(equivalent_wire_format))
  228. << "Failed to parse wire data for test case: " << test_name;
  229. switch (response.result_case()) {
  230. case ConformanceResponse::RESULT_NOT_SET:
  231. ReportFailure(test_name, level, request, response,
  232. "Response didn't have any field in the Response.");
  233. return;
  234. case ConformanceResponse::kParseError:
  235. case ConformanceResponse::kRuntimeError:
  236. case ConformanceResponse::kSerializeError:
  237. ReportFailure(test_name, level, request, response,
  238. "Failed to parse input or produce output.");
  239. return;
  240. case ConformanceResponse::kSkipped:
  241. ReportSkip(test_name, request, response);
  242. return;
  243. default:
  244. if (!ParseResponse(response, setting, test_message.get())) return;
  245. }
  246. MessageDifferencer differencer;
  247. DefaultFieldComparator field_comparator;
  248. field_comparator.set_treat_nan_as_equal(true);
  249. differencer.set_field_comparator(&field_comparator);
  250. string differences;
  251. differencer.ReportDifferencesToString(&differences);
  252. bool check = false;
  253. if (require_same_wire_format) {
  254. GOOGLE_DCHECK_EQ(response.result_case(), ConformanceResponse::kProtobufPayload);
  255. const string& protobuf_payload = response.protobuf_payload();
  256. check = equivalent_wire_format == protobuf_payload;
  257. differences = StrCat("Expect: ", ToOctString(equivalent_wire_format),
  258. ", but got: ", ToOctString(protobuf_payload));
  259. } else {
  260. check = differencer.Compare(*reference_message, *test_message);
  261. }
  262. if (check) {
  263. if (need_report_success) {
  264. ReportSuccess(test_name);
  265. }
  266. } else {
  267. ReportFailure(test_name, level, request, response,
  268. "Output was not equivalent to reference message: %s.",
  269. differences.c_str());
  270. }
  271. }
  272. void ConformanceTestSuite::RunTest(const string& test_name,
  273. const ConformanceRequest& request,
  274. ConformanceResponse* response) {
  275. if (test_names_.insert(test_name).second == false) {
  276. GOOGLE_LOG(FATAL) << "Duplicated test name: " << test_name;
  277. }
  278. string serialized_request;
  279. string serialized_response;
  280. request.SerializeToString(&serialized_request);
  281. runner_->RunTest(test_name, serialized_request, &serialized_response);
  282. if (!response->ParseFromString(serialized_response)) {
  283. response->Clear();
  284. response->set_runtime_error("response proto could not be parsed.");
  285. }
  286. if (verbose_) {
  287. StringAppendF(&output_,
  288. "conformance test: name=%s, request=%s, response=%s\n",
  289. test_name.c_str(),
  290. request.ShortDebugString().c_str(),
  291. response->ShortDebugString().c_str());
  292. }
  293. }
  294. bool ConformanceTestSuite::CheckSetEmpty(
  295. const std::set<string>& set_to_check,
  296. const std::string& write_to_file,
  297. const std::string& msg) {
  298. if (set_to_check.empty()) {
  299. return true;
  300. } else {
  301. StringAppendF(&output_, "\n");
  302. StringAppendF(&output_, "%s\n\n", msg.c_str());
  303. for (std::set<string>::const_iterator iter = set_to_check.begin();
  304. iter != set_to_check.end(); ++iter) {
  305. StringAppendF(&output_, " %s\n", iter->c_str());
  306. }
  307. StringAppendF(&output_, "\n");
  308. if (!write_to_file.empty()) {
  309. std::ofstream os(write_to_file);
  310. if (os) {
  311. for (std::set<string>::const_iterator iter = set_to_check.begin();
  312. iter != set_to_check.end(); ++iter) {
  313. os << *iter << "\n";
  314. }
  315. } else {
  316. StringAppendF(&output_, "Failed to open file: %s\n",
  317. write_to_file.c_str());
  318. }
  319. }
  320. return false;
  321. }
  322. }
  323. string ConformanceTestSuite::WireFormatToString(
  324. WireFormat wire_format) {
  325. switch (wire_format) {
  326. case conformance::PROTOBUF:
  327. return "PROTOBUF";
  328. case conformance::JSON:
  329. return "JSON";
  330. case conformance::JSPB:
  331. return "JSPB";
  332. case conformance::TEXT_FORMAT:
  333. return "TEXT_FORMAT";
  334. case conformance::UNSPECIFIED:
  335. return "UNSPECIFIED";
  336. default:
  337. GOOGLE_LOG(FATAL) << "unknown wire type: " << wire_format;
  338. }
  339. return "";
  340. }
  341. void ConformanceTestSuite::AddExpectedFailedTest(const std::string& test_name) {
  342. expected_to_fail_.insert(test_name);
  343. }
  344. bool ConformanceTestSuite::RunSuite(ConformanceTestRunner* runner,
  345. std::string* output, const string& filename,
  346. conformance::FailureSet* failure_list) {
  347. runner_ = runner;
  348. successes_ = 0;
  349. expected_failures_ = 0;
  350. skipped_.clear();
  351. test_names_.clear();
  352. unexpected_failing_tests_.clear();
  353. unexpected_succeeding_tests_.clear();
  354. output_ = "\nCONFORMANCE TEST BEGIN ====================================\n\n";
  355. failure_list_filename_ = filename;
  356. expected_to_fail_.clear();
  357. for (const string& failure : failure_list->failure()) {
  358. AddExpectedFailedTest(failure);
  359. }
  360. RunSuiteImpl();
  361. bool ok = true;
  362. if (!CheckSetEmpty(expected_to_fail_, "nonexistent_tests.txt",
  363. "These tests were listed in the failure list, but they "
  364. "don't exist. Remove them from the failure list by "
  365. "running:\n"
  366. " ./update_failure_list.py " + failure_list_filename_ +
  367. " --remove nonexistent_tests.txt")) {
  368. ok = false;
  369. }
  370. if (!CheckSetEmpty(unexpected_failing_tests_, "failing_tests.txt",
  371. "These tests failed. If they can't be fixed right now, "
  372. "you can add them to the failure list so the overall "
  373. "suite can succeed. Add them to the failure list by "
  374. "running:\n"
  375. " ./update_failure_list.py " + failure_list_filename_ +
  376. " --add failing_tests.txt")) {
  377. ok = false;
  378. }
  379. if (!CheckSetEmpty(unexpected_succeeding_tests_, "succeeding_tests.txt",
  380. "These tests succeeded, even though they were listed in "
  381. "the failure list. Remove them from the failure list "
  382. "by running:\n"
  383. " ./update_failure_list.py " + failure_list_filename_ +
  384. " --remove succeeding_tests.txt")) {
  385. ok = false;
  386. }
  387. if (verbose_) {
  388. CheckSetEmpty(skipped_, "",
  389. "These tests were skipped (probably because support for some "
  390. "features is not implemented)");
  391. }
  392. StringAppendF(&output_,
  393. "CONFORMANCE SUITE %s: %d successes, %zu skipped, "
  394. "%d expected failures, %zu unexpected failures.\n",
  395. ok ? "PASSED" : "FAILED", successes_, skipped_.size(),
  396. expected_failures_, unexpected_failing_tests_.size());
  397. StringAppendF(&output_, "\n");
  398. output->assign(output_);
  399. return ok;
  400. }
  401. } // namespace protobuf
  402. } // namespace google