diff --git a/src/FSharp.Build/Fsc.fs b/src/FSharp.Build/Fsc.fs index c18b42a3989..25cdbd34195 100644 --- a/src/FSharp.Build/Fsc.fs +++ b/src/FSharp.Build/Fsc.fs @@ -786,10 +786,10 @@ type public Fsc() as this = let builder = generateCommandLineBuilder () builder.GetCapturedArguments() |> String.concat Environment.NewLine - // expose this to internal components (for nunit testing) + // expose this to internal components (for unit testing) member internal fsc.InternalGenerateCommandLineCommands() = fsc.GenerateCommandLineCommands() - // expose this to internal components (for nunit testing) + // expose this to internal components (for unit testing) member internal fsc.InternalGenerateResponseFileCommands() = fsc.GenerateResponseFileCommands() member internal fsc.InternalExecuteTool(pathToTool, responseFileCommands, commandLineCommands) = diff --git a/src/FSharp.Build/Fsi.fs b/src/FSharp.Build/Fsi.fs index dd0ccff9754..4e7bd9c4e0a 100644 --- a/src/FSharp.Build/Fsi.fs +++ b/src/FSharp.Build/Fsi.fs @@ -388,10 +388,10 @@ type public Fsi() as this = let builder = generateCommandLineBuilder () builder.GetCapturedArguments() |> String.concat Environment.NewLine - // expose this to internal components (for nunit testing) + // expose this to internal components (for unit testing) member internal fsi.InternalGenerateCommandLineCommands() = fsi.GenerateCommandLineCommands() - // expose this to internal components (for nunit testing) + // expose this to internal components (for unit testing) member internal fsi.InternalGenerateResponseFileCommands() = fsi.GenerateResponseFileCommands() member internal fsi.InternalExecuteTool(pathToTool, responseFileCommands, commandLineCommands) = diff --git a/tests/FSharp.Compiler.ComponentTests/TypeChecks/Graph/CompilationFromCmdlineArgsTests.fs b/tests/FSharp.Compiler.ComponentTests/TypeChecks/Graph/CompilationFromCmdlineArgsTests.fs index 4525d7286f2..9cfbbb9df80 100644 --- a/tests/FSharp.Compiler.ComponentTests/TypeChecks/Graph/CompilationFromCmdlineArgsTests.fs +++ b/tests/FSharp.Compiler.ComponentTests/TypeChecks/Graph/CompilationFromCmdlineArgsTests.fs @@ -5,19 +5,19 @@ module CompilationFromCmdlineArgsTests = open System open System.IO open FSharp.Compiler.CodeAnalysis - open NUnit.Framework + open Xunit open CompilationTests // Point to a generated args.txt file. // Use scrape.fsx to generate an args.txt from a binary log file. // The path needs to be absolute. - let localProjects: string list = + let localProjects = [ @"C:\Projects\fantomas\src\Fantomas.Core\Fantomas.Core.args.txt" @"C:\Projects\FsAutoComplete\src\FsAutoComplete\FsAutoComplete.args.txt" @"C:\Projects\fsharp\src\Compiler\FSharp.Compiler.Service.args.txt" @"C:\Projects\fsharp\tests\FSharp.Compiler.ComponentTests\FSharp.Compiler.ComponentTests.args.txt" - ] + ] |> Seq.map (fun p -> [| box p |]) let checker = FSharpChecker.Create() @@ -43,16 +43,16 @@ module CompilationFromCmdlineArgsTests = for diag in diagnostics do printfn "%A" diag - Assert.That(exitCode, Is.Zero) + Assert.Equal(exitCode, 0) finally Environment.CurrentDirectory <- oldWorkDir - [] - [] + [] + [] let ``Test sequential type-checking`` (projectArgumentsFilePath: string) = testCompilerFromArgs Method.Sequential projectArgumentsFilePath - [] - [] + [] + [] let ``Test graph-based type-checking`` (projectArgumentsFilePath: string) = testCompilerFromArgs Method.Graph projectArgumentsFilePath diff --git a/tests/FSharp.Compiler.ComponentTests/TypeChecks/Graph/DependencyResolutionTests.fs b/tests/FSharp.Compiler.ComponentTests/TypeChecks/Graph/DependencyResolutionTests.fs index 36a246d6ced..81adc540766 100644 --- a/tests/FSharp.Compiler.ComponentTests/TypeChecks/Graph/DependencyResolutionTests.fs +++ b/tests/FSharp.Compiler.ComponentTests/TypeChecks/Graph/DependencyResolutionTests.fs @@ -1,11 +1,14 @@ module TypeChecks.DependencyResolutionTests open TypeChecks.TestUtils -open NUnit.Framework +open Xunit open FSharp.Compiler.GraphChecking open Scenarios -[] +let scenarios = scenarios |> Seq.map (fun p -> [| box p |]) + +[] +[] let ``Supported scenario`` (scenario: Scenario) = let files = scenario.Files @@ -18,4 +21,4 @@ let ``Supported scenario`` (scenario: Scenario) = for file in scenario.Files do let expectedDeps = file.ExpectedDependencies let actualDeps = set graph.[file.Index] - Assert.AreEqual(expectedDeps, actualDeps, $"Dependencies don't match for {System.IO.Path.GetFileName file.FileName}") + Assert.True((expectedDeps = actualDeps), $"Dependencies don't match for {System.IO.Path.GetFileName file.FileName}") diff --git a/tests/FSharp.Compiler.ComponentTests/TypeChecks/Graph/FileContentMappingTests.fs b/tests/FSharp.Compiler.ComponentTests/TypeChecks/Graph/FileContentMappingTests.fs index 12f171de5fa..070133a3d8d 100644 --- a/tests/FSharp.Compiler.ComponentTests/TypeChecks/Graph/FileContentMappingTests.fs +++ b/tests/FSharp.Compiler.ComponentTests/TypeChecks/Graph/FileContentMappingTests.fs @@ -1,6 +1,6 @@ module TypeChecks.FileContentMappingTests -open NUnit.Framework +open Xunit open FSharp.Compiler.GraphChecking open TestUtils @@ -35,7 +35,7 @@ let private (|NestedModule|_|) value e = | FileContentEntry.NestedModule(name, nestedContent) -> if name = value then Some(nestedContent) else None | _ -> None -[] +[] let ``Top level module only exposes namespace`` () = let content = getContent @@ -45,10 +45,10 @@ module X.Y.Z """ match content with - | [ TopLevelNamespace "X.Y" [] ] -> Assert.Pass() + | [ TopLevelNamespace "X.Y" [] ] -> () | content -> Assert.Fail($"Unexpected content: {content}") -[] +[] let ``Top level namespace`` () = let content = getContent @@ -58,10 +58,10 @@ namespace X.Y """ match content with - | [ TopLevelNamespace "X.Y" [] ] -> Assert.Pass() + | [ TopLevelNamespace "X.Y" [] ] -> () | content -> Assert.Fail($"Unexpected content: {content}") -[] +[] let ``Open statement in top level module`` () = let content = getContent @@ -73,10 +73,10 @@ open A.B.C """ match content with - | [ TopLevelNamespace "X.Y" [ OpenStatement "A.B.C" ] ] -> Assert.Pass() + | [ TopLevelNamespace "X.Y" [ OpenStatement "A.B.C" ] ] -> () | content -> Assert.Fail($"Unexpected content: {content}") -[] +[] let ``PrefixedIdentifier in type annotation`` () = let content = getContent @@ -88,10 +88,10 @@ let fn (a: A.B.CType) = () """ match content with - | [ TopLevelNamespace "X.Y" [ PrefixedIdentifier "A.B" ] ] -> Assert.Pass() + | [ TopLevelNamespace "X.Y" [ PrefixedIdentifier "A.B" ] ] -> () | content -> Assert.Fail($"Unexpected content: {content}") -[] +[] let ``Nested module`` () = let content = getContent @@ -104,10 +104,10 @@ module Z = """ match content with - | [ TopLevelNamespace "X" [ NestedModule "Z" [] ] ] -> Assert.Pass() + | [ TopLevelNamespace "X" [ NestedModule "Z" [] ] ] -> () | content -> Assert.Fail($"Unexpected content: {content}") -[] +[] let ``Single ident module abbreviation`` () = let content = getContent @@ -119,13 +119,13 @@ module B = C """ match content with - | [ TopLevelNamespace "" [ PrefixedIdentifier "C" ] ] -> Assert.Pass() + | [ TopLevelNamespace "" [ PrefixedIdentifier "C" ] ] -> () | content -> Assert.Fail($"Unexpected content: {content}") module InvalidSyntax = - [] + [] let ``Nested module`` () = let content = getContent @@ -137,11 +137,11 @@ module InvalidSyntax = """ match content with - | [ TopLevelNamespace "" [] ] -> Assert.Pass() + | [ TopLevelNamespace "" [] ] -> () | content -> Assert.Fail($"Unexpected content: {content}") - [] + [] let ``Module above namespace`` () = let content = getContent @@ -153,5 +153,5 @@ module InvalidSyntax = """ match content with - | [ TopLevelNamespace "" [] ] -> Assert.Pass() + | [ TopLevelNamespace "" [] ] -> () | content -> Assert.Fail($"Unexpected content: {content}") diff --git a/tests/FSharp.Compiler.ComponentTests/TypeChecks/Graph/GraphProcessingTests.fs b/tests/FSharp.Compiler.ComponentTests/TypeChecks/Graph/GraphProcessingTests.fs index f8a4c8d2d23..675294acf0c 100644 --- a/tests/FSharp.Compiler.ComponentTests/TypeChecks/Graph/GraphProcessingTests.fs +++ b/tests/FSharp.Compiler.ComponentTests/TypeChecks/Graph/GraphProcessingTests.fs @@ -2,9 +2,9 @@ open System.Threading open FSharp.Compiler.GraphChecking.GraphProcessing -open NUnit.Framework +open Xunit -[] +[] let ``When processing a node throws an exception, an exception is raised with the original exception included`` () = let graph = [1, [|2|]; 2, [||]] |> readOnlyDict let work (_processor : int -> ProcessedNode) (_node : NodeInfo) : string = failwith "Work exception" @@ -18,6 +18,6 @@ let ``When processing a node throws an exception, an exception is raised with th CancellationToken.None |> ignore ) - Assert.That(exn.Message, Is.EqualTo("Encountered exception when processing item '2'")) - Assert.That(exn.InnerException, Is.Not.Null) - Assert.That(exn.InnerException.Message, Is.EqualTo("Work exception")) + Assert.Equal(exn.Message, "Encountered exception when processing item '2'") + Assert.NotNull(exn.InnerException) + Assert.Equal(exn.InnerException.Message, "Work exception") diff --git a/tests/FSharp.Compiler.ComponentTests/TypeChecks/Graph/QueryTrieTests.fs b/tests/FSharp.Compiler.ComponentTests/TypeChecks/Graph/QueryTrieTests.fs index 613d77a29ee..524535efa32 100644 --- a/tests/FSharp.Compiler.ComponentTests/TypeChecks/Graph/QueryTrieTests.fs +++ b/tests/FSharp.Compiler.ComponentTests/TypeChecks/Graph/QueryTrieTests.fs @@ -2,7 +2,7 @@ open System.Collections.Generic open System.Collections.Immutable -open NUnit.Framework +open Xunit open FSharp.Compiler.GraphChecking open FSharp.Compiler.GraphChecking.DependencyResolution @@ -757,24 +757,24 @@ let private fantomasCoreTrie: TrieNode = |] } -[] +[] let ``Query nonexistent node in trie`` () = let result = queryTrie fantomasCoreTrie [ "System"; "System"; "Runtime"; "CompilerServices" ] match result with - | QueryTrieNodeResult.NodeDoesNotExist -> Assert.Pass() + | QueryTrieNodeResult.NodeDoesNotExist -> () | result -> Assert.Fail $"Unexpected result: %A{result}" -[] +[] let ``Query node that does not expose data in trie`` () = let result = queryTrie fantomasCoreTrie [ "Fantomas"; "Core" ] match result with - | QueryTrieNodeResult.NodeDoesNotExposeData -> Assert.Pass() + | QueryTrieNodeResult.NodeDoesNotExposeData -> () | result -> Assert.Fail $"Unexpected result: %A{result}" -[] +[] let ``Query module node that exposes one file`` () = let result = queryTrie fantomasCoreTrie [ "Fantomas"; "Core"; "ISourceTextExtensions" ] @@ -782,10 +782,10 @@ let ``Query module node that exposes one file`` () = match result with | QueryTrieNodeResult.NodeExposesData file -> let file = Seq.exactlyOne file - Assert.AreEqual(indexOf "ISourceTextExtensions.fs", file) + Assert.Equal(indexOf "ISourceTextExtensions.fs", file) | result -> Assert.Fail $"Unexpected result: %A{result}" -[] +[] let ``ProcessOpenStatement full path match`` () = let state = FileContentQueryState.Create Set.empty @@ -794,4 +794,4 @@ let ``ProcessOpenStatement full path match`` () = processOpenPath fantomasCoreTrie [ "Fantomas"; "Core"; "AstExtensions" ] state let dep = Seq.exactlyOne result.FoundDependencies - Assert.AreEqual(indexOf "AstExtensions.fsi", dep) + Assert.Equal(indexOf "AstExtensions.fsi", dep) diff --git a/tests/FSharp.Compiler.ComponentTests/TypeChecks/Graph/TrieMappingTests.fs b/tests/FSharp.Compiler.ComponentTests/TypeChecks/Graph/TrieMappingTests.fs index 6ad29818a2a..2a3d7b608ea 100644 --- a/tests/FSharp.Compiler.ComponentTests/TypeChecks/Graph/TrieMappingTests.fs +++ b/tests/FSharp.Compiler.ComponentTests/TypeChecks/Graph/TrieMappingTests.fs @@ -1,6 +1,6 @@ module TypeChecks.TrieMappingTests -open NUnit.Framework +open Xunit open FSharp.Compiler.GraphChecking open TestUtils @@ -8,7 +8,7 @@ let private noDependencies = Set.empty let private getLastTrie files = TrieMapping.mkTrie files |> Array.last |> snd -[] +[] let ``Basic trie`` () = let sampleFiles = [| @@ -49,22 +49,22 @@ type C = { CX: int; CY: int } | current -> Assert.Fail($"mkTrie should always return a TrieNodeInfo.Root, got {current}") let xNode = trie.Children.["X"] - Assert.AreEqual(1, xNode.Children.Count) + Assert.Equal(1, xNode.Children.Count) Assert.True(Seq.isEmpty xNode.Files) let yNode = xNode.Children["Y"] - Assert.AreEqual(2, yNode.Children.Count) - Assert.AreEqual(set [| 2 |], yNode.Files) + Assert.Equal(2, yNode.Children.Count) + Assert.Equal>(set [| 2 |], yNode.Files) let aNode = yNode.Children["A"] - Assert.AreEqual(0, aNode.Children.Count) - Assert.AreEqual(set [| 0 |], aNode.Files) + Assert.Equal(0, aNode.Children.Count) + Assert.Equal>(set [| 0 |], aNode.Files) let bNode = yNode.Children["B"] - Assert.AreEqual(0, bNode.Children.Count) - Assert.AreEqual(set [| 1 |], bNode.Files) + Assert.Equal(0, bNode.Children.Count) + Assert.Equal>(set [| 1 |], bNode.Files) -[] +[] let ``Toplevel AutoOpen module with prefixed namespace`` () = let trie = getLastTrie @@ -87,11 +87,11 @@ let a = 0 // Assert that both A and B expose file index 0 let aNode = trie.Children.["A"] - Assert.AreEqual(set [| 0 |], aNode.Files) + Assert.Equal>(set [| 0 |], aNode.Files) let bNode = aNode.Children.["B"] - Assert.AreEqual(set [| 0 |], bNode.Files) + Assert.Equal>(set [| 0 |], bNode.Files) -[] +[] let ``Toplevel AutoOpen module with multi prefixed namespace`` () = let trie = getLastTrie @@ -114,13 +114,13 @@ let a = 0 // Assert that B and C expose file index 0, namespace A should not. let aNode = trie.Children.["A"] - Assert.AreEqual(noDependencies, aNode.Files) + Assert.Equal>(noDependencies, aNode.Files) let bNode = aNode.Children.["B"] - Assert.AreEqual(set [| 0 |], bNode.Files) + Assert.Equal>(set [| 0 |], bNode.Files) let cNode = bNode.Children.["C"] - Assert.AreEqual(set [| 0 |], cNode.Files) + Assert.Equal>(set [| 0 |], cNode.Files) -[] +[] let ``Global namespace should link files to the root node`` () = let trie = getLastTrie @@ -159,9 +159,9 @@ type B = { Y : int } } |] - Assert.AreEqual(set [| 0; 1 |], trie.Files) + Assert.Equal>(set [| 0; 1 |], trie.Files) -[] +[] let ``Module with a single ident and AutoOpen attribute should link files to root`` () = let trie = getLastTrie @@ -202,10 +202,10 @@ type B = { Y : int } } |] - Assert.AreEqual(set [| 0; 1 |], trie.Files) - Assert.AreEqual(0, trie.Children.Count) + Assert.Equal>(set [| 0; 1 |], trie.Files) + Assert.Equal(0, trie.Children.Count) -[] +[] let ``Module with AutoOpen attribute and two ident should expose file at two levels`` () = let trie = getLastTrie @@ -226,13 +226,13 @@ type A = { A : int } } |] - Assert.AreEqual(noDependencies, trie.Files) + Assert.Equal>(noDependencies, trie.Files) let xNode = trie.Children.["X"] - Assert.AreEqual(set [| 0 |], xNode.Files) + Assert.Equal>(set [| 0 |], xNode.Files) let yNode = xNode.Children.["Y"] - Assert.AreEqual(set [| 0 |], yNode.Files) + Assert.Equal>(set [| 0 |], yNode.Files) -[] +[] let ``Module with AutoOpen attribute and three ident should expose file at last two levels`` () = let trie = getLastTrie @@ -253,15 +253,15 @@ type A = { A : int } } |] - Assert.AreEqual(noDependencies, trie.Files) + Assert.Equal>(noDependencies, trie.Files) let xNode = trie.Children.["X"] - Assert.AreEqual(noDependencies, xNode.Files) + Assert.Equal>(noDependencies, xNode.Files) let yNode = xNode.Children.["Y"] - Assert.AreEqual(set [| 0 |], yNode.Files) + Assert.Equal>(set [| 0 |], yNode.Files) let zNode = yNode.Children.["Z"] - Assert.AreEqual(set [| 0 |], zNode.Files) + Assert.Equal>(set [| 0 |], zNode.Files) -[] +[] let ``Nested AutoOpen module in namespace will expose the file to the namespace node`` () = let trie = getLastTrie @@ -284,15 +284,15 @@ module Z = } |] - Assert.AreEqual(noDependencies, trie.Files) + Assert.Equal>(noDependencies, trie.Files) let xNode = trie.Children.["X"] - Assert.AreEqual(noDependencies, xNode.Files) + Assert.Equal>(noDependencies, xNode.Files) let yNode = xNode.Children.["Y"] - Assert.AreEqual(set [| 0 |], yNode.Files) + Assert.Equal>(set [| 0 |], yNode.Files) let zNode = yNode.Children.["Z"] - Assert.AreEqual(set [| 0 |], zNode.Files) + Assert.Equal>(set [| 0 |], zNode.Files) -[] +[] let ``Two modules with the same name, only the first file exposes the index`` () = let trie = getLastTrie @@ -325,11 +325,11 @@ let _ = () } |] - Assert.AreEqual(1, trie.Children.Count) + Assert.Equal(1, trie.Children.Count) let aNode = trie.Children.["A"] - Assert.AreEqual(set [| 0 |], aNode.Files) + Assert.Equal>(set [| 0 |], aNode.Files) -[] +[] let ``Two nested modules with the same name, in named namespace`` () = let trie = getLastTrie @@ -352,11 +352,11 @@ module ``module`` = } |] - Assert.AreEqual(1, trie.Children.Count) + Assert.Equal(1, trie.Children.Count) let node = trie.Children.["N"] - Assert.AreEqual(1, node.Children.Count) + Assert.Equal(1, node.Children.Count) -[] +[] let ``Two nested modules with the same name, in namespace global`` () = let trie = getLastTrie @@ -380,9 +380,9 @@ module ``module`` = |] // namespace global leads to a Root entry, no further processing will be done. - Assert.AreEqual(set [| 0 |], trie.Files) + Assert.Equal>(set [| 0 |], trie.Files) -[] +[] let ``Two nested modules with the same name, in anonymous module`` () = let trie = getLastTrie @@ -403,10 +403,10 @@ module ``module`` = } |] - Assert.AreEqual(1, trie.Children.Count) + Assert.Equal(1, trie.Children.Count) Assert.True(trie.Children.ContainsKey("module")) -[] +[] let ``Two nested modules with the same name, in nested module`` () = let trie = getLastTrie @@ -432,10 +432,10 @@ module B = |] let bNode = trie.Children["A"].Children["B"] - Assert.AreEqual(1, bNode.Children.Count) + Assert.Equal(1, bNode.Children.Count) Assert.True(bNode.Children.ContainsKey("module")) -[] +[] let ``Two nested modules with the same name, in nested module in signature file`` () = let trie = getLastTrie @@ -459,10 +459,10 @@ module B = |] let bNode = trie.Children["A"].Children["B"] - Assert.AreEqual(1, bNode.Children.Count) + Assert.Equal(1, bNode.Children.Count) Assert.True(bNode.Children.ContainsKey("module")) -[] +[] let ``Two namespaces with the same name in the same implementation file`` () = let trie = getLastTrie @@ -486,9 +486,9 @@ module C = begin end |] let aNode = trie.Children["A"] - Assert.AreEqual(2, aNode.Children.Count) + Assert.Equal(2, aNode.Children.Count) -[] +[] let ``Two namespaces with the same name in the same signature file`` () = let trie = getLastTrie @@ -512,9 +512,9 @@ module C = begin end |] let aNode = trie.Children["A"] - Assert.AreEqual(2, aNode.Children.Count) + Assert.Equal(2, aNode.Children.Count) -[] +[] let ``Tries are built up incrementally`` () = let trie = TrieMapping.mkTrie @@ -542,12 +542,12 @@ let ``Tries are built up incrementally`` () = |] for idx, t in trie do - Assert.AreEqual(idx + 1, t.Children.Count) + Assert.Equal(idx + 1, t.Children.Count) module InvalidSyntax = - [] + [] let ``Unnamed module`` () = let trie = getLastTrie diff --git a/tests/FSharp.Compiler.ComponentTests/TypeChecks/Graph/TypedTreeGraph.fs b/tests/FSharp.Compiler.ComponentTests/TypeChecks/Graph/TypedTreeGraph.fs index c4680870efc..dc89f4f9a4c 100644 --- a/tests/FSharp.Compiler.ComponentTests/TypeChecks/Graph/TypedTreeGraph.fs +++ b/tests/FSharp.Compiler.ComponentTests/TypeChecks/Graph/TypedTreeGraph.fs @@ -7,7 +7,7 @@ open System.IO open FSharp.Compiler.CodeAnalysis open FSharp.Compiler.Text open FSharp.Compiler.Symbols -open NUnit.Framework +open Xunit open FSharp.Compiler.GraphChecking open TypeChecks.TestUtils @@ -100,8 +100,8 @@ let graphFromTypedTree (checker: FSharpChecker) (projectOptions: FSharpProjectOp return files, graph } -[] -[] +[] +[] let ``Create Graph from typed tree`` (projectArgumentsFilePath: string) = let previousDir = Environment.CurrentDirectory @@ -181,7 +181,7 @@ let ``Create Graph from typed tree`` (projectArgumentsFilePath: string) = let isSuperSet = Set.isSuperset depsFromHeuristic depsFromTypedTree let delta = Set.difference depsFromTypedTree depsFromHeuristic - Assert.IsTrue( + Assert.True( isSuperSet, $"""{relativePath fileName} did not contain a superset of the typed tree dependencies: {source} is missing dependencies: %A{depNames delta}.""" diff --git a/tests/FSharp.Compiler.Service.Tests/AssemblyReaderShim.fs b/tests/FSharp.Compiler.Service.Tests/AssemblyReaderShim.fs index a38210a6fe4..ebe2c3dd61d 100644 --- a/tests/FSharp.Compiler.Service.Tests/AssemblyReaderShim.fs +++ b/tests/FSharp.Compiler.Service.Tests/AssemblyReaderShim.fs @@ -23,4 +23,4 @@ let x = 123 let fileName, options = mkTestFileAndOptions source [| |] checker.ParseAndCheckFileInProject(fileName, 0, SourceText.ofString source, options) |> Async.RunImmediate |> ignore - gotRequest |> should be True + gotRequest |> Assert.True diff --git a/tests/FSharp.Compiler.Service.Tests/CSharpProjectAnalysis.fs b/tests/FSharp.Compiler.Service.Tests/CSharpProjectAnalysis.fs index a2f4c122591..aa4cc9af679 100644 --- a/tests/FSharp.Compiler.Service.Tests/CSharpProjectAnalysis.fs +++ b/tests/FSharp.Compiler.Service.Tests/CSharpProjectAnalysis.fs @@ -144,8 +144,8 @@ let _ = CSharpClass(0) match (ctor :?> FSharpMemberOrFunctionOrValue).DeclaringEntity with | Some e -> let members = e.MembersFunctionsAndValues - Seq.exists (fun (mfv : FSharpMemberOrFunctionOrValue) -> mfv.IsConstructor) members |> should be True - Seq.exists (fun (mfv : FSharpMemberOrFunctionOrValue) -> mfv.IsEffectivelySameAs ctor) members |> should be True + Seq.exists (fun (mfv : FSharpMemberOrFunctionOrValue) -> mfv.IsConstructor) members |> Assert.True + Seq.exists (fun (mfv : FSharpMemberOrFunctionOrValue) -> mfv.IsEffectivelySameAs ctor) members |> Assert.True | None -> failwith "Expected Some for DeclaringEntity" let getEntitiesUses source = @@ -172,7 +172,7 @@ let (s2: FSharp.Compiler.Service.Tests.String) = null |> List.filter (fun entity -> entity.LogicalName = "String") match stringSymbols with - | e1 :: e2 :: [] -> e1.IsEffectivelySameAs(e2) |> should be False + | e1 :: e2 :: [] -> e1.IsEffectivelySameAs(e2) |> Assert.False | _ -> sprintf "Expecting two symbols, got %A" stringSymbols |> failwith [] @@ -189,5 +189,5 @@ open FSharp.Compiler.Service.Tests.Linq |> List.filter (fun entity -> entity.LogicalName = "Linq") match stringSymbols with - | e1 :: e2 :: [] -> e1.IsEffectivelySameAs(e2) |> should be False + | e1 :: e2 :: [] -> e1.IsEffectivelySameAs(e2) |> Assert.False | _ -> sprintf "Expecting two symbols, got %A" stringSymbols |> failwith diff --git a/tests/FSharp.Compiler.Service.Tests/ProjectAnalysisTests.fs b/tests/FSharp.Compiler.Service.Tests/ProjectAnalysisTests.fs index 237c49d5794..92ca4a07091 100644 --- a/tests/FSharp.Compiler.Service.Tests/ProjectAnalysisTests.fs +++ b/tests/FSharp.Compiler.Service.Tests/ProjectAnalysisTests.fs @@ -5813,7 +5813,7 @@ let ``References from #r nuget are included in script project options`` () = |> Seq.choose (fun f -> f.FileName |> Option.map Path.GetFileName) |> Seq.distinct printfn "%s" (assemblyNames |> String.concat "\n") - assemblyNames |> should contain "Dapper.dll" + Assert.Contains("Dapper.dll", assemblyNames) module internal EmptyProject = let base2 = getTemporaryFileName () diff --git a/tests/FSharp.Core.UnitTests/FSharp.Core/Microsoft.FSharp.Core/IntConversionsTestGenerator.fsx b/tests/FSharp.Core.UnitTests/FSharp.Core/Microsoft.FSharp.Core/IntConversionsTestGenerator.fsx index d30d3bb324e..42f7bf98b6d 100644 --- a/tests/FSharp.Core.UnitTests/FSharp.Core/Microsoft.FSharp.Core/IntConversionsTestGenerator.fsx +++ b/tests/FSharp.Core.UnitTests/FSharp.Core/Microsoft.FSharp.Core/IntConversionsTestGenerator.fsx @@ -45,7 +45,7 @@ do // This file is automatically generated by IntConversionsTestGenerator.fsx namespace FSharp.Core.UnitTests open System -open NUnit.Framework +open XUnit open FSharp.Core.UnitTests.LibraryTestFx module UInt8 = @@ -56,7 +56,6 @@ module Int8 = let MinValue = SByte.MinValue let MaxValue = SByte.MaxValue -[] type IntConversionsGenerated() = " @@ -70,7 +69,7 @@ type IntConversionsGenerated() = // -1 converted to unsigned types. Should become MaxValues let signedToUnsignedGenerator target = signedInts |> List.iter (fun source-> - prn "[]" + prn "[]" prn "member this.``%s.m1.To.%s`` () =" source.alias target.alias shift () prn "let i : %s = -1%s" source.alias source.suffix @@ -82,7 +81,7 @@ type IntConversionsGenerated() = // -1 converted to signed types. Should stay -1. let signedToSignedGenerator target = signedInts |> List.iter (fun source-> - prn "[]" + prn "[]" prn "member this.``%s.m1.To.%s`` () =" source.alias target.alias shift () prn "let minus1 : %s = -1%s" target.alias target.suffix @@ -96,7 +95,7 @@ type IntConversionsGenerated() = let unsignedToWiderGenerator target = unsignedInts |> List.filter (fun source -> source.width < target.width) |> List.iter (fun source -> - prn "[]" + prn "[]" prn "member this.``%s.MaxValue.To.%s`` () =" source.alias target.alias shift () prn "let sourceMaxValue : %s = %s%s" target.alias (maxValueAsHexLiteral source) target.suffix @@ -109,7 +108,7 @@ type IntConversionsGenerated() = let unsignedToNarrowerSignedGenerator target = unsignedInts |> List.filter (fun source -> source.width >= target.width) |> List.iter (fun source -> - prn "[]" + prn "[]" prn "member this.``%s.MaxValue.To.%s`` () =" source.alias target.alias shift () prn "Assert.AreEqual (-1%s, %s %s.MaxValue)" target.suffix target.alias source.name @@ -121,7 +120,7 @@ type IntConversionsGenerated() = let unsignedToNarrowerUnsignedGenerator target = unsignedInts |> List.filter (fun source -> source.width >= target.width) |> List.iter (fun source -> - prn "[]" + prn "[]" prn "member this.``%s.MaxValue.To.%s`` () =" source.alias target.alias shift () prn "Assert.AreEqual (%s.MaxValue, %s %s.MaxValue)" target.name target.alias source.name @@ -131,7 +130,7 @@ type IntConversionsGenerated() = // -1 to signed nativeint stays -1 signedInts |> List.iter (fun source -> - prn "[]" + prn "[]" prn "member this.``%s.m1.To.nativeint`` () =" source.alias shift () prn "Assert.AreEqual (-1n, nativeint -1%s)" source.suffix @@ -140,7 +139,7 @@ type IntConversionsGenerated() = // unsigned MaxValues to signed nativeint stay same for narrower types, become -1 for wider types unsignedInts |> List.iter (fun source -> - prn "[]" + prn "[]" prn "member this.``%s.MaxValue.To.nativeint`` () =" source.alias shift () prn "if sizeof > sizeof<%s> then" source.alias @@ -162,7 +161,7 @@ type IntConversionsGenerated() = // -1 to unsigned nativeint should become MaxValue signedInts |> List.iter (fun source -> - prn "[]" + prn "[]" prn "member this.``%s.m1.To.unativeint`` () =" source.alias shift () prn "Assert.AreEqual (this.UnativeintMaxValue, unativeint -1%s)" source.suffix @@ -171,7 +170,7 @@ type IntConversionsGenerated() = // unsigned MaxValues to unsigned nativeint stay same for narrower types, become MaxValue for wider types unsignedInts |> List.iter (fun source -> - prn "[]" + prn "[]" prn "member this.``%s.m1.To.unativeint`` () =" source.alias shift () prn "if sizeof > sizeof<%s> then" source.alias @@ -188,7 +187,7 @@ type IntConversionsGenerated() = // -1 converted to unsigned types. Should throw let checkedSignedToUnsignedGenerator target = signedInts |> List.iter (fun source-> - prn "[]" + prn "[]" prn "member this.``Checked.%s.m1.To.%s`` () =" source.alias target.alias shift () prn "let i : %s = -1%s" source.alias source.suffix @@ -200,7 +199,7 @@ type IntConversionsGenerated() = // -1 converted to signed types. Should stay -1. let signedToSignedGenerator target = signedInts |> List.iter (fun source-> - prn "[]" + prn "[]" prn "member this.``Checked.%s.m1.To.%s`` () =" source.alias target.alias shift () prn "let minus1 : %s = -1%s" target.alias target.suffix @@ -214,7 +213,7 @@ type IntConversionsGenerated() = let checkedUnsignedToWiderGenerator target = unsignedInts |> List.filter (fun source -> source.width < target.width) |> List.iter (fun source -> - prn "[]" + prn "[]" prn "member this.``Checked.%s.MaxValue.To.%s`` () =" source.alias target.alias shift () prn "let sourceMaxValue : %s = %s%s" target.alias (maxValueAsHexLiteral source) target.suffix @@ -227,7 +226,7 @@ type IntConversionsGenerated() = let checkedUnsignedToNarrowerSignedGenerator target = unsignedInts |> List.filter (fun source -> source.width >= target.width && target.alias <> "int8") |> List.iter (fun source -> - prn "[]" + prn "[]" prn "member this.``Checked.%s.MaxValue.To.%s`` () =" source.alias target.alias shift () prn "CheckThrowsExn (fun () -> Checked.%s %s.MaxValue |> ignore)" target.alias source.name @@ -239,7 +238,7 @@ type IntConversionsGenerated() = let checkedUnsignedToNarrowerUnsignedGenerator target = unsignedInts |> List.filter (fun source -> source.width > target.width) |> List.iter (fun source -> - prn "[]" + prn "[]" prn "member this.``Checked.%s.MaxValue.To.%s`` () =" source.alias target.alias shift () prn "CheckThrowsExn (fun () -> Checked.%s %s.MaxValue |> ignore)" target.alias source.name @@ -249,7 +248,7 @@ type IntConversionsGenerated() = // -1 to signed nativeint stays -1 signedInts |> List.iter (fun source -> - prn "[]" + prn "[]" prn "member this.``Checked.%s.m1.To.nativeint`` () =" source.alias shift () prn "Assert.AreEqual (-1n, Checked.nativeint -1%s)" source.suffix @@ -258,7 +257,7 @@ type IntConversionsGenerated() = // unsigned MaxValues to signed nativeint stay same for narrower types, throw for wider types unsignedInts |> List.iter (fun source -> - prn "[]" + prn "[]" prn "member this.``Checked.%s.MaxValue.To.nativeint`` () =" source.alias shift () prn "if sizeof > sizeof<%s> then" source.alias @@ -272,7 +271,7 @@ type IntConversionsGenerated() = // -1 to unsigned nativeint should throw signedInts |> List.iter (fun source -> - prn "[]" + prn "[]" prn "member this.``Checked.%s.m1.To.unativeint`` () =" source.alias shift () prn "CheckThrowsExn (fun () -> Checked.unativeint -1%s |> ignore)" source.suffix @@ -281,7 +280,7 @@ type IntConversionsGenerated() = // unsigned MaxValues to unsigned nativeint stay same for narrower types, throw for wider types unsignedInts |> List.iter (fun source -> - prn "[]" + prn "[]" prn "member this.``Checked.%s.MaxValue.To.unativeint`` () =" source.alias shift () prn "if sizeof >= sizeof<%s> then" source.alias diff --git a/tests/FSharp.Test.Utilities/Compiler.fs b/tests/FSharp.Test.Utilities/Compiler.fs index 19c3793d64e..f535bc21c5a 100644 --- a/tests/FSharp.Test.Utilities/Compiler.fs +++ b/tests/FSharp.Test.Utilities/Compiler.fs @@ -12,7 +12,7 @@ open FSharp.Test.Utilities open FSharp.Test.ScriptHelpers open Microsoft.CodeAnalysis open Microsoft.CodeAnalysis.CSharp -open NUnit.Framework +open Xunit open System open System.Collections.Immutable open System.IO @@ -1129,7 +1129,7 @@ Actual: fOnFail() updateBaseLineIfEnvironmentSaysSo baseline createBaselineErrors baseline actual - Assert.AreEqual(expected, actual, convenienceBaselineInstructions baseline expected actual) + Assert.True((expected = actual), convenienceBaselineInstructions baseline expected actual) elif FileSystem.FileExistsShim baseline.FilePath then FileSystem.FileDeleteShim baseline.FilePath @@ -1162,7 +1162,7 @@ Actual: createBaselineErrors bsl.FSBaseline errorsActual updateBaseLineIfEnvironmentSaysSo bsl.FSBaseline let errorMsg = (convenienceBaselineInstructions bsl.FSBaseline errorsExpectedBaseLine errorsActual) - Assert.AreEqual(errorsExpectedBaseLine, errorsActual, errorMsg) + Assert.True((errorsExpectedBaseLine = errorsActual), errorMsg) elif FileSystem.FileExistsShim(bsl.FSBaseline.FilePath) then FileSystem.FileDeleteShim(bsl.FSBaseline.FilePath) @@ -1494,7 +1494,7 @@ Actual: let inline checkEqual k a b = if a <> b then - Assert.AreEqual(a, b, $"%s{what}: Mismatch in %s{k}, expected '%A{a}', got '%A{b}'.\nAll errors:\n%s{sourceErrorsAsStr}\nExpected errors:\n%s{expectedErrorsAsStr}") + failwith $"%s{what}: Mismatch in %s{k}, expected '%A{a}', got '%A{b}'.\nAll errors:\n%s{sourceErrorsAsStr}\nExpected errors:\n%s{expectedErrorsAsStr}" // For lists longer than 100 errors: expectedErrors |> List.iter System.Diagnostics.Debug.WriteLine @@ -1504,8 +1504,7 @@ Actual: (sourceErrors, expectedErrors) ||> List.iter2 (fun actual expected -> - - Assert.AreEqual(expected, actual, $"Mismatched error message:\nExpecting: {expected}\nActual: {actual}\n")) + Assert.Equal(expected, actual)) let adjust (adjust: int) (result: CompilationResult) : CompilationResult = match result with @@ -1624,7 +1623,7 @@ Actual: match Assert.shouldBeSameMultilineStringSets expectedContent actualErrors with | None -> () - | Some diff -> Assert.That(diff, Is.Empty, path) + | Some diff -> Assert.True(String.IsNullOrEmpty(diff), path) result @@ -1707,7 +1706,7 @@ Actual: | None -> failwith "Execution output is missing, cannot check exit code." | Some o -> match o with - | ExecutionOutput e -> Assert.AreEqual(e.ExitCode, expectedExitCode, sprintf "Exit code was expected to be: %A, but got %A." expectedExitCode e.ExitCode) + | ExecutionOutput e -> Assert.Equal(expectedExitCode, e.ExitCode) | _ -> failwith "Cannot check exit code on this run result." result @@ -1744,7 +1743,7 @@ Actual: let private assertEvalOutput (selector: FsiValue -> 'T) (value: 'T) (result: CompilationResult) : CompilationResult = match result.RunOutput with | None -> failwith "Execution output is missing cannot check value." - | Some (EvalOutput (Ok (Some e))) -> Assert.AreEqual(value, (selector e)) + | Some (EvalOutput (Ok (Some e))) -> Assert.Equal<'T>(value, (selector e)) | Some (EvalOutput (Ok None )) -> failwith "Cannot assert value of evaluation, since it is None." | Some (EvalOutput (Result.Error ex)) -> raise ex | Some _ -> failwith "Only 'eval' output is supported." diff --git a/tests/FSharp.Test.Utilities/CompilerAssert.fs b/tests/FSharp.Test.Utilities/CompilerAssert.fs index 0713d5fa8d2..fc2875d8955 100644 --- a/tests/FSharp.Test.Utilities/CompilerAssert.fs +++ b/tests/FSharp.Test.Utilities/CompilerAssert.fs @@ -21,7 +21,7 @@ open System.Runtime.Loader open FSharp.Test.Utilities open Microsoft.CodeAnalysis open Microsoft.CodeAnalysis.CSharp -open NUnit.Framework +open Xunit open TestFramework open System.Collections.Immutable @@ -149,12 +149,12 @@ type TestCompilation = let diagnostics = c.GetDiagnostics () if not diagnostics.IsEmpty then - NUnit.Framework.Assert.Fail ("CSharp source diagnostics:\n" + (diagnostics |> Seq.map (fun x -> x.GetMessage () + "\n") |> Seq.reduce (+))) + Assert.Fail ("CSharp source diagnostics:\n" + (diagnostics |> Seq.map (fun x -> x.GetMessage () + "\n") |> Seq.reduce (+))) | TestCompilation.IL (_, result) -> let errors, _ = result.Value if errors.Length > 0 then - NUnit.Framework.Assert.Fail ("IL source errors: " + errors) + Assert.Fail ("IL source errors: " + errors) member this.EmitAsFile (outputPath: string) = match this with @@ -484,7 +484,7 @@ module rec CompilerAssertHelpers = let checkEqual k a b = if a <> b then - Assert.AreEqual(a, b, sprintf $"Mismatch in %s{k}, expected '%A{a}', got '%A{b}'.\nAll errors:\n%s{errorsAsStr}") + failwithf $"Mismatch in %s{k}, expected '%A{a}', got '%A{b}'.\nAll errors:\n%s{errorsAsStr}" checkEqual "Errors" (Array.length expectedErrors) errors.Length @@ -771,18 +771,18 @@ Updated automatically, please check diffs in your pull request, changes must be exn |> Option.iter raise) static member ExecutionHasOutput(cmpl: Compilation, expectedOutput: string) = - CompilerAssert.Execute(cmpl, newProcess = true, onOutput = (fun output -> Assert.AreEqual(expectedOutput, output, sprintf "'%s' = '%s'" expectedOutput output))) + CompilerAssert.Execute(cmpl, newProcess = true, onOutput = (fun output -> Assert.Equal(expectedOutput, output))) static member Pass (source: string) = let parseResults, fileAnswer = checker.ParseAndCheckFileInProject("test.fs", 0, SourceText.ofString source, defaultProjectOptions TargetFramework.Current) |> Async.RunImmediate - Assert.IsEmpty(parseResults.Diagnostics, sprintf "Parse errors: %A" parseResults.Diagnostics) + Assert.Empty(parseResults.Diagnostics) match fileAnswer with | FSharpCheckFileAnswer.Aborted -> Assert.Fail("Type Checker Aborted") | FSharpCheckFileAnswer.Succeeded(typeCheckResults) -> - Assert.IsEmpty(typeCheckResults.Diagnostics, sprintf "Type Check errors: %A" typeCheckResults.Diagnostics) + Assert.Empty(typeCheckResults.Diagnostics) static member PassWithOptions options (source: string) = let defaultOptions = defaultProjectOptions TargetFramework.Current @@ -790,13 +790,13 @@ Updated automatically, please check diffs in your pull request, changes must be let parseResults, fileAnswer = checker.ParseAndCheckFileInProject("test.fs", 0, SourceText.ofString source, options) |> Async.RunImmediate - Assert.IsEmpty(parseResults.Diagnostics, sprintf "Parse errors: %A" parseResults.Diagnostics) + Assert.Empty(parseResults.Diagnostics) match fileAnswer with | FSharpCheckFileAnswer.Aborted -> Assert.Fail("Type Checker Aborted") | FSharpCheckFileAnswer.Succeeded(typeCheckResults) -> - Assert.IsEmpty(typeCheckResults.Diagnostics, sprintf "Type Check errors: %A" typeCheckResults.Diagnostics) + Assert.Empty(typeCheckResults.Diagnostics) static member TypeCheckWithErrorsAndOptionsAgainstBaseLine options (sourceDirectory:string) (sourceFile: string) = let absoluteSourceFile = System.IO.Path.Combine(sourceDirectory, sourceFile) @@ -809,7 +809,7 @@ Updated automatically, please check diffs in your pull request, changes must be { defaultOptions with OtherOptions = Array.append options defaultOptions.OtherOptions; SourceFiles = [|sourceFile|] }) |> Async.RunImmediate - Assert.IsEmpty(parseResults.Diagnostics, sprintf "Parse errors: %A" parseResults.Diagnostics) + Assert.Empty(parseResults.Diagnostics) match fileAnswer with | FSharpCheckFileAnswer.Aborted -> Assert.Fail("Type Checker Aborted") @@ -827,7 +827,7 @@ Updated automatically, please check diffs in your pull request, changes must be |> String.concat "\n" File.WriteAllText(Path.ChangeExtension(absoluteSourceFile,"err"), errorsActual) - Assert.AreEqual(errorsExpectedBaseLine.Replace("\r\n","\n"), errorsActual.Replace("\r\n","\n")) + Assert.Equal(errorsExpectedBaseLine.Replace("\r\n","\n"), errorsActual.Replace("\r\n","\n")) static member TypeCheckWithOptionsAndName options name (source: string) = let errors = @@ -895,7 +895,7 @@ Updated automatically, please check diffs in your pull request, changes must be static member TypeCheck(options, name, source: string) = let parseResults, checkResults = CompilerAssert.ParseAndTypeCheck(options, name, source) - Assert.IsEmpty(parseResults.Diagnostics, sprintf "Parse errors: %A" parseResults.Diagnostics) + Assert.Empty(parseResults.Diagnostics) checkResults @@ -1044,7 +1044,7 @@ Updated automatically, please check diffs in your pull request, changes must be else (expectedErrorMessages, errorMessages) ||> Seq.iter2 (fun expectedErrorMessage errorMessage -> - Assert.AreEqual(expectedErrorMessage, errorMessage) + Assert.Equal(expectedErrorMessage, errorMessage) ) static member RunScript source expectedErrorMessages = @@ -1069,13 +1069,13 @@ Updated automatically, please check diffs in your pull request, changes must be |> Array.distinctBy (fun e -> e.Severity, e.ErrorNumber, e.StartLine, e.StartColumn, e.EndLine, e.EndColumn, e.Message) printfn $"diagnostics: %A{[| for e in errors -> e.Severity, e.ErrorNumber, e.StartLine, e.StartColumn, e.EndLine, e.EndColumn, e.Message |]}" - Assert.AreEqual(Array.length expectedParseErrors, errors.Length, sprintf "Parse errors: %A" parseResults.Diagnostics) + Assert.True((Array.length expectedParseErrors = errors.Length), sprintf "Parse errors: %A" parseResults.Diagnostics) Array.zip errors expectedParseErrors |> Array.iter (fun (info, expectedError) -> let (expectedSeverity: FSharpDiagnosticSeverity, expectedErrorNumber: int, expectedErrorRange: int * int * int * int, expectedErrorMsg: string) = expectedError - Assert.AreEqual(expectedSeverity, info.Severity) - Assert.AreEqual(expectedErrorNumber, info.ErrorNumber, "expectedErrorNumber") - Assert.AreEqual(expectedErrorRange, (info.StartLine, info.StartColumn + 1, info.EndLine, info.EndColumn + 1), "expectedErrorRange") - Assert.AreEqual(expectedErrorMsg, info.Message, "expectedErrorMsg") + Assert.Equal(expectedSeverity, info.Severity) + Assert.Equal(expectedErrorNumber, info.ErrorNumber) + Assert.Equal(expectedErrorRange, (info.StartLine, info.StartColumn + 1, info.EndLine, info.EndColumn + 1)) + Assert.Equal(expectedErrorMsg, info.Message) ) diff --git a/tests/FSharp.Test.Utilities/FSharp.Test.Utilities.fsproj b/tests/FSharp.Test.Utilities/FSharp.Test.Utilities.fsproj index 3700eda8514..7ccc5306751 100644 --- a/tests/FSharp.Test.Utilities/FSharp.Test.Utilities.fsproj +++ b/tests/FSharp.Test.Utilities/FSharp.Test.Utilities.fsproj @@ -62,7 +62,6 @@ - diff --git a/tests/FSharp.Test.Utilities/ILChecker.fs b/tests/FSharp.Test.Utilities/ILChecker.fs index 15579833bcd..4474ef01c10 100644 --- a/tests/FSharp.Test.Utilities/ILChecker.fs +++ b/tests/FSharp.Test.Utilities/ILChecker.fs @@ -6,7 +6,7 @@ open System open System.IO open System.Text.RegularExpressions -open NUnit.Framework +open Xunit open TestFramework [] diff --git a/tests/README.md b/tests/README.md index 8f36be0195a..40c9a35b177 100644 --- a/tests/README.md +++ b/tests/README.md @@ -19,7 +19,7 @@ ## Framework for testing -The following test frameworks and libraries will be used for new test projects **[xUnit Test Framework](https://xunit.net/), [FluentAssertions](https://fluentassertions.com/) (+ [FsUnit](https://fsprojects.github.io/FsUnit/) and [FsCheck](https://github.com/fscheck/FsCheck) when needed)**. All existing NUnit test suites will be migrated to xUnit. +The following test frameworks and libraries will be used for new test projects **[xUnit Test Framework](https://xunit.net/), [FluentAssertions](https://fluentassertions.com/) (+ [FsUnit](https://fsprojects.github.io/FsUnit/) and [FsCheck](https://github.com/fscheck/FsCheck) when needed)**. **Justification:** @@ -93,7 +93,6 @@ Existing FSharpQA and Cambridge need to be migrated to corresponding test projec ## Next steps -* [**In Progress**] Migrate existing `NUnit` tests to xUnit. * Clean up CompilerAssert. * Make PEVerify tests work in netcore/non-windows environment. * Start migration of existing (namely, FSharpQA and Cambridge) suites to xUnit-based projects. diff --git a/tests/fsharp/Libraries/Async/AsyncTests.fs b/tests/fsharp/Compiler/Libraries/Core/Async/AsyncTests.fs similarity index 88% rename from tests/fsharp/Libraries/Async/AsyncTests.fs rename to tests/fsharp/Compiler/Libraries/Core/Async/AsyncTests.fs index 04a82a97160..708e7e58e2e 100644 --- a/tests/fsharp/Libraries/Async/AsyncTests.fs +++ b/tests/fsharp/Compiler/Libraries/Core/Async/AsyncTests.fs @@ -1,14 +1,14 @@ -namespace FSharp.Libraries.UnitTests +// Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information. -open System -open NUnit.Framework -open FSharp.Compiler.UnitTests +namespace FSharp.Compiler.UnitTests + +open Xunit +open FSharp.Test -[] module AsyncTests = // Regression for FSHARP1.0:5969 // Async.StartChild: error when wait async is executed more than once - [] + [] let ``Execute Async multiple times``() = CompilerAssert.CompileExeAndRun """ @@ -30,7 +30,7 @@ exit 0 // Regression for FSHARP1.0:5970 // Async.StartChild: race in implementation of ResultCell in FSharp.Core - [] + [] let ``Joining StartChild``() = CompilerAssert.CompileExeAndRun """ @@ -59,7 +59,7 @@ exit 0 """ // Regression test for FSHARP1.0:6086 - [] + [] let ``Mailbox Async dot not StackOverflow``() = CompilerAssert.CompileExeAndRun """ @@ -132,7 +132,8 @@ exit 0 """ // Regression for FSHARP1.0:5971 - [] + + [] let ``StartChild do not throw ObjectDisposedException``() = CompilerAssert.CompileExeAndRun """ @@ -144,8 +145,7 @@ printfn "%A" (b |> Async.RunSynchronously |> Async.RunSynchronously) exit 0 """ - - [] + [] let ``StartChild test Trampoline HijackLimit``() = CompilerAssert.CompileExeAndRun """ diff --git a/tests/fsharp/FSharpSuite.Tests.fsproj b/tests/fsharp/FSharpSuite.Tests.fsproj index 5bd5feda50a..36f26235ac1 100644 --- a/tests/fsharp/FSharpSuite.Tests.fsproj +++ b/tests/fsharp/FSharpSuite.Tests.fsproj @@ -76,6 +76,7 @@ + diff --git a/tests/fsharp/TypeProviderTests.fs b/tests/fsharp/TypeProviderTests.fs index 04b82f1c818..ba3d43037e6 100644 --- a/tests/fsharp/TypeProviderTests.fs +++ b/tests/fsharp/TypeProviderTests.fs @@ -2,7 +2,7 @@ #if INTERACTIVE //#r @"../../release/net40/bin/FSharp.Compiler.dll" -#r @"../../packages/NUnit.3.5.0/lib/net45/nunit.framework.dll" +#r @"../../packages/xunit.assert/2.9.0/lib/net6.0/xunit.assert.dll" #load "../../src/scripts/scriptlib.fsx" #load "../FSharp.Test.Utilities/TestFramework.fs" #load "single-test.fs" diff --git a/tests/fsharp/nunitConf.fs b/tests/fsharp/nunitConf.fs deleted file mode 100644 index 1397b3ed778..00000000000 --- a/tests/fsharp/nunitConf.fs +++ /dev/null @@ -1,240 +0,0 @@ -module NUnitConf - -open System -open System.IO -open NUnit.Framework - -open TestConfig -open PlatformHelpers -open FSharpTestSuiteTypes - -let checkResult result = - match result with - | CmdResult.ErrorLevel (msg1, err) -> Assert.Fail (sprintf "%s. ERRORLEVEL %d" msg1 err) - | CmdResult.Success -> () - -let checkErrorLevel1 result = - match result with - | CmdResult.ErrorLevel (_,1) -> () - | CmdResult.Success | CmdResult.ErrorLevel _ -> Assert.Fail (sprintf "Command passed unexpectedly") - -let envVars () = - System.Environment.GetEnvironmentVariables () - |> Seq.cast - |> Seq.map (fun d -> d.Key :?> string, d.Value :?> string) - |> Map.ofSeq - -let initializeSuite () = - -#if DEBUG - let configurationName = "debug" -#else - let configurationName = "release" -#endif - let env = envVars () - - let cfg = - let c = config configurationName env - let usedEnvVars = c.EnvironmentVariables |> Map.add "FSC" c.FSC - { c with EnvironmentVariables = usedEnvVars } - - logConfig cfg - - cfg - - -let suiteHelpers = lazy (initializeSuite ()) - -[] -type public InitializeSuiteAttribute () = - inherit TestActionAttribute() - - override x.BeforeTest details = - if details.IsSuite - then suiteHelpers.Force() |> ignore - - override x.AfterTest _details = - () - - override x.Targets = ActionTargets.Test ||| ActionTargets.Suite - - -[] -[] -() - -let fsharpSuiteDirectory = __SOURCE_DIRECTORY__ - -let testConfig testDir = - let cfg = suiteHelpers.Value - let dir = Path.GetFullPath(fsharpSuiteDirectory/testDir) - log "------------------ %s ---------------" dir - log "cd %s" dir - { cfg with Directory = dir} - -[] -type FileGuard(path: string) = - let remove path = if File.Exists(path) then Commands.rm (Path.GetTempPath()) path - do if not (Path.IsPathRooted(path)) then failwithf "path '%s' must be absolute" path - do remove path - member x.Path = path - member x.Exists = x.Path |> File.Exists - member x.CheckExists() = - if not x.Exists then - failwith (sprintf "exit code 0 but %s file doesn't exists" (x.Path |> Path.GetFileName)) - - interface IDisposable with - member x.Dispose () = remove path - - -type RedirectToType = - | Overwrite of FilePath - | Append of FilePath - -type RedirectTo = - | Inherit - | Output of RedirectToType - | OutputAndError of RedirectToType * RedirectToType - | OutputAndErrorToSameFile of RedirectToType - | Error of RedirectToType - -type RedirectFrom = - | RedirectInput of FilePath - -type RedirectInfo = - { Output : RedirectTo - Input : RedirectFrom option } - - -module Command = - - let logExec _dir path args redirect = - let inF = - function - | None -> "" - | Some(RedirectInput l) -> sprintf " <%s" l - let redirectType = function Overwrite x -> sprintf ">%s" x | Append x -> sprintf ">>%s" x - let outF = - function - | Inherit -> "" - | Output r-> sprintf " 1%s" (redirectType r) - | OutputAndError (r1, r2) -> sprintf " 1%s 2%s" (redirectType r1) (redirectType r2) - | OutputAndErrorToSameFile r -> sprintf " 1%s 2>1" (redirectType r) - | Error r -> sprintf " 2%s" (redirectType r) - sprintf "%s%s%s%s" path (match args with "" -> "" | x -> " " + x) (inF redirect.Input) (outF redirect.Output) - - let exec dir envVars redirect path args = - let { Output = o; Input = i} = redirect - - let inputWriter sources (writer: StreamWriter) = - let pipeFile name = async { - let path = Commands.getfullpath dir name - use reader = File.OpenRead (path) - use ms = new MemoryStream() - do! reader.CopyToAsync (ms) |> (Async.AwaitIAsyncResult >> Async.Ignore) - ms.Position <- 0L - try - do! ms.CopyToAsync(writer.BaseStream) |> (Async.AwaitIAsyncResult >> Async.Ignore) - do! writer.FlushAsync() |> (Async.AwaitIAsyncResult >> Async.Ignore) - with - | :? System.IO.IOException -> //input closed is ok if process is closed - () - } - sources |> pipeFile |> Async.RunSynchronously - - let inF fCont cmdArgs = - match i with - | None -> fCont cmdArgs - | Some(RedirectInput l) -> fCont { cmdArgs with RedirectInput = Some (inputWriter l) } - - let openWrite rt = - let fullpath = Commands.getfullpath dir - match rt with - | Append p -> File.AppendText( p |> fullpath) - | Overwrite p -> new StreamWriter(new FileStream(p |> fullpath, FileMode.Create)) - - let outF fCont cmdArgs = - match o with - | RedirectTo.Inherit -> - use toLog = redirectToLog () - fCont { cmdArgs with RedirectOutput = Some (toLog.Post); RedirectError = Some (toLog.Post) } - | Output r -> - use writer = openWrite r - use outFile = redirectTo writer - use toLog = redirectToLog () - fCont { cmdArgs with RedirectOutput = Some (outFile.Post); RedirectError = Some (toLog.Post) } - | OutputAndError (r1,r2) -> - use writer1 = openWrite r1 - use writer2 = openWrite r2 - use outFile1 = redirectTo writer1 - use outFile2 = redirectTo writer2 - fCont { cmdArgs with RedirectOutput = Some (outFile1.Post); RedirectError = Some (outFile2.Post) } - | OutputAndErrorToSameFile r -> - use writer = openWrite r - use outFile = redirectTo writer - fCont { cmdArgs with RedirectOutput = Some (outFile.Post); RedirectError = Some (outFile.Post) } - | Error r -> - use writer = openWrite r - use outFile = redirectTo writer - use toLog = redirectToLog () - fCont { cmdArgs with RedirectOutput = Some (toLog.Post); RedirectError = Some (outFile.Post) } - - let exec cmdArgs = - log "%s" (logExec dir path args redirect) - Process.exec cmdArgs dir envVars path args - - { RedirectOutput = None; RedirectError = None; RedirectInput = None } - |> (outF (inF exec)) - -let alwaysSuccess _ = () - -let execArgs = { Output = Inherit; Input = None; } -let execAppend cfg stdoutPath stderrPath p = Command.exec cfg.Directory cfg.EnvironmentVariables { execArgs with Output = OutputAndError(Append(stdoutPath), Append(stderrPath)) } p >> checkResult -let execAppendIgnoreExitCode cfg stdoutPath stderrPath p = Command.exec cfg.Directory cfg.EnvironmentVariables { execArgs with Output = OutputAndError(Append(stdoutPath), Append(stderrPath)) } p >> alwaysSuccess -let exec cfg p = Command.exec cfg.Directory cfg.EnvironmentVariables execArgs p >> checkResult -let execExpectFail cfg p = Command.exec cfg.Directory cfg.EnvironmentVariables execArgs p >> checkErrorLevel1 -let execIn cfg workDir p = Command.exec workDir cfg.EnvironmentVariables execArgs p >> checkResult -let execBothToOut cfg workDir outFile p = Command.exec workDir cfg.EnvironmentVariables { execArgs with Output = OutputAndErrorToSameFile(Overwrite(outFile)) } p >> checkResult -let execAppendOutIgnoreExitCode cfg workDir outFile p = Command.exec workDir cfg.EnvironmentVariables { execArgs with Output = Output(Append(outFile)) } p >> alwaysSuccess -let execAppendErrExpectFail cfg errPath p = Command.exec cfg.Directory cfg.EnvironmentVariables { execArgs with Output = Error(Overwrite(errPath)) } p -let execStdin cfg l p = Command.exec cfg.Directory cfg.EnvironmentVariables { Output = Inherit; Input = Some(RedirectInput(l)) } p >> checkResult -let execStdinAppendBothIgnoreExitCode cfg stdoutPath stderrPath stdinPath p = Command.exec cfg.Directory cfg.EnvironmentVariables { Output = OutputAndError(Append(stdoutPath), Append(stderrPath)); Input = Some(RedirectInput(stdinPath)) } p >> alwaysSuccess - -let fsc cfg arg = Printf.ksprintf (Commands.fsc cfg.Directory (exec cfg) cfg.FSC) arg -let fscIn cfg workDir arg = Printf.ksprintf (Commands.fsc workDir (execIn cfg workDir) cfg.FSC) arg -let fscAppend cfg stdoutPath stderrPath arg = Printf.ksprintf (Commands.fsc cfg.Directory (execAppend cfg stdoutPath stderrPath) cfg.FSC) arg -let fscAppendIgnoreExitCode cfg stdoutPath stderrPath arg = Printf.ksprintf (Commands.fsc cfg.Directory (execAppendIgnoreExitCode cfg stdoutPath stderrPath) cfg.FSC) arg -let fscBothToOut cfg out arg = Printf.ksprintf (Commands.fsc cfg.Directory (execBothToOut cfg cfg.Directory out) cfg.FSC) arg - -let fscAppendErrExpectFail cfg errPath arg = Printf.ksprintf (fun flags sources -> Commands.fsc cfg.Directory (execAppendErrExpectFail cfg errPath) cfg.FSC flags sources |> checkErrorLevel1) arg - -let csc cfg arg = Printf.ksprintf (Commands.csc (exec cfg) cfg.CSC) arg -let ildasm cfg arg = Printf.ksprintf (Commands.ildasm (exec cfg) cfg.ILDASM) arg -let peverify cfg = Commands.peverify (exec cfg) cfg.PEVERIFY "/nologo" -let sn cfg outfile arg = execAppendOutIgnoreExitCode cfg cfg.Directory outfile cfg.SN arg -let peverifyWithArgs cfg args = Commands.peverify (exec cfg) cfg.PEVERIFY args -let fsi cfg = Printf.ksprintf (Commands.fsi (exec cfg) cfg.FSI) -let fsiExpectFail cfg = Printf.ksprintf (Commands.fsi (execExpectFail cfg) cfg.FSI) -let fsiAppendIgnoreExitCode cfg stdoutPath stderrPath = Printf.ksprintf (Commands.fsi (execAppendIgnoreExitCode cfg stdoutPath stderrPath) cfg.FSI) -let fileguard cfg = (Commands.getfullpath cfg.Directory) >> (fun x -> new FileGuard(x)) -let getfullpath cfg = Commands.getfullpath cfg.Directory -let fileExists cfg = Commands.fileExists cfg.Directory >> Option.isSome -let fsiStdin cfg stdinPath = Printf.ksprintf (Commands.fsi (execStdin cfg stdinPath) cfg.FSI) -let fsiStdinAppendBothIgnoreExitCode cfg stdoutPath stderrPath stdinPath = Printf.ksprintf (Commands.fsi (execStdinAppendBothIgnoreExitCode cfg stdoutPath stderrPath stdinPath) cfg.FSI) -let rm cfg x = Commands.rm cfg.Directory x -let mkdir cfg = Commands.mkdir_p cfg.Directory -let copy_y cfg f = Commands.copy_y cfg.Directory f >> checkResult - -let fsdiff cfg a b = - let out = new ResizeArray() - let redirectOutputToFile path args = - log "%s %s" path args - use toLog = redirectToLog () - Process.exec { RedirectOutput = Some (function null -> () | s -> out.Add(s)); RedirectError = Some toLog.Post; RedirectInput = None; } cfg.Directory cfg.EnvironmentVariables path args - do (Commands.fsdiff redirectOutputToFile cfg.FSDIFF a b) |> (fun _ -> ()) - out.ToArray() |> List.ofArray - -let requireENCulture () = - match System.Globalization.CultureInfo.CurrentCulture.TwoLetterISOLanguageName with - | "en" -> true - | _ -> false diff --git a/tests/service/FsUnit.fs b/tests/service/FsUnit.fs index e5b0962449c..729ecbc9144 100644 --- a/tests/service/FsUnit.fs +++ b/tests/service/FsUnit.fs @@ -1,23 +1,23 @@ module FsUnit open System.Diagnostics -open NUnit.Framework -open NUnit.Framework.Constraints +open Xunit [] -let should (f : 'a -> #Constraint) x (y : obj) = - let c = f x +let should (f: 'a -> objnull -> unit) x (y: obj) = let y = match y with - | :? (unit -> unit) -> box (TestDelegate(y :?> unit -> unit)) + | :? (unit -> unit) -> box (fun () -> (y :?> unit -> unit)) | _ -> y - Assert.That(y, c) + f x y -let equal x = EqualConstraint(x) +/// Note, xunit does check types by default. +/// These are artifacts of nunit and not necessary now, just used in many places. +let equal (expected: 'a) (actual: 'a) = + Assert.Equal<'a>(expected, actual) -/// like "should equal", but validates same-type let shouldEqual (x: 'a) (y: 'a) = - Assert.AreEqual(x, y, sprintf "Expected: %A\nActual: %A" x y) + Assert.Equal<'a>(x, y) /// Same as 'shouldEqual' but goes pairwise over the collections. Lengths must be equal. let shouldPairwiseEqual (x: seq<_>) (y: seq<_>) = @@ -35,32 +35,4 @@ let shouldPairwiseEqual (x: seq<_>) (y: seq<_>) = while ex.MoveNext() do countx <- countx + 1 while ey.MoveNext() do county <- county + 1 if countx <> county then - Assert.Fail("Collections are of unequal lengths, expected length {0}, actual length is {1}.", countx, county) - -let notEqual x = NotConstraint(EqualConstraint(x)) - -let contain x = ContainsConstraint(x) - -let haveLength n = Has.Length.EqualTo(n) - -let haveCount n = Has.Count.EqualTo(n) - -let endWith (s:string) = EndsWithConstraint(s) - -let startWith (s:string) = StartsWithConstraint(s) - -let be = id - -let Null = NullConstraint() - -let Empty = EmptyConstraint() - -let EmptyString = EmptyStringConstraint() - -let True = TrueConstraint() - -let False = FalseConstraint() - -let sameAs x = SameAsConstraint(x) - -let throw = Throws.TypeOf \ No newline at end of file + Assert.Fail($"Collections are of unequal lengths, expected length {countx}, actual length is {county}.") diff --git a/vsintegration/tests/Salsa/SalsaUtils.fs b/vsintegration/tests/Salsa/SalsaUtils.fs index 1e6caca05d9..4b00dcc6b89 100644 --- a/vsintegration/tests/Salsa/SalsaUtils.fs +++ b/vsintegration/tests/Salsa/SalsaUtils.fs @@ -9,7 +9,7 @@ open Microsoft.VisualStudio.FSharp.LanguageService open Microsoft.VisualStudio.TextManager.Interop open FSharp.Compiler.CodeAnalysis open FSharp.Compiler.EditorServices -open NUnit.Framework +open Xunit open Salsa.Salsa @@ -208,7 +208,7 @@ module internal VsOpsUtils = let AssertCompListIsEmpty (completions : CompletionItem[]) = if not (Array.isEmpty completions) then printfn "Expected empty completion list but got: %A" (completions |> Array.map (fun (CompletionItem(nm, _, _, _, _)) -> nm)) - Assert.IsTrue(Array.isEmpty completions, "Expected empty completion list but got some items") + Assert.True(Array.isEmpty completions, "Expected empty completion list but got some items") /// Verify that the given completion list contains a member with the given name let AssertCompListContains(completions : CompletionItem[], membername) = @@ -263,7 +263,7 @@ module internal VsOpsUtils = // Check that the marker is unique, otherwise we can't determine where to put the '.' let markerLines = orgFileContents |> Seq.filter (fun line -> line.Contains(marker)) |> Seq.length if markerLines = 0 then Assert.Fail("Unable to find marker in source code.") - if markerLines > 1 then Assert.Fail <| sprintf "Found marker [%s] multiple times in source file." marker + if markerLines > 1 then Assert.Fail(sprintf "Found marker [%s] multiple times in source file." marker) // Replace marker with "." let replaceMarker = @@ -310,11 +310,11 @@ module internal VsOpsUtils = -> match GetIdentifierAtCursor file with | None -> Assert.Fail ("No identifier at cursor. This indicates a bug in GotoDefinition.") | Some (id, _) -> // Are we on the identifier we expect? - Assert.AreEqual (toFind, id) + Assert.Equal (toFind, id) // Do the lines of code match what we expect? // - Eliminate white space to eliminate trivial errors // - +1 to adjust for 1-index line numbers - Assert.AreEqual ( + Assert.Equal ( expLine.Trim(), (span.iStartLine |> (+) 1 |> GetLineNumber (OpenFileViaOpenFile(file.VS, actFile))).Trim () ) @@ -327,8 +327,8 @@ module internal VsOpsUtils = // Error cases | (Some (x,_), None) - -> Assert.Fail <| sprintf "Expected to find the definition of '%s' but GotoDefn failed." x + -> Assert.Fail(sprintf "Expected to find the definition of '%s' but GotoDefn failed." x) | (None, Some (_,file)) - -> Assert.Fail <| sprintf "Expected GotoDefn to fail, but it went to a definition in file %s" file + -> Assert.Fail(sprintf "Expected GotoDefn to fail, but it went to a definition in file %s" file) diff --git a/vsintegration/tests/Salsa/VisualFSharp.Salsa.fsproj b/vsintegration/tests/Salsa/VisualFSharp.Salsa.fsproj index 6b060d58780..353e08336a6 100644 --- a/vsintegration/tests/Salsa/VisualFSharp.Salsa.fsproj +++ b/vsintegration/tests/Salsa/VisualFSharp.Salsa.fsproj @@ -66,7 +66,7 @@ - + diff --git a/vsintegration/tests/Salsa/salsa.fs b/vsintegration/tests/Salsa/salsa.fs index ea12fea391f..6ac626f9fcb 100644 --- a/vsintegration/tests/Salsa/salsa.fs +++ b/vsintegration/tests/Salsa/salsa.fs @@ -1476,7 +1476,7 @@ module internal Salsa = vs.LanguageService <- ls vs :> VisualStudio with e -> - // Need to just print the error because NUnit has not fully initialized the exception at this point. + // Need to just print the error because the framework has not fully initialized the exception at this point. printf "Error in createSimple: %A" e reraise() diff --git a/vsintegration/tests/UnitTests/TestLib.Utils.fs b/vsintegration/tests/UnitTests/TestLib.Utils.fs index 8072604ca2b..49a5bfdf08a 100644 --- a/vsintegration/tests/UnitTests/TestLib.Utils.fs +++ b/vsintegration/tests/UnitTests/TestLib.Utils.fs @@ -4,7 +4,7 @@ namespace UnitTests.TestLib.Utils open System open System.IO -open NUnit.Framework +open Xunit open Microsoft.VisualStudio module Asserts =