// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information. using System; using System.IO; namespace Microsoft.TestCommon { //// TODO RONCAIN using System.Runtime.Serialization.Json; /// /// MSTest utility for testing code operating against a stream. /// public class StreamAssert { private static StreamAssert singleton = new StreamAssert(); public static StreamAssert Singleton { get { return singleton; } } /// /// Creates a , invokes to write to it, /// rewinds the stream to the beginning and invokes . /// /// Code to write to the stream. It cannot be null. /// Code that reads from the stream. It cannot be null. public void WriteAndRead(Action codeThatWrites, Action codeThatReads) { if (codeThatWrites == null) { throw new ArgumentNullException("codeThatWrites"); } if (codeThatReads == null) { throw new ArgumentNullException("codeThatReads"); } using (MemoryStream stream = new MemoryStream()) { codeThatWrites(stream); stream.Flush(); stream.Seek(0L, SeekOrigin.Begin); codeThatReads(stream); } } /// /// Creates a , invokes to write to it, /// rewinds the stream to the beginning and invokes to obtain /// the result to return from this method. /// /// Code to write to the stream. It cannot be null. /// Code that reads from the stream and returns the result. It cannot be null. /// The value returned from . public static object WriteAndReadResult(Action codeThatWrites, Func codeThatReads) { if (codeThatWrites == null) { throw new ArgumentNullException("codeThatWrites"); } if (codeThatReads == null) { throw new ArgumentNullException("codeThatReads"); } object result = null; using (MemoryStream stream = new MemoryStream()) { codeThatWrites(stream); stream.Flush(); stream.Seek(0L, SeekOrigin.Begin); result = codeThatReads(stream); } return result; } /// /// Creates a , invokes to write to it, /// rewinds the stream to the beginning and invokes to obtain /// the result to return from this method. /// /// The type of the result expected. /// Code to write to the stream. It cannot be null. /// Code that reads from the stream and returns the result. It cannot be null. /// The value returned from . public T WriteAndReadResult(Action codeThatWrites, Func codeThatReads) { return (T)WriteAndReadResult(codeThatWrites, codeThatReads); } } }