| | | 1 | | using System.Text.Json; |
| | | 2 | | |
| | | 3 | | namespace Nabs.Tests; |
| | | 4 | | |
| | | 5 | | [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)] |
| | | 6 | | public class LoadEnumerableFromJsonDataAttribute<T> : DataAttribute |
| | | 7 | | where T : notnull, new() |
| | | 8 | | { |
| | | 9 | | private readonly Type _relativeAssemblyType; |
| | | 10 | | private readonly string _resourceFilePathEndsWith; |
| | | 11 | | private readonly EmbeddedResourceLoader _resourceLoader; |
| | | 12 | | private readonly JsonSerializerOptions _jsonSerializerOptions; |
| | | 13 | | |
| | 2 | 14 | | public LoadEnumerableFromJsonDataAttribute(Type relativeAssemblyType, string resourceFilePathEndsWith) |
| | | 15 | | { |
| | 2 | 16 | | _relativeAssemblyType = relativeAssemblyType; |
| | 2 | 17 | | _resourceFilePathEndsWith = resourceFilePathEndsWith; |
| | 2 | 18 | | _resourceLoader = new EmbeddedResourceLoader(_relativeAssemblyType); |
| | 2 | 19 | | _jsonSerializerOptions = GlobalSettings.JsonSerializerOptions; |
| | 2 | 20 | | } |
| | | 21 | | |
| | | 22 | | public override IEnumerable<object[]> GetData(MethodInfo testMethod) |
| | | 23 | | { |
| | 4 | 24 | | var items = _resourceLoader.GetResourceStreamContent(x => x.Path.EndsWith(_resourceFilePathEndsWith)) |
| | 2 | 25 | | .Match( |
| | 2 | 26 | | content => |
| | 2 | 27 | | { |
| | 2 | 28 | | var streamReader = new StreamReader(content); |
| | 2 | 29 | | var records = JsonSerializer.Deserialize<T[]>(streamReader.ReadToEnd(), _jsonSerializerOptions)!; |
| | 4 | 30 | | var data = records.Select(x => new object[] { x }); |
| | 2 | 31 | | return data; |
| | 2 | 32 | | }, |
| | 2 | 33 | | exception => |
| | 2 | 34 | | { |
| | 1 | 35 | | throw exception; |
| | 2 | 36 | | }); |
| | | 37 | | |
| | 6 | 38 | | foreach (var item in items) |
| | | 39 | | { |
| | 2 | 40 | | yield return item; |
| | | 41 | | } |
| | 2 | 42 | | } |
| | | 43 | | } |