TestCustomFormat.cs 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using PetaTest;
  6. using PetaJson;
  7. using System.IO;
  8. using System.Globalization;
  9. using System.Reflection;
  10. namespace TestCases
  11. {
  12. struct PointSimple
  13. {
  14. public int X;
  15. public int Y;
  16. private string FormatJson()
  17. {
  18. return string.Format("{0},{1}", X, Y);
  19. }
  20. private static PointSimple ParseJson(string literal)
  21. {
  22. var parts = literal.Split(',');
  23. if (parts.Length == 2)
  24. {
  25. return new PointSimple()
  26. {
  27. X = int.Parse(parts[0], CultureInfo.InvariantCulture),
  28. Y = int.Parse(parts[0], CultureInfo.InvariantCulture),
  29. };
  30. }
  31. throw new InvalidDataException("Invalid point");
  32. }
  33. }
  34. struct PointComplex
  35. {
  36. public int X;
  37. public int Y;
  38. private void FormatJson(IJsonWriter writer)
  39. {
  40. writer.WriteStringLiteral(string.Format("{0},{1}", X, Y));
  41. }
  42. private static PointComplex ParseJson(IJsonReader r)
  43. {
  44. if (r.GetLiteralKind() == LiteralKind.String)
  45. {
  46. var parts = ((string)r.GetLiteralString()).Split(',');
  47. if (parts.Length == 2)
  48. {
  49. var pt = new PointComplex()
  50. {
  51. X = int.Parse(parts[0], CultureInfo.InvariantCulture),
  52. Y = int.Parse(parts[0], CultureInfo.InvariantCulture),
  53. };
  54. r.NextToken();
  55. return pt;
  56. }
  57. }
  58. throw new InvalidDataException("Invalid point");
  59. }
  60. }
  61. [TestFixture]
  62. [Obfuscation(Exclude = true, ApplyToMembers = true)]
  63. public class TestCustomFormat
  64. {
  65. [Test]
  66. public void TestSimple()
  67. {
  68. var p = new PointSimple() { X = 10, Y = 20 };
  69. var json = Json.Format(p);
  70. Assert.AreEqual(json, "\"10,20\"");
  71. var p2 = Json.Parse<PointSimple>(json);
  72. Assert.Equals(p.X, p2.X);
  73. Assert.Equals(p.Y, p2.Y);
  74. }
  75. [Test]
  76. public void TestSimpleExceptionPassed()
  77. {
  78. Assert.Throws<JsonParseException>(() => Json.Parse<PointSimple>("\"10,20,30\""));
  79. }
  80. [Test]
  81. public void TestComplex()
  82. {
  83. var p = new PointComplex() { X = 10, Y = 20 };
  84. var json = Json.Format(p);
  85. Assert.AreEqual(json, "\"10,20\"");
  86. var p2 = Json.Parse<PointComplex>(json);
  87. Assert.Equals(p.X, p2.X);
  88. Assert.Equals(p.Y, p2.Y);
  89. }
  90. [Test]
  91. public void TestComplexExceptionPassed()
  92. {
  93. Assert.Throws<JsonParseException>(() => Json.Parse<PointComplex>("\"10,20,30\""));
  94. }
  95. }
  96. }