fuzzer_util_test.cpp 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. // Part of the Carbon Language project, under the Apache License v2.0 with LLVM
  2. // Exceptions. See /LICENSE for license information.
  3. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. #include "explorer/fuzzing/fuzzer_util.h"
  5. #include <gmock/gmock.h>
  6. #include <gtest/gtest.h>
  7. #include <fstream>
  8. #include "llvm/ADT/StringRef.h"
  9. #include "llvm/Support/raw_ostream.h"
  10. namespace Carbon::Testing {
  11. namespace {
  12. static std::vector<llvm::StringRef>* carbon_files = nullptr;
  13. // A workaround for https://github.com/carbon-language/carbon-lang/issues/1208.
  14. TEST(FuzzerUtilTest, RunFuzzerOnCorpus) {
  15. int parsed_file_count = 0;
  16. for (const llvm::StringRef f : *carbon_files) {
  17. llvm::outs() << "Processing " << f << "\n";
  18. std::ifstream file(f.str(), std::ios::in);
  19. ASSERT_TRUE(file.is_open());
  20. std::stringstream contents;
  21. contents << file.rdbuf();
  22. // Parsing errors are ignored to make the fuzzer inputs less brittle as the
  23. // explorer code changes. This also matches standard fuzzer behavior.
  24. if (auto carbon_proto = ParseCarbonTextProto(contents.str());
  25. carbon_proto.ok()) {
  26. ParseAndExecute(carbon_proto->compilation_unit());
  27. ++parsed_file_count;
  28. }
  29. }
  30. EXPECT_GT(parsed_file_count, 0);
  31. }
  32. TEST(FuzzerUtilTest, GetRunfilesFile) {
  33. EXPECT_THAT(*Internal::GetRunfilesFile("carbon/explorer/data/prelude.carbon"),
  34. testing::EndsWith("/prelude.carbon"));
  35. EXPECT_THAT(Internal::GetRunfilesFile("nonexistent-file").error().message(),
  36. testing::EndsWith("doesn't exist"));
  37. }
  38. TEST(FuzzerUtilTest, ParseCarbonTextProtoWithUnknownField) {
  39. const ErrorOr<Fuzzing::Carbon> carbon_proto =
  40. ParseCarbonTextProto(R"(
  41. compilation_unit {
  42. garbage: "value"
  43. declarations {
  44. choice {
  45. name: "Ch"
  46. }
  47. }
  48. })",
  49. /*allow_unknown=*/true);
  50. ASSERT_TRUE(carbon_proto.ok());
  51. // No EqualsProto in gmock - https://github.com/google/googletest/issues/1761.
  52. EXPECT_EQ(carbon_proto->compilation_unit().declarations(0).choice().name(),
  53. "Ch");
  54. }
  55. } // namespace
  56. } // namespace Carbon::Testing
  57. auto main(int argc, char** argv) -> int {
  58. ::testing::InitGoogleTest(&argc, argv);
  59. Carbon::Testing::carbon_files =
  60. new std::vector<llvm::StringRef>(&argv[1], &argv[argc]);
  61. return RUN_ALL_TESTS();
  62. }