Exemple #1
0
        public static void SerializeTypeInstance()
        {
            Type type = typeof(int);

            NotSupportedException ex = Assert.Throws <NotSupportedException>(() => JsonSerializer.Serialize(type));
            string exAsStr           = ex.ToString();

            Assert.Contains("System.Type", exAsStr);
            Assert.Contains("$", exAsStr);

            type = null;
            string serialized = JsonSerializer.Serialize(type);

            Assert.Equal("null", serialized);

            ClassWithType obj = new ClassWithType {
                Type = typeof(int)
            };

            ex      = Assert.Throws <NotSupportedException>(() => JsonSerializer.Serialize(obj));
            exAsStr = ex.ToString();
            Assert.Contains("System.Type", exAsStr);
            Assert.Contains("$.Type", exAsStr);

            obj.Type   = null;
            serialized = JsonSerializer.Serialize(obj);
            Assert.Equal(@"{""Type"":null}", serialized);

            serialized = JsonSerializer.Serialize(obj, new JsonSerializerOptions {
                IgnoreNullValues = true
            });
            Assert.Equal(@"{}", serialized);
        }
Exemple #2
0
        public static void DeserializeUnsupportedType()
        {
            // Any test payload is fine.
            string json = @"""Some string""";

            RunTest <Type>();
            RunTest <SerializationInfo>();

            void RunTest <T>()
            {
                string fullName = typeof(T).FullName;

                NotSupportedException ex = Assert.Throws <NotSupportedException>(() => JsonSerializer.Deserialize <T>(json));
                string exAsStr           = ex.ToString();

                Assert.Contains(fullName, exAsStr);
                Assert.Contains("$", exAsStr);

                json = $@"{{""Prop"":{json}}}";

                ex      = Assert.Throws <NotSupportedException>(() => JsonSerializer.Deserialize <ClassWithType <T> >(json));
                exAsStr = ex.ToString();
                Assert.Contains(fullName, exAsStr);
                Assert.Contains("$.Prop", exAsStr);

                // NSE is not thrown because the serializer handles null.
                Assert.Null(JsonSerializer.Deserialize <T>("null"));

                ClassWithType <T> obj = JsonSerializer.Deserialize <ClassWithType <T> >(@"{""Prop"":null}");

                Assert.Null(obj.Prop);
            }
        }
