Ejemplo n.º 1
0
        // RoundTrip with all verification
        public static T RoundTrip <T>(
            T value,
            Func <T> buildT,
            TreeFormat format,
            TreeSerializationSettings settings = null,
            bool testDoubleDispose             = false) where T : ITreeSerializable
        {
            T roundTripped = buildT();

            // Request non-compact stream (debuggability)
            settings ??= new TreeSerializationSettings()
            {
                Verbose = true
            };

            byte[] buffer = null;

            using (MemoryStream stream = new MemoryStream())
            {
                using (ITreeWriter writer = Writer(format, stream, settings))
                {
                    value.Write(writer);

                    // Debuggability: To see serialized text
                    //string serializedText = StreamString(stream);

                    if (testDoubleDispose)
                    {
                        writer.Dispose();
                    }
                }

                if (!settings.LeaveStreamOpen)
                {
                    // Verify stream disposed
                    if (!Debugger.IsAttached)
                    {
                        Assert.Throws <ObjectDisposedException>(() => stream.Position);
                    }
                }
                else
                {
                    // Verify stream left open if requested
                    long verifyStreamNotDisposed = stream.Position;
                }

                // Get bytes to read back from with reader
                buffer = stream.ToArray();
            }

            using (MemoryStream stream = new MemoryStream(buffer))
            {
                using (ITreeReader reader = Reader(format, stream, settings))
                {
                    // Ensure Readers pre-read first token by default
                    // Needed to allow single value reading to work without everything having to handle this case everywhere
                    Assert.NotEqual(TreeToken.None, reader.TokenType);

                    roundTripped.Read(reader);

                    // Verify everything read back
                    Assert.Equal(buffer.Length, stream.Position);

                    if (testDoubleDispose)
                    {
                        reader.Dispose();
                    }
                }

                if (!settings.LeaveStreamOpen)
                {
                    // Verify stream disposed
                    if (!Debugger.IsAttached)
                    {
                        Assert.Throws <ObjectDisposedException>(() => stream.Position);
                    }
                }
                else
                {
                    // Verify stream left open if requested
                    long verifyStreamNotDisposed = stream.Position;
                }
            }

            return(roundTripped);
        }