// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using Microsoft.Testing.Platform.Acceptance.IntegrationTests;
using Microsoft.Testing.Platform.Acceptance.IntegrationTests.Helpers;

namespace MSTest.Acceptance.IntegrationTests;

[TestClass]
public sealed class TimeoutFromConfigTests : AcceptanceTestBase<TimeoutFromConfigTests.TestAssetFixture>
{
    private static readonly Dictionary<string, (string MethodFullName, string Prefix, string EnvVarSuffix, string ConfigKeyName)> InfoByKind = new()
    {
        ["assemblyInit"] = ("TestClass.AssemblyInit", "Assembly initialize", "ASSEMBLYINIT", "assemblyInitialize"),
        ["assemblyCleanup"] = ("TestClass.AssemblyCleanupMethod", "Assembly cleanup", "ASSEMBLYCLEANUP", "assemblyCleanup"),
        ["classInit"] = ("TestClass.ClassInit", "Class initialize", "CLASSINIT", "classInitialize"),
        ["baseClassInit"] = ("TestClassBase.ClassInitBase", "Class initialize", "BASE_CLASSINIT", "classInitialize"),
        ["classCleanup"] = ("TestClass.ClassCleanupMethod", "Class cleanup", "CLASSCLEANUP", "classCleanup"),
        ["baseClassCleanup"] = ("TestClassBase.ClassCleanupBase", "Class cleanup", "BASE_CLASSCLEANUP", "classCleanup"),
        ["testInit"] = ("TestClass.TestInit", "Test initialize", "TESTINIT", "testInitialize"),
        ["testCleanup"] = ("TestClass.TestCleanupMethod", "Test cleanup", "TESTCLEANUP", "testCleanup"),
    };

    [TestMethod]
    [DynamicData(nameof(TargetFrameworks.AllForDynamicData), typeof(TargetFrameworks))]
    public async Task AssemblyInitialize_WhenTimeoutExpires_FromConfig_AssemblyInitializeIsCanceled(string tfm)
        => await RunAndAssertFromConfigAsync(tfm, "assemblyInit");

    [TestMethod]
    [DynamicData(nameof(TargetFrameworks.AllForDynamicData), typeof(TargetFrameworks))]
    public async Task ClassInitialize_WhenTimeoutExpires_FromConfig_ClassInitializeIsCanceled(string tfm)
        => await RunAndAssertFromConfigAsync(tfm, "classInit");

    [TestMethod]
    [DynamicData(nameof(TargetFrameworks.AllForDynamicData), typeof(TargetFrameworks))]
    public async Task BaseClassInitialize_WhenTimeoutExpires_FromConfig_ClassInitializeIsCanceled(string tfm)
        => await RunAndAssertFromConfigAsync(tfm, "baseClassInit");

    [TestMethod]
    [DynamicData(nameof(TargetFrameworks.AllForDynamicData), typeof(TargetFrameworks))]
    public async Task ClassCleanup_WhenTimeoutExpires_FromConfig_ClassCleanupIsCanceled(string tfm)
        => await RunAndAssertFromConfigAsync(tfm, "classCleanup");

    [TestMethod]
    [DynamicData(nameof(TargetFrameworks.AllForDynamicData), typeof(TargetFrameworks))]
    public async Task BaseClassCleanup_WhenTimeoutExpires_FromConfig_ClassCleanupIsCanceled(string tfm)
        => await RunAndAssertFromConfigAsync(tfm, "baseClassCleanup");

    [TestMethod]
    [DynamicData(nameof(TargetFrameworks.AllForDynamicData), typeof(TargetFrameworks))]
    public async Task AssemblyCleanup_WhenTimeoutExpires_FromConfig_AssemblyCleanupIsCanceled(string tfm)
        => await RunAndAssertFromConfigAsync(tfm, "assemblyCleanup");

    [TestMethod]
    [DynamicData(nameof(TargetFrameworks.AllForDynamicData), typeof(TargetFrameworks))]
    public async Task TestInitialize_WhenTimeoutExpires_FromConfig_TestInitializeIsCanceled(string tfm)
        => await RunAndAssertFromConfigAsync(tfm, "testInit");

    [TestMethod]
    [DynamicData(nameof(TargetFrameworks.AllForDynamicData), typeof(TargetFrameworks))]
    public async Task TestCleanup_WhenTimeoutExpires_FromConfig_TestCleanupIsCanceled(string tfm)
        => await RunAndAssertFromConfigAsync(tfm, "testCleanup");

