Exemple #1
0
		public void Ignore_Protected_Property_That_Exists_In_Data() {
			var doc = CreateJson();
			var d = new JsonDeserializer();
			var p = d.Deserialize<PersonForJson>(doc);

			Assert.Null(p.IgnoreProxy);
		}
        public void Can_Deserialize_JScript_Json_Dates()
        {
            var doc = CreateJScriptDateJson();
            var d = new JsonDeserializer();
            var bd = d.Deserialize<Birthdate>(doc);

            Assert.Equal(new DateTime(1910, 9, 25, 9, 30, 25, DateTimeKind.Utc), bd.Value);
        }
        public void Can_Deserialize_Guid_String_Fields()
        {
            var doc = new JObject();
              doc["Guid"] = "b1457983-8c5c-4c11-b10e-58585ed646d2";

              var d = new JsonDeserializer();
              var p = d.Deserialize<PersonForJson>(doc.ToString());

              Assert.Equal(new Guid("b1457983-8c5c-4c11-b10e-58585ed646d2"), p.Guid);
        }
        public void Can_Deserialize_Json_MySql_Php_Date()
        {
            var doc = new JObject();
              doc["StartDate"] = "2010-01-10 14:23:54";

              var d = new JsonDeserializer();
              var p = d.Deserialize<PersonForJson>(doc.ToString());

              Assert.Equal(DateTime.Parse("01-10-2010 14:23:54"), p.StartDate);
        }
        public void Can_Deserialize_Empty_Elements_to_Nullable_Values()
        {
            var doc = CreateJsonWithNullValues();

            var json = new JsonDeserializer();
            var output = json.Deserialize<NullableValues>(new RestResponse { Content = doc });

            Assert.Null(output.Id);
            Assert.Null(output.StartDate);
            Assert.Null(output.UniqueId);
        }
Exemple #6
0
        public void Can_Deserialize_DateTime()
        {
            var doc = File.ReadAllText(Path.Combine("SampleData", "datetimes.txt"));
            var d = new JsonDeserializer();
            var response = new RestResponse { Content = doc };
            var payload = d.Deserialize<DateTimeTestStructure>(response);

            Assert.Equal(
                new DateTime(2011, 6, 30, 8, 15, 46, DateTimeKind.Utc).ToString("u"),
                payload.DateTime.ToString("u"));
        }
Exemple #7
0
        public void Can_Deserialize_4sq_Json_With_Root_Element_Specified()
        {
            var doc = File.ReadAllText(Path.Combine("SampleData", "4sq.txt"));

            var json = new JsonDeserializer();
            json.RootElement = "response";

            var output = json.Deserialize<VenuesResponse>(new RestResponse { Content = doc });

            Assert.NotEmpty(output.Groups);
        }
Exemple #8
0
        public void Can_Deserialize_Elements_to_Nullable_Values()
        {
            var doc = CreateJsonWithoutEmptyValues();

            var json = new JsonDeserializer();
            var output = json.Deserialize<NullableValues>(new RestResponse { Content = doc });

            Assert.NotNull(output.Id);
            Assert.NotNull(output.StartDate);
            Assert.NotNull(output.UniqueId);

            Assert.Equal(123, output.Id);
            Assert.Equal(new DateTime(2010, 2, 21, 9, 35, 00), output.StartDate);
            Assert.Equal(new Guid(GuidString), output.UniqueId);
        }
        public void Can_Deserialize_Custom_Formatted_Date()
        {
            var format = "dd yyyy MMM, hh:mm ss tt";
            var date = new DateTime(2010, 2, 8, 11, 11, 11);

            var formatted = new {
                StartDate = date.ToString(format)
            };

            var data = JsonConvert.SerializeObject(formatted);
            var response = new RestResponse { Content = data };

            var json = new JsonDeserializer { DateFormat = format };

            var output = json.Deserialize<PersonForJson>(response);

            Assert.Equal(date, output.StartDate);
        }
