[libc-commits] [libc] [libc] Add socket test support library (PR #193207)

Pavel Labath via libc-commits libc-commits at lists.llvm.org
Wed Apr 22 02:40:58 PDT 2026


================
@@ -0,0 +1,92 @@
+//===-- Helpers for socket tests --------------------------------*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_LIBC_TEST_SRC_SYS_SOCKET_LINUX_SOCKET_TEST_SUPPORT_H
+#define LLVM_LIBC_TEST_SRC_SYS_SOCKET_LINUX_SOCKET_TEST_SUPPORT_H
+
+#include "hdr/sys_socket_macros.h"
+#include "hdr/types/size_t.h"
+#include "hdr/types/socklen_t.h"
+#include "hdr/types/struct_sockaddr_un.h"
+#include "src/__support/common.h"
+#include "src/string/strlen.h"
+#include "src/string/strncmp.h"
+#include "src/string/strncpy.h"
+#include "test/UnitTest/LibcTest.h"
+
+namespace LIBC_NAMESPACE_DECL {
+namespace testing {
+
+LIBC_INLINE bool make_sockaddr_un(const char *path, struct sockaddr_un &sun) {
+  sun.sun_family = AF_UNIX;
+  // The kernel accepts addresses which fill the entire sun_path buffer (without
+  // the terminating '\0' character), but we don't do that as it makes matching
+  // the returned values more difficult.
+  if (strlen(path) + 1 > sizeof(sun.sun_path))
+    return false;
+  strncpy(sun.sun_path, path, sizeof(sun.sun_path));
+  return true;
+}
+
+struct SocketAddress {
+  struct sockaddr_un addr;
+  socklen_t addrlen;
+};
+
+class SocketAddressMatcher : public Matcher<SocketAddress> {
+  const char *expected_path;
+  struct sockaddr_un actual_addr;
+  socklen_t actual_addrlen;
+
+public:
+  explicit SocketAddressMatcher(const char *path) : expected_path(path) {}
----------------
labath wrote:

We can use string_view (which I've now done) for most of this. The str*n* functions still make sense in some cases since these maybe-null-terminated char arrays is exactly what they were designed for.

We could even go for a real `string` in the matcher (the string(view) is stored as a field of the object), though personally I don't think it's necessary as the matcher shouldn't outlive the ASSERT statement. I don't know what else could be done here. I'm not terribly thrilled by the duplication in the match vs. explainError functions (googletest does it in a single function), but that seems to be how the test framework is meant to be used.

https://github.com/llvm/llvm-project/pull/193207


More information about the libc-commits mailing list