1 /*
2 * Copyright (c) Huawei Technologies Co., Ltd. 2021. All rights reserved.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15 #include <fstream>
16 #include <gtest/gtest.h>
17 #include <random>
18 #include <string>
19
20 #include "ftrace_data_reader.h"
21
22 using FTRACE_NS::FtraceDataReader;
23 using testing::ext::TestSize;
24
25 namespace {
26 constexpr char RANDOM_CHAR_TABLE[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
27 constexpr long RANDOM_CHAR_NUMBER = std::size(RANDOM_CHAR_TABLE) - 1;
28 constexpr int RAW_DATA_SIZE = 1024 * 1024;
29 #ifndef PAGE_SIZE
30 constexpr uint32_t PAGE_SIZE = 4096;
31 #endif
32
33 class FtraceDataReaderTest : public ::testing::Test {
34 protected:
35 std::mt19937 gen_;
36 std::string path_ = "raw_data.bin";
37 long dataSize_ = RAW_DATA_SIZE;
38
39 void SetUp() override
40 {
41 std::ofstream fout(path_);
42 std::string data = RandomString(dataSize_);
43 fout.write(data.data(), data.size());
44 }
45
46 void TearDown() override
47 {
48 unlink(path_.c_str());
49 }
50
RandomInt(int a, int b)51 int RandomInt(int a, int b)
52 {
53 std::uniform_int_distribution<int> distrib(a, b);
54 return distrib(gen_);
55 }
56
RandomChar()57 char RandomChar()
58 {
59 return RANDOM_CHAR_TABLE[RandomInt(0, RANDOM_CHAR_NUMBER - 1)];
60 }
61
RandomString(int len)62 std::string RandomString(int len)
63 {
64 std::string str;
65 str.reserve(len);
66 for (int i = 0; i < len; i++) {
67 str.push_back(RandomChar());
68 }
69 return str;
70 }
71 };
72
73 /*
74 * @tc.name: ReadNormal
75 * @tc.desc: test FtraceDataReader::Read with normal case.
76 * @tc.type: FUNC
77 */
HWTEST_F(FtraceDataReaderTest, ReadNormal, TestSize.Level1)78 HWTEST_F(FtraceDataReaderTest, ReadNormal, TestSize.Level1)
79 {
80 FtraceDataReader reader(path_);
81 std::vector<uint8_t> zeros(PAGE_SIZE, 0);
82 std::vector<uint8_t> buffer(PAGE_SIZE, 0);
83
84 for (long i = 0; i < dataSize_; i += buffer.size()) {
85 long bufferSize = static_cast<long>(buffer.size());
86 EXPECT_EQ(reader.Read(buffer.data(), buffer.size()), bufferSize);
87 EXPECT_NE(buffer, zeros);
88 }
89 }
90 } // namespace