Exemple #10
0
		public void Can_Deserialize_Names_With_Underscores_With_Default_Root() {
			var doc = CreateJsonWithUnderscores();
			var d = new JsonDeserializer();
			var p = d.Deserialize<PersonForJson>(doc);

			Assert.Equal("John Sheehan", p.Name);
			Assert.Equal(new DateTime(2009, 9, 25, 0, 6, 1), p.StartDate);
			Assert.Equal(28, p.Age);
			Assert.Equal(long.MaxValue, p.BigNumber);
			Assert.Equal(99.9999m, p.Percent);
			Assert.Equal(false, p.IsCool);

			Assert.NotNull(p.Friends);
			Assert.Equal(10, p.Friends.Count);

			Assert.NotNull(p.BestFriend);
			Assert.Equal("The Fonz", p.BestFriend.Name);
			Assert.Equal(1952, p.BestFriend.Since);

			Assert.NotEmpty(p.Foes);
			Assert.Equal("Foe 1", p.Foes["dict1"].Nickname);
			Assert.Equal("Foe 2", p.Foes["dict2"].Nickname);
		}
Exemple #11
0
 public void Can_Deserialize_Root_Json_Array_To_List()
 {
     var data = File.ReadAllText(Path.Combine("SampleData", "jsonarray.txt"));
     var response = new RestResponse { Content = data };
     var json = new JsonDeserializer();
     var output = json.Deserialize<List<status>>(response);
     Assert.Equal(4, output.Count);
 }
Exemple #12
0
        public void Can_Deserialize_Quoted_Primitive()
        {
            var doc = new JObject();
            doc["Age"] = "28";

            var d = new JsonDeserializer();
            var response = new RestResponse { Content = doc.ToString() };
            var p = d.Deserialize<PersonForJson>(response);

            Assert.Equal(28, p.Age);
        }
Exemple #13
0
        public void Can_Deserialize_Nullable_DateTime_With_Null()
        {
            var doc = File.ReadAllText(Path.Combine("SampleData", "datetimes.txt"));
            var d = new JsonDeserializer();
            var response = new RestResponse { Content = doc };
            var payload = d.Deserialize<DateTimeTestStructure>(response);

            Assert.Null(payload.NullableDateTimeWithNull);
        }
Exemple #14
0
        public void Can_Deserialize_Lists_of_Simple_Types()
        {
            var doc = File.ReadAllText(Path.Combine("SampleData", "jsonlists.txt"));
            var json = new JsonDeserializer ();

            var output = json.Deserialize<JsonLists> (new RestResponse { Content = doc });

            Assert.NotEmpty (output.Names);
            Assert.NotEmpty (output.Numbers);
        }
Exemple #15
0
        public void Can_Deserialize_JsonNet_Dates()
        {
            var doc = File.ReadAllText(Path.Combine("SampleData", "person.json.txt"));
            var d = new JsonDeserializer();
            var response = new RestResponse { Content = doc };
            var person = d.Deserialize<PersonForJson>(response);

            Assert.Equal(
                new DateTime(2011, 6, 30, 8, 15, 46, DateTimeKind.Utc).ToString("u"),
                person.StartDate.ToString("u"));
        }
Exemple #16
0
        public void Can_Handle_Nullable_DateTime()
        {
            //  TODO:  Something is wrong with the ... ? ... of the ExtractDate function.  It's ?rounding?  Swap comments
              //  on the following two lines of code, and this test will fail because the resolution is lost.
              //DateTime? dt = DateTime.Now;
              DateTime? dt = DateTime.Parse("01-01-2010 22:47:00");

              var doc = new JObject();
              doc["NullableDate"] = null;
              doc["NullableRealDate"] = dt;

              var d = new JsonDeserializer();
              var p = d.Deserialize<PersonForJson>(doc.ToString());

              Assert.Equal(null, p.NullableDate);
              Assert.Equal(dt, p.NullableRealDate);
        }
Exemple #17
0
        public void Can_Deserialize_TimeSpan()
        {
            var doc = File.ReadAllText(Path.Combine("SampleData", "timespans.txt"));
                var d = new JsonDeserializer();
                var response = new RestResponse { Content = doc };
                var payload = d.Deserialize<TimeSpanTestStructure>(response);

                Assert.Equal(new TimeSpan(468006), payload.Tick);
                Assert.Equal(new TimeSpan(0, 0, 0, 0, 125), payload.Millisecond);
                Assert.Equal(new TimeSpan(0, 0, 8), payload.Second);
                Assert.Equal(new TimeSpan(0, 55, 2), payload.Minute);
                Assert.Equal(new TimeSpan(21, 30, 7), payload.Hour);
                Assert.Null(payload.NullableWithoutValue);
                Assert.NotNull(payload.NullableWithValue);
                Assert.Equal(new TimeSpan(21, 30, 7), payload.NullableWithValue.Value);
        }
