You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@trafficserver.apache.org by bc...@apache.org on 2026/01/21 03:32:56 UTC

(trafficserver) branch unit-test-coverage created (now a993b11aab)

This is an automated email from the ASF dual-hosted git repository.

bcall pushed a change to branch unit-test-coverage
in repository https://gitbox.apache.org/repos/asf/trafficserver.git


      at a993b11aab Add mock framework for unit testing (MockNetVC, MockCacheVC)

This branch includes the following new commits:

     new d43e14376c WIP: Unit test coverage infrastructure
     new a993b11aab Add mock framework for unit testing (MockNetVC, MockCacheVC)

The 2 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails.  The revisions
listed as "add" were already present in the repository and have only
been added to this reference.



(trafficserver) 02/02: Add mock framework for unit testing (MockNetVC, MockCacheVC)

Posted by bc...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

bcall pushed a commit to branch unit-test-coverage
in repository https://gitbox.apache.org/repos/asf/trafficserver.git

commit a993b11aabffec7add2b8b949489540edb72aa1d
Author: Bryan Call <bc...@apache.org>
AuthorDate: Tue Jan 20 19:32:43 2026 -0800

    Add mock framework for unit testing (MockNetVC, MockCacheVC)
    
    Add test utilities library with mock objects for unit testing:
    - MockNetVC: Mock NetVConnection for testing network code
    - MockCacheVC: Mock CacheVConnection for testing cache code
    - MockIOBuffer: Helper for creating/managing IOBuffers in tests
    - TestEventProcessor: Controllable event processor for tests
    
    This is part of the unit test coverage improvement initiative.
---
 src/test_utils/CMakeLists.txt |   3 +
 src/test_utils/MockCacheVC.cc | 322 ++++++++++++++++++++++++++++++++++++
 src/test_utils/MockCacheVC.h  | 155 +++++++++++++++++
 src/test_utils/MockNetVC.cc   | 376 ++++++++++++++++++++++++++++++++++++++++++
 src/test_utils/MockNetVC.h    | 176 ++++++++++++++++++++
 5 files changed, 1032 insertions(+)

diff --git a/src/test_utils/CMakeLists.txt b/src/test_utils/CMakeLists.txt
index 339994e283..7ace822e9d 100644
--- a/src/test_utils/CMakeLists.txt
+++ b/src/test_utils/CMakeLists.txt
@@ -21,6 +21,8 @@
 add_library(
   ats_test_utils STATIC
   MockIOBuffer.cc
+  MockNetVC.cc
+  MockCacheVC.cc
   TestEventProcessor.cc
 )
 