Exemple #3
0
        public async Task LeadingReferenceMetadataNotSupported()
        {
            string json = @"{""$id"":""1"",""Name"":""Jet"",""Manager"":{""$ref"":""1""}}";

            // Metadata ignored by default.
            var employee = await Serializer.DeserializeWrapper <Employee>(json);

            Assert.Equal("Jet", employee.Name);
            Assert.Null(employee.Manager.Name);;
            Assert.Null(employee.Manager.Manager);

            // Metadata not supported with preserve ref feature on.

            var options = new JsonSerializerOptions {
                ReferenceHandler = ReferenceHandler.Preserve
            };

            NotSupportedException ex = await Assert.ThrowsAsync <NotSupportedException>(
                () => Serializer.DeserializeWrapper <Employee>(json, options));

            string exStr = ex.ToString();

            Assert.Contains("System.Text.Json.Serialization.Tests.ConstructorTests+Employee", exStr);
            Assert.Contains("$.$id", exStr);
        }
        public static void Converters_AndTypeInfoCreator_NotRooted_WhenMetadataNotPresent()
        {
            RemoteExecutor.Invoke(
                new Action(() =>
            {
                object[] objArr = new object[] { new MyStruct() };

                // Metadata not generated for MyStruct without JsonSerializableAttribute.
                NotSupportedException ex = Assert.Throws <NotSupportedException>(
                    () => JsonSerializer.Serialize(objArr, MetadataContext.Default.ObjectArray));
                string exAsStr = ex.ToString();
                Assert.Contains(typeof(MyStruct).ToString(), exAsStr);
                Assert.Contains("JsonSerializerOptions", exAsStr);

                // This test uses reflection to:
                // - Access JsonSerializerOptions.s_defaultSimpleConverters
                // - Access JsonSerializerOptions.s_defaultFactoryConverters
                // - Access JsonSerializerOptions._typeInfoCreationFunc
                //
                // If any of them changes, this test will need to be kept in sync.

                // Confirm built-in converters not set.
                AssertFieldNull("s_defaultSimpleConverters", optionsInstance: null);
                AssertFieldNull("s_defaultFactoryConverters", optionsInstance: null);

                // Confirm type info dynamic creator not set.
                AssertFieldNull("_typeInfoCreationFunc", MetadataContext.Default.Options);
        private async Task TestDeserialization <TCollection, TElement>(string json, JsonSerializerOptions options)
        {
            if (TypeHelper <TElement> .NotSupportedForDeserialization.Contains(typeof(TCollection)))
            {
                NotSupportedException exception = await Assert.ThrowsAsync <NotSupportedException>(() => Serializer.DeserializeWrapper <TCollection>(json, options));

                Assert.Contains(typeof(TCollection).ToString(), exception.ToString());
                return;
            }

            TCollection deserialized = await Serializer.DeserializeWrapper <TCollection>(json, options);

            // Validate the integrity of the deserialized value by reserializing
            // it using the non-streaming serializer and comparing the roundtripped value.
            string roundtrippedJson = JsonSerializer.Serialize(deserialized, options);

            // Stack elements reversed during serialization.
            if (TypeHelper <TElement> .StackTypes.Contains(typeof(TCollection)))
            {
                deserialized     = JsonSerializer.Deserialize <TCollection>(roundtrippedJson, options);
                roundtrippedJson = JsonSerializer.Serialize(deserialized, options);
            }

            // TODO: https://github.com/dotnet/runtime/issues/35611.
            // Can't control order of dictionary elements when serializing, so reference metadata might not match up.
            if (options.ReferenceHandler == ReferenceHandler.Preserve &&
                TypeHelper <TElement> .DictionaryTypes.Contains(typeof(TCollection)))
            {
                return;
            }

            JsonTestHelper.AssertJsonEqual(json, roundtrippedJson);
        }
Exemple #6
0
        public static void SerializeUnsupportedType()
        {
            RunTest(typeof(int));
            RunTest(new SerializationInfo(typeof(Type), new FormatterConverter()));
            RunTest((IntPtr)123);
            RunTest((UIntPtr)123);
#if NETCOREAPP
            RunTest(DateOnly.MaxValue);
            RunTest(TimeOnly.MinValue);
#endif

            void RunTest <T>(T value)
            {
                Type   type     = typeof(T);
                string fullName = type.FullName;

                NotSupportedException ex = Assert.Throws <NotSupportedException>(() => JsonSerializer.Serialize(value));
                string exAsStr           = ex.ToString();

                Assert.Contains(fullName, exAsStr);
                Assert.Contains("$", exAsStr);

                ClassWithType <T> obj = new ClassWithType <T> {
                    Prop = value
                };

                ex      = Assert.Throws <NotSupportedException>(() => JsonSerializer.Serialize(obj));
                exAsStr = ex.ToString();
                Assert.Contains(fullName, exAsStr);
                Assert.Contains("$.Prop", exAsStr);

                if (!type.IsValueType)
                {
                    string serialized = JsonSerializer.Serialize((T)(object)null);
                    Assert.Equal("null", serialized);

                    obj.Prop   = (T)(object)null;
                    serialized = JsonSerializer.Serialize(obj);
                    Assert.Equal(@"{""Prop"":null}", serialized);

                    serialized = JsonSerializer.Serialize(obj, new JsonSerializerOptions {
                        IgnoreNullValues = true
                    });
                    Assert.Equal(@"{}", serialized);
                }
            }
        }
        public async Task Cannot_Deserialize_ObjectWith_Ctor_With_65_Params()
        {
            async Task RunTestAsync <T>()
            {
                Type type = typeof(T);

                StringBuilder sb = new StringBuilder();

                sb.Append("{");
                for (int i = 0; i < 64; i++)
                {
                    sb.Append($@"""Int{i}"":{i},");
                }
                sb.Append($@"""Int64"":64");
                sb.Append("}");

                string input = sb.ToString();

                sb = new StringBuilder();
                sb.Append("(");
                for (int i = 0; i < 64; i++)
                {
                    sb.Append("Int32, ");
                }
                sb.Append("Int32");
                sb.Append(")");

                string ctorAsString = sb.ToString();

                NotSupportedException ex = await Assert.ThrowsAsync <NotSupportedException>(() => Serializer.DeserializeWrapper <T>(input));

                string strEx = ex.ToString();

                Assert.Contains(ctorAsString, strEx);
                Assert.Contains(type.ToString(), strEx);

                ex = await Assert.ThrowsAsync <NotSupportedException>(() => Serializer.DeserializeWrapper <T>("{}"));

                strEx = ex.ToString();
                Assert.Contains(ctorAsString, strEx);
                Assert.Contains(type.ToString(), strEx);
            }

            await RunTestAsync <Class_With_Ctor_With_65_Params>();
            await RunTestAsync <Struct_With_Ctor_With_65_Params>();
        }
Exemple #8
0
        public static void SerializeUnsupportedType()
        {
            RunTest <Type>(typeof(int));
            RunTest <SerializationInfo>(new SerializationInfo(typeof(Type), new FormatterConverter()));

            void RunTest <T>(T value)
            {
                string fullName = typeof(T).FullName;

                NotSupportedException ex = Assert.Throws <NotSupportedException>(() => JsonSerializer.Serialize(value));
                string exAsStr           = ex.ToString();

                Assert.Contains(fullName, exAsStr);
                Assert.Contains("$", exAsStr);

                string serialized = JsonSerializer.Serialize((T)(object)null);

                Assert.Equal("null", serialized);

                ClassWithType <T> obj = new ClassWithType <T> {
                    Prop = value
                };

                ex      = Assert.Throws <NotSupportedException>(() => JsonSerializer.Serialize(obj));
                exAsStr = ex.ToString();
                Assert.Contains(fullName, exAsStr);
                Assert.Contains("$.Prop", exAsStr);

                obj.Prop   = (T)(object)null;
                serialized = JsonSerializer.Serialize(obj);
                Assert.Equal(@"{""Prop"":null}", serialized);

                serialized = JsonSerializer.Serialize(obj, new JsonSerializerOptions {
                    IgnoreNullValues = true
                });
                Assert.Equal(@"{}", serialized);
            }
        }
Exemple #9
0
        public void RequestAnalysis_NotSupportedException_IsLoggedWithoutCallStack()
        {
            var ex = new NotSupportedException("thrown in a test");

            mockAnalysisScheduler
            .Setup(x => x.Schedule("doc1.js", It.IsAny <Action <CancellationToken> >(), It.IsAny <int>()))
            .Throws(ex);

            provider.RequestAnalysis("doc1.js", "", new[] { AnalysisLanguage.CFamily }, null, null);

            // Note: checking for an exact string here to be sure that the call stack is not included
            logger.AssertOutputStringExists("Unable to analyze: thrown in a test");
            logger.AssertPartialOutputStringDoesNotExist(ex.ToString());
        }
Exemple #10
0
        public static void DeserializeTypeInstance()
        {
            string json = @"""System.Int32, System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e""";

            NotSupportedException ex = Assert.Throws <NotSupportedException>(() => JsonSerializer.Deserialize <Type>(json));
            string exAsStr           = ex.ToString();

            Assert.Contains("System.Type", exAsStr);
            Assert.Contains("$", exAsStr);

            json = $@"{{""Type"":{json}}}";

            ex      = Assert.Throws <NotSupportedException>(() => JsonSerializer.Deserialize <ClassWithType>(json));
            exAsStr = ex.ToString();
            Assert.Contains("System.Type", exAsStr);
            Assert.Contains("$.Type", exAsStr);

            // NSE is not thrown because the serializer handles null.
            Assert.Null(JsonSerializer.Deserialize <Type>("null"));

            ClassWithType obj = JsonSerializer.Deserialize <ClassWithType>(@"{""Type"":null}");

            Assert.Null(obj.Type);
        }
        public void NonPublicCtors_NotSupported()
        {
            void RunTest <T>()
            {
                NotSupportedException ex = Assert.Throws <NotSupportedException>(() => Serializer.Deserialize <T>("{}"));

                Assert.Contains("JsonConstructorAttribute", ex.ToString());
            }

            RunTest <PrivateParameterlessCtor>();
            RunTest <InternalParameterlessCtor>();
            RunTest <ProtectedParameterlessCtor>();
            RunTest <PrivateParameterizedCtor>();
            RunTest <InternalParameterizedCtor>();
            RunTest <ProtectedParameterizedCtor>();
            RunTest <PrivateParameterizedCtor_WithAttribute>();
            RunTest <InternalParameterizedCtor_WithAttribute>();
            RunTest <ProtectedParameterizedCtor_WithAttribute>();
        }
Exemple #12
0
        public async Task NonPublicCtors_NotSupported()
        {
            async Task RunTestAsync <T>()
            {
                NotSupportedException ex = await Assert.ThrowsAsync <NotSupportedException>(() => Serializer.DeserializeWrapper <T>("{}"));

                Assert.Contains("JsonConstructorAttribute", ex.ToString());
            }

            await RunTestAsync <PrivateParameterlessCtor>();
            await RunTestAsync <InternalParameterlessCtor>();
            await RunTestAsync <ProtectedParameterlessCtor>();
            await RunTestAsync <PrivateParameterizedCtor>();
            await RunTestAsync <InternalParameterizedCtor>();
            await RunTestAsync <ProtectedParameterizedCtor>();
            await RunTestAsync <PrivateParameterizedCtor_WithAttribute>();
            await RunTestAsync <InternalParameterizedCtor_WithAttribute>();
            await RunTestAsync <ProtectedParameterizedCtor_WithAttribute>();
        }
Exemple #13
0
        public void RandomReferenceMetadataNotSupported()
        {
            string json = @"{""Name"":""Jet"",""$random"":10}";

            // Baseline, preserve ref feature off.

            var employee = JsonSerializer.Deserialize <Employee>(json);

            Assert.Equal("Jet", employee.Name);

            // Metadata not supported with preserve ref feature on.

            var options = new JsonSerializerOptions {
                ReferenceHandler = ReferenceHandler.Preserve
            };

            NotSupportedException ex = Assert.Throws <NotSupportedException>(() => Serializer.Deserialize <Employee>(json, options));
            string exStr             = ex.ToString();

            Assert.Contains("System.Text.Json.Serialization.Tests.ConstructorTests+Employee", exStr);
            Assert.Contains("$.$random", exStr);
        }
Exemple #14
0
        public async Task Routine_ReturnsFaultedTask_LogsFaultedTask()
        {
            // Arrange
            using IJobManager jobManager = TestHelper.CreateJobManager(true);
            var job = jobManager.Create("my-job");

            var start       = "2000-01-01Z".ToUtcDateOffset();
            var timeMachine = ShiftedTimeProvider.CreateTimeMachine(start);

            TimeProvider.Override(timeMachine);

            var output = new StringWriterWithEncoding(Encoding.UTF8);

            job.Output = output;

            var exception = new NotSupportedException("Bye baby!");

            JobDelegate routine = (parameter, tracker, writer, token) =>
            {
                writer.WriteLine("Hi there!");
                return(Task.FromException(exception));
            };

            job.Schedule = new ConcreteSchedule(
                start.AddSeconds(1));

            job.IsEnabled = true;

            // Act
            job.Routine = routine;
            var updatedRoutine = job.Routine;

            await timeMachine.WaitUntilSecondsElapse(start, 1.5); // will fail by this time

            var outputResult = output.ToString();

            var info = job.GetInfo(null);

            // Assert
            try
            {
                Assert.That(updatedRoutine, Is.SameAs(routine));
                Assert.That(outputResult, Does.Contain("Hi there!"));
                Assert.That(outputResult, Does.Contain(exception.ToString()));

                Assert.That(info.CurrentRun, Is.Null);

                Assert.That(info.RunCount, Is.EqualTo(1));
                var run = info.Runs.Single();

                Assert.That(run.Status, Is.EqualTo(JobRunStatus.Faulted));
                Assert.That(run.Exception, Is.SameAs(exception));
                Assert.That(run.Output, Does.Contain(exception.ToString()));

                var log = _logWriter.ToString();

                Assert.That(log,
                            Does.Contain($"Job 'my-job' completed synchronously. Reason of start was 'ScheduleDueTime'."));
            }
            catch (Exception ex)
            {
                var sb = new StringBuilder();
                sb.AppendLine("*** Test Failed ***");
                sb.AppendLine(ex.ToString());
                sb.AppendLine("*** Log: ***");

                var log = _logWriter.ToString();

                sb.AppendLine(log);

                Assert.Fail(sb.ToString());
            }
        }
Exemple #15
0
        private static void WriteEventAndThrow(string message)
        {
            var exception = new NotSupportedException(message);

            if (EventLog.SourceExists(EventSource))
            {
                EventLog.WriteEntry(EventSource,
                                    $"{Process.GetCurrentProcess().ProcessName}{Environment.NewLine}{exception.ToString()}",
                                    EventLogEntryType.Error, EventId);
            }

            throw exception;
        }
Exemple #16
0
        internal static void VerifySwitches(Dispatcher dispatcher)
        {
            if (Interlocked.CompareExchange(ref s_SwitchesVerified, 1, 0) == 0)
            {
                // If a flag is set to false, we also must ensure the prior accessibility switch is also false.
                // Otherwise we should inform the developer, via an exception, to enable all the flags.
                if (UseLegacyAccessibilityFeatures && !UseLegacyAccessibilityFeatures2)
                {
                    // Dispatch an EventLog and error throw so we get loaded UI, then the crash.
                    // This ensures the WER dialog shows.
                    dispatcher.BeginInvoke(DispatcherPriority.Loaded,
                                           new Action(() =>
                    {
                        var exception = new NotSupportedException(SR.Get(SRID.CombinationOfAccessibilitySwitchesNotSupported));

                        if (EventLog.SourceExists(EventSource))
                        {
                            EventLog.WriteEntry(EventSource,
                                                $"{Process.GetCurrentProcess().ProcessName}{Environment.NewLine}{exception.ToString()}",
                                                EventLogEntryType.Error, EventId);
                        }

                        throw exception;
                    }));
                }
            }
        }