Exemple #18
0
        public void Can_Deserialize_With_Default_Root()
        {
            var doc = CreateJson();
            var d = new JsonDeserializer();
            var response = new RestResponse { Content = doc };
            var p = d.Deserialize<PersonForJson>(response);

            Assert.Equal("John Sheehan", p.Name);
            Assert.Equal(new DateTime(2009, 9, 25, 0, 6, 1, DateTimeKind.Utc), p.StartDate);
            Assert.Equal(28, p.Age);
            Assert.Equal(long.MaxValue, p.BigNumber);
            Assert.Equal(99.9999m, p.Percent);
            Assert.Equal(false, p.IsCool);
            Assert.Equal(new Uri("http://example.com", UriKind.RelativeOrAbsolute), p.Url);
            Assert.Equal(new Uri("/foo/bar", UriKind.RelativeOrAbsolute), p.UrlPath);

            Assert.Equal(Guid.Empty, p.EmptyGuid);
            Assert.Equal(new Guid(GuidString), p.Guid);

            Assert.Equal(Order.Third, p.Order);
            Assert.Equal(Disposition.SoSo, p.Disposition);

            Assert.NotNull(p.Friends);
            Assert.Equal(10, p.Friends.Count);

            Assert.NotNull(p.BestFriend);
            Assert.Equal("The Fonz", p.BestFriend.Name);
            Assert.Equal(1952, p.BestFriend.Since);

            Assert.NotEmpty(p.Foes);
            Assert.Equal("Foe 1", p.Foes["dict1"].Nickname);
            Assert.Equal("Foe 2", p.Foes["dict2"].Nickname);
        }
Exemple #19
0
        public void Can_Deserialize_Various_Enum_Values()
        {
            var data = File.ReadAllText (Path.Combine ("SampleData", "jsonenums.txt"));
            var response = new RestResponse { Content = data };
            var json = new JsonDeserializer ();
            var output = json.Deserialize<JsonEnumsTestStructure>(response);

            Assert.Equal (output.Upper, Disposition.Friendly);
            Assert.Equal (output.Lower, Disposition.Friendly);
            Assert.Equal (output.CamelCased, Disposition.SoSo);
            Assert.Equal (output.Underscores, Disposition.SoSo);
            Assert.Equal (output.LowerUnderscores, Disposition.SoSo);
            Assert.Equal (output.Dashes, Disposition.SoSo);
            Assert.Equal (output.LowerDashes, Disposition.SoSo);
        }
Exemple #20
0
        public void Can_Deserialize_To_Dictionary_String_String_With_Dynamic_Values()
        {
            var doc = CreateDynamicJsonStringDictionary ();
            var d = new JsonDeserializer ();
            var response = new RestResponse { Content = doc };
            var bd = d.Deserialize<Dictionary<string, string>> (response);

            Assert.Equal ("[\"Value1\",\"Value2\"]", bd["Thing1"]);
            Assert.Equal ("Thing2", bd["Thing2"]);
            Assert.Equal ("{\"Name\":\"ThingRed\",\"Color\":\"Red\"}", bd["ThingRed"]);
            Assert.Equal ("{\"Name\":\"ThingBlue\",\"Color\":\"Blue\"}", bd["ThingBlue"]);
        }