@@ -33,6 +35,7 @@ target_include_directories(
 target_link_libraries(
   ats_test_utils
   PUBLIC ts::inkevent
+         ts::inknet
          ts::tscore
 )
 
diff --git a/src/test_utils/MockCacheVC.cc b/src/test_utils/MockCacheVC.cc
new file mode 100644
index 0000000000..af7b6c945b
--- /dev/null
+++ b/src/test_utils/MockCacheVC.cc
@@ -0,0 +1,322 @@
+/** @file
+
+  Mock CacheVConnection implementation for unit testing
+
+  @section license License
+
+  Licensed to the Apache Software Foundation (ASF) under one
+  or more contributor license agreements.  See the NOTICE file
+  distributed with this work for additional information
+  regarding copyright ownership.  The ASF licenses this file
+  to you under the Apache License, Version 2.0 (the
+  "License"); you may not use this file except in compliance
+  with the License.  You may obtain a copy of the License at
+
+      http://www.apache.org/licenses/LICENSE-2.0
+
+  Unless required by applicable law or agreed to in writing, software
+  distributed under the License is distributed on an "AS IS" BASIS,
+  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+  See the License for the specific language governing permissions and
+  limitations under the License.
+*/
+
+#include "test_utils/MockCacheVC.h"
+#include "tscore/ink_memory.h"
+#include <cstring>
+
+MockCacheVC::MockCacheVC()
+{
+  // Initialize read buffer for simulating cached data
+  read_buffer_        = new_MIOBuffer(BUFFER_SIZE_INDEX_4K);
+  read_buffer_reader_ = read_buffer_->alloc_reader();
+
+  // Initialize write capture buffer
+  write_capture_        = new_MIOBuffer(BUFFER_SIZE_INDEX_4K);
+  write_capture_reader_ = write_capture_->alloc_reader();
+}
+
+MockCacheVC::~MockCacheVC()
+{
+  if (read_buffer_) {
+    free_MIOBuffer(read_buffer_);
+  }
+  if (write_capture_) {
+    free_MIOBuffer(write_capture_);
+  }
+  if (header_) {
+    ats_free(header_);
+  }
+}
+
+// ============== Test Setup Methods ==============
+
+void
+MockCacheVC::set_read_data(std::string_view data)
+{
+  // Clear existing data
+  read_buffer_reader_->consume(read_buffer_reader_->read_avail());
+  // Write new data
+  read_buffer_->write(data.data(), data.size());
+  object_size_ = data.size();
+}
+
+std::string
+MockCacheVC::get_written_data() const
+{
+  std::string result;
+  int64_t     avail = write_capture_reader_->read_avail();
+  if (avail > 0) {
+    result.resize(avail);
+    IOBufferBlock *block  = write_capture_reader_->get_current_block();
+    int64_t        offset = write_capture_reader_->start_offset;
+    size_t         pos    = 0;
+
+    while (block && pos < static_cast<size_t>(avail)) {
+      const char *start = block->start() + offset;
+      int64_t     len   = block->read_avail() - offset;
+      if (len > 0) {
+        if (pos + len > static_cast<size_t>(avail)) {
+          len = avail - pos;
+        }
+        memcpy(&result[pos], start, len);
+        pos += len;
+      }
+      block  = block->next.get();
+      offset = 0;
+    }
+  }
+  return result;
+}
+
+void
+MockCacheVC::clear_written_data()
+{
+  write_capture_reader_->consume(write_capture_reader_->read_avail());
+}
+
+void
+MockCacheVC::set_http_info_for_test(CacheHTTPInfo *info)
+{
+  http_info_ = info;
+}
+
+void
+MockCacheVC::set_ram_cache_hit(bool is_hit)
+{
+  ram_cache_hit_ = is_hit;
+}
+
+void
+MockCacheVC::set_object_size(int64_t size)
+{
+  object_size_ = size;
+}
+
+void
+MockCacheVC::simulate_cache_miss()
+{
+  if (read_vio_.cont) {
+    read_vio_.cont->handleEvent(CACHE_EVENT_OPEN_READ_FAILED, this);
+  }
+}
+
+void
+MockCacheVC::simulate_error(int lerrno)
+{
+  if (read_vio_.cont) {
+    read_vio_.cont->handleEvent(VC_EVENT_ERROR, this);
+  }
+  close_error_ = lerrno;
+}
+
+// ============== CacheVConnection Interface Implementation ==============
+
+VIO *
+MockCacheVC::do_io_read(Continuation *c, int64_t nbytes, MIOBuffer *buf)
+{
+  read_vio_.op        = VIO::READ;
+  read_vio_.cont      = c;
+  read_vio_.nbytes    = nbytes;
+  read_vio_.ndone     = 0;
+  read_vio_.buffer.writer_for(buf);
+  read_vio_.vc_server = this;
+
+  // Copy available data from our read_buffer to the provided buffer
+  int64_t avail = read_buffer_reader_->read_avail();
+  if (avail > 0) {
+    int64_t to_copy = (nbytes == INT64_MAX) ? avail : std::min(avail, nbytes);
+    buf->write(read_buffer_reader_, to_copy);
+    read_buffer_reader_->consume(to_copy);
+    read_vio_.ndone = to_copy;
+  }
+
+  return &read_vio_;
+}
+
+VIO *
+MockCacheVC::do_io_pread(Continuation *c, int64_t nbytes, MIOBuffer *buf, int64_t offset)
+{
+  // For simplicity, pread behaves like read but skips 'offset' bytes first
+  if (offset > 0) {
+    int64_t avail = read_buffer_reader_->read_avail();
+    if (offset < avail) {
+      read_buffer_reader_->consume(offset);
+    } else {
+      read_buffer_reader_->consume(avail);
+    }
+  }
+  return do_io_read(c, nbytes, buf);
+}
+
+VIO *
+MockCacheVC::do_io_write(Continuation *c, int64_t nbytes, IOBufferReader *buf, bool /* owner ATS_UNUSED */)
+{
+  write_vio_.op        = VIO::WRITE;
+  write_vio_.cont      = c;
+  write_vio_.nbytes    = nbytes;
+  write_vio_.ndone     = 0;
+  write_vio_.buffer.reader_for(buf);
+  write_vio_.vc_server = this;
+
+  // Capture any data that's already available
+  int64_t avail = buf->read_avail();
+  if (avail > 0) {
+    int64_t to_copy = (nbytes == INT64_MAX) ? avail : std::min(avail, nbytes);
+    write_capture_->write(buf, to_copy);
+    buf->consume(to_copy);
+    write_vio_.ndone = to_copy;
+  }
+
+  return &write_vio_;
+}
+
+void
+MockCacheVC::do_io_close(int lerrno)
+{
+  closed_       = true;
+  close_error_  = lerrno;
+  read_vio_.op  = VIO::NONE;
+  write_vio_.op = VIO::NONE;
+}
+
+void
+MockCacheVC::reenable(VIO *vio)
+{
+  if (vio == &read_vio_ && read_vio_.op == VIO::READ) {
+    int64_t avail = read_buffer_reader_->read_avail();
+    if (avail > 0 && read_vio_.cont) {
+      int64_t remaining = read_vio_.nbytes - read_vio_.ndone;
+      int64_t to_copy   = (remaining == INT64_MAX) ? avail : std::min(avail, remaining);
+      if (to_copy > 0) {
+        read_vio_.buffer.writer()->write(read_buffer_reader_, to_copy);
+        read_buffer_reader_->consume(to_copy);
+        read_vio_.ndone += to_copy;
+        read_vio_.cont->handleEvent(VC_EVENT_READ_READY, &read_vio_);
+      }
+    }
+  } else if (vio == &write_vio_ && write_vio_.op == VIO::WRITE) {
+    IOBufferReader *reader = write_vio_.buffer.reader();
+    if (reader) {
+      int64_t avail     = reader->read_avail();
+      int64_t remaining = write_vio_.nbytes - write_vio_.ndone;
+      int64_t to_copy   = (remaining == INT64_MAX) ? avail : std::min(avail, remaining);
+      if (to_copy > 0) {
+        write_capture_->write(reader, to_copy);
+        reader->consume(to_copy);
+        write_vio_.ndone += to_copy;
+        if (write_vio_.cont) {
+          write_vio_.cont->handleEvent(VC_EVENT_WRITE_READY, &write_vio_);
+        }
+      }
+    }
+  }
+}
+
+void
+MockCacheVC::reenable_re(VIO *vio)
+{
+  reenable(vio);
+}
+
+int
+MockCacheVC::get_header(void **ptr, int *len)
+{
+  if (header_ && header_len_ > 0) {
+    *ptr = header_;
+    *len = header_len_;
+    return 0;
+  }
+  return -1;
+}
+
+int
+MockCacheVC::set_header(void *ptr, int len)
+{
+  if (header_) {
+    ats_free(header_);
+  }
+  header_     = ats_malloc(len);
+  header_len_ = len;
+  memcpy(header_, ptr, len);
+  return 0;
+}
+
+int
+MockCacheVC::get_single_data(void **ptr, int *len)
+{
+  // Return available data as a single block
+  int64_t avail = read_buffer_reader_->read_avail();
+  if (avail > 0) {
+    IOBufferBlock *block = read_buffer_reader_->get_current_block();
+    if (block) {
+      *ptr = const_cast<char *>(block->start() + read_buffer_reader_->start_offset);
+      *len = static_cast<int>(avail);
+      return 0;
+    }
+  }
+  return -1;
+}
+
+void
+MockCacheVC::set_http_info(CacheHTTPInfo *info)
+{
+  http_info_ = info;
+}
+
+void
+MockCacheVC::get_http_info(CacheHTTPInfo **info)
+{
+  *info = http_info_;
+}
+
+bool
+MockCacheVC::is_ram_cache_hit() const
+{
+  return ram_cache_hit_;
+}
+
+bool
+MockCacheVC::set_pin_in_cache(time_t t)
+{
+  pin_in_cache_ = t;
+  return true;
+}
+
+time_t
+MockCacheVC::get_pin_in_cache()
+{
+  return pin_in_cache_;
+}
+
+int64_t
+MockCacheVC::get_object_size()
+{
+  return object_size_;
+}
+
+bool
+MockCacheVC::is_pread_capable()
+{
+  return true; // Mock supports pread
+}
diff --git a/src/test_utils/MockCacheVC.h b/src/test_utils/MockCacheVC.h
new file mode 100644
index 0000000000..94ef3fffc1
--- /dev/null
+++ b/src/test_utils/MockCacheVC.h
@@ -0,0 +1,155 @@
+/** @file
+
+  Mock CacheVConnection for unit testing
+
+  @section license License
+
+  Licensed to the Apache Software Foundation (ASF) under one
+  or more contributor license agreements.  See the NOTICE file
+  distributed with this work for additional information
+  regarding copyright ownership.  The ASF licenses this file
+  to you under the Apache License, Version 2.0 (the
+  "License"); you may not use this file except in compliance
+  with the License.  You may obtain a copy of the License at
+
+      http://www.apache.org/licenses/LICENSE-2.0
+
+  Unless required by applicable law or agreed to in writing, software
+  distributed under the License is distributed on an "AS IS" BASIS,
+  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+  See the License for the specific language governing permissions and
+  limitations under the License.
+*/
+
+#pragma once
+
+#include "iocore/cache/Cache.h"
+#include "iocore/eventsystem/IOBuffer.h"
+#include <string>
+#include <string_view>
+
+/**
+ * @class MockCacheVC
+ * @brief Mock CacheVConnection for unit testing
+ *
+ * This class provides a testable mock for CacheVConnection that allows:
+ * - Simulating cache reads (what would be read from cache)
+ * - Capturing cache writes (what would be written to cache)
+ * - Simulating cache miss/hit scenarios
+ * - Testing HTTP header handling
+ *
+ * Usage:
+ * @code
+ * MockCacheVC mock_cache;
+ * mock_cache.set_read_data("cached content");
+ * mock_cache.set_http_info(&cached_http_info);
+ * // ... use mock_cache in test ...
+ * std::string written = mock_cache.get_written_data();
+ * @endcode
+ */
+class MockCacheVC : public CacheVConnection
+{
+public:
+  MockCacheVC();
+  ~MockCacheVC() override;
+
+  // ============== Test Setup Methods ==============
+
+  /**
+   * Set the data that will be available for reading (cache hit scenario)
+   * @param data Data to be read from cache
+   */
+  void set_read_data(std::string_view data);
+
+  /**
+   * Get data that has been written to cache
+   * @return All data written to this mock cache
+   */
+  std::string get_written_data() const;
+
+  /**
+   * Clear the write buffer (reset captured writes)
+   */
+  void clear_written_data();
+
+  /**
+   * Set the HTTP info for this cache entry
+   * @param info HTTP info to associate with this cache entry
+   */
+  void set_http_info_for_test(CacheHTTPInfo *info);
+
+  /**
+   * Set whether this is a RAM cache hit
+   * @param is_hit true if this should simulate a RAM cache hit
+   */
+  void set_ram_cache_hit(bool is_hit);
+
+  /**
+   * Set the object size
+   * @param size Size of the cached object
+   */
+  void set_object_size(int64_t size);
+
+  /**
+   * Simulate a cache miss (sends CACHE_EVENT_OPEN_READ_FAILED)
+   */
+  void simulate_cache_miss();
+
+  /**
+   * Simulate a cache error
+   * @param lerrno Error number
+   */
+  void simulate_error(int lerrno);
+
+  // ============== CacheVConnection Interface Implementation ==============
+
+  VIO *do_io_read(Continuation *c, int64_t nbytes, MIOBuffer *buf) override;
+  VIO *do_io_pread(Continuation *c, int64_t nbytes, MIOBuffer *buf, int64_t offset) override;
+  VIO *do_io_write(Continuation *c, int64_t nbytes, IOBufferReader *buf, bool owner = false) override;
+  void do_io_close(int lerrno = -1) override;
+  void reenable(VIO *vio) override;
+  void reenable_re(VIO *vio) override;
+
+  int get_header(void **ptr, int *len) override;
+  int set_header(void *ptr, int len) override;
+  int get_single_data(void **ptr, int *len) override;
+
+  void set_http_info(CacheHTTPInfo *info) override;
+  void get_http_info(CacheHTTPInfo **info) override;
+
+  bool    is_ram_cache_hit() const override;
+  bool    set_pin_in_cache(time_t t) override;
+  time_t  get_pin_in_cache() override;
+  int64_t get_object_size() override;
+  bool    is_pread_capable() override;
+
+  // ============== Test State Access ==============
+
+  bool is_closed() const { return closed_; }
+  int  get_close_error() const { return close_error_; }
+
+private:
+  // Read side
+  MIOBuffer      *read_buffer_        = nullptr;
+  IOBufferReader *read_buffer_reader_ = nullptr;
+  VIO             read_vio_;
+
+  // Write side
+  MIOBuffer      *write_capture_        = nullptr;
+  IOBufferReader *write_capture_reader_ = nullptr;
+  VIO             write_vio_;
+
+  // Header storage
+  void  *header_     = nullptr;
+  int    header_len_ = 0;
+
+  // HTTP info
+  CacheHTTPInfo *http_info_ = nullptr;
+
+  // State
+  bool    closed_        = false;
+  int     close_error_   = 0;
+  bool    ram_cache_hit_ = false;
+  time_t  pin_in_cache_  = 0;
+  int64_t object_size_   = 0;
+};
diff --git a/src/test_utils/MockNetVC.cc b/src/test_utils/MockNetVC.cc
new file mode 100644
index 0000000000..145bbfe750
--- /dev/null
+++ b/src/test_utils/MockNetVC.cc
@@ -0,0 +1,376 @@
+/** @file
+
+  Mock NetVConnection implementation for unit testing
+
+  @section license License
+
+  Licensed to the Apache Software Foundation (ASF) under one
+  or more contributor license agreements.  See the NOTICE file
+  distributed with this work for additional information
+  regarding copyright ownership.  The ASF licenses this file
+  to you under the Apache License, Version 2.0 (the
+  "License"); you may not use this file except in compliance
+  with the License.  You may obtain a copy of the License at
+
+      http://www.apache.org/licenses/LICENSE-2.0
+
+  Unless required by applicable law or agreed to in writing, software
+  distributed under the License is distributed on an "AS IS" BASIS,
+  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+  See the License for the specific language governing permissions and
+  limitations under the License.
+*/
+
+#include "test_utils/MockNetVC.h"
+#include "tscore/ink_memory.h"
+
+MockNetVC::MockNetVC()
+{
+  // Initialize read buffer for simulating incoming data
+  read_buffer_        = new_MIOBuffer(BUFFER_SIZE_INDEX_4K);
+  read_buffer_reader_ = read_buffer_->alloc_reader();
+
+  // Initialize write capture buffer
+  write_capture_        = new_MIOBuffer(BUFFER_SIZE_INDEX_4K);
+  write_capture_reader_ = write_capture_->alloc_reader();
+}
+
+MockNetVC::~MockNetVC()
+{
+  if (read_buffer_) {
+    free_MIOBuffer(read_buffer_);
+  }
+  if (write_capture_) {
+    free_MIOBuffer(write_capture_);
+  }
+}
+
+// ============== Test Setup Methods ==============
+
+void
+MockNetVC::set_read_data(std::string_view data)
+{
+  // Clear existing data
+  read_buffer_reader_->consume(read_buffer_reader_->read_avail());
+  // Write new data
+  read_buffer_->write(data.data(), data.size());
+}
+
+void
+MockNetVC::append_read_data(std::string_view data)
+{
+  read_buffer_->write(data.data(), data.size());
+}
+
+std::string
+MockNetVC::get_written_data() const
+{
+  std::string result;
+  int64_t     avail = write_capture_reader_->read_avail();
+  if (avail > 0) {
+    result.resize(avail);
+    // We need to read without consuming, so copy block by block
+    IOBufferBlock *block = write_capture_reader_->get_current_block();
+    int64_t        offset = write_capture_reader_->start_offset;
+    size_t         pos    = 0;
+
+    while (block && pos < static_cast<size_t>(avail)) {
+      const char *start = block->start() + offset;
+      int64_t     len   = block->read_avail() - offset;
+      if (len > 0) {
+        if (pos + len > static_cast<size_t>(avail)) {
+          len = avail - pos;
+        }
+        memcpy(&result[pos], start, len);
+        pos += len;
+      }
+      block  = block->next.get();
+      offset = 0;
+    }
+  }
+  return result;
+}
+
+void
+MockNetVC::clear_written_data()
+{
+  write_capture_reader_->consume(write_capture_reader_->read_avail());
+}
+
+void
+MockNetVC::simulate_eos()
+{
+  eos_ = true;
+  if (read_vio_.cont) {
+    read_vio_.cont->handleEvent(VC_EVENT_EOS, &read_vio_);
+  }
+}
+
+void
+MockNetVC::simulate_error(int lerrno)
+{
+  error_ = lerrno;
+  if (read_vio_.cont) {
+    read_vio_.cont->handleEvent(VC_EVENT_ERROR, &read_vio_);
+  }
+}
+
+void
+MockNetVC::simulate_inactivity_timeout()
+{
+  if (read_vio_.cont) {
+    read_vio_.cont->handleEvent(VC_EVENT_INACTIVITY_TIMEOUT, &read_vio_);
+  }
+}
+
+void
+MockNetVC::simulate_active_timeout()
+{
+  if (read_vio_.cont) {
+    read_vio_.cont->handleEvent(VC_EVENT_ACTIVE_TIMEOUT, &read_vio_);
+  }
+}
+
+void
+MockNetVC::set_local_address(const sockaddr *addr)
+{
+  ats_ip_copy(&local_addr, addr);
+  got_local_addr = true;
+}
+
+void
+MockNetVC::set_remote_address(const sockaddr *addr)
+{
+  ats_ip_copy(&remote_addr, addr);
+  got_remote_addr = true;
+}
+
+// ============== NetVConnection Interface Implementation ==============
+
+VIO *
+MockNetVC::do_io_read(Continuation *c, int64_t nbytes, MIOBuffer *buf)
+{
+  read_vio_.op        = VIO::READ;
+  read_vio_.cont      = c;
+  read_vio_.nbytes    = nbytes;
+  read_vio_.ndone     = 0;
+  read_vio_.buffer.writer_for(buf);
+  read_vio_.vc_server = this;
+
+  // Copy available data from our read_buffer to the provided buffer
+  int64_t avail = read_buffer_reader_->read_avail();
+  if (avail > 0) {
+    int64_t to_copy = (nbytes == INT64_MAX) ? avail : std::min(avail, nbytes);
+    buf->write(read_buffer_reader_, to_copy);
+    read_buffer_reader_->consume(to_copy);
+    read_vio_.ndone = to_copy;
+  }
+
+  return &read_vio_;
+}
+
+VIO *
+MockNetVC::do_io_write(Continuation *c, int64_t nbytes, IOBufferReader *buf, bool /* owner ATS_UNUSED */)
+{
+  write_vio_.op        = VIO::WRITE;
+  write_vio_.cont      = c;
+  write_vio_.nbytes    = nbytes;
+  write_vio_.ndone     = 0;
+  write_vio_.buffer.reader_for(buf);
+  write_vio_.vc_server = this;
+
+  // Capture any data that's already available
+  int64_t avail = buf->read_avail();
+  if (avail > 0) {
+    int64_t to_copy = (nbytes == INT64_MAX) ? avail : std::min(avail, nbytes);
+    write_capture_->write(buf, to_copy);
+    buf->consume(to_copy);
+    write_vio_.ndone = to_copy;
+  }
+
+  return &write_vio_;
+}
+
+void
+MockNetVC::do_io_close(int lerrno)
+{
+  closed_      = true;
+  close_error_ = lerrno;
+  read_vio_.op  = VIO::NONE;
+  write_vio_.op = VIO::NONE;
+}
+
+void
+MockNetVC::do_io_shutdown(ShutdownHowTo_t howto)
+{
+  switch (howto) {
+  case IO_SHUTDOWN_READ:
+    read_shutdown_ = true;
+    read_vio_.op   = VIO::NONE;
+    break;
+  case IO_SHUTDOWN_WRITE:
+    write_shutdown_ = true;
+    write_vio_.op   = VIO::NONE;
+    break;
+  case IO_SHUTDOWN_READWRITE:
+    read_shutdown_  = true;
+    write_shutdown_ = true;
+    read_vio_.op    = VIO::NONE;
+    write_vio_.op   = VIO::NONE;
+    break;
+  }
+}
+
+void
+MockNetVC::reenable(VIO *vio)
+{
+  if (vio == &read_vio_ && read_vio_.op == VIO::READ) {
+    // Check if there's more data to read
+    int64_t avail = read_buffer_reader_->read_avail();
+    if (avail > 0 && read_vio_.cont) {
+      int64_t remaining = read_vio_.nbytes - read_vio_.ndone;
+      int64_t to_copy   = (remaining == INT64_MAX) ? avail : std::min(avail, remaining);
+      if (to_copy > 0) {
+        read_vio_.buffer.writer()->write(read_buffer_reader_, to_copy);
+        read_buffer_reader_->consume(to_copy);
+        read_vio_.ndone += to_copy;
+        read_vio_.cont->handleEvent(VC_EVENT_READ_READY, &read_vio_);
+      }
+    } else if (eos_ && read_vio_.cont) {
+      read_vio_.cont->handleEvent(VC_EVENT_EOS, &read_vio_);
+    }
+  } else if (vio == &write_vio_ && write_vio_.op == VIO::WRITE) {
+    // Capture any newly available write data
+    IOBufferReader *reader = write_vio_.buffer.reader();
+    if (reader) {
+      int64_t avail     = reader->read_avail();
+      int64_t remaining = write_vio_.nbytes - write_vio_.ndone;
+      int64_t to_copy   = (remaining == INT64_MAX) ? avail : std::min(avail, remaining);
+      if (to_copy > 0) {
+        write_capture_->write(reader, to_copy);
+        reader->consume(to_copy);
+        write_vio_.ndone += to_copy;
+        if (write_vio_.cont) {
+          write_vio_.cont->handleEvent(VC_EVENT_WRITE_READY, &write_vio_);
+        }
+      }
+    }
+  }
+}
+
+void
+MockNetVC::reenable_re(VIO *vio)
+{
+  reenable(vio);
+}
+
+void
+MockNetVC::set_active_timeout(ink_hrtime timeout_in)
+{
+  active_timeout_ = timeout_in;
+}
+
+void
+MockNetVC::set_inactivity_timeout(ink_hrtime timeout_in)
+{
+  inactivity_timeout_         = timeout_in;
+  default_inactivity_timeout_ = false;
+}
+
+void
+MockNetVC::set_default_inactivity_timeout(ink_hrtime timeout_in)
+{
+  inactivity_timeout_         = timeout_in;
+  default_inactivity_timeout_ = true;
+}
+
+bool
+MockNetVC::is_default_inactivity_timeout()
+{
+  return default_inactivity_timeout_;
+}
+
+void
+MockNetVC::cancel_active_timeout()
+{
+  active_timeout_ = 0;
+}
+
+void
+MockNetVC::cancel_inactivity_timeout()
+{
+  inactivity_timeout_ = 0;
+}
+
+ink_hrtime
+MockNetVC::get_active_timeout()
+{
+  return active_timeout_;
+}
+
+ink_hrtime
+MockNetVC::get_inactivity_timeout()
+{
+  return inactivity_timeout_;
+}
+
+void
+MockNetVC::apply_options()
+{
+  // No-op for mock
+}
+
+SOCKET
+MockNetVC::get_socket()
+{
+  return -1; // Invalid socket for mock
+}
+
+int
+MockNetVC::set_tcp_congestion_control(tcp_congestion_control_side /* side ATS_UNUSED */)
+{
+  return 0; // Success for mock
+}
+
+void
+MockNetVC::set_local_addr()
+{
+  // No-op for mock - use set_local_address() instead
+}
+
+void
+MockNetVC::set_remote_addr()
+{
+  // No-op for mock - use set_remote_address() instead
+}
+
+void
+MockNetVC::set_remote_addr(const sockaddr *addr)
+{
+  set_remote_address(addr);
+}
+
+void
+MockNetVC::set_mptcp_state()
+{
+  // No-op for mock
+}
+
+int
+MockNetVC::populate_protocol(std::string_view *results, int n) const
+{
+  if (n > 0) {
+    results[0] = "tcp";
+    return 1;
+  }
+  return 0;
+}
+
+const char *
+MockNetVC::protocol_contains(std::string_view tag) const
+{
+  if (tag == "tcp") {
+    return "tcp";
+  }
+  return nullptr;
+}
diff --git a/src/test_utils/MockNetVC.h b/src/test_utils/MockNetVC.h
new file mode 100644
index 0000000000..6fb7d0f2d7
--- /dev/null
+++ b/src/test_utils/MockNetVC.h
@@ -0,0 +1,176 @@
+/** @file
+
+  Mock NetVConnection for unit testing
+
+  @section license License
+
+  Licensed to the Apache Software Foundation (ASF) under one
+  or more contributor license agreements.  See the NOTICE file
+  distributed with this work for additional information
+  regarding copyright ownership.  The ASF licenses this file
+  to you under the Apache License, Version 2.0 (the
+  "License"); you may not use this file except in compliance
+  with the License.  You may obtain a copy of the License at
+
+      http://www.apache.org/licenses/LICENSE-2.0
+
+  Unless required by applicable law or agreed to in writing, software
+  distributed under the License is distributed on an "AS IS" BASIS,
+  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+  See the License for the specific language governing permissions and
+  limitations under the License.
+*/
+
+#pragma once
+
+#include "iocore/net/NetVConnection.h"
+#include "iocore/eventsystem/IOBuffer.h"
+#include <string>
+#include <string_view>
+
+/**
+ * @class MockNetVC
+ * @brief Mock NetVConnection for unit testing
+ *
+ * This class provides a testable mock for NetVConnection that allows:
+ * - Simulating incoming data (what would be read from a network connection)
+ * - Capturing outgoing data (what would be written to a network connection)
+ * - Simulating network events (EOS, errors, timeouts)
+ *
+ * Usage:
+ * @code
+ * MockNetVC mock_vc;
+ * mock_vc.set_read_data("GET / HTTP/1.1\r\n\r\n");
+ * // ... use mock_vc in test ...
+ * std::string written = mock_vc.get_written_data();
+ * @endcode
+ */
+class MockNetVC : public NetVConnection
+{
+public:
+  MockNetVC();
+  ~MockNetVC() override;
+
+  // ============== Test Setup Methods ==============
+
+  /**
+   * Set the data that will be available for reading
+   * @param data Data to be read from this mock connection
+   */
+  void set_read_data(std::string_view data);
+
+  /**
+   * Append more data to be read (simulates data arriving later)
+   * @param data Additional data to be read
+   */
+  void append_read_data(std::string_view data);
+
+  /**
+   * Get data that has been written to this connection
+   * @return All data written to this mock connection
+   */
+  std::string get_written_data() const;
+
+  /**
+   * Clear the write buffer (reset captured writes)
+   */
+  void clear_written_data();
+
+  /**
+   * Simulate an end-of-stream condition
+   */
+  void simulate_eos();
+
+  /**
+   * Simulate an error condition
+   * @param lerrno The error number to simulate
+   */
+  void simulate_error(int lerrno);
+
+  /**
+   * Simulate an inactivity timeout
+   */
+  void simulate_inactivity_timeout();
+
+  /**
+   * Simulate an active timeout
+   */
+  void simulate_active_timeout();
+
+  /**
+   * Set the local address for this connection
+   */
+  void set_local_address(const sockaddr *addr);
+
+  /**
+   * Set the remote address for this connection
+   */
+  void set_remote_address(const sockaddr *addr);
+
+  // ============== NetVConnection Interface Implementation ==============
+
+  VIO *do_io_read(Continuation *c, int64_t nbytes, MIOBuffer *buf) override;
+  VIO *do_io_write(Continuation *c, int64_t nbytes, IOBufferReader *buf, bool owner = false) override;
+  void do_io_close(int lerrno = -1) override;
+  void do_io_shutdown(ShutdownHowTo_t howto) override;
+
+  void reenable(VIO *vio) override;
+  void reenable_re(VIO *vio) override;
+
+  // Timeout methods (store values but don't actually time out)
+  void         set_active_timeout(ink_hrtime timeout_in) override;
+  void         set_inactivity_timeout(ink_hrtime timeout_in) override;
+  void         set_default_inactivity_timeout(ink_hrtime timeout_in) override;
+  bool         is_default_inactivity_timeout() override;
+  void         cancel_active_timeout() override;
+  void         cancel_inactivity_timeout() override;
+  ink_hrtime   get_active_timeout() override;
+  ink_hrtime   get_inactivity_timeout() override;
+  virtual void apply_options() override;
+
+  // Note: Address methods are not virtual in NetVConnection.
+  // They use the protected local_addr/remote_addr members directly.
+  // We set these via set_local_address() and set_remote_address() above.
+
+  // Misc methods
+  SOCKET get_socket() override;
+  int    set_tcp_congestion_control(tcp_congestion_control_side side) override;
+  void   set_local_addr() override;
+  void   set_remote_addr() override;
+  void   set_remote_addr(const sockaddr *) override;
+  void   set_mptcp_state() override;
+
+  int populate_protocol(std::string_view *results, int n) const override;
+  const char  *protocol_contains(std::string_view tag) const override;
+
+  // ============== Test State Access ==============
+
+  bool is_closed() const { return closed_; }
+  int  get_close_error() const { return close_error_; }
+  bool is_read_shutdown() const { return read_shutdown_; }
+  bool is_write_shutdown() const { return write_shutdown_; }
+
+private:
+  // Read side
+  MIOBuffer      *read_buffer_       = nullptr;
+  IOBufferReader *read_buffer_reader_ = nullptr;
+  VIO             read_vio_;
+
+  // Write side
+  MIOBuffer      *write_capture_     = nullptr;
+  IOBufferReader *write_capture_reader_ = nullptr;
+  VIO             write_vio_;
+
+  // State
+  bool closed_          = false;
+  int  close_error_     = 0;
+  bool read_shutdown_   = false;
+  bool write_shutdown_  = false;
+  bool eos_             = false;
+  int  error_           = 0;
+
+  // Timeouts
+  ink_hrtime active_timeout_     = 0;
+  ink_hrtime inactivity_timeout_ = 0;
+  bool       default_inactivity_timeout_ = false;
+};


(trafficserver) 01/02: WIP: Unit test coverage infrastructure

Posted by bc...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

bcall pushed a commit to branch unit-test-coverage
in repository https://gitbox.apache.org/repos/asf/trafficserver.git

commit d43e14376ca5f0b1f1b1e71605c5a712a07eccdd
Author: Bryan Call <bc...@apache.org>
AuthorDate: Tue Jan 20 19:24:52 2026 -0800

    WIP: Unit test coverage infrastructure
    
    Phase 1 progress:
    - Add dev-coverage CMake preset for gcov instrumentation
    - Add tools/coverage-report.sh for generating coverage reports
    - Add src/test_utils/ with MockIOBuffer and TestEventProcessor
    
    Part of unit test coverage improvement plan.
---
 CMakeLists.txt                       |   3 +
 CMakePresets.json                    |  17 ++++
 src/test_utils/CMakeLists.txt        |  39 ++++++++
 src/test_utils/MockIOBuffer.cc       | 140 ++++++++++++++++++++++++++++
 src/test_utils/MockIOBuffer.h        | 146 ++++++++++++++++++++++++++++++
 src/test_utils/TestEventProcessor.cc |  73 +++++++++++++++
 src/test_utils/TestEventProcessor.h  | 115 +++++++++++++++++++++++
 tools/coverage-report.sh             | 171 +++++++++++++++++++++++++++++++++++
 8 files changed, 704 insertions(+)

diff --git a/CMakeLists.txt b/CMakeLists.txt
index 7df4f8b63c..817a0cc5b8 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -741,6 +741,9 @@ add_subdirectory(src/tsutil)
 add_subdirectory(src/tscore)
 add_subdirectory(src/records)
 add_subdirectory(src/iocore)
+if(BUILD_TESTING)
+  add_subdirectory(src/test_utils)
+endif()
 add_subdirectory(src/proxy)
 add_subdirectory(src/shared)
 add_subdirectory(src/mgmt/config)
diff --git a/CMakePresets.json b/CMakePresets.json
index 3fe7e010b8..996cc20af8 100644
--- a/CMakePresets.json
+++ b/CMakePresets.json
@@ -116,6 +116,23 @@
       "description": "Development Presets with ASAN sanitizer",
       "inherits": ["dev", "asan"]
     },
