[libc-commits] [libc] [libc] implement mkstemp (PR #199220)
Michael Jones via libc-commits
libc-commits at lists.llvm.org
Tue May 26 13:59:04 PDT 2026
================
@@ -0,0 +1,182 @@
+//===-- Unittests for mkstemp ---------------------------------------------===//
+//
+// 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
+//
+//===----------------------------------------------------------------------===//
+
+#include "hdr/errno_macros.h"
+#include "hdr/fcntl_macros.h"
+#include "hdr/signal_macros.h"
+#include "src/stdlib/mkstemp.h"
+#include "src/string/strdup.h"
+#include "src/unistd/access.h"
+#include "src/unistd/close.h"
+#include "src/unistd/read.h"
+#include "src/unistd/unlink.h"
+#include "src/unistd/write.h"
+#include "test/UnitTest/ErrnoCheckingTest.h"
+#include "test/UnitTest/Test.h"
+
+using LlvmLibcMkstempTest = LIBC_NAMESPACE::testing::ErrnoCheckingTest;
+
+TEST_F(LlvmLibcMkstempTest, ValidTemplate) {
+ char *tmpl = LIBC_NAMESPACE::strdup(libc_make_test_file_path("tmp_XXXXXX"));
+ int fd = LIBC_NAMESPACE::mkstemp(tmpl);
+ ASSERT_GE(fd, 0);
+ LIBC_NAMESPACE::close(fd);
+ LIBC_NAMESPACE::unlink(tmpl);
+ ::free(tmpl);
+}
+
+TEST_F(LlvmLibcMkstempTest, TemplateModifiedInPlace) {
+ char *tmpl = LIBC_NAMESPACE::strdup(libc_make_test_file_path("tmp_XXXXXX"));
+ size_t len = 0;
+ while (tmpl[len] != '\0')
+ len++;
+ size_t count = 0;
+ for (size_t i = len; i > 0 && tmpl[i - 1] == 'X'; i--)
+ count++;
+ int fd = LIBC_NAMESPACE::mkstemp(tmpl);
+ ASSERT_GE(fd, 0);
+ bool modified = false;
+ for (size_t i = len - count; i < len; i++)
+ if (tmpl[i] != 'X') {
+ modified = true;
+ break;
+ }
+ EXPECT_TRUE(modified);
+ LIBC_NAMESPACE::close(fd);
+ LIBC_NAMESPACE::unlink(tmpl);
+ ::free(tmpl);
+}
+
+TEST_F(LlvmLibcMkstempTest, FileExists) {
+ char *tmpl = LIBC_NAMESPACE::strdup(libc_make_test_file_path("tmp_XXXXXX"));
+ int fd = LIBC_NAMESPACE::mkstemp(tmpl);
+ ASSERT_GE(fd, 0);
+ EXPECT_EQ(LIBC_NAMESPACE::access(tmpl, F_OK), 0);
+ LIBC_NAMESPACE::close(fd);
+ LIBC_NAMESPACE::unlink(tmpl);
+ ::free(tmpl);
+}
+
+TEST_F(LlvmLibcMkstempTest, FdIsWritable) {
+ char *tmpl = LIBC_NAMESPACE::strdup(libc_make_test_file_path("tmp_XXXXXX"));
+ int fd = LIBC_NAMESPACE::mkstemp(tmpl);
+ ASSERT_GE(fd, 0);
+ const char msg[] = "hello";
+ EXPECT_EQ(LIBC_NAMESPACE::write(fd, msg, 5), static_cast<ssize_t>(5));
+ LIBC_NAMESPACE::close(fd);
+ LIBC_NAMESPACE::unlink(tmpl);
+ ::free(tmpl);
+}
----------------
michaelrj-google wrote:
these tests can be combined, since they're effectively testing the same thing: Was the file opened correctly.
https://github.com/llvm/llvm-project/pull/199220
More information about the libc-commits
mailing list