Exemple #21
0
        /// <summary>
        /// Loads the test assembly configuration for the given test assembly from a JSON stream. Caller is responsible for opening the stream.
        /// </summary>
        /// <param name="configStream">Stream containing config for an assembly</param>
        /// <returns>The test assembly configuration.</returns>
        public static TestAssemblyConfiguration Load(Stream configStream)
        {
            var result = new TestAssemblyConfiguration();

            try
            {
                using (var reader = new StreamReader(configStream))
                {
                    var config = JsonDeserializer.Deserialize(reader) as JsonObject;

                    foreach (var propertyName in config.Keys)
                    {
                        var propertyValue = config.Value(propertyName);
                        var booleanValue  = propertyValue as JsonBoolean;

                        if (booleanValue != null)
                        {
                            if (string.Equals(propertyName, Configuration.DiagnosticMessages, StringComparison.OrdinalIgnoreCase))
                            {
                                result.DiagnosticMessages = booleanValue;
                            }
                            if (string.Equals(propertyName, Configuration.ParallelizeAssembly, StringComparison.OrdinalIgnoreCase))
                            {
                                result.ParallelizeAssembly = booleanValue;
                            }
                            if (string.Equals(propertyName, Configuration.ParallelizeTestCollections, StringComparison.OrdinalIgnoreCase))
                            {
                                result.ParallelizeTestCollections = booleanValue;
                            }
                            if (string.Equals(propertyName, Configuration.PreEnumerateTheories, StringComparison.OrdinalIgnoreCase))
                            {
                                result.PreEnumerateTheories = booleanValue;
                            }
                            if (string.Equals(propertyName, Configuration.ShadowCopy, StringComparison.OrdinalIgnoreCase))
                            {
                                result.ShadowCopy = booleanValue;
                            }
                        }
                        else if (string.Equals(propertyName, Configuration.MaxParallelThreads, StringComparison.OrdinalIgnoreCase))
                        {
                            var numberValue = propertyValue as JsonNumber;
                            if (numberValue != null)
                            {
                                int maxParallelThreads;
                                if (int.TryParse(numberValue.Raw, out maxParallelThreads) && maxParallelThreads > 0)
                                {
                                    result.MaxParallelThreads = maxParallelThreads;
                                }
                            }
                        }
                        else if (string.Equals(propertyName, Configuration.MethodDisplay, StringComparison.OrdinalIgnoreCase))
                        {
                            var stringValue = propertyValue as JsonString;
                            if (stringValue != null)
                            {
                                try
                                {
                                    var methodDisplay = Enum.Parse(typeof(TestMethodDisplay), stringValue, true);
                                    result.MethodDisplay = (TestMethodDisplay)methodDisplay;
                                }
                                catch { }
                            }
                        }
                        else if (string.Equals(propertyName, Configuration.AppDomain, StringComparison.OrdinalIgnoreCase))
                        {
                            var stringValue = propertyValue as JsonString;
                            if (stringValue != null)
                            {
                                try
                                {
                                    var appDomain = Enum.Parse(typeof(AppDomainSupport), stringValue, true);
                                    result.AppDomain = (AppDomainSupport)appDomain;
                                }
                                catch { }
                            }
                        }
                    }
                }
            }
            catch { }

            return(result);
        }
Exemple #22
0
        public void Can_Deserialize_Simple_Generic_List_Given_Toplevel_Item_Without_Array()
        {
            const string content = "\"johnsheehan\"";
            var json = new JsonDeserializer ();

            var output = json.Deserialize<List<string>> (new RestResponse { Content = content });

            Assert.True (output.SequenceEqual (new[] { "johnsheehan" }));
        }
