Skip to content

Commit 7e9fd41

Browse files
authored
Tests: remove dependency on CurrentDirectory ("test.ok" files) (#17815)
1 parent e754739 commit 7e9fd41

File tree

147 files changed

+448
-611
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

147 files changed

+448
-611
lines changed

FSharpTests.Directory.Build.targets

Lines changed: 29 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -7,33 +7,35 @@
77
Returns=""
88
DependsOnTargets="$(CoreCompileDependsOn)"
99
>
10-
<Fsi Condition=" '%(_CoreCompileResourceInputs.WithCulture)' != 'true' "
11-
CodePage="$(CodePage)"
12-
DefineConstants="$(DefineConstants)"
13-
DisabledWarnings="$(NoWarn)"
14-
DotnetFsiCompilerPath="$(DotnetFsiCompilerPath)"
15-
FsiExec="@(FsiExec)"
16-
LangVersion="$(LangVersion)"
17-
LCID="$(LCID)"
18-
LoadSources="@(LoadSource)"
19-
NoFramework="false"
20-
Optimize="$(Optimize)"
21-
OtherFlags="$(OtherFlags)"
22-
PreferredUILang="$(PreferredUILang)"
23-
ProvideCommandLineArgs="$(ProvideCommandLineArgs)"
24-
UseSources="@(UseSource)"
25-
SkipCompilerExecution="$(SkipCompilerExecution)"
26-
Sources="@(CompileBefore);@(Compile);@(CompileAfter)"
27-
Tailcalls="$(Tailcalls)"
28-
TargetProfile="$(TargetProfile)"
29-
ToolExe="$(FsiToolExe)"
30-
ToolPath="$(FsiToolPath)"
31-
TreatWarningsAsErrors="$(TreatWarningsAsErrors)"
32-
Utf8Output="$(Utf8Output)"
33-
WarningLevel="$(WarningLevel)"
34-
WarningsAsErrors="$(WarningsAsErrors)">
35-
<Output TaskParameter="CommandLineArgs" ItemName="FsiCommandLineArgs" />
36-
</Fsi>
10+
<Fsi Condition=" '%(_CoreCompileResourceInputs.WithCulture)' != 'true' "
11+
CodePage="$(CodePage)"
12+
DefineConstants="$(DefineConstants)"
13+
DisabledWarnings="$(NoWarn)"
14+
DotnetFsiCompilerPath="$(DotnetFsiCompilerPath)"
15+
FsiExec="@(FsiExec)"
16+
LangVersion="$(LangVersion)"
17+
LCID="$(LCID)"
18+
LoadSources="@(LoadSource)"
19+
NoFramework="false"
20+
Optimize="$(Optimize)"
21+
OtherFlags="$(OtherFlags)"
22+
PreferredUILang="$(PreferredUILang)"
23+
ProvideCommandLineArgs="$(ProvideCommandLineArgs)"
24+
UseSources="@(UseSource)"
25+
SkipCompilerExecution="$(SkipCompilerExecution)"
26+
Sources="@(CompileBefore);@(Compile);@(CompileAfter)"
27+
Tailcalls="$(Tailcalls)"
28+
TargetProfile="$(TargetProfile)"
29+
ToolExe="$(FsiToolExe)"
30+
ToolPath="$(FsiToolPath)"
31+
TreatWarningsAsErrors="$(TreatWarningsAsErrors)"
32+
Utf8Output="$(Utf8Output)"
33+
WarningLevel="$(WarningLevel)"
34+
WarningsAsErrors="$(WarningsAsErrors)"
35+
CaptureTextOutput="true" >
36+
<Output TaskParameter="CommandLineArgs" ItemName="FsiCommandLineArgs" />
37+
<Output TaskParameter="TextOutput" ItemName="FsiTextOutput" />
38+
</Fsi>
3739

3840
<ItemGroup>
3941
<_CoreCompileResourceInputs Remove="@(_CoreCompileResourceInputs)" />

src/FSharp.Build/Fsi.fs

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -161,6 +161,34 @@ type public Fsi() as this =
161161

162162
builder
163163

164+
let mutable bufferLimit = None
165+
166+
let textOutput =
167+
lazy System.Collections.Generic.Queue<_>(defaultArg bufferLimit 1024)
168+
169+
override this.LogEventsFromTextOutput(line, msgImportance) =
170+
if this.CaptureTextOutput then
171+
textOutput.Value.Enqueue line
172+
173+
match bufferLimit with
174+
| Some limit when textOutput.Value.Count > limit -> textOutput.Value.Dequeue() |> ignore
175+
| _ -> ()
176+
177+
base.LogEventsFromTextOutput(line, msgImportance)
178+
179+
member _.BufferLimit
180+
with get () = defaultArg bufferLimit 0
181+
and set limit = bufferLimit <- if limit = 0 then None else Some limit
182+
183+
member val CaptureTextOutput = false with get, set
184+
185+
[<Output>]
186+
member this.TextOutput =
187+
if this.CaptureTextOutput then
188+
textOutput.Value |> String.concat Environment.NewLine
189+
else
190+
String.Empty
191+
164192
// --codepage <int>: Specify the codepage to use when opening source files
165193
member _.CodePage
166194
with get () = codePage

tests/FSharp.Compiler.ComponentTests/Conformance/InferenceProcedures/ByrefSafetyAnalysis/MigratedTest02.fs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -57,4 +57,4 @@ module Tests =
5757
let test3 () =
5858
StaticTest.Test2 // is passing, but probably shouldn't be
5959

60-
printfn "Test Passed"
60+
printf "TEST PASSED OK"

tests/FSharp.Compiler.ComponentTests/Miscellaneous/FsharpSuiteMigrated.fs

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -31,16 +31,15 @@ module ScriptRunner =
3131
let cu = cu |> withDefines defaultDefines
3232
match cu with
3333
| FS fsSource ->
34-
File.Delete("test.ok")
3534
let engine = createEngine (fsSource.Options |> Array.ofList,version)
3635
let res = evalScriptFromDiskInSharedSession engine cu
3736
match res with
3837
| CompilationResult.Failure _ -> res
39-
| CompilationResult.Success s ->
40-
if File.Exists("test.ok") then
38+
| CompilationResult.Success s ->
39+
if engine.GetOutput().Contains "TEST PASSED OK" then
4140
res
4241
else
43-
failwith $"Results looked correct, but 'test.ok' file was not created. Result: %A{s}"
42+
failwith $"Results looked correct, but 'TEST PASSED OK' was not printed. Result: %A{s}"
4443

4544
| _ -> failwith $"Compilation unit other than fsharp is not supported, cannot process %A{cu}"
4645

tests/FSharp.Compiler.ComponentTests/Signatures/TestCasesForGenerationRoundTrip/access.fsx

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -278,7 +278,7 @@ let aa =
278278
match failures.Value with
279279
| [] ->
280280
stdout.WriteLine "Test Passed"
281-
System.IO.File.WriteAllText("test.ok","ok")
281+
printf "TEST PASSED OK" ;
282282
exit 0
283283
| _ ->
284284
stdout.WriteLine "Test Failed"

tests/FSharp.Compiler.ComponentTests/Signatures/TestCasesForGenerationRoundTrip/array.fsx

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1142,7 +1142,7 @@ let aa =
11421142
match failures with
11431143
| [] ->
11441144
stdout.WriteLine "Test Passed"
1145-
System.IO.File.WriteAllText("test.ok","ok")
1145+
printf "TEST PASSED OK" ;
11461146
exit 0
11471147
| _ ->
11481148
stdout.WriteLine "Test Failed"

tests/FSharp.Compiler.ComponentTests/Signatures/TestCasesForGenerationRoundTrip/libtest.fsx

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5651,7 +5651,7 @@ let aa =
56515651
match !failures with
56525652
| [] ->
56535653
stdout.WriteLine "Test Passed"
5654-
System.IO.File.WriteAllText("test.ok","ok")
5654+
printf "TEST PASSED OK" ;
56555655
exit 0
56565656
| _ ->
56575657
stdout.WriteLine "Test Failed"

tests/FSharp.Compiler.Private.Scripting.UnitTests/DependencyManagerInteractiveTests.fs

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -760,10 +760,9 @@ x |> Seq.iter(fun r ->
760760
if found = expected.Length then sawExpectedOutput.Set() |> ignore
761761

762762
let text = "#help"
763-
use output = new RedirectConsoleOutput()
764763
use script = new FSharpScript(quiet = false, langVersion = LangVersion.V47)
765764
let mutable found = 0
766-
output.OutputProduced.Add (fun line -> verifyOutput line)
765+
script.OutputProduced.Add (fun line -> verifyOutput line)
767766
let opt = script.Eval(text) |> getValue
768767
Assert.True(sawExpectedOutput.WaitOne(TimeSpan.FromSeconds(5.0)), sprintf "Expected to see error sentinel value written\nexpected:%A\nactual:%A" expected lines)
769768

@@ -811,10 +810,9 @@ x |> Seq.iter(fun r ->
811810
if found = expected.Length then sawExpectedOutput.Set() |> ignore
812811

813812
let text = "#help"
814-
use output = new RedirectConsoleOutput()
815813
use script = new FSharpScript(quiet = false, langVersion = LangVersion.Preview)
816814
let mutable found = 0
817-
output.OutputProduced.Add (fun line -> verifyOutput line)
815+
script.OutputProduced.Add (fun line -> verifyOutput line)
818816
let opt = script.Eval(text) |> getValue
819817
Assert.True(sawExpectedOutput.WaitOne(TimeSpan.FromSeconds(5.0)), sprintf "Expected to see error sentinel value written\nexpected:%A\nactual:%A" expected lines)
820818

tests/FSharp.Compiler.Private.Scripting.UnitTests/FSharpScriptTests.fs

Lines changed: 5 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -83,22 +83,19 @@ x
8383

8484
[<Fact>]
8585
member _.``Capture console input``() =
86-
use input = new RedirectConsoleInput()
87-
use script = new FSharpScript()
88-
input.ProvideInput "stdin:1234\r\n"
86+
use script = new FSharpScript(input = "stdin:1234\r\n")
8987
let opt = script.Eval("System.Console.ReadLine()") |> getValue
9088
let value = opt.Value
9189
Assert.Equal(typeof<string>, value.ReflectionType)
9290
Assert.Equal("stdin:1234", downcast value.ReflectionValue)
9391

9492
[<Fact>]
9593
member _.``Capture console output/error``() =
96-
use output = new RedirectConsoleOutput()
9794
use script = new FSharpScript()
9895
use sawOutputSentinel = new ManualResetEvent(false)
9996
use sawErrorSentinel = new ManualResetEvent(false)
100-
output.OutputProduced.Add (fun line -> if line = "stdout:1234" then sawOutputSentinel.Set() |> ignore)
101-
output.ErrorProduced.Add (fun line -> if line = "stderr:5678" then sawErrorSentinel.Set() |> ignore)
97+
script.OutputProduced.Add (fun line -> if line = "stdout:1234" then sawOutputSentinel.Set() |> ignore)
98+
script.ErrorProduced.Add (fun line -> if line = "stderr:5678" then sawErrorSentinel.Set() |> ignore)
10299
script.Eval("printfn \"stdout:1234\"; eprintfn \"stderr:5678\"") |> ignoreValue
103100
Assert.True(sawOutputSentinel.WaitOne(TimeSpan.FromSeconds(5.0)), "Expected to see output sentinel value written")
104101
Assert.True(sawErrorSentinel.WaitOne(TimeSpan.FromSeconds(5.0)), "Expected to see error sentinel value written")
@@ -305,11 +302,10 @@ printfn ""%A"" result
305302

306303
[<Fact>]
307304
member _.``Eval script with invalid PackageName should fail immediately``() =
308-
use output = new RedirectConsoleOutput()
309305
use script = new FSharpScript(additionalArgs=[| |])
310306
let mutable found = 0
311307
let outp = System.Collections.Generic.List<string>()
312-
output.OutputProduced.Add(
308+
script.OutputProduced.Add(
313309
fun line ->
314310
if line.Contains("error NU1101:") && line.Contains("FSharp.Really.Not.A.Package") then
315311
found <- found + 1
@@ -321,10 +317,9 @@ printfn ""%A"" result
321317

322318
[<Fact>]
323319
member _.``Eval script with invalid PackageName should fail immediately and resolve one time only``() =
324-
use output = new RedirectConsoleOutput()
325320
use script = new FSharpScript(additionalArgs=[| |])
326321
let mutable foundResolve = 0
327-
output.OutputProduced.Add (fun line -> if line.Contains("error NU1101:") then foundResolve <- foundResolve + 1)
322+
script.OutputProduced.Add (fun line -> if line.Contains("error NU1101:") then foundResolve <- foundResolve + 1)
328323
let result, errors =
329324
script.Eval("""
330325
#r "nuget:FSharp.Really.Not.A.Package"

tests/FSharp.Test.Utilities/ScriptHelpers.fs

Lines changed: 46 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -3,15 +3,14 @@
33
namespace FSharp.Test.ScriptHelpers
44

55
open System
6-
open System.Collections.Generic
76
open System.IO
87
open System.Text
98
open System.Threading
109
open FSharp.Compiler
1110
open FSharp.Compiler.Interactive.Shell
1211
open FSharp.Compiler.Diagnostics
1312
open FSharp.Compiler.EditorServices
14-
open FSharp.Test.Utilities
13+
open FSharp.Test
1514

1615
[<RequireQualifiedAccess>]
1716
type LangVersion =
@@ -25,7 +24,26 @@ type LangVersion =
2524
| Latest
2625
| SupportsMl
2726

28-
type FSharpScript(?additionalArgs: string[], ?quiet: bool, ?langVersion: LangVersion) =
27+
type private EventedTextWriter() =
28+
inherit TextWriter()
29+
let sb = StringBuilder()
30+
let sw = new StringWriter()
31+
let lineWritten = Event<string>()
32+
member _.LineWritten = lineWritten.Publish
33+
override _.Encoding = Encoding.UTF8
34+
override _.Write(c: char) =
35+
if c = '\n' then
36+
let line =
37+
let v = sb.ToString()
38+
if v.EndsWith("\r") then v.Substring(0, v.Length - 1)
39+
else v
40+
sb.Clear() |> ignore
41+
sw.WriteLine line
42+
lineWritten.Trigger(line)
43+
else sb.Append(c) |> ignore
44+
override _.ToString() = sw.ToString()
45+
46+
type FSharpScript(?additionalArgs: string[], ?quiet: bool, ?langVersion: LangVersion, ?input: string) =
2947

3048
let additionalArgs = defaultArg additionalArgs [||]
3149
let quiet = defaultArg quiet true
@@ -54,13 +72,32 @@ type FSharpScript(?additionalArgs: string[], ?quiet: bool, ?langVersion: LangVer
5472

5573
let argv = Array.append baseArgs additionalArgs
5674

75+
let inReader = new StringReader(defaultArg input "")
76+
let outWriter = new EventedTextWriter()
77+
let errorWriter = new EventedTextWriter()
78+
79+
let previousIn, previousOut, previousError = Console.In, Console.Out, Console.Error
80+
81+
do
82+
Console.SetIn inReader
83+
Console.SetOut outWriter
84+
Console.SetError errorWriter
85+
5786
let fsi = FsiEvaluationSession.Create (config, argv, stdin, stdout, stderr)
5887

5988
member _.ValueBound = fsi.ValueBound
6089

6190
member _.Fsi = fsi
6291

63-
member _.Eval(code: string, ?cancellationToken: CancellationToken, ?desiredCulture: Globalization.CultureInfo) =
92+
member _.OutputProduced = outWriter.LineWritten
93+
94+
member _.ErrorProduced = errorWriter.LineWritten
95+
96+
member _.GetOutput() = string outWriter
97+
98+
member _.GetErrorOutput() = string errorWriter
99+
100+
member this.Eval(code: string, ?cancellationToken: CancellationToken, ?desiredCulture: Globalization.CultureInfo) =
64101
let originalCulture = Thread.CurrentThread.CurrentCulture
65102
Thread.CurrentThread.CurrentCulture <- Option.defaultValue Globalization.CultureInfo.InvariantCulture desiredCulture
66103

@@ -88,7 +125,11 @@ type FSharpScript(?additionalArgs: string[], ?quiet: bool, ?langVersion: LangVer
88125
}
89126

90127
interface IDisposable with
91-
member this.Dispose() = ((this.Fsi) :> IDisposable).Dispose()
128+
member this.Dispose() =
129+
((this.Fsi) :> IDisposable).Dispose()
130+
Console.SetIn previousIn
131+
Console.SetOut previousOut
132+
Console.SetError previousError
92133

93134
[<AutoOpen>]
94135
module TestHelpers =
@@ -101,15 +142,3 @@ module TestHelpers =
101142
| Error ex -> raise ex
102143

103144
let ignoreValue = getValue >> ignore
104-
105-
let getTempDir () =
106-
let sysTempDir = Path.GetTempPath()
107-
let customTempDirName = Guid.NewGuid().ToString("D")
108-
let fullDirName = Path.Combine(sysTempDir, customTempDirName)
109-
let dirInfo = Directory.CreateDirectory(fullDirName)
110-
{ new Object() with
111-
member _.ToString() = dirInfo.FullName
112-
interface IDisposable with
113-
member _.Dispose() =
114-
dirInfo.Delete(true)
115-
}

0 commit comments

Comments
 (0)