mirror of
https://github.com/MindWorkAI/AI-Studio.git
synced 2026-12-04 08:12:01 +00:00
Moved temporary files into a folder of their own below the data directory (#1245)
This commit is contained in:
1 parent
ddfc632b63
commit
12d3e1ec6c
52 files changed
+1219
-396
No files matched your search
@@ -0,0 +1,78 @@
|
||||
using AIStudio.Tests.Models.Generation;
|
||||
|
||||
using SourceCodeRules.UsageAnalyzers;
|
||||
|
||||
namespace AIStudio.Tests.Analyzers;
|
||||
|
||||
/// <summary>
|
||||
/// Checks that MWAIS0019 refuses the temporary folder of the system and leaves everything else alone.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// On many Linux systems, and always in a Flatpak, the temporary folder of the system lives in memory. A file there
|
||||
/// takes memory, which nobody notices on a developer computer with plenty of it.
|
||||
/// </remarks>
|
||||
[TestFixture]
|
||||
public sealed class TemporaryFolderAnalyzerTests
|
||||
{
|
||||
[TestCase("return Path.GetTempPath();", "GetTempPath", TestName = "Path.GetTempPath")]
|
||||
[TestCase("return Path.GetTempFileName();", "GetTempFileName", TestName = "Path.GetTempFileName")]
|
||||
[TestCase("""return Path.Combine(System.IO.Path.GetTempPath(), "file.md");""", "GetTempPath", TestName = "Path.GetTempPath with its namespace")]
|
||||
[TestCase("Func<string> folder = Path.GetTempPath; return folder();", "GetTempPath", TestName = "Path.GetTempPath as a method group")]
|
||||
public async Task TheTemporaryFolderOfTheSystemIsRefused(string statement, string name)
|
||||
{
|
||||
var reported = await CompilationHarness.AnalyzeAsync(ClassWith(statement), new TemporaryFolderAnalyzer());
|
||||
|
||||
using (Assert.EnterMultipleScope())
|
||||
{
|
||||
Assert.That(reported, Has.Count.EqualTo(1));
|
||||
Assert.That(reported.FirstOrDefault()?.Id, Is.EqualTo("MWAIS0019"));
|
||||
Assert.That(reported.FirstOrDefault()?.GetMessage(), Does.Contain($"'Path.{name}'"));
|
||||
}
|
||||
}
|
||||
|
||||
[TestCase("""return Path.Combine(dataDirectory, "tmp");""", TestName = "Another method of Path")]
|
||||
[TestCase("return Folders.GetTempPath();", TestName = "A method GetTempPath of another type")]
|
||||
[TestCase("return Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);", TestName = "Another folder of the system")]
|
||||
public async Task AnythingElseIsLeftAlone(string statement)
|
||||
{
|
||||
var reported = await CompilationHarness.AnalyzeAsync(ClassWith(statement), new TemporaryFolderAnalyzer());
|
||||
|
||||
Assert.That(reported, Is.Empty);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task APragmaWithAReasonLetsItPass()
|
||||
{
|
||||
const string STATEMENT = """
|
||||
// A diagnostic has to outlast a restart:
|
||||
#pragma warning disable MWAIS0019
|
||||
return Path.GetTempPath();
|
||||
#pragma warning restore MWAIS0019
|
||||
""";
|
||||
|
||||
var reported = await CompilationHarness.AnalyzeAsync(ClassWith(STATEMENT), new TemporaryFolderAnalyzer());
|
||||
|
||||
Assert.That(reported, Is.Empty);
|
||||
}
|
||||
|
||||
private static string ClassWith(string statement) =>
|
||||
$$"""
|
||||
using System;
|
||||
using System.IO;
|
||||
|
||||
namespace Sample;
|
||||
|
||||
public static class Folders
|
||||
{
|
||||
public static string GetTempPath() => "/data/tmp";
|
||||
}
|
||||
|
||||
public static class Files
|
||||
{
|
||||
public static string Locate(string dataDirectory)
|
||||
{
|
||||
{{statement}}
|
||||
}
|
||||
}
|
||||
""";
|
||||
}
|
||||
@@ -74,27 +74,30 @@ public sealed class BflRecordingTests
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ATranscriptWaitsInAFolderOfItsOwnBelowTheStaging()
|
||||
public async Task ATranscriptWaitsInAFolderOfItsOwnInTheTemporaryFolder()
|
||||
{
|
||||
var first = new BflTranscriptLocation(this.dataDirectory);
|
||||
var second = new BflTranscriptLocation(this.dataDirectory);
|
||||
var first = new BflTranscriptLocation();
|
||||
var second = new BflTranscriptLocation();
|
||||
|
||||
var slot = await first.ResolveAsync("/Users/person/Interview.mp3", CancellationToken.None);
|
||||
var stagingDirectory = Path.Combine(this.dataDirectory, "media-staging");
|
||||
var temporaryFolder = Path.Join(TestHost.DATA_DIRECTORY, "tmp");
|
||||
|
||||
using (Assert.EnterMultipleScope())
|
||||
{
|
||||
Assert.That(Path.GetDirectoryName(slot.Path), Is.EqualTo(first.FolderPath));
|
||||
Assert.That(Path.GetDirectoryName(first.FolderPath), Is.EqualTo(stagingDirectory), "The cleanup at the start of AI Studio removes only what lies below the staging.");
|
||||
Assert.That(Path.GetDirectoryName(first.FolderPath), Is.EqualTo(temporaryFolder), "AI Studio empties only its temporary folder when it starts.");
|
||||
Assert.That(second.FolderPath, Is.Not.EqualTo(first.FolderPath), "Two imports would share one transcript.");
|
||||
Assert.That(slot.Path, Does.Not.Contain("Interview"), "The folder of the person decides nothing in the data directory.");
|
||||
}
|
||||
|
||||
first.TryDelete();
|
||||
second.TryDelete();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task DeletingTheLocationRemovesTheTranscript()
|
||||
{
|
||||
var location = new BflTranscriptLocation(this.dataDirectory);
|
||||
var location = new BflTranscriptLocation();
|
||||
var slot = await location.ResolveAsync("/Users/person/Interview.mp3", CancellationToken.None);
|
||||
Directory.CreateDirectory(location.FolderPath);
|
||||
await File.WriteAllTextAsync(slot.Path, "Guten Tag.");
|
||||
@@ -103,7 +106,7 @@ public sealed class BflRecordingTests
|
||||
{
|
||||
Assert.That(location.TryDelete(), Is.True);
|
||||
Assert.That(Directory.Exists(location.FolderPath), Is.False);
|
||||
Assert.That(new BflTranscriptLocation(this.dataDirectory).TryDelete(), Is.True, "A location without a transcript is no failure.");
|
||||
Assert.That(new BflTranscriptLocation().TryDelete(), Is.True, "A location without a transcript is no failure.");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -21,7 +21,7 @@ public sealed class ChatDraftTests
|
||||
private static readonly FileAttachment MINUTES = new(FileAttachmentType.DOCUMENT, "minutes.pdf", "/documents/minutes.pdf", 2048);
|
||||
private static readonly FileAttachmentImage CHART = new("chart.png", "/documents/chart.png", 4096);
|
||||
private static readonly ManagedTranscriptAttachment TRANSCRIPT = new("meeting-transcript-0001.md", "/data/tempChats/meeting-transcript-0001.md", 512, "meeting.mp4", false);
|
||||
private static readonly ManagedTranscriptAttachment STAGED_TRANSCRIPT = new("4f1c.md", "/data/media-staging/4f1c.md", 256, "kickoff.mp4", true);
|
||||
private static readonly ManagedTranscriptAttachment STAGED_TRANSCRIPT = new("4f1c.md", "/data/tmp/0123456789abcdef0123456789abcdef/4f1c.md", 256, "kickoff.mp4", true);
|
||||
|
||||
[Test]
|
||||
public void MirroringTheComposerKeepsATranscriptItDoesNotShowYet()
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
using AIStudio.Chat;
|
||||
using AIStudio.Settings;
|
||||
using AIStudio.Tools;
|
||||
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
|
||||
namespace AIStudio.Tests.Chat;
|
||||
|
||||
@@ -9,7 +12,7 @@ namespace AIStudio.Tests.Chat;
|
||||
/// <remarks>
|
||||
/// A transcript carries a full path, which a chat file edited outside the app may point anywhere. AI
|
||||
/// Studio therefore deletes a file only where it keeps transcripts itself: in the transcript folder of a
|
||||
/// chat, or in the staging area.
|
||||
/// chat, or in a folder of its own in the temporary folder of AI Studio.
|
||||
/// </remarks>
|
||||
[TestFixture]
|
||||
[NonParallelizable]
|
||||
@@ -26,12 +29,16 @@ public sealed class ManagedTranscriptAttachmentTests
|
||||
this.testDirectory = Path.Combine(Path.GetTempPath(), $"ai-studio-transcripts-{Guid.NewGuid():N}");
|
||||
Directory.CreateDirectory(this.testDirectory);
|
||||
SettingsManager.DataDirectory = this.testDirectory;
|
||||
|
||||
// The app sets its temporary folder below the same data directory:
|
||||
TemporaryFiles.Initialize(this.testDirectory, NullLogger.Instance);
|
||||
}
|
||||
|
||||
[TearDown]
|
||||
public void RemoveDataDirectory()
|
||||
{
|
||||
SettingsManager.DataDirectory = this.previousDataDirectory;
|
||||
TemporaryFiles.Initialize(TestHost.DATA_DIRECTORY, NullLogger.Instance);
|
||||
|
||||
try
|
||||
{
|
||||
@@ -43,6 +50,33 @@ public sealed class ManagedTranscriptAttachmentTests
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AStagedTranscriptIsDeletedTogetherWithItsFolder()
|
||||
{
|
||||
var transcript = await ManagedTranscriptAttachment.CreateStagedAsync("/Users/person/Kickoff.mp4", "Guten Tag.");
|
||||
var folder = Path.GetDirectoryName(transcript.FilePath)!;
|
||||
|
||||
using (Assert.EnterMultipleScope())
|
||||
{
|
||||
Assert.That(Path.GetDirectoryName(folder), Is.EqualTo(Path.Combine(this.testDirectory, "tmp")), "The transcript waits in the temporary folder of AI Studio.");
|
||||
Assert.That(ManagedTranscriptAttachment.TryDeleteOwnedFile(transcript), Is.True);
|
||||
Assert.That(File.Exists(transcript.FilePath), Is.False);
|
||||
Assert.That(Directory.Exists(folder), Is.False);
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void AFileDirectlyInTheTemporaryFolderStays()
|
||||
{
|
||||
var file = WriteTranscript(Path.Combine(this.testDirectory, "tmp"));
|
||||
|
||||
using (Assert.EnterMultipleScope())
|
||||
{
|
||||
Assert.That(ManagedTranscriptAttachment.TryDeleteOwnedFile(file), Is.False, "A staged transcript has a folder of its own.");
|
||||
Assert.That(File.Exists(file.FilePath), Is.True);
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void TheTranscriptOfAWorkspaceChatIsDeleted()
|
||||
{
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
|
||||
using AIStudio.Provider;
|
||||
|
||||
namespace AIStudio.Tests.Provider;
|
||||
|
||||
/// <summary>
|
||||
/// Checks which failures of a request count as a failed connection, before the provider answered.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// A transcription which fails that way says so, instead of claiming that the provider could not transcribe the file.
|
||||
/// The exceptions come from a real HttpClient and a real socket, since only they show how .NET reports a connection
|
||||
/// which breaks off while the media file is on its way.
|
||||
/// </remarks>
|
||||
[TestFixture]
|
||||
public sealed class ConnectionFailureTests
|
||||
{
|
||||
private static readonly TimeSpan TIME_LIMIT = TimeSpan.FromSeconds(10);
|
||||
|
||||
private static readonly HttpClient HTTP_CLIENT = new();
|
||||
|
||||
[Test]
|
||||
public async Task AConnectionWhichBreaksOffDuringTheUploadCounts()
|
||||
{
|
||||
using var timeout = new CancellationTokenSource(TIME_LIMIT);
|
||||
var listener = new TcpListener(IPAddress.Loopback, 0);
|
||||
listener.Start();
|
||||
try
|
||||
{
|
||||
var server = ResetFirstConnectionAsync(listener, timeout.Token);
|
||||
var failure = await SendMediaFileAsync(AddressOf(listener), timeout.Token);
|
||||
await server;
|
||||
|
||||
Assert.That(BaseProvider.IsConnectionFailure(failure), Is.True, failure.ToString());
|
||||
}
|
||||
finally
|
||||
{
|
||||
listener.Stop();
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AServerWhichCannotBeReachedCounts()
|
||||
{
|
||||
using var timeout = new CancellationTokenSource(TIME_LIMIT);
|
||||
|
||||
// A port which was free a moment ago and has no listener anymore:
|
||||
var listener = new TcpListener(IPAddress.Loopback, 0);
|
||||
listener.Start();
|
||||
var address = AddressOf(listener);
|
||||
listener.Stop();
|
||||
|
||||
var failure = await SendMediaFileAsync(address, timeout.Token);
|
||||
|
||||
Assert.That(BaseProvider.IsConnectionFailure(failure), Is.True, failure.ToString());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void AnAnswerOfTheProviderDoesNotCount()
|
||||
{
|
||||
var failure = new HttpRequestException("Response status code does not indicate success: 500 (Internal Server Error).", null, HttpStatusCode.InternalServerError);
|
||||
|
||||
Assert.That(BaseProvider.IsConnectionFailure(failure), Is.False);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ATimeoutDoesNotCount()
|
||||
{
|
||||
var failure = new TaskCanceledException("The request was canceled due to the configured HttpClient.Timeout of 100 seconds elapsing.", new TimeoutException());
|
||||
|
||||
Assert.That(BaseProvider.IsConnectionFailure(failure), Is.False);
|
||||
}
|
||||
|
||||
private static Uri AddressOf(TcpListener listener) => new($"http://127.0.0.1:{((IPEndPoint)listener.LocalEndpoint).Port}/audio/transcriptions");
|
||||
|
||||
/// <summary>
|
||||
/// Accepts one connection, reads the beginning of the request, and closes the connection with a reset, as a
|
||||
/// provider does which drops an upload.
|
||||
/// </summary>
|
||||
private static async Task ResetFirstConnectionAsync(TcpListener listener, CancellationToken token)
|
||||
{
|
||||
using var client = await listener.AcceptTcpClientAsync(token);
|
||||
var buffer = new byte[16 * 1_024];
|
||||
_ = await client.GetStream().ReadAsync(buffer, token);
|
||||
client.Client.LingerState = new LingerOption(true, 0);
|
||||
client.Close();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Uploads a media file of several MB, as a transcription request does, and returns what the request threw.
|
||||
/// </summary>
|
||||
private static async Task<Exception> SendMediaFileAsync(Uri address, CancellationToken token)
|
||||
{
|
||||
using var form = new MultipartFormDataContent();
|
||||
form.Add(new ByteArrayContent(new byte[8 * 1_024 * 1_024]), "file", "recording.webm");
|
||||
form.Add(new StringContent("whisper-1"), "model");
|
||||
|
||||
try
|
||||
{
|
||||
using var response = await HTTP_CLIENT.PostAsync(address, form, token);
|
||||
}
|
||||
catch (Exception exception) when (exception is not OperationCanceledException || !token.IsCancellationRequested)
|
||||
{
|
||||
return exception;
|
||||
}
|
||||
|
||||
throw new AssertionException("The request did not fail.");
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,5 @@
|
||||
using AIStudio.Tools;
|
||||
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
|
||||
//
|
||||
@@ -11,9 +13,21 @@ namespace AIStudio.Tests;
|
||||
[SetUpFixture]
|
||||
public sealed class TestHost
|
||||
{
|
||||
/// <summary>
|
||||
/// The data directory of the tests, below which TemporaryFiles keeps its folder.
|
||||
/// </summary>
|
||||
public static readonly string DATA_DIRECTORY = Path.Join(Path.GetTempPath(), $"ai-studio-tests-{Guid.NewGuid():N}");
|
||||
|
||||
[OneTimeSetUp]
|
||||
public void PrepareStaticApplicationState() => PrepareStaticState();
|
||||
|
||||
[OneTimeTearDown]
|
||||
public void DeleteDataDirectory()
|
||||
{
|
||||
if (Directory.Exists(DATA_DIRECTORY))
|
||||
Directory.Delete(DATA_DIRECTORY, true);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Fills the static state of the app which the tests need.
|
||||
/// </summary>
|
||||
@@ -31,5 +45,11 @@ public sealed class TestHost
|
||||
// that writes nowhere is all it takes to get past that.
|
||||
//
|
||||
Program.LOGGER_FACTORY = NullLoggerFactory.Instance;
|
||||
|
||||
//
|
||||
// The app sets its temporary folder below its data directory while it starts. The tests have no
|
||||
// data directory, so the folder lies below one of their own:
|
||||
//
|
||||
TemporaryFiles.Initialize(DATA_DIRECTORY, NullLogger.Instance);
|
||||
}
|
||||
}
|
||||
@@ -52,7 +52,7 @@
|
||||
the tests, too, until it is listed here.
|
||||
-->
|
||||
<PropertyGroup>
|
||||
<NoWarn>$(NoWarn);MWAIS0001;MWAIS0002;MWAIS0003;MWAIS0004;MWAIS0005;MWAIS0006;MWAIS0007;MWAIS0008;MWAIS0009;MWAIS0010;MWAIS0011;MWAIS0012;MWAIS0013;MWAIS0014;MWAIS0015;MWAIS0016;MWAIS0017</NoWarn>
|
||||
<NoWarn>$(NoWarn);MWAIS0001;MWAIS0002;MWAIS0003;MWAIS0004;MWAIS0005;MWAIS0006;MWAIS0007;MWAIS0008;MWAIS0009;MWAIS0010;MWAIS0011;MWAIS0012;MWAIS0013;MWAIS0014;MWAIS0015;MWAIS0016;MWAIS0017;MWAIS0019</NoWarn>
|
||||
</PropertyGroup>
|
||||
|
||||
<!--
|
||||
|
||||
@@ -56,7 +56,7 @@ public sealed class DataBackupWriterTests
|
||||
this.WriteDataFile("visualBriefings/briefing/manifest.json", "{}");
|
||||
this.WriteDataFile("beyondFactsLab/preparation/project.json", "{}");
|
||||
this.WriteDataFile("modelComparisons/presets/preset.json", "{}");
|
||||
this.WriteDataFile("media-staging/operation/transcript.md", "temporary");
|
||||
this.WriteDataFile("tmp/operation/transcript.md", "temporary");
|
||||
this.WriteDataFile("databases/sqlite/rag-index.sqlite3", "the index while AI Studio writes to it");
|
||||
this.WriteDataFile("databases/provenance/provenance.sqlite3", "the provenance store while AI Studio writes to it");
|
||||
this.WriteDataFile("databases/provenance/provenance.sqlite3-wal", "the write-ahead log of the provenance store");
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
using AIStudio.Tools.OpenXml;
|
||||
|
||||
namespace AIStudio.Tests.Tools.OpenXml;
|
||||
|
||||
/// <summary>
|
||||
/// The folder in which StagedDocument puts its files. Tests have no data directory, so it lies in the temporary folder.
|
||||
/// The folder in which StagedDocument puts its files: the temporary folder of AI Studio, which lies below the data
|
||||
/// directory of the tests, see TestHost.
|
||||
/// </summary>
|
||||
internal static class StagingFolder
|
||||
{
|
||||
@@ -12,7 +11,7 @@ internal static class StagingFolder
|
||||
/// </summary>
|
||||
public static HashSet<string> Files()
|
||||
{
|
||||
var directory = Path.Join(Path.GetTempPath(), StagedDocument.DIRECTORY);
|
||||
var directory = Path.Join(TestHost.DATA_DIRECTORY, "tmp");
|
||||
return Directory.Exists(directory) ? Directory.EnumerateFiles(directory).ToHashSet() : [];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
using System.ComponentModel;
|
||||
using System.Diagnostics;
|
||||
|
||||
using AIStudio.Tools;
|
||||
|
||||
namespace AIStudio.Tests.Tools;
|
||||
|
||||
/// <summary>
|
||||
/// Checks which failures to start Pandoc mean that it is not installed.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Most users have no Pandoc until they install it through AI Studio. The log notes that once, without a stack trace,
|
||||
/// and keeps errors with their stack traces for what nobody expects. The exception comes from a real Process.Start, since
|
||||
/// only it shows what each OS reports for a program which does not exist.
|
||||
/// </remarks>
|
||||
[TestFixture]
|
||||
public sealed class PandocMissingExecutableTests
|
||||
{
|
||||
[Test]
|
||||
public void AProgramWhichDoesNotExistCounts()
|
||||
{
|
||||
var startInfo = new ProcessStartInfo($"ai-studio-missing-program-{Guid.NewGuid():N}")
|
||||
{
|
||||
ArgumentList = { "--version" },
|
||||
UseShellExecute = false,
|
||||
RedirectStandardOutput = true,
|
||||
RedirectStandardError = true
|
||||
};
|
||||
|
||||
var failure = Assert.Catch(() => Process.Start(startInfo)?.Dispose());
|
||||
|
||||
Assert.That(Pandoc.IsMissingExecutable(failure!), Is.True, failure?.ToString());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void AProgramWhichCannotBeStartedDoesNotCount()
|
||||
{
|
||||
// Windows reports a denied access as ERROR_ACCESS_DENIED (5), macOS and Linux as EACCES (13):
|
||||
var failure = new Win32Exception(OperatingSystem.IsWindows() ? 5 : 13);
|
||||
|
||||
Assert.That(Pandoc.IsMissingExecutable(failure), Is.False);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void AnotherExceptionDoesNotCount()
|
||||
{
|
||||
var failure = new InvalidOperationException("No process is associated with this object.");
|
||||
|
||||
Assert.That(Pandoc.IsMissingExecutable(failure), Is.False);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
using AIStudio.Tools.PluginSystem;
|
||||
|
||||
namespace AIStudio.Tests.Tools.PluginSystem;
|
||||
|
||||
/// <summary>
|
||||
/// Checks how a deployment which AI Studio downloaded from the configuration server of an organization reaches its place.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// AI Studio unpacks the deployment in its temporary folder and moves it to plugins/.config afterward. That folder
|
||||
/// is missing on a new installation until the first deployment arrives, and once somebody deleted it.
|
||||
/// </remarks>
|
||||
[TestFixture]
|
||||
public sealed class ConfigPluginDeploymentTests
|
||||
{
|
||||
private string dataDirectory = string.Empty;
|
||||
|
||||
[SetUp]
|
||||
public void CreateDataDirectory()
|
||||
{
|
||||
// A user name beyond ASCII, as in the path of many data directories:
|
||||
this.dataDirectory = Path.Combine(Path.GetTempPath(), $"ai-studio-deployment-ä-ж-日本-{Guid.NewGuid():N}");
|
||||
Directory.CreateDirectory(Path.Combine(this.dataDirectory, "plugins"));
|
||||
}
|
||||
|
||||
[TearDown]
|
||||
public void DeleteDataDirectory()
|
||||
{
|
||||
if (Directory.Exists(this.dataDirectory))
|
||||
Directory.Delete(this.dataDirectory, true);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void TheFirstDeploymentArrivesAlthoughItsFolderIsMissing()
|
||||
{
|
||||
var stagedDirectory = this.StageDeployment("ID = \"first\"");
|
||||
var deploymentDirectory = Path.Combine(this.dataDirectory, "plugins", ".config", Guid.NewGuid().ToString());
|
||||
|
||||
PluginFactory.MoveDeploymentIntoPlace(stagedDirectory, deploymentDirectory);
|
||||
|
||||
using (Assert.EnterMultipleScope())
|
||||
{
|
||||
Assert.That(File.ReadAllText(Path.Combine(deploymentDirectory, "plugin.lua")), Is.EqualTo("ID = \"first\""));
|
||||
Assert.That(Directory.Exists(stagedDirectory), Is.False);
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ADeploymentArrivesNextToTheOthers()
|
||||
{
|
||||
var otherDeploymentDirectory = Path.Combine(this.dataDirectory, "plugins", ".config", Guid.NewGuid().ToString());
|
||||
Directory.CreateDirectory(otherDeploymentDirectory);
|
||||
File.WriteAllText(Path.Combine(otherDeploymentDirectory, "plugin.lua"), "ID = \"other\"");
|
||||
|
||||
var stagedDirectory = this.StageDeployment("ID = \"next\"");
|
||||
var deploymentDirectory = Path.Combine(this.dataDirectory, "plugins", ".config", Guid.NewGuid().ToString());
|
||||
|
||||
PluginFactory.MoveDeploymentIntoPlace(stagedDirectory, deploymentDirectory);
|
||||
|
||||
using (Assert.EnterMultipleScope())
|
||||
{
|
||||
Assert.That(File.ReadAllText(Path.Combine(deploymentDirectory, "plugin.lua")), Is.EqualTo("ID = \"next\""));
|
||||
Assert.That(File.ReadAllText(Path.Combine(otherDeploymentDirectory, "plugin.lua")), Is.EqualTo("ID = \"other\""));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Places an unpacked deployment in the temporary folder below the data directory, as the download does.
|
||||
/// </summary>
|
||||
private string StageDeployment(string pluginCode)
|
||||
{
|
||||
var stagedDirectory = Path.Combine(this.dataDirectory, "tmp", Guid.NewGuid().ToString("N"), "deployment");
|
||||
Directory.CreateDirectory(stagedDirectory);
|
||||
File.WriteAllText(Path.Combine(stagedDirectory, "plugin.lua"), pluginCode);
|
||||
return stagedDirectory;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,193 @@
|
||||
using AIStudio.Tools;
|
||||
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
|
||||
namespace AIStudio.Tests.Tools;
|
||||
|
||||
/// <summary>
|
||||
/// Checks the temporary folder of AI Studio below its data directory: where its files go, that starting and
|
||||
/// stopping empty it, and that emptying it never deletes anything outside.
|
||||
/// </summary>
|
||||
[TestFixture]
|
||||
[NonParallelizable]
|
||||
public sealed class TemporaryFilesTests
|
||||
{
|
||||
private string dataDirectory = string.Empty;
|
||||
|
||||
private string outsideDirectory = string.Empty;
|
||||
|
||||
private string TemporaryFolder => Path.Join(this.dataDirectory, "tmp");
|
||||
|
||||
[SetUp]
|
||||
public void CreateDirectories()
|
||||
{
|
||||
this.dataDirectory = Path.Join(Path.GetTempPath(), $"ai-studio-temporary-files-{Guid.NewGuid():N}");
|
||||
this.outsideDirectory = Path.Join(Path.GetTempPath(), $"ai-studio-temporary-files-outside-{Guid.NewGuid():N}");
|
||||
Directory.CreateDirectory(this.dataDirectory);
|
||||
Directory.CreateDirectory(this.outsideDirectory);
|
||||
}
|
||||
|
||||
[TearDown]
|
||||
public void RestoreTheFolderOfTheTests()
|
||||
{
|
||||
TemporaryFiles.Initialize(TestHost.DATA_DIRECTORY, NullLogger.Instance);
|
||||
foreach (var directory in new[] { this.dataDirectory, this.outsideDirectory })
|
||||
{
|
||||
if (Directory.Exists(directory))
|
||||
Directory.Delete(directory, true);
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ANewFileLiesInTheTemporaryFolderAndDoesNotExistYet()
|
||||
{
|
||||
TemporaryFiles.Initialize(this.dataDirectory, NullLogger.Instance);
|
||||
|
||||
var first = TemporaryFiles.GetFilePath(".webm");
|
||||
var second = TemporaryFiles.GetFilePath(".webm");
|
||||
|
||||
using (Assert.EnterMultipleScope())
|
||||
{
|
||||
Assert.That(Path.GetDirectoryName(first), Is.EqualTo(this.TemporaryFolder));
|
||||
Assert.That(Path.GetExtension(first), Is.EqualTo(".webm"));
|
||||
Assert.That(File.Exists(first), Is.False);
|
||||
Assert.That(Directory.Exists(this.TemporaryFolder), Is.True);
|
||||
Assert.That(second, Is.Not.EqualTo(first));
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ANewFolderLiesInTheTemporaryFolderAndIsEmpty()
|
||||
{
|
||||
TemporaryFiles.Initialize(this.dataDirectory, NullLogger.Instance);
|
||||
|
||||
var first = TemporaryFiles.CreateDirectory();
|
||||
var second = TemporaryFiles.CreateDirectory();
|
||||
|
||||
using (Assert.EnterMultipleScope())
|
||||
{
|
||||
Assert.That(Path.GetDirectoryName(first), Is.EqualTo(this.TemporaryFolder));
|
||||
Assert.That(Directory.Exists(first), Is.True);
|
||||
Assert.That(Directory.EnumerateFileSystemEntries(first), Is.Empty);
|
||||
Assert.That(second, Is.Not.EqualTo(first));
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task StartingEmptiesTheTemporaryFolderAndTheFoldersOfEarlierVersions()
|
||||
{
|
||||
var leftover = Path.Join(this.TemporaryFolder, "recording.webm");
|
||||
var nestedLeftover = Path.Join(this.TemporaryFolder, "briefing", "picture.png");
|
||||
var attachmentOfAnEarlierVersion = Path.Join(this.dataDirectory, "mailAttachments", "invoice.pdf");
|
||||
var pandocOfAnInterruptedInstallation = Path.Join(this.dataDirectory, "pandoc-install-0123456789abcdef", "pandoc");
|
||||
var stagedDocument = Path.Join(this.dataDirectory, ".document-staging", "0123456789abcdef.docx");
|
||||
var stagedPlugin = Path.Join(this.dataDirectory, ".plugin-staging", "plugin-import.staging-0123456789abcdef", "plugin.lua");
|
||||
var stagedTranscript = Path.Join(this.dataDirectory, "media-staging", "0123456789abcdef", "transcript.md");
|
||||
var chat = Path.Join(this.dataDirectory, "workspaces", "chat.json");
|
||||
var pandoc = Path.Join(this.dataDirectory, "pandoc", "pandoc");
|
||||
foreach (var path in new[] { leftover, nestedLeftover, attachmentOfAnEarlierVersion, pandocOfAnInterruptedInstallation, stagedDocument, stagedPlugin, stagedTranscript, chat, pandoc })
|
||||
{
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
|
||||
await File.WriteAllTextAsync(path, "content");
|
||||
}
|
||||
|
||||
TemporaryFiles.Initialize(this.dataDirectory, NullLogger.Instance);
|
||||
|
||||
using (Assert.EnterMultipleScope())
|
||||
{
|
||||
Assert.That(Directory.Exists(this.TemporaryFolder), Is.False);
|
||||
Assert.That(Directory.Exists(Path.Join(this.dataDirectory, "mailAttachments")), Is.False);
|
||||
Assert.That(Directory.Exists(Path.GetDirectoryName(pandocOfAnInterruptedInstallation)), Is.False);
|
||||
Assert.That(Directory.Exists(Path.Join(this.dataDirectory, ".document-staging")), Is.False, "A folder whose name begins with a dot counts as hidden on Linux and macOS.");
|
||||
Assert.That(Directory.Exists(Path.Join(this.dataDirectory, ".plugin-staging")), Is.False);
|
||||
Assert.That(Directory.Exists(Path.Join(this.dataDirectory, "media-staging")), Is.False);
|
||||
Assert.That(File.ReadAllText(chat), Is.EqualTo("content"));
|
||||
Assert.That(File.ReadAllText(pandoc), Is.EqualTo("content"));
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ClearingEmptiesTheTemporaryFolder()
|
||||
{
|
||||
TemporaryFiles.Initialize(this.dataDirectory, NullLogger.Instance);
|
||||
var file = TemporaryFiles.GetFilePath(".md");
|
||||
await File.WriteAllTextAsync(file, "content");
|
||||
var folder = TemporaryFiles.CreateDirectory();
|
||||
|
||||
TemporaryFiles.Clear(NullLogger.Instance);
|
||||
|
||||
using (Assert.EnterMultipleScope())
|
||||
{
|
||||
Assert.That(File.Exists(file), Is.False);
|
||||
Assert.That(Directory.Exists(folder), Is.False);
|
||||
Assert.That(Path.GetDirectoryName(TemporaryFiles.GetFilePath(".md")), Is.EqualTo(this.TemporaryFolder), "The folder is created again on demand.");
|
||||
}
|
||||
}
|
||||
|
||||
[TestCase("")]
|
||||
[TestCase("relative/data")]
|
||||
public async Task ADataDirectoryWithoutAnAbsolutePathDeletesNothing(string dataDirectoryOfTheRuntime)
|
||||
{
|
||||
TemporaryFiles.Initialize(this.dataDirectory, NullLogger.Instance);
|
||||
var file = TemporaryFiles.GetFilePath(".md");
|
||||
await File.WriteAllTextAsync(file, "content");
|
||||
|
||||
TemporaryFiles.Initialize(dataDirectoryOfTheRuntime, NullLogger.Instance);
|
||||
|
||||
using (Assert.EnterMultipleScope())
|
||||
{
|
||||
Assert.That(File.Exists(file), Is.True);
|
||||
Assert.That(Path.GetDirectoryName(TemporaryFiles.GetFilePath(".md")), Is.EqualTo(this.TemporaryFolder));
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ALinkInTheTemporaryFolderIsRemovedButNotFollowed()
|
||||
{
|
||||
var precious = Path.Join(this.outsideDirectory, "precious.md");
|
||||
await File.WriteAllTextAsync(precious, "Precious");
|
||||
Directory.CreateDirectory(this.TemporaryFolder);
|
||||
|
||||
try
|
||||
{
|
||||
Directory.CreateSymbolicLink(Path.Join(this.TemporaryFolder, "folder-link"), this.outsideDirectory);
|
||||
File.CreateSymbolicLink(Path.Join(this.TemporaryFolder, "file-link.md"), precious);
|
||||
}
|
||||
catch (Exception exception) when (exception is UnauthorizedAccessException or IOException)
|
||||
{
|
||||
Assert.Ignore("Creating symbolic links needs a privilege this system does not grant.");
|
||||
}
|
||||
|
||||
TemporaryFiles.Initialize(this.dataDirectory, NullLogger.Instance);
|
||||
|
||||
using (Assert.EnterMultipleScope())
|
||||
{
|
||||
Assert.That(Directory.Exists(this.TemporaryFolder), Is.False);
|
||||
Assert.That(File.ReadAllText(precious), Is.EqualTo("Precious"));
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ATemporaryFolderWhichIsALinkIsRemovedButNotFollowed()
|
||||
{
|
||||
var precious = Path.Join(this.outsideDirectory, "precious.md");
|
||||
await File.WriteAllTextAsync(precious, "Precious");
|
||||
|
||||
try
|
||||
{
|
||||
Directory.CreateSymbolicLink(this.TemporaryFolder, this.outsideDirectory);
|
||||
}
|
||||
catch (Exception exception) when (exception is UnauthorizedAccessException or IOException)
|
||||
{
|
||||
Assert.Ignore("Creating symbolic links needs a privilege this system does not grant.");
|
||||
}
|
||||
|
||||
TemporaryFiles.Initialize(this.dataDirectory, NullLogger.Instance);
|
||||
|
||||
using (Assert.EnterMultipleScope())
|
||||
{
|
||||
Assert.That(new DirectoryInfo(this.TemporaryFolder).LinkTarget, Is.Null);
|
||||
Assert.That(File.ReadAllText(precious), Is.EqualTo("Precious"));
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user