Exemple #23
0
        async Task SendTestResults(bool isAdd, int runId, ICollection <IDictionary <string, object> > body)
        {
            if (body.Count == 0)
            {
                return;
            }

            // For adds, we need to remove the unique IDs and correlate to the responses
            // For update we need to look up the responses
            List <ITest> added = null;

            if (isAdd)
            {
                added = new List <ITest>(body.Count);

                // Add them to the list so we can ref by ordinal on the response
                foreach (var item in body)
                {
                    var uniqueId = (ITest)item[UNIQUEIDKEY];
                    item.Remove(UNIQUEIDKEY);

                    added.Add(uniqueId);
                }
            }
            else
            {
                // The values should be in the map
                foreach (var item in body)
                {
                    var test = (ITest)item[UNIQUEIDKEY];
                    item.Remove(UNIQUEIDKEY);

                    // lookup and add
                    var testId = testToTestIdMap[test];
                    item.Add("id", testId);
                }
            }

            var method     = isAdd ? HttpMethod.Post : PatchHttpMethod;
            var bodyString = ToJson(body);

            var url = $"{baseUri}/{runId}/results?api-version=3.0-preview";

            try
            {
                var bodyBytes = Encoding.UTF8.GetBytes(bodyString);

                var request = new HttpRequestMessage(method, url)
                {
                    Content = new ByteArrayContent(bodyBytes)
                };
                request.Content.Headers.ContentType = JsonMediaType;
                request.Headers.Accept.Add(JsonMediaType);

                using var tcs = new CancellationTokenSource(TimeSpan.FromSeconds(30));
                var response = await client.SendAsync(request, tcs.Token).ConfigureAwait(false);

                if (!response.IsSuccessStatusCode)
                {
                    logger.LogWarning($"When sending '{method} {url}', received status code '{response.StatusCode}'; request body:\n{bodyString}");
                    previousErrors = true;
                }

                if (isAdd)
                {
                    var respString = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

                    using var sr = new StringReader(respString);
                    var resp = JsonDeserializer.Deserialize(sr) as JsonObject;

                    var testCases = resp.Value("value") as JsonArray;
                    for (var i = 0; i < testCases.Length; ++i)
                    {
                        var testCase = testCases[i] as JsonObject;
                        var id       = testCase.ValueAsInt("id");

                        // Match the test by ordinal
                        var test = added[i];
                        testToTestIdMap[test] = id;
                    }
                }
            }
            catch (Exception ex)
            {
                logger.LogError($"When sending '{method} {url}' with body '{bodyString}', exception was thrown: {ex.Message}");
                throw;
            }
        }
Exemple #24
0
        public void Can_Deserialize_Simple_Generic_List_of_Simple_Types_With_Nulls()
        {
            const string content = "{\"users\":[\"johnsheehan\",\"jagregory\",null,\"drusellers\",\"structuremap\"]}";
            var json = new JsonDeserializer { RootElement = "users" };

            var output = json.Deserialize<List<string>> (new RestResponse { Content = content });

            Assert.NotEmpty (output);
            Assert.Equal (null, output[2]);
            Assert.Equal (5, output.Count);
        }
Exemple #25
0
        public void Can_Deserialize_Iso_Json_Dates()
        {
            var doc = CreateIsoDateJson();
            var d = new JsonDeserializer();
            var response = new RestResponse { Content = doc };
            var bd = d.Deserialize<Birthdate>(response);

            Assert.Equal(new DateTime(1910, 9, 25, 9, 30, 25, DateTimeKind.Utc), bd.Value);
        }
Exemple #26
0
        public void Can_Deserialize_To_Dictionary_String_String()
        {
            var doc = CreateJsonStringDictionary();
            var d = new JsonDeserializer();
            var response = new RestResponse { Content = doc };
            var bd = d.Deserialize<Dictionary<string,string>>(response);

            Assert.Equal(bd["Thing1"], "Thing1");
            Assert.Equal(bd["Thing2"], "Thing2");
            Assert.Equal(bd["ThingRed"], "ThingRed");
            Assert.Equal(bd["ThingBlue"], "ThingBlue");
        }
Exemple #27
0
 public void Can_Deserialize_Root_Json_Array_To_List()
 {
     var data = File.ReadAllText(@"..\..\SampleData\jsonarray.txt");
     var json = new JsonDeserializer();
     var output = json.Deserialize<List<status>>(data);
     Assert.Equal(4, output.Count);
 }
Exemple #28
0
        public void Can_Deserialize_Unix_Json_Dates()
        {
            var doc = CreateUnixDateJson();
            var d = new JsonDeserializer();
            var response = new RestResponse { Content = doc };
            var bd = d.Deserialize<Birthdate>(response);

            Assert.Equal(new DateTime(2011, 6, 30, 8, 15, 46, DateTimeKind.Utc), bd.Value);
        }
Exemple #29
0
        public void Can_Deserialize_From_Root_Element()
        {
            var doc = File.ReadAllText(Path.Combine("SampleData", "sojson.txt"));

            var json = new JsonDeserializer();
            json.RootElement = "User";

            var output = json.Deserialize<SOUser>(new RestResponse { Content = doc });
            Assert.Equal("John Sheehan", output.DisplayName);
        }