+    {
+      "name": "coverage",
+      "hidden": true,
+      "cacheVariables": {
+        "CMAKE_CXX_FLAGS": "-fprofile-arcs -ftest-coverage -g -O0",
+        "CMAKE_C_FLAGS": "-fprofile-arcs -ftest-coverage -g -O0",
+        "CMAKE_EXE_LINKER_FLAGS": "-lgcov --coverage",
+        "CMAKE_SHARED_LINKER_FLAGS": "-lgcov --coverage"
+      }
+    },
+    {
+      "name": "dev-coverage",
+      "displayName": "dev with coverage",
+      "description": "Development build with gcov code coverage instrumentation",
+      "inherits": ["dev", "coverage"],
+      "binaryDir": "${sourceDir}/build-coverage"
+    },
     {
       "name": "ci",
       "displayName": "CI defaults",
diff --git a/src/test_utils/CMakeLists.txt b/src/test_utils/CMakeLists.txt
new file mode 100644
index 0000000000..339994e283
--- /dev/null
+++ b/src/test_utils/CMakeLists.txt
@@ -0,0 +1,39 @@
+#######################
+#
+#  Licensed to the Apache Software Foundation (ASF) under one or more contributor license
+#  agreements.  See the NOTICE file distributed with this work for additional information regarding
+#  copyright ownership.  The ASF licenses this file to you under the Apache License, Version 2.0
+#  (the "License"); you may not use this file except in compliance with the License.  You may obtain
+#  a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+#  Unless required by applicable law or agreed to in writing, software distributed under the License
+#  is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
+#  or implied. See the License for the specific language governing permissions and limitations under
+#  the License.
+#
+#######################
+
+# Test utilities library
+# Provides mock objects and test infrastructure for unit testing
+
+add_library(
+  ats_test_utils STATIC
+  MockIOBuffer.cc
+  TestEventProcessor.cc
+)
+
+target_include_directories(
+  ats_test_utils
+  PUBLIC ${PROJECT_SOURCE_DIR}/include
+         ${PROJECT_SOURCE_DIR}/src
+)
+
+target_link_libraries(
+  ats_test_utils
+  PUBLIC ts::inkevent
+         ts::tscore
+)
+
+add_library(ts::ats_test_utils ALIAS ats_test_utils)
diff --git a/src/test_utils/MockIOBuffer.cc b/src/test_utils/MockIOBuffer.cc
new file mode 100644
index 0000000000..05ab07d0fd
--- /dev/null
+++ b/src/test_utils/MockIOBuffer.cc
@@ -0,0 +1,140 @@
+/** @file
+
+  Mock IOBuffer implementation
+
+  @section license License
+
+  Licensed to the Apache Software Foundation (ASF) under one
+  or more contributor license agreements.  See the NOTICE file
+  distributed with this work for additional information
+  regarding copyright ownership.  The ASF licenses this file
+  to you under the Apache License, Version 2.0 (the
+  "License"); you may not use this file except in compliance
+  with the License.  You may obtain a copy of the License at
+
+      http://www.apache.org/licenses/LICENSE-2.0
+
+  Unless required by applicable law or agreed to in writing, software
+  distributed under the License is distributed on an "AS IS" BASIS,
+  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+  See the License for the specific language governing permissions and
+  limitations under the License.
+*/
+
+#include "test_utils/MockIOBuffer.h"
+
+MockIOBuffer::MockIOBuffer(int64_t size_index)
+{
+  buffer_ = new_MIOBuffer(size_index);
+  reader_ = buffer_->alloc_reader();
+}
+
+MockIOBuffer::MockIOBuffer(std::string_view data, int64_t size_index) : MockIOBuffer(size_index)
+{
+  write(data);
+}
+
+MockIOBuffer::~MockIOBuffer()
+{
+  if (buffer_) {
+    free_MIOBuffer(buffer_);
+  }
+}
+
+MockIOBuffer::MockIOBuffer(MockIOBuffer &&other) noexcept : buffer_(other.buffer_), reader_(other.reader_)
+{
+  other.buffer_ = nullptr;
+  other.reader_ = nullptr;
+}
+
+MockIOBuffer &
+MockIOBuffer::operator=(MockIOBuffer &&other) noexcept
+{
+  if (this != &other) {
+    if (buffer_) {
+      free_MIOBuffer(buffer_);
+    }
+    buffer_       = other.buffer_;
+    reader_       = other.reader_;
+    other.buffer_ = nullptr;
+    other.reader_ = nullptr;
+  }
+  return *this;
+}
+
+int64_t
+MockIOBuffer::write(std::string_view data)
+{
+  return write(data.data(), data.size());
+}
+
+int64_t
+MockIOBuffer::write(const void *data, int64_t len)
+{
+  return buffer_->write(data, len);
+}
+
+IOBufferReader *
+MockIOBuffer::reader()
+{
+  return reader_;
+}
+
+std::string
+MockIOBuffer::read_all()
+{
+  std::string result;
+  int64_t     avail = reader_->read_avail();
+  if (avail > 0) {
+    result.resize(avail);
+    reader_->read(result.data(), avail);
+  }
+  return result;
+}
+
+int64_t
+MockIOBuffer::available() const
+{
+  return reader_->read_avail();
+}
+
+void
+MockIOBuffer::reset()
+{
+  reader_->consume(reader_->read_avail());
+}
+
+// MockIOBufferChain implementation
+
+MockIOBufferChain::MockIOBufferChain(std::string_view data, int64_t block_size)
+{
+  buffer_ = new_MIOBuffer(BUFFER_SIZE_INDEX_4K);
+  reader_ = buffer_->alloc_reader();
+
+  // Write data in chunks to create multiple blocks
+  size_t offset = 0;
+  while (offset < data.size()) {
+    size_t chunk_size = std::min(static_cast<size_t>(block_size), data.size() - offset);
+    buffer_->write(data.data() + offset, chunk_size);
+    offset += chunk_size;
+  }
+}
+
+MockIOBufferChain::~MockIOBufferChain()
+{
+  if (buffer_) {
+    free_MIOBuffer(buffer_);
+  }
+}
+
+IOBufferReader *
+MockIOBufferChain::reader()
+{
+  return reader_;
+}
+
+MIOBuffer *
+MockIOBufferChain::buffer()
+{
+  return buffer_;
+}
diff --git a/src/test_utils/MockIOBuffer.h b/src/test_utils/MockIOBuffer.h
new file mode 100644
index 0000000000..51e6db3008
--- /dev/null
+++ b/src/test_utils/MockIOBuffer.h
@@ -0,0 +1,146 @@
+/** @file
+
+  Mock IOBuffer utilities for unit testing
+
+  @section license License
+
+  Licensed to the Apache Software Foundation (ASF) under one
+  or more contributor license agreements.  See the NOTICE file
+  distributed with this work for additional information
+  regarding copyright ownership.  The ASF licenses this file
+  to you under the Apache License, Version 2.0 (the
+  "License"); you may not use this file except in compliance
+  with the License.  You may obtain a copy of the License at
+
+      http://www.apache.org/licenses/LICENSE-2.0
+
+  Unless required by applicable law or agreed to in writing, software
+  distributed under the License is distributed on an "AS IS" BASIS,
+  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+  See the License for the specific language governing permissions and
+  limitations under the License.
+*/
+
+#pragma once
+
+#include "iocore/eventsystem/IOBuffer.h"
+#include <string>
+#include <string_view>
+
+/**
+ * @class MockIOBuffer
+ * @brief Helper class for creating and managing IOBuffers in tests
+ *
+ * Simplifies the creation and manipulation of IOBuffers for unit testing.
+ * Handles proper allocation and cleanup.
+ *
+ * Usage:
+ * @code
+ * MockIOBuffer buf("test data");
+ * IOBufferReader *reader = buf.reader();
+ * // ... use reader in tests ...
+ * @endcode
+ */
+class MockIOBuffer
+{
+public:
+  /**
+   * Create an empty MockIOBuffer
+   * @param size_index Buffer size index (default: BUFFER_SIZE_INDEX_4K)
+   */
+  explicit MockIOBuffer(int64_t size_index = BUFFER_SIZE_INDEX_4K);
+
+  /**
+   * Create a MockIOBuffer with initial data
+   * @param data Initial data to write to the buffer
+   * @param size_index Buffer size index (default: BUFFER_SIZE_INDEX_4K)
+   */
+  MockIOBuffer(std::string_view data, int64_t size_index = BUFFER_SIZE_INDEX_4K);
+
+  ~MockIOBuffer();
+
+  // Non-copyable
+  MockIOBuffer(const MockIOBuffer &)            = delete;
+  MockIOBuffer &operator=(const MockIOBuffer &) = delete;
+
+  // Movable
+  MockIOBuffer(MockIOBuffer &&other) noexcept;
+  MockIOBuffer &operator=(MockIOBuffer &&other) noexcept;
+
+  /**
+   * Write data to the buffer
+   * @param data Data to write
+   * @return Number of bytes written
+   */
+  int64_t write(std::string_view data);
+
+  /**
+   * Write data to the buffer
+   * @param data Pointer to data
+   * @param len Length of data
+   * @return Number of bytes written
+   */
+  int64_t write(const void *data, int64_t len);
+
+  /**
+   * Get a reader for this buffer
+   * @return Pointer to IOBufferReader (owned by the MIOBuffer)
+   */
+  IOBufferReader *reader();
+
+  /**
+   * Get the underlying MIOBuffer
+   * @return Pointer to MIOBuffer
+   */
+  MIOBuffer *
+  buffer()
+  {
+    return buffer_;
+  }
+
+  /**
+   * Read all available data as a string
+   * @return String containing all data in the buffer
+   */
+  std::string read_all();
+
+  /**
+   * Get the number of bytes available to read
+   */
+  int64_t available() const;
+
+  /**
+   * Reset the buffer (clear all data)
+   */
+  void reset();
+
+private:
+  MIOBuffer      *buffer_ = nullptr;
+  IOBufferReader *reader_ = nullptr;
+};
+
+/**
+ * @class MockIOBufferChain
+ * @brief Helper for creating multi-block IOBuffer chains for testing
+ *
+ * Useful for testing code that handles data spanning multiple IOBuffer blocks.
+ */
+class MockIOBufferChain
+{
+public:
+  /**
+   * Create a chain with data split across multiple blocks
+   * @param data Data to write
+   * @param block_size Maximum size per block
+   */
+  MockIOBufferChain(std::string_view data, int64_t block_size);
+
+  ~MockIOBufferChain();
+
+  IOBufferReader *reader();
+  MIOBuffer      *buffer();
+
+private:
+  MIOBuffer      *buffer_ = nullptr;
+  IOBufferReader *reader_ = nullptr;
+};
diff --git a/src/test_utils/TestEventProcessor.cc b/src/test_utils/TestEventProcessor.cc
new file mode 100644
index 0000000000..24db51a495
--- /dev/null
+++ b/src/test_utils/TestEventProcessor.cc
@@ -0,0 +1,73 @@
+/** @file
+
+  Test Event Processor implementation
+
+  @section license License
+
+  Licensed to the Apache Software Foundation (ASF) under one
+  or more contributor license agreements.  See the NOTICE file
+  distributed with this work for additional information
+  regarding copyright ownership.  The ASF licenses this file
+  to you under the Apache License, Version 2.0 (the
+  "License"); you may not use this file except in compliance
+  with the License.  You may obtain a copy of the License at
+
+      http://www.apache.org/licenses/LICENSE-2.0
+
+  Unless required by applicable law or agreed to in writing, software
+  distributed under the License is distributed on an "AS IS" BASIS,
+  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+  See the License for the specific language governing permissions and
+  limitations under the License.
+*/
+
+#include "test_utils/TestEventProcessor.h"
+#include "iocore/eventsystem/IOBuffer.h"
+#include "tscore/ink_memory.h"
+
+TestEventProcessor *TestEventProcessor::instance_ = nullptr;
+
+TestEventProcessor::TestEventProcessor()
+{
+  if (instance_ != nullptr) {
+    // Only one instance allowed at a time
+    ink_release_assert(!"TestEventProcessor already instantiated");
+  }
+  instance_ = this;
+}
+
+TestEventProcessor::~TestEventProcessor()
+{
+  if (running_.load()) {
+    stop();
+  }
+  instance_ = nullptr;
+}
+
+void
+TestEventProcessor::start()
+{
+  if (running_.exchange(true)) {
+    return; // Already running
+  }
+
+  // Initialize IOBuffer system
+  // This is the minimum required for most unit tests
+  init_buffer_allocators(0); // Use default thread ID
+}
+
+void
+TestEventProcessor::stop()
+{
+  if (!running_.exchange(false)) {
+    return; // Already stopped
+  }
+
+  // Cleanup is handled by the IOBuffer system's static destructors
+}
+
+TestEventProcessor *
+TestEventProcessor::instance()
+{
+  return instance_;
+}
diff --git a/src/test_utils/TestEventProcessor.h b/src/test_utils/TestEventProcessor.h
new file mode 100644
index 0000000000..febabd125a
--- /dev/null
+++ b/src/test_utils/TestEventProcessor.h
@@ -0,0 +1,115 @@
+/** @file
+
+  Test Event Processor - Controllable event loop for unit testing
+
+  @section license License
+
+  Licensed to the Apache Software Foundation (ASF) under one
+  or more contributor license agreements.  See the NOTICE file
+  distributed with this work for additional information
+  regarding copyright ownership.  The ASF licenses this file
+  to you under the Apache License, Version 2.0 (the
+  "License"); you may not use this file except in compliance
+  with the License.  You may obtain a copy of the License at
+
+      http://www.apache.org/licenses/LICENSE-2.0
+
+  Unless required by applicable law or agreed to in writing, software
+  distributed under the License is distributed on an "AS IS" BASIS,
+  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+  See the License for the specific language governing permissions and
+  limitations under the License.
+*/
+
+#pragma once
+
+#include "iocore/eventsystem/EventSystem.h"
+#include "iocore/eventsystem/EThread.h"
+#include "iocore/eventsystem/Tasks.h"
+
+#include <atomic>
+
+/**
+ * @class TestEventProcessor
+ * @brief A simplified event processor for unit testing
+ *
+ * This class provides a controllable event loop that can be used in unit tests
+ * without requiring the full ATS event system infrastructure. It supports:
+ *
+ * - Single-threaded event processing
+ * - Synchronous event dispatch for deterministic testing
+ * - IOBuffer operations without network I/O
+ *
+ * Usage:
+ * @code
+ * TestEventProcessor ep;
+ * ep.start();
+ * // ... run tests ...
+ * ep.stop();
+ * @endcode
+ */
+class TestEventProcessor
+{
+public:
+  TestEventProcessor();
+  ~TestEventProcessor();
+
+  /**
+   * Start the test event processor
+   * Initializes minimal infrastructure needed for IOBuffer operations
+   */
+  void start();
+
+  /**
+   * Stop the test event processor
+   * Cleans up all resources
+   */
+  void stop();
+
+  /**
+   * Check if the event processor is running
+   */
+  bool
+  is_running() const
+  {
+    return running_.load();
+  }
+
+  /**
+   * Get the event processor singleton
+   * Ensures only one test event processor is active
+   */
+  static TestEventProcessor *instance();
+
+private:
+  std::atomic<bool> running_{false};
+  static TestEventProcessor *instance_;
+};
+
+/**
+ * @class TestEventProcessorScope
+ * @brief RAII wrapper for TestEventProcessor
+ *
+ * Automatically starts the event processor on construction and stops on destruction.
+ *
+ * Usage:
+ * @code
+ * TEST_CASE("my test") {
+ *   TestEventProcessorScope ep_scope;
+ *   // Event processor is now running
+ *   // ... test code ...
+ * } // Event processor automatically stopped
+ * @endcode
+ */
+class TestEventProcessorScope
+{
+public:
+  TestEventProcessorScope() { ep_.start(); }
+  ~TestEventProcessorScope() { ep_.stop(); }
+
+  TestEventProcessorScope(const TestEventProcessorScope &)            = delete;
+  TestEventProcessorScope &operator=(const TestEventProcessorScope &) = delete;
+
+private:
+  TestEventProcessor ep_;
+};
diff --git a/tools/coverage-report.sh b/tools/coverage-report.sh
new file mode 100755
index 0000000000..23606316ce
--- /dev/null
+++ b/tools/coverage-report.sh
@@ -0,0 +1,171 @@
+#!/bin/bash
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+# Generate code coverage report using gcov/lcov
+#
+# Usage: ./tools/coverage-report.sh [--html] [--threshold N]
+#
+# Options:
+#   --html        Generate HTML report (requires genhtml)
+#   --threshold N Fail if coverage is below N% (default: 0, disabled)
+#   --clean       Clean build directory before building
+#   --help        Show this help message
+#
+
+set -e
+
+SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+PROJECT_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)"
+BUILD_DIR="${PROJECT_ROOT}/build-coverage"
+COVERAGE_DIR="${PROJECT_ROOT}/coverage-report"
+
+GENERATE_HTML=0
+THRESHOLD=0
+CLEAN=0
+
+# Parse arguments
+while [[ $# -gt 0 ]]; do
+    case $1 in
+        --html)
+            GENERATE_HTML=1
+            shift
+            ;;
+        --threshold)
+            THRESHOLD="$2"
+            shift 2
+            ;;
+        --clean)
+            CLEAN=1
+            shift
+            ;;
+        --help)
+            echo "Usage: $0 [--html] [--threshold N] [--clean]"
+            echo ""
+            echo "Options:"
+            echo "  --html        Generate HTML report (requires genhtml)"
+            echo "  --threshold N Fail if coverage is below N% (default: 0, disabled)"
+            echo "  --clean       Clean build directory before building"
+            echo "  --help        Show this help message"
+            exit 0
+            ;;
+        *)
+            echo "Unknown option: $1"
+            exit 1
+            ;;
+    esac
+done
+
+# Check for required tools
+check_tool() {
+    if ! command -v "$1" &> /dev/null; then
+        echo "Error: $1 is required but not installed."
+        echo "Install with: $2"
+        exit 1
+    fi
+}
+
+check_tool lcov "brew install lcov (macOS) or apt install lcov (Linux)"
+if [[ $GENERATE_HTML -eq 1 ]]; then
+    check_tool genhtml "brew install lcov (macOS) or apt install lcov (Linux)"
+fi
+
+cd "${PROJECT_ROOT}"
+
+# Clean if requested
+if [[ $CLEAN -eq 1 ]] && [[ -d "${BUILD_DIR}" ]]; then
+    echo "==> Cleaning build directory..."
+    rm -rf "${BUILD_DIR}"
+fi
+
+# Configure
+echo "==> Configuring with coverage preset..."
+cmake --preset dev-coverage
+
+# Build
+echo "==> Building..."
+cmake --build "${BUILD_DIR}" -j "$(nproc 2>/dev/null || sysctl -n hw.ncpu)"
+
+# Run tests
+echo "==> Running tests..."
+ctest --test-dir "${BUILD_DIR}" --output-on-failure || true
+
+# Capture coverage data
+echo "==> Capturing coverage data..."
+lcov --capture \
+    --directory "${BUILD_DIR}" \
+    --output-file "${BUILD_DIR}/coverage.info" \
+    --ignore-errors mismatch
+
+# Remove system headers and test files from coverage
+echo "==> Filtering coverage data..."
+lcov --remove "${BUILD_DIR}/coverage.info" \
+    '/usr/*' \
+    '/opt/*' \
+    '*/unit_tests/*' \
+    '*/test_*' \
+    '*/lib/Catch2/*' \
+    '*/lib/yamlcpp/*' \
+    '*/lib/swoc/*' \
+    --output-file "${BUILD_DIR}/coverage-filtered.info" \
+    --ignore-errors unused
+
+# Generate summary
+echo ""
+echo "==> Coverage Summary:"
+lcov --summary "${BUILD_DIR}/coverage-filtered.info" 2>&1 | tee "${BUILD_DIR}/coverage-summary.txt"
+
+# Extract coverage percentage
+COVERAGE=$(lcov --summary "${BUILD_DIR}/coverage-filtered.info" 2>&1 | grep "lines" | grep -oP '\d+\.\d+%' | head -1 | tr -d '%')
+
+if [[ -z "$COVERAGE" ]]; then
+    # Try alternative parsing for different lcov versions
+    COVERAGE=$(lcov --summary "${BUILD_DIR}/coverage-filtered.info" 2>&1 | grep -oE '[0-9]+\.[0-9]+%' | head -1 | tr -d '%')
+fi
+
+echo ""
+echo "Line coverage: ${COVERAGE:-unknown}%"
+
+# Generate HTML report if requested
+if [[ $GENERATE_HTML -eq 1 ]]; then
+    echo "==> Generating HTML report..."
+    rm -rf "${COVERAGE_DIR}"
+    genhtml "${BUILD_DIR}/coverage-filtered.info" \
+        --output-directory "${COVERAGE_DIR}" \
+        --title "ATS Code Coverage" \
+        --legend \
+        --show-details
+    echo ""
+    echo "HTML report generated at: ${COVERAGE_DIR}/index.html"
+fi
+
+# Check threshold
+if [[ $THRESHOLD -gt 0 ]] && [[ -n "$COVERAGE" ]]; then
+    COVERAGE_INT=${COVERAGE%.*}
+    if [[ $COVERAGE_INT -lt $THRESHOLD ]]; then
+        echo ""
+        echo "ERROR: Coverage ${COVERAGE}% is below threshold ${THRESHOLD}%"
+        exit 1
+    fi
+    echo "Coverage ${COVERAGE}% meets threshold ${THRESHOLD}%"
+fi
+
+echo ""
+echo "==> Coverage report complete!"
+echo "Raw coverage data: ${BUILD_DIR}/coverage.info"
+echo "Filtered coverage: ${BUILD_DIR}/coverage-filtered.info"
+echo "Summary: ${BUILD_DIR}/coverage-summary.txt"