|
| 1 | +using System.Text.RegularExpressions; |
| 2 | +using Microsoft.VisualStudio.TestTools.UnitTesting; |
| 3 | + |
| 4 | +namespace Grand.Modules.Tests.Views; |
| 5 | + |
| 6 | +/// <summary> |
| 7 | +/// Razor turns <c><vc:...></c> into a tag helper only for the view components of an assembly |
| 8 | +/// the view registers with <c>@addTagHelper</c>. Any other <c><vc:...></c> compiles without a |
| 9 | +/// warning and reaches the browser as an empty unknown element, so the component never runs. |
| 10 | +/// </summary> |
| 11 | +[TestClass] |
| 12 | +public class ViewComponentTagTests |
| 13 | +{ |
| 14 | + private static readonly string Src = Path.Combine(Installer.RepositoryPaths.Root, "src"); |
| 15 | + private static readonly HashSet<string> SkippedFolders = ["bin", "obj", "node_modules", "wwwroot"]; |
| 16 | + |
| 17 | + [TestMethod] |
| 18 | + public void EveryVcTagResolvesToAComponentItsViewRegisters() |
| 19 | + { |
| 20 | + var components = ComponentAssemblies(); |
| 21 | + var problems = new List<string>(); |
| 22 | + var checkedTags = 0; |
| 23 | + |
| 24 | + foreach (var view in SourceFiles(Src, "*.cshtml")) |
| 25 | + { |
| 26 | + var tags = Regex.Matches(File.ReadAllText(view), "<vc:([a-z0-9-]+)") |
| 27 | + .Select(m => m.Groups[1].Value).Distinct().ToList(); |
| 28 | + if (tags.Count == 0) continue; |
| 29 | + |
| 30 | + var project = ProjectOf(view); |
| 31 | + var registered = RegisteredAssemblies(view, project.Dir); |
| 32 | + foreach (var tag in tags) |
| 33 | + { |
| 34 | + checkedTags++; |
| 35 | + if (!components.TryGetValue(tag, out var assemblies)) |
| 36 | + problems.Add($"{Path.GetRelativePath(Src, view)}: <vc:{tag}> matches no view component"); |
| 37 | + else if (!assemblies.Overlaps(registered)) |
| 38 | + problems.Add($"{Path.GetRelativePath(Src, view)}: <vc:{tag}> lives in {string.Join(", ", assemblies)}, " + |
| 39 | + $"which {project.Name} does not register with @addTagHelper"); |
| 40 | + } |
| 41 | + } |
| 42 | + |
| 43 | + Assert.IsTrue(checkedTags > 0, "No <vc:...> tag found, so the scan itself is broken"); |
| 44 | + Assert.AreEqual(0, problems.Count, Environment.NewLine + string.Join(Environment.NewLine, problems)); |
| 45 | + } |
| 46 | + |
| 47 | + [TestMethod] |
| 48 | + public void ComponentScan_FindsWidgetComponentsOfEveryPanel() |
| 49 | + { |
| 50 | + var components = ComponentAssemblies(); |
| 51 | + |
| 52 | + CollectionAssert.AreEquivalent(new[] { "Grand.Web.Common" }, components["widget"].ToList()); |
| 53 | + CollectionAssert.AreEquivalent(new[] { "Grand.Web.Admin" }, components["admin-widget"].ToList()); |
| 54 | + CollectionAssert.AreEquivalent(new[] { "Grand.Web.Store" }, components["store-widget"].ToList()); |
| 55 | + CollectionAssert.AreEquivalent(new[] { "Grand.Web.Vendor" }, components["vendor-widget"].ToList()); |
| 56 | + CollectionAssert.AreEquivalent(new[] { "Grand.Web" }, components["related-products"].ToList()); |
| 57 | + } |
| 58 | + |
| 59 | + //tag name -> assemblies that declare a view component with that name |
| 60 | + private static Dictionary<string, HashSet<string>> ComponentAssemblies() |
| 61 | + { |
| 62 | + var declaration = new Regex( |
| 63 | + @"(?:\[ViewComponent\(Name\s*=\s*""(?<name>[^""]+)""\)\]\s*)?public\s+(?:sealed\s+)?class\s+(?<class>\w+)(?:\s*:\s*(?<base>\w+))?"); |
| 64 | + var components = new Dictionary<string, HashSet<string>>(); |
| 65 | + foreach (var file in SourceFiles(Src, "*.cs").Where(f => !f.Contains($"{Path.DirectorySeparatorChar}Tests{Path.DirectorySeparatorChar}"))) |
| 66 | + foreach (Match m in declaration.Matches(File.ReadAllText(file))) |
| 67 | + { |
| 68 | + var className = m.Groups["class"].Value; |
| 69 | + var isComponent = m.Groups["name"].Success || className.EndsWith("ViewComponent") || |
| 70 | + m.Groups["base"].Value.EndsWith("ViewComponent"); |
| 71 | + if (!isComponent) continue; |
| 72 | + |
| 73 | + var name = m.Groups["name"].Success ? m.Groups["name"].Value : className[..^"ViewComponent".Length]; |
| 74 | + var tag = Regex.Replace(name, "(?<=[a-z0-9])(?=[A-Z])", "-").ToLowerInvariant(); |
| 75 | + if (!components.TryGetValue(tag, out var assemblies)) |
| 76 | + components[tag] = assemblies = []; |
| 77 | + assemblies.Add(ProjectOf(file).Name); |
| 78 | + } |
| 79 | + |
| 80 | + return components; |
| 81 | + } |
| 82 | + |
| 83 | + private static HashSet<string> RegisteredAssemblies(string view, string projectDir) |
| 84 | + { |
| 85 | + var assemblies = new HashSet<string>(); |
| 86 | + for (var dir = Path.GetDirectoryName(view); dir != null && dir.Length >= projectDir.Length; dir = Path.GetDirectoryName(dir)) |
| 87 | + { |
| 88 | + var imports = Path.Combine(dir, "_ViewImports.cshtml"); |
| 89 | + if (!File.Exists(imports)) continue; |
| 90 | + foreach (Match m in Regex.Matches(File.ReadAllText(imports), @"@addTagHelper\s+\*\s*,\s*([\w.]+)")) |
| 91 | + assemblies.Add(m.Groups[1].Value); |
| 92 | + } |
| 93 | + |
| 94 | + return assemblies; |
| 95 | + } |
| 96 | + |
| 97 | + private static (string Dir, string Name) ProjectOf(string file) |
| 98 | + { |
| 99 | + for (var dir = Path.GetDirectoryName(file); dir != null; dir = Path.GetDirectoryName(dir)) |
| 100 | + { |
| 101 | + var project = Directory.GetFiles(dir, "*.csproj").FirstOrDefault(); |
| 102 | + if (project != null) return (dir, Path.GetFileNameWithoutExtension(project)); |
| 103 | + } |
| 104 | + |
| 105 | + throw new InvalidOperationException($"{file} belongs to no project"); |
| 106 | + } |
| 107 | + |
| 108 | + private static IEnumerable<string> SourceFiles(string dir, string pattern) |
| 109 | + { |
| 110 | + foreach (var file in Directory.GetFiles(dir, pattern)) |
| 111 | + yield return file; |
| 112 | + foreach (var sub in Directory.GetDirectories(dir).Where(d => !SkippedFolders.Contains(Path.GetFileName(d)))) |
| 113 | + foreach (var file in SourceFiles(sub, pattern)) |
| 114 | + yield return file; |
| 115 | + } |
| 116 | +} |
0 commit comments