using System; using System.Collections.Generic; using System.IO; using System.Linq; using DotnetStandardStreams; using DotnetStandardStreamsTests.Testables; namespace DotnetStandardStreamsTests; public class StdInTextSourceTests { private static TextReader CreateStdIn() => new ListTextReader(["1", "2", "", "3"]); private static TextReader CreateEmptyStdIn() => new ListTextReader([]); private static void WrapStdInTest(Action testCode, TextReader? explicitStdIn = null) { explicitStdIn ??= CreateStdIn(); TextReader oldInputReader = System.Console.In; try { System.Console.SetIn(explicitStdIn); ITextSource stdin = new StdInTextSource(); stdin.Open(); try { testCode.Invoke(stdin); } finally { stdin.Close(); } } finally { System.Console.SetIn(oldInputReader); } } [Fact] public void CanReadAllFromStandardIn() { WrapStdInTest(static stdin => { List actual = stdin.ReadAll().ToList(); actual.Count.ShouldBe(4); actual[0].ShouldBe("1"); actual[1].ShouldBe("2"); actual[2].ShouldBe(string.Empty); actual[3].ShouldBe("3"); }); } [Fact] public void CanReadIndividualLinesFromStandardIn() { WrapStdInTest(static stdin => { string s; s = stdin.Read(); stdin.Eof().ShouldBe(false); s.ShouldBe("1"); s = stdin.Read(); stdin.Eof().ShouldBe(false); s.ShouldBe("2"); s = stdin.Read(); stdin.Eof().ShouldBe(false); s.ShouldBe(string.Empty); s = stdin.Read(); stdin.Eof().ShouldBe(false); s.ShouldBe("3"); _ = stdin.Read(); stdin.Eof().ShouldBe(true); }); } [Fact] public void CanWhileLoopThroughStdInNormally() { WrapStdInTest(static stdin => { int lineCount = 0; _ = stdin.Read(); while (!stdin.Eof()) { lineCount++; _ = stdin.Read(); } lineCount.ShouldBe(4); }); } [Fact] public void CanReadAllThroughStdInNormally() { WrapStdInTest(static stdin => { List lines = stdin.ReadAll().ToList(); int lineCount = lines.Count; lineCount.ShouldBe(4); lines.ShouldBe(["1", "2", "", "3"]); }); } [Fact] public void CanWhileLoopThroughStdInEmpty() { WrapStdInTest( static stdin => { int lineCount = 0; _ = stdin.Read(); while (!stdin.Eof()) { lineCount++; _ = stdin.Read(); } lineCount.ShouldBe(0); }, CreateEmptyStdIn()); } [Fact] public void CanReadAllThroughStdInEmpty() { WrapStdInTest(static stdin => { List lines = stdin.ReadAll().ToList(); int lineCount = lines.Count; lineCount.ShouldBe(0); }, CreateEmptyStdIn()); } }