xref: /aosp_15_r20/external/perfetto/src/perfetto_cmd/packet_writer_unittest.cc (revision 6dbdd20afdafa5e3ca9b8809fa73465d530080dc)
1 /*
2  * Copyright (C) 2019 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include "src/perfetto_cmd/packet_writer.h"
18 
19 #include <string.h>
20 
21 #include <random>
22 
23 #include "perfetto/base/build_config.h"
24 #include "perfetto/ext/base/file_utils.h"
25 #include "perfetto/ext/base/scoped_file.h"
26 #include "perfetto/ext/base/temp_file.h"
27 #include "perfetto/ext/tracing/core/trace_packet.h"
28 #include "src/perfetto_cmd/packet_writer.h"
29 #include "test/gtest_and_gmock.h"
30 
31 #include "protos/perfetto/trace/test_event.gen.h"
32 #include "protos/perfetto/trace/trace.gen.h"
33 #include "protos/perfetto/trace/trace_packet.gen.h"
34 
35 namespace perfetto {
36 namespace {
37 
38 using TracePacketProto = protos::gen::TracePacket;
39 
40 template <typename F>
CreateTracePacket(F fill_function)41 TracePacket CreateTracePacket(F fill_function) {
42   TracePacketProto msg;
43   fill_function(&msg);
44   std::vector<uint8_t> buf = msg.SerializeAsArray();
45   Slice slice = Slice::Allocate(buf.size());
46   memcpy(slice.own_data(), buf.data(), buf.size());
47   perfetto::TracePacket packet;
48   packet.AddSlice(std::move(slice));
49   return packet;
50 }
51 
TEST(PacketWriterTest,FilePacketWriter)52 TEST(PacketWriterTest, FilePacketWriter) {
53   base::TempFile tmp = base::TempFile::CreateUnlinked();
54   base::ScopedResource<FILE*, fclose, nullptr> f(
55       fdopen(tmp.ReleaseFD().release(), "wb"));
56 
57   std::vector<perfetto::TracePacket> packets;
58   packets.push_back(CreateTracePacket([](TracePacketProto* msg) {
59     auto* for_testing = msg->mutable_for_testing();
60     for_testing->set_str("abc");
61   }));
62 
63   {
64     PacketWriter writer(*f);
65     EXPECT_TRUE(writer.WritePackets(std::move(packets)));
66   }
67 
68   fseek(*f, 0, SEEK_SET);
69   std::string s;
70   EXPECT_TRUE(base::ReadFileStream(*f, &s));
71   EXPECT_GT(s.size(), 0u);
72 
73   protos::gen::Trace trace;
74   EXPECT_TRUE(trace.ParseFromString(s));
75   EXPECT_EQ(trace.packet()[0].for_testing().str(), "abc");
76 }
77 
78 }  // namespace
79 }  // namespace perfetto
80