File size: 9,883 Bytes
5cdf637
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
// SPDX-License-Identifier: BSD-3-Clause
// Copyright (c) 2023-2025, The OpenROAD Authors

#include <chrono>
#include <cstdint>
#include <cstdio>
#include <ctime>
#include <filesystem>
#include <fstream>
#include <ios>
#include <iterator>
#include <memory>
#include <numeric>
#include <ostream>
#include <stdexcept>
#include <string>
#include <thread>
#include <vector>

#include "boost/asio.hpp"
#include "boost/beast.hpp"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "utl/CFileUtils.h"
#include "utl/Logger.h"
#include "utl/ScopedTemporaryFile.h"
#include "utl/prometheus/gauge.h"

namespace utl {
using ::testing::HasSubstr;

namespace {

// Helper function to make an HTTP request and return the response body.
std::string MakeHttpRequest(const std::string& host,
                            const std::string& port,
                            const std::string& target)
{
  boost::asio::io_context io_context;
  boost::asio::ip::tcp::resolver resolver(io_context);
  boost::asio::ip::tcp::socket socket(io_context);

  auto const results = resolver.resolve(host, port);
  boost::asio::connect(socket, results.begin(), results.end());

  // HTTP 1.1 request
  boost::beast::http::request<boost::beast::http::string_body> req{
      boost::beast::http::verb::get, target, /*version=*/11};
  req.set(boost::beast::http::field::host, host);
  req.set(boost::beast::http::field::user_agent, "BoostBeastTestClient");

  boost::beast::http::write(socket, req);

  boost::beast::flat_buffer buffer;
  boost::beast::http::response<boost::beast::http::string_body> res;
  boost::beast::http::read(socket, buffer, res);

  socket.shutdown(boost::asio::ip::tcp::socket::shutdown_both);

  return res.body();
}

}  // namespace

TEST(Utl, read_all_of_empty_file)
{
  Logger logger;
  ScopedTemporaryFile stf(&logger);
  std::string contents = GetContents(stf.file(), &logger);
  EXPECT_TRUE(contents.empty());
}

// Writes then reads 4B of data.
TEST(Utl, read_all_of_written_file_seek_required)
{
  Logger logger;
  ScopedTemporaryFile stf(&logger);

  const std::vector<uint8_t> kTestData = {0x01, 0x02, 0x03, 0x04};
  WriteAll(stf.file(), kTestData, &logger);

  std::string contents = GetContents(stf.file(), &logger);
  EXPECT_EQ(contents.size(), kTestData.size());
  for (size_t i = 0; i < contents.size(); ++i) {
    EXPECT_EQ(static_cast<uint8_t>(contents.at(i)), kTestData.at(i));
  }
}

// Writes then reads 1024B of data.
TEST(Utl, read_all_of_file_exactly_1024B)
{
  Logger logger;
  ScopedTemporaryFile stf(&logger);

  std::vector<uint8_t> test_data(1024);
  std::iota(test_data.begin(), test_data.end(), 0);

  WriteAll(stf.file(), test_data, &logger);

  std::string contents = GetContents(stf.file(), &logger);
  EXPECT_EQ(contents.size(), test_data.size());
  for (size_t i = 0; i < contents.size(); ++i) {
    EXPECT_EQ(static_cast<uint8_t>(contents.at(i)), test_data.at(i));
  }
}

// Writes then reads 1025B of data (whitebox test, we know internally the read
// buffer size is 1024B so this causes two chunks of read).
TEST(Utl, read_all_of_file_exactly_1025B)
{
  Logger logger;
  ScopedTemporaryFile stf(&logger);

  std::vector<uint8_t> test_data(1025);
  std::iota(test_data.begin(), test_data.end(), 0);

  WriteAll(stf.file(), test_data, &logger);

  std::string contents = GetContents(stf.file(), &logger);
  EXPECT_EQ(contents.size(), test_data.size());
  for (size_t i = 0; i < contents.size(); ++i) {
    EXPECT_EQ(static_cast<uint8_t>(contents.at(i)), test_data.at(i));
  }
}

// Add new tests for OutStreamHandler
TEST(Utl, stream_handler_write_and_read)
{
  const char* filename = "test_write_and_read.txt";
  const std::string kTestData = "\x1\x2\x3\x4";

  {
    OutStreamHandler sh(filename);
    std::ostream& os = sh.getStream();
    os.write(kTestData.c_str(), kTestData.size());
  }

  InStreamHandler ish(filename);
  std::string contents((std::istreambuf_iterator<char>(ish.getStream())),
                       std::istreambuf_iterator<char>());
  EXPECT_EQ(contents, kTestData);
  std::filesystem::remove(filename);
}

TEST(Utl, stream_handler_write_and_read_gzip)
{
  const char* filename = "test_write_and_read.txt.gz";
  const std::string kTestData = "\x1\x2\x3\x4";

  {
    OutStreamHandler sh(filename);
    std::ostream& os = sh.getStream();
    os.write(kTestData.c_str(), kTestData.size());
  }

  InStreamHandler ish(filename);
  std::string contents((std::istreambuf_iterator<char>(ish.getStream())),
                       std::istreambuf_iterator<char>());
  EXPECT_EQ(contents, kTestData);
  std::filesystem::remove(filename);
}

TEST(Utl, stream_handler_gzip_compression_levels)
{
  const char* filename_l1 = "test_l1.txt.gz";
  const char* filename_l9 = "test_l9.txt.gz";

  std::string kTestData;
  kTestData.reserve(100000 * 27);
  for (int i = 0; i < 100000; ++i) {
    kTestData.append("abcdefghijklmnopqrstuvwxyz\n");
  }

  {
    OutStreamHandler sh(filename_l1, true, 1);
    std::ostream& os = sh.getStream();
    os.write(kTestData.c_str(), kTestData.size());
  }

  {
    OutStreamHandler sh(filename_l9, true, 9);
    std::ostream& os = sh.getStream();
    os.write(kTestData.c_str(), kTestData.size());
  }

  {
    InStreamHandler ish(filename_l1);
    std::string contents((std::istreambuf_iterator<char>(ish.getStream())),
                         std::istreambuf_iterator<char>());
    EXPECT_EQ(contents, kTestData);
  }
  {
    InStreamHandler ish(filename_l9);
    std::string contents((std::istreambuf_iterator<char>(ish.getStream())),
                         std::istreambuf_iterator<char>());
    EXPECT_EQ(contents, kTestData);
  }

  std::uintmax_t size_l1 = std::filesystem::file_size(filename_l1);
  std::uintmax_t size_l9 = std::filesystem::file_size(filename_l9);

  EXPECT_LE(size_l9, size_l1);

  std::filesystem::remove(filename_l1);
  std::filesystem::remove(filename_l9);
}

TEST(Utl, stream_handler_temp_file_handling)
{
  const char* filename = "test_temp_file_handling.txt";
  std::string tmp_filename = std::string(filename) + ".1";

  // Check that the temp file is created
  {
    OutStreamHandler sh(filename);
    EXPECT_TRUE(std::filesystem::exists(tmp_filename));
  }

  // Check that the temp file is renamed to the original filename
  EXPECT_TRUE(!std::filesystem::exists(tmp_filename));
  EXPECT_TRUE(std::filesystem::exists(filename));
  std::filesystem::remove(filename);
}

TEST(Utl, stream_handler_exception_handling)
{
  const char* filename = "test_exception_handling.txt";

  // Ensure the temporary file is handled correctly if an exception occurs
  try {
    OutStreamHandler sh(filename);
    throw std::runtime_error("Simulated exception");
  } catch (...) {
    std::string tmp_filename = std::string(filename) + ".1";
    // Ensure temporary file is cleaned up
    EXPECT_TRUE(!std::filesystem::exists(tmp_filename));
    // Original file should exist
    EXPECT_TRUE(std::filesystem::exists(filename));
    std::filesystem::remove(filename);
  }
}

// Add new tests for FileHandler
TEST(Utl, file_handler_write_and_read)
{
  const char* filename = "test_write_and_read_file.txt";
  const std::string kTestData = "\x1\x2\x3\x4";
  {
    FileHandler fh(filename, true);  // binary mode
    FILE* file = fh.getFile();
    fwrite(kTestData.c_str(), sizeof(uint8_t), kTestData.size(), file);
  }

  std::ifstream is(filename, std::ios_base::binary);
  std::string contents((std::istreambuf_iterator<char>(is)),
                       std::istreambuf_iterator<char>());
  EXPECT_EQ(contents, kTestData);
  std::filesystem::remove(filename);
}

TEST(Utl, file_handler_temp_file_handling)
{
  const char* filename = "test_temp_file_handling_file.txt";
  std::string tmp_filename = std::string(filename) + ".1";

  // Check that the temp file is created
  {
    FileHandler fh(filename, true);  // binary mode
    EXPECT_TRUE(std::filesystem::exists(tmp_filename));
  }

  // Check that the temp file is renamed to the original filename
  EXPECT_TRUE(!std::filesystem::exists(tmp_filename));
  EXPECT_TRUE(std::filesystem::exists(filename));
  std::filesystem::remove(filename);
}

TEST(Utl, file_handler_exception_handling)
{
  const char* filename = "test_exception_handling_file.txt";

  // Ensure the temporary file is handled correctly if an exception occurs
  try {
    FileHandler fh(filename, true);  // binary mode
    throw std::runtime_error("Simulated exception");
  } catch (...) {
    std::string tmp_filename = std::string(filename) + ".1";
    // Ensure temporary file is cleaned up
    EXPECT_TRUE(!std::filesystem::exists(tmp_filename));
    // Original file should exist
    EXPECT_TRUE(std::filesystem::exists(filename));
    std::filesystem::remove(filename);
  }
}

TEST(Utl, metrics_server_responds_with_basic_metric)
{
  using namespace std::chrono_literals;

  Logger logger;
  logger.startPrometheusEndpoint(0);
  std::shared_ptr<PrometheusRegistry> registry = logger.getRegistry();
  auto& test_gauge_family = BuildGauge()
                                .Name("test_gauge")
                                .Help("A test gauge for testing")
                                .Register(*registry);
  auto& test_gauge = test_gauge_family.Add({});
  test_gauge.Set(10101);

  const auto deadline = std::chrono::steady_clock::now() + 10s;
  while (!logger.isPrometheusServerReadyToServe()) {
    if (logger.hasPrometheusServerStartupFailed()) {
      GTEST_SKIP() << "Prometheus endpoint could not start in this runtime.";
    }

    if (std::chrono::steady_clock::now() >= deadline) {
      GTEST_SKIP()
          << "Prometheus endpoint did not become ready before timeout.";
    }

    std::this_thread::sleep_for(10ms);
  }

  uint16_t port = logger.getPrometheusPort();
  std::string response
      = MakeHttpRequest("localhost", fmt::format("{}", port), "/metrics");
  EXPECT_THAT(response, HasSubstr("10101"));
}

}  // namespace utl