• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2023 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #ifndef BASE_TEST_TEST_PROTO_LOADER_H_
6 #define BASE_TEST_TEST_PROTO_LOADER_H_
7 
8 #include "base/files/file_path.h"
9 #include "base/memory/raw_ptr.h"
10 #include "third_party/protobuf/src/google/protobuf/descriptor.h"
11 #include "third_party/protobuf/src/google/protobuf/descriptor.pb.h"
12 #include "third_party/protobuf/src/google/protobuf/dynamic_message.h"
13 
14 namespace base {
15 
16 #if defined(COMPONENT_BUILD)
17 #if defined(WIN32)
18 
19 #if defined(PROTO_TEST_IMPLEMENTATION)
20 #define PROTO_TEST_EXPORT __declspec(dllexport)
21 #else
22 #define PROTO_TEST_EXPORT __declspec(dllimport)
23 #endif  // defined(PROTO_TEST_IMPLEMENTATION)
24 
25 #else  // defined(WIN32)
26 #if defined(PROTO_TEST_IMPLEMENTATION)
27 #define PROTO_TEST_EXPORT __attribute__((visibility("default")))
28 #else
29 #define PROTO_TEST_EXPORT
30 #endif
31 #endif
32 #else  // defined(COMPONENT_BUILD)
33 #define PROTO_TEST_EXPORT
34 #endif
35 
36 // This class works around the fact that chrome only includes the lite runtime
37 // of protobufs. Lite protobufs inherit from |MessageLite| and cannot be used to
38 // parse from text format. Parsing from text
39 // format is useful in tests. We cannot include the full version of a protobuf
40 // in test code because it would clash with the lite version.
41 //
42 // This class uses the protobuf descriptors (generated at compile time) to
43 // generate a |Message| that can be used to parse from text. This message can
44 // then be serialized to binary which can be parsed by the |MessageLite|.
45 class PROTO_TEST_EXPORT TestProtoLoader {
46  public:
47   TestProtoLoader(const base::FilePath& descriptor_path,
48                   base::StringPiece type_name);
49   ~TestProtoLoader();
50   TestProtoLoader(const TestProtoLoader&) = delete;
51   TestProtoLoader& operator=(const TestProtoLoader&) = delete;
52 
53   void ParseFromText(const std::string& proto_text, std::string& message);
54   void PrintToText(const std::string& message, std::string& proto_text);
55 
56  private:
57   const google::protobuf::Message* GetPrototype(base::FilePath descriptor_path,
58                                                 base::StringPiece package,
59                                                 base::StringPiece name);
60 
61   google::protobuf::DescriptorPool descriptor_pool_;
62   google::protobuf::FileDescriptorSet descriptor_set_;
63   google::protobuf::DynamicMessageFactory dynamic_message_factory_;
64   raw_ptr<const google::protobuf::Message> prototype_;
65 };
66 
67 }  // namespace base
68 
69 #endif  // BASE_TEST_TEST_PROTO_LOADER_H_
70