forked from tiadrop/face
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathJsonTest.cs
161 lines (140 loc) · 7.41 KB
/
JsonTest.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using Lantern.Face.Json;
namespace face.demo {
public static class JsonTest {
public static void Run() {
var bm = new Benchmarker("JSON");
if (File.Exists(compareDataFilename))
bm.PreviousData = JsValue.FromJson(File.ReadAllText(compareDataFilename));
bm.TimeLimitMs = 3000;
bm.Participants["Utf8Json"] = data => Utf8Json.JsonSerializer.Deserialize<object>(data as string);
bm.Participants["System.Text"] = data => System.Text.Json.JsonSerializer.Deserialize<object>(data as string);
bm.Participants["Newtonsoft"] = data => Newtonsoft.Json.JsonConvert.DeserializeObject<object>(data as string);
bm.Participants["Face.Json"] = data => JsValue.FromJson(data as string);
bm.Tests.Add("hardcoded_example", new Benchmarker.Test {
Remark = "basic example test",
Action = (run, data) => run("[2, 4,6, 8, null, 3.142]") // called for each bm.Participants["..."] as run, data is from Setup:
// Setup: () => "eg data" // called once per Test before iterating participants
});
// load the rest from testidx.json
JsValue[] testIndex = JsValue.FromJson(File.ReadAllText("demo/testidx.json"), true);
foreach (var testSpec in testIndex) {
if (testSpec.ContainsKey("filename") && !File.Exists(testSpec["filename"])) {
Console.WriteLine($"Missing test source '{testSpec["filename"]}'");
continue;
}
Func<object> setup;
string testRef;
string remark;
if (testSpec.IsString) {
var displayJson = testSpec.StringValue.Replace("\n", "␊").Replace("\r", "");
if (displayJson.Length > 24) displayJson = displayJson.Substring(0, 21) + "...";
remark = $"{formatFileSize(testSpec.StringValue.Length)} ━ '{displayJson}'";
setup = () => testSpec.StringValue;
testRef = testSpec.StringValue;
} else if (testSpec.ContainsKey("filename")) {
string filename = testSpec["filename"];
var length = new FileInfo(filename).Length;
testRef = testSpec["filename"].StringValue.Split("/").Last();
setup = () => File.ReadAllText(filename);
remark = $"{formatFileSize(length)} ━ {testSpec.PropertyValueOr("remark", testRef)}";
} else {
string json = testSpec["json"];
var md5 = System.Security.Cryptography.MD5.Create();
testRef = string.Join("", md5.ComputeHash(System.Text.Encoding.UTF8.GetBytes(json)).Select(b => $"{b:X}"));
setup = () => json;
var displayJson = json.Replace("\n", "␊").Replace("\r", "");
if (displayJson.Length > 24) displayJson = displayJson.Substring(0, 21) + "...";
remark =
$"{formatFileSize(json.Length)} ━ {testSpec.PropertyValueOr("remark", testRef.Substring(0, 6))} ━ '{displayJson}'";
}
bm.Tests[testRef] = new Benchmarker.Test {
Remark = remark,
//Action = (run, data) => run(data), // this is now the default action
Setup = setup // result passed to Action as data
};
}
File.WriteAllText(logFilename, "");
Thread.Sleep(1000);
bm.Run((s, col) => {
Console.ForegroundColor = col;
Console.Write(s);
var writer = File.AppendText(logFilename);
writer.WriteAsync(s);
writer.Close();
});
File.WriteAllText(compareDataFilename, bm.PreviousData.ToJson(true));
}
private const string logFilename = "jsonbenchmark.log";
private const string compareDataFilename = "benchmarkStandard.json";
private static string formatFileSize(long size) {
string unit = "b";
double newSize = Convert.ToDouble(size);
if (newSize > 1024) {
unit = "kb";
newSize /= 1024;
}
if (newSize > 1024) {
unit = "mb";
newSize /= 1024;
}
if (newSize > 1024) {
unit = "gb"; // lofl
newSize /= 1024;
}
return $"{newSize:F0}{unit}";
}
/// <summary>
/// Attempts to parse all .json files in the given directory. Files beginning with 'y' are expected to parse without error, 'n' to fail and anything else to either parse or fail.
/// </summary>
/// <param name="pathToJsonFiles"></param>
/// <param name="showPass">True to output all test results, false to only show failures</param>
/// <param name="filter">Limits tests to filenames containing this string</param>
public static void RunSuite(string pathToJsonFiles, bool showPass, string filter = "") {
var filenames = Directory.GetFiles(pathToJsonFiles);
foreach (var filename in filenames) {
if(!filename.Contains(filter)) continue;
string content = File.ReadAllText(filename);
var basename = filename.Split("/").Last();
basename += " " + (content.Length > 32 ? content.Substring(0, 32) + "..." : content);
var expectSuccess = basename[0] == 'y';
var expectFailure = basename[0] == 'n';
try {
JsValue.FromJson(content);
} catch (Exception e) {
if (expectSuccess) {
Console.WriteLine("** FAILED ** - " + basename + " - " + RenderException(e));
} else if (expectFailure) {
if(showPass) Console.WriteLine("Pass (expected error) - " + basename + " - " + RenderException(e));
} else {
if(showPass) Console.WriteLine("Pass (optional, thrown) - " + basename + " - " + RenderException(e));
}
continue;
}
if (expectSuccess) {
if(showPass) Console.WriteLine("Pass (expected success) - " + basename);
} else if (expectFailure) {
Console.WriteLine("** FAILED ** (expected error) - " + basename);
Console.WriteLine(content);
} else {
if(showPass) Console.WriteLine("Pass (optional) - " + basename);
}
}
}
public static string RenderException(Exception e) {
List<string> result = new List<string>{$"{e.GetType().Name}: {e.Message}"};
while (e.InnerException != null) {
e = e.InnerException;
result.Add($"{e.GetType().Name}: {e.Message}");
}
return string.Join(" ⟶ ", result);
}
private static void assert(bool cond, string remark) {
if(!cond) Console.WriteLine($"** ASSERTION FAILED ** {remark}");
}
}
}