2
0

JsonTests.cs 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. using Jint.Native.Json;
  2. using Jint.Runtime;
  3. using Xunit;
  4. namespace Jint.Tests.Runtime
  5. {
  6. public class JsonTests
  7. {
  8. [Fact]
  9. public void CanParseTabsInProperties()
  10. {
  11. var engine = new Engine();
  12. const string script = @"JSON.parse(""{\""abc\\tdef\"": \""42\""}"");";
  13. var obj = engine.Evaluate(script).AsObject();
  14. Assert.True(obj.HasOwnProperty("abc\tdef"));
  15. }
  16. [Theory]
  17. [InlineData("{\"a\":1", "Unexpected end of JSON input at position 6")]
  18. [InlineData("{\"a\":1},", "Unexpected token ',' in JSON at position 7")]
  19. [InlineData("{1}", "Unexpected number in JSON at position 1")]
  20. [InlineData("{\"a\" \"a\"}", "Unexpected string in JSON at position 5")]
  21. [InlineData("{true}", "Unexpected token 'true' in JSON at position 1")]
  22. [InlineData("{null}", "Unexpected token 'null' in JSON at position 1")]
  23. [InlineData("{:}", "Unexpected token ':' in JSON at position 1")]
  24. [InlineData("\"\\xah\"", "Expected hexadecimal digit in JSON at position 4")]
  25. [InlineData("0123", "Unexpected token '1' in JSON at position 1")] // leading 0 (octal number) not allowed
  26. [InlineData("1e+A", "Unexpected token 'A' in JSON at position 3")]
  27. [InlineData("truE", "Unexpected token 'tru' in JSON at position 0")]
  28. [InlineData("nul", "Unexpected token 'nul' in JSON at position 0")]
  29. [InlineData("\"ab\t\"", "Invalid character in JSON at position 3")] // invalid char in string literal
  30. [InlineData("\"ab", "Unexpected end of JSON input at position 3")] // unterminated string literal
  31. [InlineData("alpha", "Unexpected token 'a' in JSON at position 0")]
  32. [InlineData("[1,\na]", "Unexpected token 'a' in JSON at position 4")] // multiline
  33. [InlineData("\x06", "Unexpected token '\x06' in JSON at position 0")] // control char
  34. public void ShouldReportHelpfulSyntaxErrorForInvalidJson(string json, string expectedMessage)
  35. {
  36. var engine = new Engine();
  37. var parser = new JsonParser(engine);
  38. var ex = Assert.ThrowsAny<JavaScriptException>(() =>
  39. {
  40. parser.Parse(json);
  41. });
  42. Assert.Equal(expectedMessage, ex.Message);
  43. var error = ex.Error as Native.Error.ErrorInstance;
  44. Assert.NotNull(error);
  45. Assert.Equal("SyntaxError", error.Get("name"));
  46. }
  47. }
  48. }