aboutsummaryrefslogtreecommitdiffstats
path: root/tests/Test_Qt.DotNet.Generator/Support/DiffAssert.cs
blob: a028698276d9b6607f63c8bbaabf491f359d7f3d (plain)
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
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
/***************************************************************************************************
 Copyright (C) 2025 The Qt Company Ltd.
 SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
***************************************************************************************************/

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using DiffPlex;
using DiffPlex.DiffBuilder;
using DiffPlex.DiffBuilder.Model;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Test_Qt.DotNet.Generator.Support
{
    internal enum DiffFormat
    {
        Unified /* Context, SideBySide */
    }

    internal static class DiffAssert
    {
        /// <summary>Optional sanitizer (e.g., strip timestamps/paths).</summary>
        internal static Func<string, string> Sanitize { get; set; } = s => s;

        /// <summary>
        /// Compare two strings in memory.
        /// </summary>
        internal static void ContentEquals(string actual, string expected, int contextLines = 3,
            DiffFormat format = DiffFormat.Unified)
        {
            var actualContent = Sanitize(NormalizeNewlines(actual));
            var expectedContent = Sanitize(NormalizeNewlines(expected));
            if (!string.Equals(expectedContent, actualContent, StringComparison.Ordinal))
                FailWithDiff(expectedContent, actualContent, contextLines, format);
        }

        /// <summary>
        /// Compare a string in memory against a file on disk.
        /// </summary>
        internal static void ContentEquals(string actual, FileInfo expected, int contextLines = 3,
            DiffFormat format = DiffFormat.Unified)
        {
            if (expected is not { Exists: true })
                Assert.Fail($"Expected file not found: {expected?.FullName ?? "<null>"}");

            var actualContent = Sanitize(NormalizeNewlines(actual));
            var expectedContent = Sanitize(NormalizeNewlines(File.ReadAllText(expected.FullName,
                new UTF8Encoding(encoderShouldEmitUTF8Identifier: false))));

            if (!string.Equals(expectedContent, actualContent, StringComparison.Ordinal))
                FailWithDiff(expectedContent, actualContent, contextLines, format);
        }

        private static string NormalizeNewlines(string text)
        {
            return string.IsNullOrEmpty(text) ? "" : text.Replace("\r\n", "\n").Replace('\r', '\n');
        }

        private static void FailWithDiff(string expected, string actual, int contextLines,
            DiffFormat format)
        {
            var diff = format switch
            {
                DiffFormat.Unified => BuildUnifiedDiff(expected, actual, contextLines),
                _ => throw new NotSupportedException($"Diff format '{format}' not implemented.")
            };
            Assert.Fail("Content mismatch:\n\n" + diff);
        }

        private static string BuildUnifiedDiff(string expected, string actual, int contextLines)
        {
            var differ = new Differ();
            var diffModel = new SideBySideDiffBuilder(differ).BuildDiffModel(expected, actual);

            var expectedLines = diffModel.OldText.Lines;
            var actualLines = diffModel.NewText.Lines;
            var maxLineCount = Math.Max(expectedLines.Count, actualLines.Count);

            var changedLineIndices = Enumerable.Range(0, maxLineCount)
                .Where(i =>
                {
                    var expectedLineType = i < expectedLines.Count
                        ? expectedLines[i].Type : ChangeType.Imaginary;
                    var actualLineType = i < actualLines.Count
                        ? actualLines[i].Type : ChangeType.Imaginary;
                    return expectedLineType != ChangeType.Unchanged
                        || actualLineType != ChangeType.Unchanged;
                })
                .ToArray();

            var diffBuilder = new StringBuilder();
            diffBuilder.AppendLine("--- a/expected");
            diffBuilder.AppendLine("+++ b/actual");

            if (changedLineIndices.Length == 0)
                return diffBuilder.ToString();

            for (var changedIndex = 0; changedIndex < changedLineIndices.Length;) {
                var hunkStart = Math.Max(changedLineIndices[changedIndex] - contextLines, 0);
                var hunkEnd = Math.Min(changedLineIndices[changedIndex] + contextLines,
                    maxLineCount - 1);

                // Merge adjacent hunks within context
                var nextChangedIndex = changedIndex + 1;
                while (nextChangedIndex < changedLineIndices.Length &&
                       changedLineIndices[nextChangedIndex] <= hunkEnd + contextLines) {
                    hunkEnd = Math.Min(changedLineIndices[nextChangedIndex] + contextLines,
                        maxLineCount - 1);
                    nextChangedIndex++;
                }

                var oldLineStart = FirstRealLineNumber(expectedLines, hunkStart);
                var newLineStart = FirstRealLineNumber(actualLines, hunkStart);
                var oldLineCount = CountRealLines(expectedLines, hunkStart, hunkEnd);
                var newLineCount = CountRealLines(actualLines, hunkStart, hunkEnd);

                diffBuilder.AppendLine($"@@ -{oldLineStart},{oldLineCount} +{newLineStart},"
                    + $"{newLineCount} @@");

                for (var lineIndex = hunkStart; lineIndex <= hunkEnd; lineIndex++) {
                    var expectedLine = lineIndex < expectedLines.Count
                        ? expectedLines[lineIndex]
                        : new DiffPiece("", ChangeType.Imaginary, lineIndex + 1);
                    var actualLine = lineIndex < actualLines.Count
                        ? actualLines[lineIndex]
                        : new DiffPiece("", ChangeType.Imaginary, lineIndex + 1);

                    if (expectedLine.Type == ChangeType.Unchanged
                        && actualLine.Type == ChangeType.Unchanged) {
                        diffBuilder.Append(' ').AppendLine(expectedLine.Text ?? "");
                        continue;
                    }

                    if (expectedLine.Type != ChangeType.Unchanged
                        && expectedLine.Type != ChangeType.Imaginary) {
                        diffBuilder.Append('-').AppendLine(expectedLine.Text ?? "");
                    }

                    if (actualLine.Type != ChangeType.Unchanged
                        && actualLine.Type != ChangeType.Imaginary) {
                        diffBuilder.Append('+').AppendLine(actualLine.Text ?? "");
                    }
                }

                changedIndex = nextChangedIndex;
            }

            return diffBuilder.ToString();
        }

        private static int FirstRealLineNumber(IReadOnlyList<DiffPiece> lines, int index)
        {
            // Search forward from the given index
            for (var i = index; i < lines.Count; ++i) {
                if (lines[i].Position.HasValue)
                    return lines[i].Position.Value;
            }

            // Search backward from the given index
            for (var i = Math.Min(index, lines.Count - 1); i >= 0; --i) {
                if (lines[i].Position.HasValue)
                    return lines[i].Position.Value + 1;
            }
            return 1; // Default if no real line is found
        }

        private static int CountRealLines(IReadOnlyList<DiffPiece> lines, int start, int end)
        {
            return Enumerable.Range(start, end - start + 1)
                .Count(i => i < lines.Count && lines[i].Position.HasValue);
        }
    }
}