using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; namespace Luneraria.Core.Tests { /// /// JSON protocol of a suite run, identical for the .NET harness and the Unity Test Runner /// (docs/port/logs/u1/core-tests.json, docs/port/logs/u1_5/*.json). The target file comes from /// the environment variable LUNE_TEST_REPORT; without it nothing is written. /// public sealed class SuiteReport { readonly StringBuilder _suites = new StringBuilder(); int _count; public int Failures { get; private set; } public static string TargetPath { get { return Environment.GetEnvironmentVariable("LUNE_TEST_REPORT"); } } public void Add(CheckSuite suite, double seconds) { Failures += suite.Failures.Count; _suites.Append(_count == 0 ? "" : ",\n"); _count++; _suites.AppendFormat(CultureInfo.InvariantCulture, " {{\"suite\": \"{0}\", \"checks\": {1}, \"failures\": {2}, \"seconds\": {3:0.00}, \"failed\": [{4}], \"notes\": [{5}]}}", suite.Name, suite.Checks, suite.Failures.Count, seconds, Join(suite.Failures), Join(suite.Notes)); } public string ToJson(string runtime, string label) { var text = new StringBuilder("{\n \"suites\": [\n"); text.Append(_suites); text.Append("\n ],\n"); text.Append(" \"runtime\": \"" + Escape(runtime) + "\",\n"); text.Append(" \"label\": \"" + Escape(label) + "\",\n"); text.Append(" \"os\": \"" + Escape(System.Runtime.InteropServices.RuntimeInformation.OSDescription + " " + System.Runtime.InteropServices.RuntimeInformation.ProcessArchitecture) + "\"\n}\n"); return text.ToString(); } public void WriteTo(string path, string runtime, string label) { string directory = Path.GetDirectoryName(Path.GetFullPath(path)); if (!string.IsNullOrEmpty(directory)) Directory.CreateDirectory(directory); File.WriteAllText(path, ToJson(runtime, label)); } static string Join(List values) { var parts = new List(); foreach (string value in values) parts.Add("\"" + Escape(value) + "\""); return string.Join(", ", parts); } static string Escape(string value) { return value.Replace("\\", "\\\\").Replace("\"", "\\\"").Replace("\n", "\\n"); } } }