Exemple #30
0
        public void Can_Deserialize_Generic_Members()
        {
            var doc = File.ReadAllText(Path.Combine("SampleData", "GenericWithList.txt"));
            var json = new JsonDeserializer();

            var output = json.Deserialize<Generic<GenericWithList<Foe>>>(new RestResponse { Content = doc });
            Assert.Equal("Foe sho", output.Data.Items[0].Nickname);
        }
Exemple #31
0
        public void Can_Deserialize_Guid_String_Fields()
        {
            var doc = new JObject();
            doc["Guid"] = GuidString;

            var d = new JsonDeserializer();
            var response = new RestResponse { Content = doc.ToString() };
            var p = d.Deserialize<PersonForJson>(response);

            Assert.Equal(new Guid(GuidString), p.Guid);
        }
Exemple #32
0
        public void Ignore_ReadOnly_Property_That_Exists_In_Data()
        {
            var doc = CreateJson();
            var response = new RestResponse { Content = doc };
            var d = new JsonDeserializer();
            var p = d.Deserialize<PersonForJson>(response);

            Assert.Null(p.ReadOnlyProxy);
        }
Exemple #33
0
        /// <summary>
        /// Loads the test assembly configuration for the given test assembly.
        /// </summary>
        /// <param name="assemblyFileName">The test assembly.</param>
        /// <param name="configFileName">The test assembly configuration file.</param>
        /// <returns>The test assembly configuration.</returns>
        public static TestAssemblyConfiguration Load(string assemblyFileName, string configFileName = null)
        {
            if (configFileName == null)
            {
                configFileName = Path.Combine(Path.GetDirectoryName(assemblyFileName), "xunit.runner.json");
            }

            if (configFileName.EndsWith(".json"))
            {
                try
                {
                    var result = new TestAssemblyConfiguration();

                    using (var stream = File.OpenRead(configFileName))
                        using (var reader = new StreamReader(stream))
                        {
                            var config = JsonDeserializer.Deserialize(reader) as JsonObject;

                            foreach (var propertyName in config.Keys)
                            {
                                var propertyValue = config.Value(propertyName);
                                var booleanValue  = propertyValue as JsonBoolean;

                                if (booleanValue != null)
                                {
                                    if (string.Equals(propertyName, Configuration.DiagnosticMessages, StringComparison.OrdinalIgnoreCase))
                                    {
                                        result.DiagnosticMessages = booleanValue;
                                    }
                                    if (string.Equals(propertyName, Configuration.ParallelizeAssembly, StringComparison.OrdinalIgnoreCase))
                                    {
                                        result.ParallelizeAssembly = booleanValue;
                                    }
                                    if (string.Equals(propertyName, Configuration.ParallelizeTestCollections, StringComparison.OrdinalIgnoreCase))
                                    {
                                        result.ParallelizeTestCollections = booleanValue;
                                    }
                                    if (string.Equals(propertyName, Configuration.PreEnumerateTheories, StringComparison.OrdinalIgnoreCase))
                                    {
                                        result.PreEnumerateTheories = booleanValue;
                                    }
                                }
                                else if (string.Equals(propertyName, Configuration.MaxParallelThreads, StringComparison.OrdinalIgnoreCase))
                                {
                                    var numberValue = propertyValue as JsonNumber;
                                    if (numberValue != null)
                                    {
                                        int maxParallelThreads;
                                        if (int.TryParse(numberValue.Raw, out maxParallelThreads) && maxParallelThreads > 0)
                                        {
                                            result.MaxParallelThreads = maxParallelThreads;
                                        }
                                    }
                                }
                                else if (string.Equals(propertyName, Configuration.MethodDisplay, StringComparison.OrdinalIgnoreCase))
                                {
                                    var stringValue = propertyValue as JsonString;
                                    if (stringValue != null)
                                    {
                                        try
                                        {
                                            var methodDisplay = Enum.Parse(typeof(TestMethodDisplay), stringValue, true);
                                            result.MethodDisplay = (TestMethodDisplay)methodDisplay;
                                        }
                                        catch { }
                                    }
                                }
                            }
                        }

                    return(result);
                }
                catch { }
            }

            return(null);
        }