Skip to content

Truly independent web browser

LibTest: Add a temporary directory for tests

Shannon Boothe064a59a64cb
diff --git a/Libraries/LibTest/CMakeLists.txt b/Libraries/LibTest/CMakeLists.txt
index 182e863af47..1d7aed88ad3 100644
--- a/Libraries/LibTest/CMakeLists.txt
+++ b/Libraries/LibTest/CMakeLists.txt
@@ -5,6 +5,7 @@ add_library(JavaScriptTestRunnerMain OBJECT JavaScriptTestRunnerMain.cpp)
target_link_libraries(JavaScriptTestRunnerMain PRIVATE LibJSStandalone LibGC)
set(SOURCES
+ TemporaryDirectory.cpp
TestSuite.cpp
)
diff --git a/Libraries/LibTest/TemporaryDirectory.cpp b/Libraries/LibTest/TemporaryDirectory.cpp
new file mode 100644
index 00000000000..dbfd224a615
--- /dev/null
+++ b/Libraries/LibTest/TemporaryDirectory.cpp
@@ -0,0 +1,39 @@
+/*
+ * Copyright (c) 2026, Shannon Booth <[email protected]>
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <AK/ByteString.h>
+#include <LibCore/Directory.h>
+#include <LibCore/StandardPaths.h>
+#include <LibCore/System.h>
+#include <LibFileSystem/FileSystem.h>
+#include <LibTest/TemporaryDirectory.h>
+
+namespace Test {
+
+static LexicalPath create_directory(StringView name)
+{
+ static int count = 0;
+ auto path = LexicalPath::join(Core::StandardPaths::tempfile_directory(), ByteString::formatted("{}-{}-{}", name, Core::System::getpid(), count++));
+
+ // A crashed run with the same process ID can leave it behind.
+ (void)FileSystem::remove(path.string(), FileSystem::RecursionMode::Allowed);
+ MUST(Core::Directory::create(path, Core::Directory::CreateDirectories::Yes, 0700));
+
+ // File watchers report resolved paths, and the temp directory can be behind a symbolic link.
+ return LexicalPath { MUST(FileSystem::real_path(path.string())) };
+}
+
+TemporaryDirectory::TemporaryDirectory(StringView name)
+ : m_path(create_directory(name))
+{
+}
+
+TemporaryDirectory::~TemporaryDirectory()
+{
+ (void)FileSystem::remove(m_path.string(), FileSystem::RecursionMode::Allowed);
+}
+
+}
diff --git a/Libraries/LibTest/TemporaryDirectory.h b/Libraries/LibTest/TemporaryDirectory.h
new file mode 100644
index 00000000000..825c996a18f
--- /dev/null
+++ b/Libraries/LibTest/TemporaryDirectory.h
@@ -0,0 +1,31 @@
+/*
+ * Copyright (c) 2026, Shannon Booth <[email protected]>
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <AK/LexicalPath.h>
+#include <AK/Noncopyable.h>
+#include <AK/StringView.h>
+#include <LibTest/Export.h>
+
+namespace Test {
+
+// A uniquely named directory under the temp directory, removed with its contents on destruction.
+class TEST_API TemporaryDirectory {
+ AK_MAKE_NONCOPYABLE(TemporaryDirectory);
+ AK_MAKE_NONMOVABLE(TemporaryDirectory);
+
+public:
+ explicit TemporaryDirectory(StringView name);
+ ~TemporaryDirectory();
+
+ LexicalPath const& path() const { return m_path; }
+
+private:
+ LexicalPath m_path;
+};
+
+}