    private async Task RunAndAssertFromConfigAsync(string tfm, string entryKind)
    {
        const int timeoutValue = 300;
        (string MethodFullName, string Prefix, string EnvVarSuffix, string ConfigKeyName) info = InfoByKind[entryKind];
        string testConfig = $$"""
{
  "mstest": {
    "timeout": {
      "{{info.ConfigKeyName}}": {{timeoutValue}}
    }
  }
}
""";

        var testHost = TestHost.LocateFrom(AssetFixture.TargetAssetPath, TestAssetFixture.ProjectName, tfm);
        string testConfigFilePath = Path.Combine(testHost.DirectoryName, $"{Guid.NewGuid():N}.json");
        File.WriteAllText(testConfigFilePath, testConfig);

        TestHostResult testHostResult = await testHost.ExecuteAsync($"--config-file \"{testConfigFilePath}\"", environmentVariables: new() { [$"TIMEOUT_{info.EnvVarSuffix}"] = "1" }, cancellationToken: TestContext.CancellationToken);
        testHostResult.AssertOutputContains($"{info.Prefix} method '{info.MethodFullName}' timed out after {timeoutValue}ms");
    }

    public sealed class TestAssetFixture : TestAssetFixtureBase
    {
        public const string ProjectName = "TimeoutCodeWithNoTimeoutFromConfig";

        public string TargetAssetPath => GetAssetPath(ProjectName);

        public override (string ID, string Name, string Code) GetAssetsToGenerate() => (ProjectName, ProjectName,
                SourceCode
                .PatchCodeWithReplace("$TimeoutAttribute$", string.Empty)
                .PatchCodeWithReplace("$ProjectName$", ProjectName)
                .PatchTargetFrameworks(TargetFrameworks.All)
                .PatchCodeWithReplace("$MSTestVersion$", MSTestVersion));

        private const string SourceCode = """
#file $ProjectName$.csproj
<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <EnableMSTestRunner>true</EnableMSTestRunner>
    <TargetFrameworks>$TargetFrameworks$</TargetFrameworks>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="MSTest.TestAdapter" Version="$MSTestVersion$" />
    <PackageReference Include="MSTest.TestFramework" Version="$MSTestVersion$" />
  </ItemGroup>

</Project>

#file UnitTest1.cs

using System;
using System.Threading.Tasks;
using Microsoft.VisualStudio.TestTools.UnitTesting;

public class TestClassBase
{
    $TimeoutAttribute$
    [ClassInitialize(inheritanceBehavior: InheritanceBehavior.BeforeEachDerivedClass)]
    public static async Task ClassInitBase(TestContext testContext)
    {
        if (Environment.GetEnvironmentVariable("TIMEOUT_BASE_CLASSINIT") == "1")
        {
            await Task.Delay(10_000, testContext.CancellationTokenSource.Token);
        }
        else
        {
            await Task.CompletedTask;
        }
    }

    $TimeoutAttribute$
    [ClassCleanup(inheritanceBehavior: InheritanceBehavior.BeforeEachDerivedClass)]
    public static async Task ClassCleanupBase()
    {
        if (Environment.GetEnvironmentVariable("TIMEOUT_BASE_CLASSCLEANUP") == "1")
        {
            await Task.Delay(10_000);
        }
        else
        {
            await Task.CompletedTask;
        }
    }

}

[TestClass]
public class TestClass : TestClassBase
{
    $TimeoutAttribute$
    [AssemblyInitialize]
    public static async Task AssemblyInit(TestContext testContext)
    {
        if (Environment.GetEnvironmentVariable("TIMEOUT_ASSEMBLYINIT") == "1")
        {
            await Task.Delay(60_000, testContext.CancellationTokenSource.Token);
        }
        else
        {
            await Task.CompletedTask;
        }
    }

    $TimeoutAttribute$
    [AssemblyCleanup]
    public static async Task AssemblyCleanupMethod()
    {
        if (Environment.GetEnvironmentVariable("TIMEOUT_ASSEMBLYCLEANUP") == "1")
        {
            await Task.Delay(10_000);
        }
        else
        {
            await Task.CompletedTask;
        }
    }

    $TimeoutAttribute$
    [ClassInitialize]
    public static async Task ClassInit(TestContext testContext)
    {
        if (Environment.GetEnvironmentVariable("TIMEOUT_CLASSINIT") == "1")
        {
            await Task.Delay(60_000, testContext.CancellationTokenSource.Token);
        }
        else
        {
            await Task.CompletedTask;
        }
    }

    $TimeoutAttribute$
    [ClassCleanup]
    public static async Task ClassCleanupMethod()
    {
        if (Environment.GetEnvironmentVariable("TIMEOUT_CLASSCLEANUP") == "1")
        {
            await Task.Delay(10_000);
        }
        else
        {
            await Task.CompletedTask;
        }
    }

    $TimeoutAttribute$
    [TestInitialize]
    public async Task TestInit()
    {
        if (Environment.GetEnvironmentVariable("TIMEOUT_TESTINIT") == "1")
        {
            await Task.Delay(10_000);
        }
        else
        {
            await Task.CompletedTask;
        }
    }

    $TimeoutAttribute$
    [TestCleanup]
    public async Task TestCleanupMethod()
    {
        if (Environment.GetEnvironmentVariable("TIMEOUT_TESTCLEANUP") == "1")
        {
            await Task.Delay(10_000);
        }
        else
        {
            await Task.CompletedTask;
        }
    }

    [TestMethod]
    public Task Test1() => Task.CompletedTask;
}
""";
    }

    public TestContext TestContext { get; set; } = default!;
}
