using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Http; using System.Text.RegularExpressions; using FitConnect.Encryption; using FitConnect.Models; using FluentAssertions; using Microsoft.IdentityModel.Tokens; using Newtonsoft.Json.Linq; using Newtonsoft.Json.Schema; using NUnit.Framework; using JsonSchema = NJsonSchema.JsonSchema; namespace BasicUnitTest; [TestFixture] public class JsonSchemaValidation { [OneTimeSetUp] public void OneTimeSetUp() { var jsonItems = File.ReadAllLines("events.txt"); _jsonData = jsonItems.Where(l => !l.StartsWith("#")) .Select(l => Base64UrlEncoder.Decode(l.Split('.')[1])) .ToList(); var schemaResponse = new HttpClient() .GetAsync( "https://schema.fitko.de/fit-connect/set-payload/1.0.0/set-payload.schema.json") .Result; _schemaJson = schemaResponse.Content.ReadAsStringAsync().Result; } private List<string> _jsonData = null!; private string _schemaJson = null!; [Test] [Ignore("Package does not support this yet")] public void NJson_ShouldPass() { var schema = JsonSchema.FromJsonAsync(_schemaJson).Result; _jsonData.ForEach(l => schema.Validate(l)); } [Test] public void JsonSchema_ShouldPass() { _jsonData.ForEach(l => { var jObject = JObject.Parse(l); var schema = JSchema.Parse(_schemaJson); var result = jObject.IsValid(schema); if (!result) Console.WriteLine(jObject.ToString()); else Console.WriteLine("OK"); result.Should().BeTrue(); }); } [Test] public void JsonSchema_ShouldFail() { var schema = JSchema.Parse(_schemaJson); JObject.Parse( "{\"sub\":\"submission:22a69c34-4ca4-43f7-a909-dcfe7f972c27\",\"$schema\":\"https://schema.fitko.de/fit-connect/set-payload/1.0.0/set-payload.schema.json\",\"iss\":\"https://submission-api-testing.fit-connect.fitko.dev\",\"txn\":\"case:5ef6d3c7-a9db-4b23-89a6-75f5011bd57a\",\"iat\":1661228799,\"jti\":\"c7ff0d9d-2caa-481d-b9ce-c6d4a1c6ee02\",\"event\":{\"https://schema.fitko.de/fit-connect/events/submit-submission\":{\"authenticationTags\":{\"data\":\"6hvHPpXSgRfeFAUWJRb5eQ\",\"metadata\":\"T_kVHCwoMCpg42c3CjeZAQ\",\"attachments\":{\"33b17890-2a86-47a4-8fb9-92befc782e13\":\"DxndA7vZAq_karEDRL31-Q\"}}}}}") .IsValid(schema).Should().BeFalse(); } [Test] public void JsonSchemaOfMetadataInResourcesShouldMatchSchemaUriString() { var schema = JSchema.Parse(JsonHelper.LoadContentOfResource("metadata.schema.json")); schema.Id.Should().Be(Metadata.SchemaUrl); new Regex(Metadata.SchemaPattern).IsMatch(Metadata.SchemaUrl).Should().BeTrue(); } }