-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathTextSnapshotStrategy.cs
More file actions
65 lines (57 loc) · 2.59 KB
/
TextSnapshotStrategy.cs
File metadata and controls
65 lines (57 loc) · 2.59 KB
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
// ----------------------------------------------------------------------
// <copyright file="TextSnapshotStrategy.cs" company="Xavier Solau">
// Copyright © 2021-2026 Xavier Solau.
// Licensed under the MIT license.
// See LICENSE file in the project root for full license information.
// </copyright>
// ----------------------------------------------------------------------
using System.IO;
using System.Text;
using System.Threading.Tasks;
using DiffPlex.Renderer;
namespace SoloX.CodeQuality.Test.Helpers.Snapshot.Impl
{
/// <summary>
/// Provides a snapshot strategy for handling plain text files, supporting saving and comparing text-based
/// snapshots.
/// </summary>
/// <remarks>This class implements the ISnapshotStrategy interface for string-based snapshots, using the
/// ".txt" file extension. It is suitable for scenarios where snapshot data is represented as plain text, such as
/// generated code files or textual outputs.</remarks>
public class TextSnapshotStrategy : ISnapshotStrategy<string>
{
private readonly bool ignoreWhitespace;
private readonly bool ignoreCase;
private readonly Encoding encoding;
/// <inheritdoc/>
public string FileExtension => "txt";
public TextSnapshotStrategy(bool ignoreWhitespace = true, bool ignoreCase = false, Encoding? encoding = null)
{
this.ignoreWhitespace = ignoreWhitespace;
this.ignoreCase = ignoreCase;
this.encoding = encoding ?? Encoding.Default;
}
/// <inheritdoc/>
public Task SaveAsync(string snapshotFile, string snapshotData)
{
if (File.Exists(snapshotFile))
{
File.Delete(snapshotFile);
}
return File.WriteAllTextAsync(snapshotFile, snapshotData, this.encoding);
}
/// <inheritdoc/>
public async Task<CompareSnapshotResult<string>> CompareAsync(string snapshotReferenceFile, string snapshotData)
{
var referenceText = await File.ReadAllTextAsync(snapshotReferenceFile, this.encoding).ConfigureAwait(false);
var snapshotDiffs = UnidiffRenderer.GenerateUnidiff(
referenceText,
snapshotData,
oldFileName: "Snapshot reference",
newFileName: "Snapshot run",
ignoreWhitespace: this.ignoreWhitespace,
ignoreCase: this.ignoreCase);
return new CompareSnapshotResult<string>(IsDifferent: !string.IsNullOrEmpty(snapshotDiffs), DiffsData: snapshotDiffs, DiffsString: snapshotDiffs);
}
}
}