Files
AI-Studio/app/Tests/Analyzers/TemporaryFolderAnalyzerTests.cs
T

78 lines
3.1 KiB
C#
Raw Normal View History

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}}
}
}
""";
}