From 32483f8bd36adab67bd129bc99831f467018f06e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20P=C3=B6tzl?= Date: Mon, 16 Nov 2026 12:44:40 +0100 Subject: [PATCH 1/5] Add accunit-tests skill, install tool and short server instructions --- .github/workflows/build.yml | 4 +- .../AccessCodeLib.AccUnit.McpServer.csproj | 5 + mcp-server/AccUnit.McpServer/Program.cs | 16 +- .../AccUnit.McpServer/SkillInstaller.cs | 161 ++++++++++++++++++ mcp-server/AccUnit.McpServer/SkillTools.cs | 39 +++++ .../AccUnit.McpServer/TestAuthoringGuide.cs | 26 +++ mcp-server/AccUnit.McpServer/TestTools.cs | 6 +- mcp-server/README.md | 25 +++ .../SkillInstallerTests.cs | 135 +++++++++++++++ .../TestAuthoringGuideTests.cs | 58 +++++++ mcp-server/skills/accunit-tests/SKILL.md | 71 ++++++++ 11 files changed, 538 insertions(+), 8 deletions(-) create mode 100644 mcp-server/AccUnit.McpServer/SkillInstaller.cs create mode 100644 mcp-server/AccUnit.McpServer/SkillTools.cs create mode 100644 mcp-server/AccUnit.McpServer/TestAuthoringGuide.cs create mode 100644 mcp-server/Tests/AccUnit.McpServer.Tests/SkillInstallerTests.cs create mode 100644 mcp-server/Tests/AccUnit.McpServer.Tests/TestAuthoringGuideTests.cs create mode 100644 mcp-server/skills/accunit-tests/SKILL.md diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index f4988d4..87d523c 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -135,10 +135,12 @@ jobs: run: | $serverDir = "mcp-server\AccUnit.McpServer\bin\Release\net48" if (-not (Test-Path "$serverDir\AccUnit.McpServer.exe")) { throw "AccUnit.McpServer.exe not found in $serverDir" } + if (-not (Test-Path "$serverDir\skills\accunit-tests\SKILL.md")) { throw "Skill accunit-tests not found in $serverDir\skills" } $files = @(Get-ChildItem -Path $serverDir -File | Where-Object { $_.Extension -ne '.pdb' }) $files | Format-Table Name, Length, LastWriteTime $zipFile = "build\AccUnit.McpServer.$env:VERSION.zip" - Compress-Archive -Path $files.FullName -DestinationPath $zipFile -Force + # The folder skills (skill accunit-tests) is installed with the tool accunit_install_skill + Compress-Archive -Path (@($files.FullName) + "$serverDir\skills") -DestinationPath $zipFile -Force # The artifact name is used by release.yml - name: "Upload MCP server zip" diff --git a/mcp-server/AccUnit.McpServer/AccessCodeLib.AccUnit.McpServer.csproj b/mcp-server/AccUnit.McpServer/AccessCodeLib.AccUnit.McpServer.csproj index 6f74aa2..4d17028 100644 --- a/mcp-server/AccUnit.McpServer/AccessCodeLib.AccUnit.McpServer.csproj +++ b/mcp-server/AccUnit.McpServer/AccessCodeLib.AccUnit.McpServer.csproj @@ -39,4 +39,9 @@ + + + + + diff --git a/mcp-server/AccUnit.McpServer/Program.cs b/mcp-server/AccUnit.McpServer/Program.cs index 7ca95cb..e6911a0 100644 --- a/mcp-server/AccUnit.McpServer/Program.cs +++ b/mcp-server/AccUnit.McpServer/Program.cs @@ -22,16 +22,22 @@ private static async Task Main(string[] args) builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddSingleton(); + builder.Services.AddSingleton(_ => new SkillInstaller()); builder.Services - .AddMcpServer(options => options.ServerInfo = new Implementation + .AddMcpServer(options => { - Name = ServerName, - // The server is released together with AccUnit and uses its version. - Version = typeof(AccessCodeLib.AccUnit.Interop.AccUnitFactory).Assembly.GetName().Version.ToString(3) + options.ServerInfo = new Implementation + { + Name = ServerName, + // The server is released together with AccUnit and uses its version. + Version = typeof(AccessCodeLib.AccUnit.Interop.AccUnitFactory).Assembly.GetName().Version.ToString(3) + }; + options.ServerInstructions = TestAuthoringGuide.Text; }) .WithStdioServerTransport() .WithTools() - .WithTools(); + .WithTools() + .WithTools(); await builder.Build().RunAsync(); } diff --git a/mcp-server/AccUnit.McpServer/SkillInstaller.cs b/mcp-server/AccUnit.McpServer/SkillInstaller.cs new file mode 100644 index 0000000..da3f78d --- /dev/null +++ b/mcp-server/AccUnit.McpServer/SkillInstaller.cs @@ -0,0 +1,161 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; + +namespace AccessCodeLib.AccUnit.McpServer +{ + /// + /// Installs the skill accunit-tests that is shipped with the server (folder skills next to the exe) + /// into a project or the user profile. An installed skill is never overwritten without overwrite = true, + /// because it may contain local improvements; overwritten files are backed up first. + /// + public sealed class SkillInstaller + { + public const string TargetClaude = "claude"; + public const string TargetAgents = "agents"; + public const string ScopeProject = "project"; + public const string ScopeUser = "user"; + + private const string BackupExtension = ".bak"; + private static readonly Dictionary TargetFolders = new Dictionary(StringComparer.OrdinalIgnoreCase) + { + { TargetClaude, ".claude" }, // Claude Code (also read by Copilot) + { TargetAgents, ".agents" } // Codex, GitHub Copilot, Gemini CLI + }; + + private readonly string _bundledSkillDirectory; + private readonly string _userProfileDirectory; + + public SkillInstaller() + : this(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "skills", TestAuthoringGuide.SkillName), + Environment.GetFolderPath(Environment.SpecialFolder.UserProfile)) + { + } + + public SkillInstaller(string bundledSkillDirectory, string userProfileDirectory) + { + _bundledSkillDirectory = bundledSkillDirectory; + _userProfileDirectory = userProfileDirectory; + } + + public string GetTargetDirectory(string target, string scope, string projectPath) + { + if (string.IsNullOrWhiteSpace(target) || !TargetFolders.TryGetValue(target, out var agentFolder)) + throw new DatabaseSessionException("Unknown target '" + target + "'. Allowed: " + TargetClaude + ", " + TargetAgents + "."); + + string baseDirectory; + if (string.Equals(scope, ScopeUser, StringComparison.OrdinalIgnoreCase)) + { + baseDirectory = _userProfileDirectory; + } + else if (string.IsNullOrWhiteSpace(scope) || string.Equals(scope, ScopeProject, StringComparison.OrdinalIgnoreCase)) + { + baseDirectory = GetCheckedProjectDirectory(projectPath); + } + else + { + throw new DatabaseSessionException("Unknown scope '" + scope + "'. Allowed: " + ScopeProject + ", " + ScopeUser + "."); + } + + return Path.Combine(baseDirectory, agentFolder, "skills", TestAuthoringGuide.SkillName); + } + + public SkillInstallResult Install(string target, string scope, string projectPath, bool overwrite) + { + var sourceFiles = GetBundledSkillFiles(); + var targetDirectory = GetTargetDirectory(target, scope, projectPath); + var result = new SkillInstallResult { TargetDirectory = targetDirectory }; + + var existingFiles = sourceFiles.Where(file => File.Exists(GetTargetFile(file, targetDirectory))).ToList(); + var differingFiles = existingFiles.Where(file => !FilesAreEqual(file, GetTargetFile(file, targetDirectory))).ToList(); + + if (existingFiles.Count == 0) + { + CopyFiles(sourceFiles, targetDirectory, result); + result.Status = SkillInstallStatus.Installed; + } + else if (differingFiles.Count == 0 && existingFiles.Count == sourceFiles.Count) + { + result.Status = SkillInstallStatus.UpToDate; + } + else if (!overwrite) + { + result.Status = SkillInstallStatus.AlreadyInstalledDifferent; + result.Message = "The installed skill differs from the version shipped with the server (it may contain local changes). " + + "Nothing was changed; use overwrite = true to replace it (a backup is made)."; + } + else + { + foreach (var file in differingFiles) + { + var targetFile = GetTargetFile(file, targetDirectory); + var backupFile = targetFile + BackupExtension; + File.Copy(targetFile, backupFile, true); + result.BackupFiles.Add(backupFile); + } + CopyFiles(sourceFiles, targetDirectory, result); + result.Status = SkillInstallStatus.Updated; + } + return result; + } + + private List GetBundledSkillFiles() + { + if (!Directory.Exists(_bundledSkillDirectory)) + throw new DatabaseSessionException("The skill shipped with the server was not found: " + _bundledSkillDirectory); + return Directory.GetFiles(_bundledSkillDirectory, "*", SearchOption.AllDirectories).ToList(); + } + + private static string GetCheckedProjectDirectory(string projectPath) + { + if (string.IsNullOrWhiteSpace(projectPath)) + throw new DatabaseSessionException("projectPath is required for scope project (the root directory of the project)."); + if (!Path.IsPathRooted(projectPath)) + throw new DatabaseSessionException("projectPath must be an absolute path."); + var fullPath = Path.GetFullPath(projectPath); + if (!Directory.Exists(fullPath)) + throw new DatabaseSessionException("The project directory does not exist: " + fullPath); + return fullPath; + } + + private string GetTargetFile(string sourceFile, string targetDirectory) + { + var relativePath = sourceFile.Substring(_bundledSkillDirectory.TrimEnd(Path.DirectorySeparatorChar).Length + 1); + return Path.Combine(targetDirectory, relativePath); + } + + private void CopyFiles(IEnumerable sourceFiles, string targetDirectory, SkillInstallResult result) + { + foreach (var file in sourceFiles) + { + var targetFile = GetTargetFile(file, targetDirectory); + Directory.CreateDirectory(Path.GetDirectoryName(targetFile)); + File.Copy(file, targetFile, true); + result.Files.Add(targetFile); + } + } + + private static bool FilesAreEqual(string file1, string file2) + { + return File.ReadAllBytes(file1).SequenceEqual(File.ReadAllBytes(file2)); + } + } + + public enum SkillInstallStatus + { + Installed, + UpToDate, + AlreadyInstalledDifferent, + Updated + } + + public class SkillInstallResult + { + public SkillInstallStatus Status { get; set; } + public string TargetDirectory { get; set; } + public List Files { get; set; } = new List(); + public List BackupFiles { get; set; } = new List(); + public string Message { get; set; } + } +} diff --git a/mcp-server/AccUnit.McpServer/SkillTools.cs b/mcp-server/AccUnit.McpServer/SkillTools.cs new file mode 100644 index 0000000..39903e8 --- /dev/null +++ b/mcp-server/AccUnit.McpServer/SkillTools.cs @@ -0,0 +1,39 @@ +using System.ComponentModel; +using ModelContextProtocol; +using ModelContextProtocol.Server; + +namespace AccessCodeLib.AccUnit.McpServer +{ + [McpServerToolType] + public class SkillTools + { + private readonly SkillInstaller _skillInstaller; + + public SkillTools(SkillInstaller skillInstaller) + { + _skillInstaller = skillInstaller; + } + + [McpServerTool(Name = "accunit_install_skill")] + [Description("Installs the skill accunit-tests (guide for writing and running AccUnit tests) shipped with this server. " + + "target \"claude\": .claude/skills (Claude Code, also read by GitHub Copilot); target \"agents\": .agents/skills " + + "(Codex, GitHub Copilot, Gemini CLI). scope \"project\" (default) installs into the project directory, so the skill is " + + "only active in projects that use AccUnit; scope \"user\" installs into the user profile. An installed skill is not " + + "overwritten unless overwrite = true (it may contain local improvements); changed files are backed up as .bak first.")] + public SkillInstallResult InstallSkill( + [Description("\"claude\" or \"agents\".")] string target = SkillInstaller.TargetClaude, + [Description("\"project\" (default) or \"user\".")] string scope = SkillInstaller.ScopeProject, + [Description("Absolute path of the project root directory (required for scope \"project\").")] string projectPath = null, + [Description("Replace an installed skill that differs from the shipped version (backup as .bak).")] bool overwrite = false) + { + try + { + return _skillInstaller.Install(target, scope, projectPath, overwrite); + } + catch (DatabaseSessionException ex) + { + throw new McpException(ex.Message); + } + } + } +} diff --git a/mcp-server/AccUnit.McpServer/TestAuthoringGuide.cs b/mcp-server/AccUnit.McpServer/TestAuthoringGuide.cs new file mode 100644 index 0000000..1fbdf47 --- /dev/null +++ b/mcp-server/AccUnit.McpServer/TestAuthoringGuide.cs @@ -0,0 +1,26 @@ +namespace AccessCodeLib.AccUnit.McpServer +{ + /// + /// Server instructions sent to every MCP client. Kept short: the full guide is the skill accunit-tests + /// (skills/accunit-tests/SKILL.md). Only the rules that depend on the AccUnit core are repeated here, + /// so clients without skill support get them as well. + /// + public static class TestAuthoringGuide + { + public const string SkillName = "accunit-tests"; + + public const string Text = +@"AccUnit MCP server: run and write AccUnit tests for the VBA code of a Microsoft Access database. + +Use the skill accunit-tests for writing and running tests. If it is not available in the project, offer to install it +with accunit_install_skill (target ""claude"" for Claude Code, ""agents"" for Codex, Copilot and Gemini). + +Essential rules if the skill is not available: +- For methods with parameters prefer ONE row test with several 'AccUnit:Row(inputs..., expected).Name(""case"") lines + above the test Sub over one test per case. +- Row values are VB.NET expressions, not VBA: no constants or enums of the own VBA project (use the numeric value), + no VBA functions (dates: System.Convert.ToDateTime(""2014-05-16"")), Array(...) only as the only value of a row. +- Iz.EqualTo distinguishes vbNullString and """". +- Write the tests from the specification, not from the implementation; add test classes through the source files."; + } +} diff --git a/mcp-server/AccUnit.McpServer/TestTools.cs b/mcp-server/AccUnit.McpServer/TestTools.cs index 6a0bce4..9b9596e 100644 --- a/mcp-server/AccUnit.McpServer/TestTools.cs +++ b/mcp-server/AccUnit.McpServer/TestTools.cs @@ -27,8 +27,10 @@ public TestTools(TestRunService testRunService, TestClassDraftService testClassD "do not just confirm the current behavior; if the specification is unclear, ask the developer. " + "Test names: the recommended pattern is MethodUnderTest_StateUnderTest_ExpectedBehaviour (replace the placeholders); " + "it is a recommendation, leave out parts that add nothing (e.g. NetPrice_ReturnsZeroForZero). " + - "Row tests: 'AccUnit:Row(arg1, arg2, expected).Name(\"case name\") above the test method; arguments are literals: " + - "strings in double quotes, numbers with decimal point, True/False, Null, Array(...), VBA or enum constants. " + + "Methods with parameters get a row test skeleton: write one 'AccUnit:Row(inputs..., expected).Name(\"case\") line per case " + + "(normal case, boundaries, invalid input, Null) instead of separate test methods. Row values are VB.NET expressions, not VBA: " + + "no constants or enums of the own VBA project (use the numeric value), no VBA functions (dates: " + + "System.Convert.ToDateTime(\"2014-05-16\")); see the server instructions for an example. " + "Add the finished class through the source files (e.g. msaccess-vcs import), not by writing into the database.")] public TestClassDraft GenerateTestClass( [Description("Name of the standard module or class module under test.")] string moduleName, diff --git a/mcp-server/README.md b/mcp-server/README.md index 9edebbe..355ef79 100644 --- a/mcp-server/README.md +++ b/mcp-server/README.md @@ -59,6 +59,7 @@ Start `AccUnit.McpServer.exe` as a stdio server without arguments. Log output go | `accunit_run_tests` | `classNames`, `testNameFilter`, `tags`, `includePassed` (default `false`) | Runs the tests; returns a summary and the failed, error and ignored tests. | | `accunit_generate_test_class` | `moduleName`, `methodNames` | Draft of a test class for a module: code skeleton plus declaration and comment of each method under test. Writes nothing to the database. | | `accunit_remove_test_environment` | `removeTestModules` (default `false`), `exportBeforeRemoving` (default `true`) | Removes the test environment like the VBE add-in menu item; optionally also the test classes (exported first). | +| `accunit_install_skill` | `target` (`claude`/`agents`), `scope` (`project`/`user`), `projectPath`, `overwrite` (default `false`) | Installs the skill `accunit-tests` shipped with the server (see below). | ### Writing tests with `accunit_generate_test_class` @@ -68,6 +69,30 @@ If the specification is unclear, the agent should ask the developer. The recommended test name pattern is `MethodUnderTest_StateUnderTest_ExpectedBehaviour`; parts that add nothing may be left out. The finished test class is added through the source files (e.g. msaccess-vcs import), not written into the database by the server. +## Skill `accunit-tests` + +The guide for writing and running AccUnit tests is the skill `accunit-tests` (`skills/accunit-tests/SKILL.md`, +portable Agent Skills format). Agents load it only when they work on AccUnit tests. It asks for row tests for methods +with parameters and explains the rules for row values: AccUnit compiles them as VB.NET expressions, so constants and +enums of the own VBA project and VBA functions are not available (use numeric values and .NET expressions such as +`System.Convert.ToDateTime("2014-05-16")`), and `Array(...)` works only as the only value of a row. + +Install it with `accunit_install_skill` or copy the folder `skills/accunit-tests` from the zip: + +| `target` | `scope` = `project` (default) | `scope` = `user` | Used by | +|---|---|---|---| +| `claude` | `\.claude\skills\accunit-tests` | `%USERPROFILE%\.claude\skills\accunit-tests` | Claude Code (also GitHub Copilot) | +| `agents` | `\.agents\skills\accunit-tests` | `%USERPROFILE%\.agents\skills\accunit-tests` | Codex, GitHub Copilot, Gemini CLI | + +With `scope` = `project` the skill is only active in the Access projects that use AccUnit and can be committed with the +project. An installed skill is not overwritten unless `overwrite` = `true` (it may contain local improvements); +changed files are backed up as `.bak` first. Improvements made locally can be brought back into this repository. + +The server also sends short MCP server instructions with the essential rules, for clients without skill support +(source: `AccUnit.McpServer/TestAuthoringGuide.cs`). + +A larger example of row tests: [SqlToolsBuildCriteriaTests.cls](https://github.com/AccessCodeLib/AccessCodeLib/blob/master/_test/data/SqlToolsBuildCriteriaTests.cls) in the AccessCodeLib repository. + ## Behavior and changes to the database - **One database at a time**, opened exclusively in an Access instance started by the server; the server never uses diff --git a/mcp-server/Tests/AccUnit.McpServer.Tests/SkillInstallerTests.cs b/mcp-server/Tests/AccUnit.McpServer.Tests/SkillInstallerTests.cs new file mode 100644 index 0000000..f6ddf59 --- /dev/null +++ b/mcp-server/Tests/AccUnit.McpServer.Tests/SkillInstallerTests.cs @@ -0,0 +1,135 @@ +using System; +using System.IO; +using NUnit.Framework; + +namespace AccessCodeLib.AccUnit.McpServer.Tests +{ + public class SkillInstallerTests + { + private string _root; + private string _bundled; + private string _userProfile; + private string _project; + private SkillInstaller _installer; + + [SetUp] + public void SetUp() + { + _root = Path.Combine(Path.GetTempPath(), "AccUnitSkillInstallerTests", Guid.NewGuid().ToString("N")); + _bundled = Path.Combine(_root, "server", "skills", "accunit-tests"); + _userProfile = Path.Combine(_root, "user"); + _project = Path.Combine(_root, "project"); + Directory.CreateDirectory(_bundled); + Directory.CreateDirectory(_userProfile); + Directory.CreateDirectory(_project); + File.WriteAllText(Path.Combine(_bundled, "SKILL.md"), "shipped"); + _installer = new SkillInstaller(_bundled, _userProfile); + } + + [TearDown] + public void TearDown() + { + Directory.Delete(_root, true); + } + + [TestCase("claude", ".claude")] + [TestCase("agents", ".agents")] + [TestCase("CLAUDE", ".claude")] + public void GetTargetDirectory_ProjectScope_UsesAgentFolderInProject(string target, string agentFolder) + { + var directory = _installer.GetTargetDirectory(target, "project", _project); + + Assert.That(directory, Is.EqualTo(Path.Combine(_project, agentFolder, "skills", "accunit-tests"))); + } + + [Test] + public void GetTargetDirectory_UserScope_UsesUserProfile() + { + var directory = _installer.GetTargetDirectory("agents", "user", null); + + Assert.That(directory, Is.EqualTo(Path.Combine(_userProfile, ".agents", "skills", "accunit-tests"))); + } + + [Test] + public void GetTargetDirectory_DefaultScope_IsProject() + { + Assert.That(_installer.GetTargetDirectory("claude", null, _project), Does.StartWith(_project)); + } + + [TestCase("copilot", "project")] + [TestCase("claude", "global")] + public void GetTargetDirectory_UnknownTargetOrScope_Throws(string target, string scope) + { + Assert.Throws(() => _installer.GetTargetDirectory(target, scope, _project)); + } + + [TestCase(null)] + [TestCase("relative\\project")] + public void GetTargetDirectory_ProjectScopeWithoutAbsolutePath_Throws(string projectPath) + { + Assert.Throws(() => _installer.GetTargetDirectory("claude", "project", projectPath)); + } + + [Test] + public void GetTargetDirectory_MissingProjectDirectory_Throws() + { + var missing = Path.Combine(_root, "missing"); + + Assert.Throws(() => _installer.GetTargetDirectory("claude", "project", missing)); + } + + [Test] + public void Install_NotInstalled_CopiesSkill() + { + var result = _installer.Install("claude", "project", _project, false); + + Assert.That(result.Status, Is.EqualTo(SkillInstallStatus.Installed)); + Assert.That(File.ReadAllText(Path.Combine(result.TargetDirectory, "SKILL.md")), Is.EqualTo("shipped")); + } + + [Test] + public void Install_SameContent_IsUpToDate() + { + _installer.Install("claude", "project", _project, false); + + var result = _installer.Install("claude", "project", _project, false); + + Assert.That(result.Status, Is.EqualTo(SkillInstallStatus.UpToDate)); + } + + [Test] + public void Install_LocallyChangedWithoutOverwrite_KeepsLocalChanges() + { + var first = _installer.Install("claude", "project", _project, false); + var skillFile = Path.Combine(first.TargetDirectory, "SKILL.md"); + File.WriteAllText(skillFile, "local improvement"); + + var result = _installer.Install("claude", "project", _project, false); + + Assert.That(result.Status, Is.EqualTo(SkillInstallStatus.AlreadyInstalledDifferent)); + Assert.That(File.ReadAllText(skillFile), Is.EqualTo("local improvement")); + } + + [Test] + public void Install_LocallyChangedWithOverwrite_ReplacesAndBacksUp() + { + var first = _installer.Install("claude", "project", _project, false); + var skillFile = Path.Combine(first.TargetDirectory, "SKILL.md"); + File.WriteAllText(skillFile, "local improvement"); + + var result = _installer.Install("claude", "project", _project, true); + + Assert.That(result.Status, Is.EqualTo(SkillInstallStatus.Updated)); + Assert.That(File.ReadAllText(skillFile), Is.EqualTo("shipped")); + Assert.That(File.ReadAllText(skillFile + ".bak"), Is.EqualTo("local improvement")); + } + + [Test] + public void Install_BundledSkillMissing_Throws() + { + var installer = new SkillInstaller(Path.Combine(_root, "nothing"), _userProfile); + + Assert.Throws(() => installer.Install("claude", "project", _project, false)); + } + } +} diff --git a/mcp-server/Tests/AccUnit.McpServer.Tests/TestAuthoringGuideTests.cs b/mcp-server/Tests/AccUnit.McpServer.Tests/TestAuthoringGuideTests.cs new file mode 100644 index 0000000..b2b4a03 --- /dev/null +++ b/mcp-server/Tests/AccUnit.McpServer.Tests/TestAuthoringGuideTests.cs @@ -0,0 +1,58 @@ +using System; +using System.IO; +using NUnit.Framework; + +namespace AccessCodeLib.AccUnit.McpServer.Tests +{ + public class TestAuthoringGuideTests + { + private static string ShippedSkillFile + { + get { return Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "skills", "accunit-tests", "SKILL.md"); } + } + + [TestCase("skill accunit-tests")] + [TestCase("accunit_install_skill")] + [TestCase("not VBA")] + [TestCase("no constants or enums of the own VBA project")] + [TestCase("System.Convert.ToDateTime")] + [TestCase("Array(...) only as the only value of a row")] + [TestCase("distinguishes vbNullString")] + public void ServerInstructions_ContainSkillReferenceAndCoreRules(string text) + { + Assert.That(TestAuthoringGuide.Text, Does.Contain(text)); + } + + [Test] + public void Skill_IsShippedNextToTheServer() + { + Assert.That(File.Exists(ShippedSkillFile), Is.True, ShippedSkillFile); + } + + [Test] + public void Skill_HasPortableFrontmatter() + { + var lines = File.ReadAllLines(ShippedSkillFile); + + Assert.That(lines[0], Is.EqualTo("---")); + Assert.That(lines[1], Is.EqualTo("name: " + TestAuthoringGuide.SkillName)); + Assert.That(lines[2], Does.StartWith("description: ")); + Assert.That(lines[3], Is.EqualTo("---")); + } + + [TestCase("'AccUnit:Row(2+8,")] + [TestCase("'AccUnit:Row(2, Null,")] + [TestCase("System.Convert.ToDateTime(\"2014-05-16\")")] + [TestCase(".Name(\"Equal\")")] + [TestCase("not VBA")] + [TestCase("Constants and enums of the own VBA project are not available")] + [TestCase("inputs first, expected value last")] + [TestCase("`Array(...)` works only as the only value of a row")] + [TestCase("distinguishes `vbNullString`")] + [TestCase("accunit_run_tests")] + public void Skill_ContainsExampleAndRules(string text) + { + Assert.That(File.ReadAllText(ShippedSkillFile), Does.Contain(text)); + } + } +} diff --git a/mcp-server/skills/accunit-tests/SKILL.md b/mcp-server/skills/accunit-tests/SKILL.md new file mode 100644 index 0000000..a8590f8 --- /dev/null +++ b/mcp-server/skills/accunit-tests/SKILL.md @@ -0,0 +1,71 @@ +--- +name: accunit-tests +description: Write and run AccUnit unit tests for VBA code in Microsoft Access - test classes, row tests ('AccUnit:Row), Assert/Iz - with the AccUnit MCP server (accunit_* tools). Use when creating or changing AccUnit test classes or when running AccUnit tests. +--- + +# AccUnit tests + +AccUnit runs unit tests for VBA code in Microsoft Access. The AccUnit MCP server (tools `accunit_*`) lists and runs +the tests and creates drafts of test classes. + +## Workflow + +1. `accunit_open` the database (absolute path; it must be in a trusted location). +2. `accunit_generate_test_class` for the module under test: you get a draft plus the declaration and the comment of + each method under test, read from the current code in the database. Methods with parameters already get a row test skeleton. +3. Fill the tests (see below) and add the test class through the source files (e.g. msaccess-vcs export/import). + The server does not write test code into the database. +4. `accunit_run_tests` (optionally `classNames`, `testNameFilter`, `tags`); it returns a summary and the failed, + error and ignored tests. Fix and run again. +5. `accunit_close` when done. + +Notes on running: +- The tests run inside Access with the installed AccUnitLoader add-in; private test classes work unchanged. +- The server inserts the module `AccUnit_Factory` and factory methods in `AccUnit_TestClassFactory` if needed and + lists that in `environmentChanges`; these modules belong to the test environment, do not edit them. +- "The VBA project does not compile": ask the developer to compile in the VBA editor (Debug > Compile) and to report the line. +- Never run tests in parallel against the same database. + +## Writing tests + +- Test class: class module named `Tests` with the comment `'AccUnit:TestClass`, + `Option Compare Text`, `Option Explicit`. Every public `Sub` is a test; `Setup` and `Teardown` run before/after each test. +- Write the tests from the specification or the task, not from the implementation, so they do not just confirm the + current behavior. If the specification is unclear, ask the developer. +- One behavior per test; Arrange - Act - Assert. +- Assertions: `Assert.That Actual, Iz.EqualTo(Expected)` (also `Iz.Empty`, `Iz.Null`, ...). + Expected error: `Assert.Throws ` before the call that raises it. +- Names: `MethodUnderTest_StateUnderTest_ExpectedBehaviour` is recommended; leave out parts that add nothing + (e.g. `NetPrice_ReturnsZeroForZero`). +- Annotations above a test: `'AccUnit:Tags(Fast, Database)`, `'AccUnit:Ignore reason text`, + `'AccUnit:Rollback` (the test changes data). + +## Row tests + +For methods with parameters prefer ONE test method with several `'AccUnit:Row` lines over one test method per case +(normal case, boundaries, invalid input, Null). Example: + +```vba +'AccUnit:Row(2, "a", "F = 'a'").Name("Equal") +'AccUnit:Row(2+8, "a", "F >= 'a'").Name("Equal+GreaterThan") +'AccUnit:Row(2, Null, "").Name("Null value") +'AccUnit:Row(2, System.Convert.ToDateTime("2014-05-16"), "F = #2014-05-16#").Name("Date") +Public Sub BuildCriteria_ReturnsCriteria(ByVal RelationalOperator As Long, ByVal FilterValue As Variant, ByVal Expected As String) + Dim Actual As String + Actual = modCriteria.BuildCriteria("F", RelationalOperator, FilterValue) + Assert.That Actual, Iz.EqualTo(Expected) +End Sub +``` + +Rules for row values - AccUnit compiles them as VB.NET expressions, not VBA: +- One value per parameter of the test method, in parameter order: inputs first, expected value last. +- Constants and enums of the own VBA project are not available: use the numeric value (`2+8` above), add a comment if helpful. +- VBA functions (`DateSerial`, `CDate`, `Chr`, ...) are not available: use .NET expressions, + e.g. `System.Convert.ToDateTime("2014-05-16")`. +- Numbers with decimal point; strings in double quotes (double a quote inside a string); `Null` passes VBA Null; + VBA constants such as `vbTextCompare` work. +- `Array(...)` works only as the only value of a row; together with other values the method receives a nested array. +- `.Name("case")` for each row makes the results readable. + +Strings: `Iz.EqualTo` distinguishes `vbNullString` and `""`. A String function that never assigns its result returns +`vbNullString`; compare `"" & Actual` or use `Iz.StringCompare(StringCompareMode_vbNullStringEqualEmptyString)`. From 29cfb56c0b1a6e7235dedecd334e2c971875adce Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20P=C3=B6tzl?= Date: Mon, 16 Nov 2026 13:09:23 +0100 Subject: [PATCH 2/5] Describe array and number rules for row values in accunit-tests skill --- mcp-server/AccUnit.McpServer/TestAuthoringGuide.cs | 3 ++- .../Tests/AccUnit.McpServer.Tests/TestAuthoringGuideTests.cs | 5 ++++- mcp-server/skills/accunit-tests/SKILL.md | 4 +++- 3 files changed, 9 insertions(+), 3 deletions(-) diff --git a/mcp-server/AccUnit.McpServer/TestAuthoringGuide.cs b/mcp-server/AccUnit.McpServer/TestAuthoringGuide.cs index 1fbdf47..18e19bd 100644 --- a/mcp-server/AccUnit.McpServer/TestAuthoringGuide.cs +++ b/mcp-server/AccUnit.McpServer/TestAuthoringGuide.cs @@ -19,7 +19,8 @@ public static class TestAuthoringGuide - For methods with parameters prefer ONE row test with several 'AccUnit:Row(inputs..., expected).Name(""case"") lines above the test Sub over one test per case. - Row values are VB.NET expressions, not VBA: no constants or enums of the own VBA project (use the numeric value), - no VBA functions (dates: System.Convert.ToDateTime(""2014-05-16"")), Array(...) only as the only value of a row. + no VBA functions (dates: System.Convert.ToDateTime(""2014-05-16"")); arrays next to other values as {""a"", ""b""}, + Array(...) only as the only value of a row. - Iz.EqualTo distinguishes vbNullString and """". - Write the tests from the specification, not from the implementation; add test classes through the source files."; } diff --git a/mcp-server/Tests/AccUnit.McpServer.Tests/TestAuthoringGuideTests.cs b/mcp-server/Tests/AccUnit.McpServer.Tests/TestAuthoringGuideTests.cs index b2b4a03..eaf71d4 100644 --- a/mcp-server/Tests/AccUnit.McpServer.Tests/TestAuthoringGuideTests.cs +++ b/mcp-server/Tests/AccUnit.McpServer.Tests/TestAuthoringGuideTests.cs @@ -16,6 +16,7 @@ private static string ShippedSkillFile [TestCase("not VBA")] [TestCase("no constants or enums of the own VBA project")] [TestCase("System.Convert.ToDateTime")] + [TestCase("arrays next to other values as {\"a\", \"b\"}")] [TestCase("Array(...) only as the only value of a row")] [TestCase("distinguishes vbNullString")] public void ServerInstructions_ContainSkillReferenceAndCoreRules(string text) @@ -47,7 +48,9 @@ public void Skill_HasPortableFrontmatter() [TestCase("not VBA")] [TestCase("Constants and enums of the own VBA project are not available")] [TestCase("inputs first, expected value last")] - [TestCase("`Array(...)` works only as the only value of a row")] + [TestCase("Arrays next to other values in VB.NET syntax: `'AccUnit:Row(1, {\"a\", \"b\"}, ...)`")] + [TestCase("`Array(\"a\", \"b\")` only when the array is the only value of the row")] + [TestCase("Whole numbers arrive as Long")] [TestCase("distinguishes `vbNullString`")] [TestCase("accunit_run_tests")] public void Skill_ContainsExampleAndRules(string text) diff --git a/mcp-server/skills/accunit-tests/SKILL.md b/mcp-server/skills/accunit-tests/SKILL.md index a8590f8..bfc9cac 100644 --- a/mcp-server/skills/accunit-tests/SKILL.md +++ b/mcp-server/skills/accunit-tests/SKILL.md @@ -64,7 +64,9 @@ Rules for row values - AccUnit compiles them as VB.NET expressions, not VBA: e.g. `System.Convert.ToDateTime("2014-05-16")`. - Numbers with decimal point; strings in double quotes (double a quote inside a string); `Null` passes VBA Null; VBA constants such as `vbTextCompare` work. -- `Array(...)` works only as the only value of a row; together with other values the method receives a nested array. +- Arrays next to other values in VB.NET syntax: `'AccUnit:Row(1, {"a", "b"}, ...)`. + `Array("a", "b")` only when the array is the only value of the row; next to other values it arrives nested. +- Whole numbers arrive as Long (VB.NET Integer), so use `Long` or `Variant` parameters. - `.Name("case")` for each row makes the results readable. Strings: `Iz.EqualTo` distinguishes `vbNullString` and `""`. A String function that never assigns its result returns From 4f86ed51042126a9ca6cf8057b06ea71ad27ed60 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20P=C3=B6tzl?= Date: Tue, 17 Nov 2026 10:20:32 +0100 Subject: [PATCH 3/5] Tighten test authoring rules in accunit-tests skill and server Start with accunit_generate_test_class and do not read the source of the module under test; ask the developer once how to handle behavior that cannot be derived. Use the VBA error number for Assert.Throws, restrict Ignore to open expected behavior and note explicit skill invocation. --- .../AccUnit.McpServer/TestAuthoringGuide.cs | 9 +++++- mcp-server/AccUnit.McpServer/TestTools.cs | 6 ++-- mcp-server/README.md | 4 +++ .../TestAuthoringGuideTests.cs | 9 ++++++ mcp-server/skills/accunit-tests/SKILL.md | 31 ++++++++++++++----- 5 files changed, 49 insertions(+), 10 deletions(-) diff --git a/mcp-server/AccUnit.McpServer/TestAuthoringGuide.cs b/mcp-server/AccUnit.McpServer/TestAuthoringGuide.cs index 18e19bd..ed4ed5c 100644 --- a/mcp-server/AccUnit.McpServer/TestAuthoringGuide.cs +++ b/mcp-server/AccUnit.McpServer/TestAuthoringGuide.cs @@ -12,6 +12,9 @@ public static class TestAuthoringGuide public const string Text = @"AccUnit MCP server: run and write AccUnit tests for the VBA code of a Microsoft Access database. +To write tests for a module, start with accunit_generate_test_class. Do not read the source of the module under test +first, neither the exported source files nor through other tools. + Use the skill accunit-tests for writing and running tests. If it is not available in the project, offer to install it with accunit_install_skill (target ""claude"" for Claude Code, ""agents"" for Codex, Copilot and Gemini). @@ -22,6 +25,10 @@ above the test Sub over one test per case. no VBA functions (dates: System.Convert.ToDateTime(""2014-05-16"")); arrays next to other values as {""a"", ""b""}, Array(...) only as the only value of a row. - Iz.EqualTo distinguishes vbNullString and """". -- Write the tests from the specification, not from the implementation; add test classes through the source files."; +- The specification is the method name plus the declaration and comment returned by accunit_generate_test_class; + do not read the body of the method under test on your own. If the expected behavior cannot be derived, ask the + developer once how to proceed (assume values, look at the code, developer specifies, leave out). +- Expected error: Assert.Throws with the VBA error number as seen in Err.Number (e.g. Assert.Throws 457). +- Add test classes through the source files."; } } diff --git a/mcp-server/AccUnit.McpServer/TestTools.cs b/mcp-server/AccUnit.McpServer/TestTools.cs index 9b9596e..fb068b6 100644 --- a/mcp-server/AccUnit.McpServer/TestTools.cs +++ b/mcp-server/AccUnit.McpServer/TestTools.cs @@ -23,8 +23,10 @@ public TestTools(TestRunService testRunService, TestClassDraftService testClassD [Description("Creates the DRAFT of an AccUnit test class for a module of the open database (same generator as the VBE add-in): " + "class header with 'AccUnit:TestClass and one empty test method per public method, plus the declaration and the comment " + "(e.g. NaturalDoc) of each method under test, read from the current code in the database. Nothing is written to the database. " + - "Fill the test methods (Arrange - Act - Assert) from the specification or task, NOT from the implementation, so the tests " + - "do not just confirm the current behavior; if the specification is unclear, ask the developer. " + + "Fill the test methods (Arrange - Act - Assert) from the specification: the method name plus the returned declaration " + + "and comment. Do not read the body of the method under test on your own, so the tests do not just confirm the current behavior. " + + "If the expected behavior cannot be derived for some methods or cases, ask the developer once how to proceed " + + "(assume values, look at the code, developer specifies, leave out). " + "Test names: the recommended pattern is MethodUnderTest_StateUnderTest_ExpectedBehaviour (replace the placeholders); " + "it is a recommendation, leave out parts that add nothing (e.g. NetPrice_ReturnsZeroForZero). " + "Methods with parameters get a row test skeleton: write one 'AccUnit:Row(inputs..., expected).Name(\"case\") line per case " + diff --git a/mcp-server/README.md b/mcp-server/README.md index 355ef79..b3034b0 100644 --- a/mcp-server/README.md +++ b/mcp-server/README.md @@ -88,6 +88,10 @@ With `scope` = `project` the skill is only active in the Access projects that us project. An installed skill is not overwritten unless `overwrite` = `true` (it may contain local improvements); changed files are backed up as `.bak` first. Improvements made locally can be brought back into this repository. +Installing the skill once per project is enough; there is no need to check it before each session. The agent decides +from the skill description whether to load it, so this is not guaranteed. To make sure the skill is used, invoke it +explicitly (in Claude Code: `/accunit-tests`). + The server also sends short MCP server instructions with the essential rules, for clients without skill support (source: `AccUnit.McpServer/TestAuthoringGuide.cs`). diff --git a/mcp-server/Tests/AccUnit.McpServer.Tests/TestAuthoringGuideTests.cs b/mcp-server/Tests/AccUnit.McpServer.Tests/TestAuthoringGuideTests.cs index eaf71d4..3140cc6 100644 --- a/mcp-server/Tests/AccUnit.McpServer.Tests/TestAuthoringGuideTests.cs +++ b/mcp-server/Tests/AccUnit.McpServer.Tests/TestAuthoringGuideTests.cs @@ -19,6 +19,10 @@ private static string ShippedSkillFile [TestCase("arrays next to other values as {\"a\", \"b\"}")] [TestCase("Array(...) only as the only value of a row")] [TestCase("distinguishes vbNullString")] + [TestCase("do not read the body of the method under test")] + [TestCase("Assert.Throws 457")] + [TestCase("start with accunit_generate_test_class")] + [TestCase("neither the exported source files nor through other tools")] public void ServerInstructions_ContainSkillReferenceAndCoreRules(string text) { Assert.That(TestAuthoringGuide.Text, Does.Contain(text)); @@ -53,6 +57,11 @@ public void Skill_HasPortableFrontmatter() [TestCase("Whole numbers arrive as Long")] [TestCase("distinguishes `vbNullString`")] [TestCase("accunit_run_tests")] + [TestCase("Do not read the body of the method under test")] + [TestCase("`Assert.Throws 457`")] + [TestCase("for expected errors use `Assert.Throws`")] + [TestCase("Start here: do not read the source of the module under")] + [TestCase("Use when the user asks to create unit tests for VBA code")] public void Skill_ContainsExampleAndRules(string text) { Assert.That(File.ReadAllText(ShippedSkillFile), Does.Contain(text)); diff --git a/mcp-server/skills/accunit-tests/SKILL.md b/mcp-server/skills/accunit-tests/SKILL.md index bfc9cac..952d8ce 100644 --- a/mcp-server/skills/accunit-tests/SKILL.md +++ b/mcp-server/skills/accunit-tests/SKILL.md @@ -1,6 +1,6 @@ --- name: accunit-tests -description: Write and run AccUnit unit tests for VBA code in Microsoft Access - test classes, row tests ('AccUnit:Row), Assert/Iz - with the AccUnit MCP server (accunit_* tools). Use when creating or changing AccUnit test classes or when running AccUnit tests. +description: Write and run AccUnit unit tests for VBA code in Microsoft Access - test classes, row tests ('AccUnit:Row), Assert/Iz - with the AccUnit MCP server (accunit_* tools). Use when the user asks to create unit tests for VBA code, when creating or changing AccUnit test classes or when running AccUnit tests. --- # AccUnit tests @@ -11,9 +11,11 @@ the tests and creates drafts of test classes. ## Workflow 1. `accunit_open` the database (absolute path; it must be in a trusted location). -2. `accunit_generate_test_class` for the module under test: you get a draft plus the declaration and the comment of +2. `accunit_generate_test_class` for the module under test. Start here: do not read the source of the module under + test first, neither the exported source files nor through other tools. You get a draft plus the declaration and the comment of each method under test, read from the current code in the database. Methods with parameters already get a row test skeleton. -3. Fill the tests (see below) and add the test class through the source files (e.g. msaccess-vcs export/import). +3. Fill the tests (see below), add the test class through the source files and import them with msaccess-vcs + (e.g. `vcs_import_objects`). The server does not write test code into the database. 4. `accunit_run_tests` (optionally `classNames`, `testNameFilter`, `tags`); it returns a summary and the failed, error and ignored tests. Fix and run again. @@ -30,14 +32,29 @@ Notes on running: - Test class: class module named `Tests` with the comment `'AccUnit:TestClass`, `Option Compare Text`, `Option Explicit`. Every public `Sub` is a test; `Setup` and `Teardown` run before/after each test. -- Write the tests from the specification or the task, not from the implementation, so they do not just confirm the - current behavior. If the specification is unclear, ask the developer. +- The specification is the method name plus the declaration and comment returned by + `accunit_generate_test_class`. Do not read the body of the method under test on your own, neither in the + exported source files nor through other tools; this includes the procedures it calls. Public declarations + used by the method (enums, constants) may be looked up. + If the expected behavior cannot be derived from that for some methods or cases (e.g. Null, empty + input, boundaries, error behavior), tell the developer once, listing the affected methods/cases + briefly, and let them choose how to proceed: + - **Assume values:** choose expected values from the method's purpose and common conventions; mark + them with `' assumption: ...` and list them in the summary. + - **Look at the code:** derive the expected values from the implementation; the tests then pin the + current behavior (characterization tests). Say so in the summary. + - **Developer specifies:** the developer states the expected behavior. + - **Leave out:** skip these cases. + A failing test is a result: report it as "assumption or code wrong?" and do not adjust the + expectation to the current behavior unless the developer agrees. - One behavior per test; Arrange - Act - Assert. - Assertions: `Assert.That Actual, Iz.EqualTo(Expected)` (also `Iz.Empty`, `Iz.Null`, ...). - Expected error: `Assert.Throws ` before the call that raises it. + Expected error: `Assert.Throws ` before the call that raises it, with the VBA error number + as seen in `Err.Number` (e.g. `Assert.Throws 457`). - Names: `MethodUnderTest_StateUnderTest_ExpectedBehaviour` is recommended; leave out parts that add nothing (e.g. `NetPrice_ReturnsZeroForZero`). -- Annotations above a test: `'AccUnit:Tags(Fast, Database)`, `'AccUnit:Ignore reason text`, +- Annotations above a test: `'AccUnit:Tags(Fast, Database)`, `'AccUnit:Ignore reason text` + (only for tests whose expected behavior is still open; for expected errors use `Assert.Throws`), `'AccUnit:Rollback` (the test changes data). ## Row tests From 2765778af0a04d22461a9634c4ae9647a8c8137f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20P=C3=B6tzl?= Date: Tue, 17 Nov 2026 13:46:20 +0100 Subject: [PATCH 4/5] Add accunit_import_test_classes tool to MCP server Import test classes and test related modules from source files with the import of the AccUnit core, so writing tests no longer depends on msaccess-vcs. Files are converted to the ANSI code page, get the class export header if missing and are saved with DoCmd.Save to avoid the Save As dialog on quit. Modules that are not test modules are never replaced. The draft returns the AccUnit test folder. --- mcp-server/AccUnit.McpServer/Program.cs | 1 + .../AccUnit.McpServer/TestAuthoringGuide.cs | 3 +- .../AccUnit.McpServer/TestClassDraft.cs | 3 + .../TestClassDraftService.cs | 10 + .../TestClassImportService.cs | 213 ++++++++++++++++++ .../AccUnit.McpServer/TestModuleSourceFile.cs | 139 ++++++++++++ mcp-server/AccUnit.McpServer/TestTools.cs | 29 ++- mcp-server/README.md | 20 +- .../TestAuthoringGuideTests.cs | 3 + .../TestClassImportServiceTests.cs | 52 +++++ .../TestModuleSourceFileTests.cs | 161 +++++++++++++ mcp-server/skills/accunit-tests/SKILL.md | 16 +- 12 files changed, 634 insertions(+), 16 deletions(-) create mode 100644 mcp-server/AccUnit.McpServer/TestClassImportService.cs create mode 100644 mcp-server/AccUnit.McpServer/TestModuleSourceFile.cs create mode 100644 mcp-server/Tests/AccUnit.McpServer.Tests/TestClassImportServiceTests.cs create mode 100644 mcp-server/Tests/AccUnit.McpServer.Tests/TestModuleSourceFileTests.cs diff --git a/mcp-server/AccUnit.McpServer/Program.cs b/mcp-server/AccUnit.McpServer/Program.cs index e6911a0..cab004b 100644 --- a/mcp-server/AccUnit.McpServer/Program.cs +++ b/mcp-server/AccUnit.McpServer/Program.cs @@ -22,6 +22,7 @@ private static async Task Main(string[] args) builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddSingleton(); + builder.Services.AddSingleton(); builder.Services.AddSingleton(_ => new SkillInstaller()); builder.Services .AddMcpServer(options => diff --git a/mcp-server/AccUnit.McpServer/TestAuthoringGuide.cs b/mcp-server/AccUnit.McpServer/TestAuthoringGuide.cs index ed4ed5c..f814838 100644 --- a/mcp-server/AccUnit.McpServer/TestAuthoringGuide.cs +++ b/mcp-server/AccUnit.McpServer/TestAuthoringGuide.cs @@ -29,6 +29,7 @@ above the test Sub over one test per case. do not read the body of the method under test on your own. If the expected behavior cannot be derived, ask the developer once how to proceed (assume values, look at the code, developer specifies, leave out). - Expected error: Assert.Throws with the VBA error number as seen in Err.Number (e.g. Assert.Throws 457). -- Add test classes through the source files."; +- Save the test class as .cls in the testFolder returned by accunit_generate_test_class and import it + with accunit_import_test_classes."; } } diff --git a/mcp-server/AccUnit.McpServer/TestClassDraft.cs b/mcp-server/AccUnit.McpServer/TestClassDraft.cs index 52a3cdf..565cd5e 100644 --- a/mcp-server/AccUnit.McpServer/TestClassDraft.cs +++ b/mcp-server/AccUnit.McpServer/TestClassDraft.cs @@ -8,6 +8,9 @@ public class TestClassDraft public string TestClassName { get; set; } public string ModuleUnderTest { get; set; } public string SourceCode { get; set; } + + /// AccUnit test folder of the database: default folder of accunit_import_test_classes. + public string TestFolder { get; set; } public List MethodsUnderTest { get; set; } = new List(); } diff --git a/mcp-server/AccUnit.McpServer/TestClassDraftService.cs b/mcp-server/AccUnit.McpServer/TestClassDraftService.cs index 4eb05fc..3b6116a 100644 --- a/mcp-server/AccUnit.McpServer/TestClassDraftService.cs +++ b/mcp-server/AccUnit.McpServer/TestClassDraftService.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Linq; +using AccessCodeLib.AccUnit.Configuration; using AccessCodeLib.AccUnit.Tools; using AccessCodeLib.Common.VBIDETools; using Microsoft.Vbe.Interop; @@ -53,6 +54,7 @@ private static TestClassDraft CreateDraft(VBProject vbProject, CodeModuleReader TestClassName = new TestClassNameGenerator(vbProject).GetTestClassName(moduleName), ModuleUnderTest = moduleName, SourceCode = generator.GenerateSourceCode(), + TestFolder = GetTestFolder(vbProject), MethodsUnderTest = members.Select(member => new MethodUnderTest { Name = member.Name, @@ -63,6 +65,14 @@ private static TestClassDraft CreateDraft(VBProject vbProject, CodeModuleReader }; } + private static string GetTestFolder(VBProject vbProject) + { + using (var testClassManager = new TestClassManager(new VBProjectOnlyApplicatonHelper(vbProject))) + { + return testClassManager.ImportDirectory; + } + } + private static List SelectMembers(List publicMembers, IList methodNames) { if (methodNames == null || methodNames.Count == 0) diff --git a/mcp-server/AccUnit.McpServer/TestClassImportService.cs b/mcp-server/AccUnit.McpServer/TestClassImportService.cs new file mode 100644 index 0000000..483dcd9 --- /dev/null +++ b/mcp-server/AccUnit.McpServer/TestClassImportService.cs @@ -0,0 +1,213 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Runtime.InteropServices; +using System.Text; +using AccessCodeLib.AccUnit.Configuration; +using AccessCodeLib.Common.VBIDETools; +using Microsoft.Vbe.Interop; +using Access = Microsoft.Office.Interop.Access; + +namespace AccessCodeLib.AccUnit.McpServer +{ + /// + /// Imports test classes and test related modules from source files into the open database with the import of the + /// AccUnit core (as the VBE add-in does). Other modules are never written. + /// + public sealed class TestClassImportService + { + private static readonly string[] ImportableExtensions = { ".cls", ".bas" }; + private static readonly char[] PathCharacters = { '\\', '/', ':' }; + private const string ParentDirectory = ".."; + + private readonly AccessSession _session; + + public TestClassImportService(AccessSession session) + { + _session = session ?? throw new ArgumentNullException(nameof(session)); + } + + /// VBComponents.Import reads the system ANSI code page (Encoding.Default on .NET Framework). + private static Encoding AnsiEncoding + { + get { return Encoding.Default; } + } + + public TestClassImportResult ImportTestClasses(string fileNameFilter, string importPath) + { + var filter = NormalizeFileNameFilter(fileNameFilter); + var directory = importPath == null ? null : ValidateImportPath(importPath); + + var result = _session.Execute(application => + { + var importResult = ImportOnStaThread(VBProjectLocator.GetCurrentVBProject(application), filter, directory); + SaveModules(application, importResult.ImportedModules); + return importResult; + }); + + if (result.ImportedModules.Count == 0) + { + result.Message = "Nothing was imported."; + return result; + } + + // A module replaced with VBComponents.Remove is kept removed only if the VBA project is saved, so save and open again. + _session.SaveAndReopen(); + result.Message = "Imported and saved; the database was closed with saving and opened again."; + return result; + } + + /// File name without extension, wildcards * and ? allowed, no path. + public static string NormalizeFileNameFilter(string fileNameFilter) + { + if (string.IsNullOrWhiteSpace(fileNameFilter)) + throw new DatabaseSessionException("The file name filter is empty. Use the module name, wildcards * and ? are allowed."); + + var filter = fileNameFilter.Trim(); + if (filter.IndexOfAny(PathCharacters) >= 0 || filter.Contains(ParentDirectory)) + throw new DatabaseSessionException("The file name filter must not contain a path; use importPath for the folder."); + + var extension = Path.GetExtension(filter); + return ImportableExtensions.Contains(extension, StringComparer.OrdinalIgnoreCase) + ? filter.Substring(0, filter.Length - extension.Length) + : filter; + } + + public static string ValidateImportPath(string importPath) + { + string fullPath; + try + { + fullPath = Path.IsPathRooted(importPath) ? Path.GetFullPath(importPath) : null; + } + catch (Exception ex) when (ex is ArgumentException || ex is NotSupportedException || ex is PathTooLongException) + { + throw new DatabaseSessionException("The import path is not a valid folder path.", ex); + } + + if (fullPath == null) + throw new DatabaseSessionException("The import path must be an absolute path."); + if (!Directory.Exists(fullPath)) + throw new DatabaseSessionException("The import folder does not exist: " + fullPath); + return fullPath; + } + + private static TestClassImportResult ImportOnStaThread(VBProject vbProject, string fileNameFilter, string importPath) + { + using (var testClassManager = new TestClassManager(new VBProjectOnlyApplicatonHelper(vbProject))) + { + var result = new TestClassImportResult { ImportDirectory = importPath ?? testClassManager.ImportDirectory }; + var files = GetSourceFiles(result.ImportDirectory, fileNameFilter); + if (files.Count == 0) + { + result.RejectedFiles.Add(new RejectedTestModuleFile + { + FileName = fileNameFilter + ".cls/.bas", + Reason = "No matching file in " + result.ImportDirectory + "." + }); + return result; + } + + var accepted = SelectImportableFiles(vbProject, files, result.RejectedFiles); + if (accepted.Count > 0) + Import(testClassManager, accepted, result); + return result; + } + } + + private static List GetSourceFiles(string directory, string fileNameFilter) + { + return TestClassReader.GetTestFilesFromDirectory(directory, fileNameFilter) + .Where(file => ImportableExtensions.Contains(file.Extension, StringComparer.OrdinalIgnoreCase)) + .Select(file => file.FullName) + .ToList(); + } + + private static List SelectImportableFiles(VBProject vbProject, IEnumerable files, + List rejectedFiles) + { + var componentNames = GetComponentNames(vbProject); + var testModuleNames = new TestClassReader(vbProject).GetTestComponents().Select(module => module.Name).ToList(); + + var accepted = new List(); + foreach (var filePath in files) + { + var file = TestModuleSourceFile.Read(filePath, AnsiEncoding); + var reason = file.GetRejectReason(AnsiEncoding); + if (reason == null && componentNames.Contains(file.ModuleName, StringComparer.OrdinalIgnoreCase) && + !testModuleNames.Contains(file.ModuleName, StringComparer.OrdinalIgnoreCase)) + { + reason = "The database contains a module " + file.ModuleName + " that is not a test module; it is not replaced."; + } + + if (reason == null) + accepted.Add(file); + else + rejectedFiles.Add(new RejectedTestModuleFile { FileName = Path.GetFileName(filePath), Reason = reason }); + } + return accepted; + } + + private static void Import(TestClassManager testClassManager, List files, TestClassImportResult result) + { + var ansiDirectory = Path.Combine(Path.GetTempPath(), "AccUnitMcpServer", "Import-" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(ansiDirectory); + try + { + foreach (var file in files) + file.WriteAnsiCopy(ansiDirectory, AnsiEncoding); + + // Same import as the VBE add-in: an existing module with the same name is replaced. + testClassManager.ImportTestComponents( + files.Select(file => new CodeModuleInfo(new FileInfo(Path.Combine(ansiDirectory, Path.GetFileName(file.FilePath))))), + true); + result.ImportedModules.AddRange(files.Select(file => file.ModuleName)); + } + finally + { + Directory.Delete(ansiDirectory, true); + } + } + + /// + /// Saves each imported module without compiling (test classes compile only with AccUnit_Factory). + /// Without it, quitting Access with acQuitSaveAll shows a modal "Save As" dialog for every imported module. + /// + private static void SaveModules(Access.Application application, IEnumerable moduleNames) + { + var doCmd = application.DoCmd; + try + { + foreach (var moduleName in moduleNames) + doCmd.Save(Access.AcObjectType.acModule, moduleName); + } + finally + { + Marshal.ReleaseComObject(doCmd); + } + } + + private static List GetComponentNames(VBProject vbProject) + { + var names = new List(); + foreach (VBComponent component in vbProject.VBComponents) + names.Add(component.Name); + return names; + } + } + + public class TestClassImportResult + { + public string ImportDirectory { get; set; } + public List ImportedModules { get; set; } = new List(); + public List RejectedFiles { get; set; } = new List(); + public string Message { get; set; } + } + + public class RejectedTestModuleFile + { + public string FileName { get; set; } + public string Reason { get; set; } + } +} diff --git a/mcp-server/AccUnit.McpServer/TestModuleSourceFile.cs b/mcp-server/AccUnit.McpServer/TestModuleSourceFile.cs new file mode 100644 index 0000000..abf0205 --- /dev/null +++ b/mcp-server/AccUnit.McpServer/TestModuleSourceFile.cs @@ -0,0 +1,139 @@ +using System; +using System.IO; +using System.Linq; +using System.Text; +using System.Text.RegularExpressions; + +namespace AccessCodeLib.AccUnit.McpServer +{ + /// + /// A test class or test related module in a source file (VBA export format), checked before it is imported. + /// VBComponents.Import reads the ANSI code page, while source files of agents and msaccess-vcs are usually UTF-8. + /// + public sealed class TestModuleSourceFile + { + // Same header rule as TestClassReader.IsTestRelatedCodeModule in the AccUnit core. + private static readonly Regex TestModuleHeaderRegex = new Regex(@"^\s*'\s*AccUnit:(TestClass|TestRelated)\s*$", + RegexOptions.CultureInvariant | RegexOptions.Multiline | RegexOptions.IgnoreCase); + private static readonly Regex ProcedureDeclarationRegex = new Regex( + @"^\s*((Public|Private|Friend)\s+)?(Static\s+)?(Sub|Function|Property\s+(Get|Let|Set))\s+\w+", + RegexOptions.CultureInvariant | RegexOptions.IgnoreCase); + private static readonly Regex VbNameRegex = new Regex(@"^\s*Attribute\s+VB_Name\s*=\s*""([^""]+)""", + RegexOptions.CultureInvariant | RegexOptions.Multiline | RegexOptions.IgnoreCase); + private static readonly Regex ClassExportHeaderRegex = new Regex(@"\A\s*VERSION\s+1\.0\s+CLASS\b", + RegexOptions.CultureInvariant | RegexOptions.IgnoreCase); + private const string ClassModuleExtension = ".cls"; + private static readonly string[] LineSeparators = { "\r\n", "\n" }; + private static readonly byte[] Utf8Preamble = Encoding.UTF8.GetPreamble(); + + private TestModuleSourceFile(string filePath, string sourceCode) + { + FilePath = filePath; + ModuleName = Path.GetFileNameWithoutExtension(filePath); + SourceCode = sourceCode; + } + + public string FilePath { get; } + + /// Module name from the file name; the core removes the existing module with this name before the import. + public string ModuleName { get; } + + public string SourceCode { get; } + + public static TestModuleSourceFile Read(string filePath, Encoding ansiEncoding) + { + return new TestModuleSourceFile(filePath, Decode(File.ReadAllBytes(filePath), ansiEncoding)); + } + + /// UTF-8 with or without BOM if the bytes are valid UTF-8, otherwise the ANSI code page. + public static string Decode(byte[] bytes, Encoding ansiEncoding) + { + if (bytes.Take(Utf8Preamble.Length).SequenceEqual(Utf8Preamble)) + return Encoding.UTF8.GetString(bytes, Utf8Preamble.Length, bytes.Length - Utf8Preamble.Length); + + try + { + return new UTF8Encoding(false, true).GetString(bytes); + } + catch (DecoderFallbackException) + { + return ansiEncoding.GetString(bytes); + } + } + + /// null if the file can be imported, otherwise the reason why not. + public string GetRejectReason(Encoding ansiEncoding) + { + if (!HasTestModuleHeader(SourceCode)) + return "Not a test module: the header needs the comment 'AccUnit:TestClass or 'AccUnit:TestRelated."; + + var vbName = GetVbName(SourceCode); + if (vbName != null && !string.Equals(vbName, ModuleName, StringComparison.OrdinalIgnoreCase)) + return "The file name must match the module name (Attribute VB_Name = \"" + vbName + "\")."; + + if (!CanBeEncoded(SourceCode, ansiEncoding)) + return "The file contains characters that are not available in the ANSI code page " + ansiEncoding.WebName + + " used by the VBA editor."; + + return null; + } + + /// Writes the source in the ANSI code page with CRLF line endings, as the VBA editor exports it. + public void WriteAnsiCopy(string directory, Encoding ansiEncoding) + { + File.WriteAllText(Path.Combine(directory, Path.GetFileName(FilePath)), ToCrLf(GetImportSource()), ansiEncoding); + } + + /// + /// Source as VBComponents.Import expects it. Code without export header (e.g. the draft of accunit_generate_test_class) + /// gets the header the VBA editor writes; without it a .cls file would not be imported as class module. + /// + public string GetImportSource() + { + if (IsClassModule) + return ClassExportHeaderRegex.IsMatch(SourceCode) ? SourceCode : GetClassExportHeader(ModuleName) + SourceCode; + return GetVbName(SourceCode) != null ? SourceCode : "Attribute VB_Name = \"" + ModuleName + "\"\r\n" + SourceCode; + } + + private bool IsClassModule + { + get { return string.Equals(Path.GetExtension(FilePath), ClassModuleExtension, StringComparison.OrdinalIgnoreCase); } + } + + private static string GetClassExportHeader(string moduleName) + { + return "VERSION 1.0 CLASS\r\n" + + "BEGIN\r\n" + + " MultiUse = -1 'True\r\n" + + "END\r\n" + + "Attribute VB_Name = \"" + moduleName + "\"\r\n" + + "Attribute VB_GlobalNameSpace = False\r\n" + + "Attribute VB_Creatable = False\r\n" + + "Attribute VB_PredeclaredId = False\r\n" + + "Attribute VB_Exposed = False\r\n"; + } + + public static string ToCrLf(string sourceCode) + { + return string.Join("\r\n", sourceCode.Split(LineSeparators, StringSplitOptions.None)); + } + + public static bool HasTestModuleHeader(string sourceCode) + { + var headerLines = sourceCode.Split(LineSeparators, StringSplitOptions.None) + .TakeWhile(line => !ProcedureDeclarationRegex.IsMatch(line)); + return TestModuleHeaderRegex.IsMatch(string.Join("\n", headerLines)); + } + + public static string GetVbName(string sourceCode) + { + var match = VbNameRegex.Match(sourceCode); + return match.Success ? match.Groups[1].Value : null; + } + + private static bool CanBeEncoded(string sourceCode, Encoding ansiEncoding) + { + return ansiEncoding.GetString(ansiEncoding.GetBytes(sourceCode)) == sourceCode; + } + } +} diff --git a/mcp-server/AccUnit.McpServer/TestTools.cs b/mcp-server/AccUnit.McpServer/TestTools.cs index fb068b6..c45534d 100644 --- a/mcp-server/AccUnit.McpServer/TestTools.cs +++ b/mcp-server/AccUnit.McpServer/TestTools.cs @@ -11,12 +11,15 @@ public class TestTools private readonly TestRunService _testRunService; private readonly TestClassDraftService _testClassDraftService; private readonly TestEnvironmentService _testEnvironmentService; + private readonly TestClassImportService _testClassImportService; - public TestTools(TestRunService testRunService, TestClassDraftService testClassDraftService, TestEnvironmentService testEnvironmentService) + public TestTools(TestRunService testRunService, TestClassDraftService testClassDraftService, + TestEnvironmentService testEnvironmentService, TestClassImportService testClassImportService) { _testRunService = testRunService; _testClassDraftService = testClassDraftService; _testEnvironmentService = testEnvironmentService; + _testClassImportService = testClassImportService; } [McpServerTool(Name = "accunit_generate_test_class", ReadOnly = true)] @@ -33,7 +36,8 @@ public TestTools(TestRunService testRunService, TestClassDraftService testClassD "(normal case, boundaries, invalid input, Null) instead of separate test methods. Row values are VB.NET expressions, not VBA: " + "no constants or enums of the own VBA project (use the numeric value), no VBA functions (dates: " + "System.Convert.ToDateTime(\"2014-05-16\")); see the server instructions for an example. " + - "Add the finished class through the source files (e.g. msaccess-vcs import), not by writing into the database.")] + "Save the finished class as a source file (e.g. .cls in the AccUnit test folder) and import it with " + + "accunit_import_test_classes.")] public TestClassDraft GenerateTestClass( [Description("Name of the standard module or class module under test.")] string moduleName, [Description("Only these public methods (optional, default: all public methods).")] string[] methodNames = null) @@ -48,6 +52,27 @@ public TestClassDraft GenerateTestClass( } } + [McpServerTool(Name = "accunit_import_test_classes", Destructive = true)] + [Description("Imports test classes and test related modules from source files (.cls/.bas, VBA export format, UTF-8 or ANSI) " + + "into the open database with the import of the AccUnit core, as the VBE add-in does. Only files with the header comment " + + "'AccUnit:TestClass or 'AccUnit:TestRelated are imported; the file name must match the module name. An existing test module " + + "with the same name is replaced; a module that is not a test module is never replaced. " + + "Default folder: the AccUnit test folder of the database (\\Tests\\, returned as importDirectory). " + + "To keep the import, Access is closed with saving and the database is opened again.")] + public TestClassImportResult ImportTestClasses( + [Description("File name without extension, wildcards * and ? allowed (e.g. modStringsTests).")] string fileNameFilter, + [Description("Absolute path of the folder with the source files (optional, default: AccUnit test folder of the database).")] string importPath = null) + { + try + { + return _testClassImportService.ImportTestClasses(fileNameFilter, importPath); + } + catch (DatabaseSessionException ex) + { + throw new McpException(ex.Message); + } + } + [McpServerTool(Name = "accunit_remove_test_environment", Destructive = true)] [Description("Removes the AccUnit test environment from the open database like the menu item of the VBE add-in: " + "the modules AccUnit_Factory and AccUnit_TestClassFactory and the AccUnit type library reference. " + diff --git a/mcp-server/README.md b/mcp-server/README.md index b3034b0..7c88b4e 100644 --- a/mcp-server/README.md +++ b/mcp-server/README.md @@ -57,17 +57,19 @@ Start `AccUnit.McpServer.exe` as a stdio server without arguments. Log output go | `accunit_status` | | Path, Access version, process id, whether the database is trusted. | | `accunit_list_tests` | `classNames` | Test classes with test methods, tags, ignore info and number of data rows (row tests). | | `accunit_run_tests` | `classNames`, `testNameFilter`, `tags`, `includePassed` (default `false`) | Runs the tests; returns a summary and the failed, error and ignored tests. | -| `accunit_generate_test_class` | `moduleName`, `methodNames` | Draft of a test class for a module: code skeleton plus declaration and comment of each method under test. Writes nothing to the database. | +| `accunit_generate_test_class` | `moduleName`, `methodNames` | Draft of a test class for a module: code skeleton plus declaration and comment of each method under test, and the AccUnit test folder (`testFolder`). Writes nothing to the database. | +| `accunit_import_test_classes` | `fileNameFilter`, `importPath` (default: AccUnit test folder) | Imports test classes and test related modules from source files with the import of the AccUnit core. | | `accunit_remove_test_environment` | `removeTestModules` (default `false`), `exportBeforeRemoving` (default `true`) | Removes the test environment like the VBE add-in menu item; optionally also the test classes (exported first). | | `accunit_install_skill` | `target` (`claude`/`agents`), `scope` (`project`/`user`), `projectPath`, `overwrite` (default `false`) | Installs the skill `accunit-tests` shipped with the server (see below). | ### Writing tests with `accunit_generate_test_class` The tool returns a draft only. The agent fills the test methods (Arrange - Act - Assert) from the specification -or the task, not from the implementation, so the tests do not just confirm the current behavior. -If the specification is unclear, the agent should ask the developer. +(method name, declaration and comment), not from the implementation, so the tests do not just confirm the current behavior. +If the expected behavior cannot be derived, the agent asks the developer once how to proceed. The recommended test name pattern is `MethodUnderTest_StateUnderTest_ExpectedBehaviour`; parts that add nothing may be left out. -The finished test class is added through the source files (e.g. msaccess-vcs import), not written into the database by the server. +The finished test class is saved as a source file in the AccUnit test folder (`testFolder` of the draft) and imported +with `accunit_import_test_classes`; no other tool (e.g. msaccess-vcs) is needed. ## Skill `accunit-tests` @@ -107,8 +109,14 @@ A larger example of row tests: [SqlToolsBuildCriteriaTests.cls](https://github.c and adds missing factory methods to `AccUnit_TestClassFactory`. These changes are kept and listed in `environmentChanges`. Test classes are not changed. The results are read from the JUnit XML file AccUnit writes (`%TEMP%\AccUnitMcpServer`). -- **`accunit_remove_test_environment`** saves the database and opens it again: Access keeps removed modules only - when the VBA project is saved. +- **`accunit_import_test_classes`** writes only test classes and test related modules (header comment + `'AccUnit:TestClass` or `'AccUnit:TestRelated`). An existing test module with the same name is replaced; a module that is + not a test module is never replaced. The file name must match the module name. The files may be UTF-8 or ANSI; they are + converted to the ANSI code page of the VBA editor (characters outside it are rejected), and code without export + header gets the header the VBA editor writes. Default folder: the AccUnit test folder + (`\Tests\` or the folder of the AccUnit setting `ImportExportFolder`). +- **`accunit_remove_test_environment`** and **`accunit_import_test_classes`** save the database and open it again: + Access keeps removed and imported modules only when the VBA project is saved. - Tests never run in parallel; all calls to Access are serialized. ## Limitations diff --git a/mcp-server/Tests/AccUnit.McpServer.Tests/TestAuthoringGuideTests.cs b/mcp-server/Tests/AccUnit.McpServer.Tests/TestAuthoringGuideTests.cs index 3140cc6..8c08798 100644 --- a/mcp-server/Tests/AccUnit.McpServer.Tests/TestAuthoringGuideTests.cs +++ b/mcp-server/Tests/AccUnit.McpServer.Tests/TestAuthoringGuideTests.cs @@ -23,6 +23,7 @@ private static string ShippedSkillFile [TestCase("Assert.Throws 457")] [TestCase("start with accunit_generate_test_class")] [TestCase("neither the exported source files nor through other tools")] + [TestCase("with accunit_import_test_classes")] public void ServerInstructions_ContainSkillReferenceAndCoreRules(string text) { Assert.That(TestAuthoringGuide.Text, Does.Contain(text)); @@ -62,6 +63,8 @@ public void Skill_HasPortableFrontmatter() [TestCase("for expected errors use `Assert.Throws`")] [TestCase("Start here: do not read the source of the module under")] [TestCase("Use when the user asks to create unit tests for VBA code")] + [TestCase("`accunit_import_test_classes` with the class name as `fileNameFilter`")] + [TestCase("in the `testFolder` returned by the draft")] public void Skill_ContainsExampleAndRules(string text) { Assert.That(File.ReadAllText(ShippedSkillFile), Does.Contain(text)); diff --git a/mcp-server/Tests/AccUnit.McpServer.Tests/TestClassImportServiceTests.cs b/mcp-server/Tests/AccUnit.McpServer.Tests/TestClassImportServiceTests.cs new file mode 100644 index 0000000..5714537 --- /dev/null +++ b/mcp-server/Tests/AccUnit.McpServer.Tests/TestClassImportServiceTests.cs @@ -0,0 +1,52 @@ +using System; +using System.IO; +using NUnit.Framework; + +namespace AccessCodeLib.AccUnit.McpServer.Tests +{ + public class TestClassImportServiceTests + { + [TestCase("modStringsTests", "modStringsTests")] + [TestCase(" modStringsTests ", "modStringsTests")] + [TestCase("modStringsTests.cls", "modStringsTests")] + [TestCase("TestHelper.BAS", "TestHelper")] + [TestCase("*Tests", "*Tests")] + public void NormalizeFileNameFilter_ValidFilter_ReturnsNameWithoutExtension(string filter, string expected) + { + Assert.That(TestClassImportService.NormalizeFileNameFilter(filter), Is.EqualTo(expected)); + } + + [TestCase(null)] + [TestCase("")] + [TestCase(" ")] + [TestCase("..\\modStringsTests")] + [TestCase("C:\\Test\\modStringsTests")] + [TestCase("sub/modStringsTests")] + public void NormalizeFileNameFilter_EmptyOrPath_Throws(string filter) + { + Assert.Throws(() => TestClassImportService.NormalizeFileNameFilter(filter)); + } + + [Test] + public void ValidateImportPath_ExistingAbsoluteFolder_ReturnsFullPath() + { + var folder = Path.GetTempPath(); + + Assert.That(TestClassImportService.ValidateImportPath(folder), Is.EqualTo(Path.GetFullPath(folder))); + } + + [Test] + public void ValidateImportPath_RelativePath_Throws() + { + Assert.Throws(() => TestClassImportService.ValidateImportPath("Tests\\NVdev")); + } + + [Test] + public void ValidateImportPath_MissingFolder_Throws() + { + var missing = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N")); + + Assert.Throws(() => TestClassImportService.ValidateImportPath(missing)); + } + } +} diff --git a/mcp-server/Tests/AccUnit.McpServer.Tests/TestModuleSourceFileTests.cs b/mcp-server/Tests/AccUnit.McpServer.Tests/TestModuleSourceFileTests.cs new file mode 100644 index 0000000..2dd3903 --- /dev/null +++ b/mcp-server/Tests/AccUnit.McpServer.Tests/TestModuleSourceFileTests.cs @@ -0,0 +1,161 @@ +using System; +using System.IO; +using System.Text; +using NUnit.Framework; + +namespace AccessCodeLib.AccUnit.McpServer.Tests +{ + public class TestModuleSourceFileTests + { + private const string TestClassCode = "Option Compare Text\r\nOption Explicit\r\n\r\n'AccUnit:TestClass\r\n\r\n" + + "Public Sub Test_Works()\r\n Assert.That 1, Iz.EqualTo(1)\r\nEnd Sub\r\n"; + private const string ClassExportHeader = "VERSION 1.0 CLASS\r\nBEGIN\r\n MultiUse = -1 'True\r\nEND\r\n" + + "Attribute VB_Name = \"modStringsTests\"\r\n"; + + private static readonly Encoding Ansi = Encoding.GetEncoding(1252); + + private string _directory; + + [SetUp] + public void SetUp() + { + _directory = Path.Combine(Path.GetTempPath(), "AccUnitTestModuleSourceFileTests", Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(_directory); + } + + [TearDown] + public void TearDown() + { + Directory.Delete(_directory, true); + } + + private TestModuleSourceFile CreateFile(string fileName, string content, Encoding encoding) + { + var path = Path.Combine(_directory, fileName); + File.WriteAllText(path, content, encoding); + return TestModuleSourceFile.Read(path, Ansi); + } + + [Test] + public void Decode_Utf8WithBom_RemovesBomAndKeepsUmlauts() + { + var bytes = new UTF8Encoding(true).GetPreamble(); + bytes = Concat(bytes, Encoding.UTF8.GetBytes("' Gr\u00F6\u00DFe")); + + Assert.That(TestModuleSourceFile.Decode(bytes, Ansi), Is.EqualTo("' Gr\u00F6\u00DFe")); + } + + [Test] + public void Decode_Utf8WithoutBom_KeepsUmlauts() + { + Assert.That(TestModuleSourceFile.Decode(Encoding.UTF8.GetBytes("' Gr\u00F6\u00DFe"), Ansi), Is.EqualTo("' Gr\u00F6\u00DFe")); + } + + [Test] + public void Decode_Ansi_KeepsUmlauts() + { + Assert.That(TestModuleSourceFile.Decode(Ansi.GetBytes("' Gr\u00F6\u00DFe"), Ansi), Is.EqualTo("' Gr\u00F6\u00DFe")); + } + + [TestCase("'AccUnit:TestClass")] + [TestCase("' AccUnit:TestRelated")] + [TestCase("'accunit:testclass ")] + public void HasTestModuleHeader_MarkerInHeader_IsTrue(string marker) + { + Assert.That(TestModuleSourceFile.HasTestModuleHeader("Option Explicit\r\n" + marker + "\r\n\r\nPublic Sub A()\r\nEnd Sub"), Is.True); + } + + [Test] + public void HasTestModuleHeader_MarkerOnlyInProcedure_IsFalse() + { + Assert.That(TestModuleSourceFile.HasTestModuleHeader("Option Explicit\r\n\r\nPublic Sub A()\r\n'AccUnit:TestClass\r\nEnd Sub"), Is.False); + } + + [Test] + public void HasTestModuleHeader_NoMarker_IsFalse() + { + Assert.That(TestModuleSourceFile.HasTestModuleHeader("Option Explicit\r\n\r\nPublic Function A()\r\nEnd Function"), Is.False); + } + + [Test] + public void GetRejectReason_TestClass_IsNull() + { + var file = CreateFile("modStringsTests.cls", TestClassCode, new UTF8Encoding(true)); + + Assert.That(file.GetRejectReason(Ansi), Is.Null); + } + + [Test] + public void GetRejectReason_NoTestModule_IsReported() + { + var file = CreateFile("modStrings.bas", "Option Explicit\r\n\r\nPublic Function A()\r\nEnd Function\r\n", Ansi); + + Assert.That(file.GetRejectReason(Ansi), Does.Contain("Not a test module")); + } + + [Test] + public void GetRejectReason_VbNameDiffersFromFileName_IsReported() + { + var file = CreateFile("OtherName.cls", ClassExportHeader + TestClassCode, Ansi); + + Assert.That(file.GetRejectReason(Ansi), Does.Contain("file name must match the module name")); + } + + [Test] + public void GetRejectReason_CharacterNotInAnsiCodePage_IsReported() + { + var file = CreateFile("modStringsTests.cls", TestClassCode + "' \u4E2D\r\n", Encoding.UTF8); + + Assert.That(file.GetRejectReason(Ansi), Does.Contain("ANSI code page")); + } + + [Test] + public void GetImportSource_ClassWithoutExportHeader_AddsHeaderWithModuleName() + { + var file = CreateFile("modStringsTests.cls", TestClassCode, Encoding.UTF8); + + var source = file.GetImportSource(); + + Assert.That(source, Does.StartWith("VERSION 1.0 CLASS\r\n")); + Assert.That(source, Does.Contain("Attribute VB_Name = \"modStringsTests\"\r\n")); + Assert.That(source, Does.EndWith(TestClassCode)); + } + + [Test] + public void GetImportSource_ClassWithExportHeader_IsUnchanged() + { + var file = CreateFile("modStringsTests.cls", ClassExportHeader + TestClassCode, new UTF8Encoding(true)); + + Assert.That(file.GetImportSource(), Is.EqualTo(ClassExportHeader + TestClassCode)); + } + + [Test] + public void GetImportSource_StandardModuleWithoutVbName_AddsVbName() + { + var file = CreateFile("TestHelper.bas", "'AccUnit:TestRelated\r\nOption Explicit\r\n", Ansi); + + Assert.That(file.GetImportSource(), Does.StartWith("Attribute VB_Name = \"TestHelper\"\r\n'AccUnit:TestRelated")); + } + + [Test] + public void WriteAnsiCopy_Utf8WithLf_WritesAnsiWithCrLf() + { + var file = CreateFile("modStringsTests.cls", ClassExportHeader.Replace("\r\n", "\n") + "'AccUnit:TestClass\n' Gr\u00F6\u00DFe\n", new UTF8Encoding(true)); + var targetDirectory = Path.Combine(_directory, "ansi"); + Directory.CreateDirectory(targetDirectory); + + file.WriteAnsiCopy(targetDirectory, Ansi); + + var bytes = File.ReadAllBytes(Path.Combine(targetDirectory, "modStringsTests.cls")); + Assert.That(bytes, Is.EqualTo(Ansi.GetBytes(ClassExportHeader + "'AccUnit:TestClass\r\n' Gr\u00F6\u00DFe\r\n"))); + } + + private static byte[] Concat(byte[] first, byte[] second) + { + var result = new byte[first.Length + second.Length]; + first.CopyTo(result, 0); + second.CopyTo(result, first.Length); + return result; + } + } +} diff --git a/mcp-server/skills/accunit-tests/SKILL.md b/mcp-server/skills/accunit-tests/SKILL.md index 952d8ce..7aae025 100644 --- a/mcp-server/skills/accunit-tests/SKILL.md +++ b/mcp-server/skills/accunit-tests/SKILL.md @@ -6,7 +6,7 @@ description: Write and run AccUnit unit tests for VBA code in Microsoft Access - # AccUnit tests AccUnit runs unit tests for VBA code in Microsoft Access. The AccUnit MCP server (tools `accunit_*`) lists and runs -the tests and creates drafts of test classes. +the tests, creates drafts of test classes and imports test classes into the database. ## Workflow @@ -14,12 +14,14 @@ the tests and creates drafts of test classes. 2. `accunit_generate_test_class` for the module under test. Start here: do not read the source of the module under test first, neither the exported source files nor through other tools. You get a draft plus the declaration and the comment of each method under test, read from the current code in the database. Methods with parameters already get a row test skeleton. -3. Fill the tests (see below), add the test class through the source files and import them with msaccess-vcs - (e.g. `vcs_import_objects`). - The server does not write test code into the database. -4. `accunit_run_tests` (optionally `classNames`, `testNameFilter`, `tags`); it returns a summary and the failed, - error and ignored tests. Fix and run again. -5. `accunit_close` when done. +3. Fill the tests (see below) and save the class as `.cls` in the `testFolder` returned by the draft + (the AccUnit test folder of the database). The draft code can be saved as it is; the export header is added on import. +4. `accunit_import_test_classes` with the class name as `fileNameFilter` (optionally `importPath` for another folder, + e.g. the source folder of msaccess-vcs). Only modules with `'AccUnit:TestClass` or `'AccUnit:TestRelated` are imported; + an existing test module with the same name is replaced. Import again after each change of the file. +5. `accunit_run_tests` (optionally `classNames`, `testNameFilter`, `tags`); it returns a summary and the failed, + error and ignored tests. Fix the file, import and run again. +6. `accunit_close` when done. Notes on running: - The tests run inside Access with the installed AccUnitLoader add-in; private test classes work unchanged. From 125a0bcf320da05b9f7cddd7c35f66f6303d4997 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20P=C3=B6tzl?= Date: Tue, 17 Nov 2026 14:27:15 +0100 Subject: [PATCH 5/5] Add tools to export and remove single test classes accunit_export_test_classes and accunit_remove_test_classes work only on test modules and keep files they write over as .bak. The skill now creates a second test class first and asks the developer whether to merge it, replace the existing class or keep both. --- mcp-server/AccUnit.McpServer/Program.cs | 1 + .../AccUnit.McpServer/SourceFileBackup.cs | 23 +++ .../AccUnit.McpServer/TestAuthoringGuide.cs | 5 +- .../TestModuleExportService.cs | 141 ++++++++++++++++++ .../AccUnit.McpServer/TestModuleSelection.cs | 70 +++++++++ mcp-server/AccUnit.McpServer/TestTools.cs | 48 +++++- mcp-server/README.md | 10 +- ...cessCodeLib.AccUnit.McpServer.Tests.csproj | 8 + .../SourceFileBackupTests.cs | 55 +++++++ .../TestAuthoringGuideTests.cs | 3 + .../TestModuleSelectionTests.cs | 91 +++++++++++ mcp-server/skills/accunit-tests/SKILL.md | 10 +- 12 files changed, 459 insertions(+), 6 deletions(-) create mode 100644 mcp-server/AccUnit.McpServer/SourceFileBackup.cs create mode 100644 mcp-server/AccUnit.McpServer/TestModuleExportService.cs create mode 100644 mcp-server/AccUnit.McpServer/TestModuleSelection.cs create mode 100644 mcp-server/Tests/AccUnit.McpServer.Tests/SourceFileBackupTests.cs create mode 100644 mcp-server/Tests/AccUnit.McpServer.Tests/TestModuleSelectionTests.cs diff --git a/mcp-server/AccUnit.McpServer/Program.cs b/mcp-server/AccUnit.McpServer/Program.cs index cab004b..e62a1d7 100644 --- a/mcp-server/AccUnit.McpServer/Program.cs +++ b/mcp-server/AccUnit.McpServer/Program.cs @@ -23,6 +23,7 @@ private static async Task Main(string[] args) builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddSingleton(); + builder.Services.AddSingleton(); builder.Services.AddSingleton(_ => new SkillInstaller()); builder.Services .AddMcpServer(options => diff --git a/mcp-server/AccUnit.McpServer/SourceFileBackup.cs b/mcp-server/AccUnit.McpServer/SourceFileBackup.cs new file mode 100644 index 0000000..2b476dd --- /dev/null +++ b/mcp-server/AccUnit.McpServer/SourceFileBackup.cs @@ -0,0 +1,23 @@ +using System.IO; + +namespace AccessCodeLib.AccUnit.McpServer +{ + /// + /// Keeps a copy of a source file before an export writes over it (the file may contain work not yet imported). + /// + public static class SourceFileBackup + { + private const string BackupExtension = ".bak"; + + /// Path of the backup, or null if the file does not exist. + public static string BackupIfExists(string filePath) + { + if (!File.Exists(filePath)) + return null; + + var backupPath = filePath + BackupExtension; + File.Copy(filePath, backupPath, true); + return backupPath; + } + } +} diff --git a/mcp-server/AccUnit.McpServer/TestAuthoringGuide.cs b/mcp-server/AccUnit.McpServer/TestAuthoringGuide.cs index f814838..d3eed47 100644 --- a/mcp-server/AccUnit.McpServer/TestAuthoringGuide.cs +++ b/mcp-server/AccUnit.McpServer/TestAuthoringGuide.cs @@ -30,6 +30,9 @@ above the test Sub over one test per case. developer once how to proceed (assume values, look at the code, developer specifies, leave out). - Expected error: Assert.Throws with the VBA error number as seen in Err.Number (e.g. Assert.Throws 457). - Save the test class as .cls in the testFolder returned by accunit_generate_test_class and import it - with accunit_import_test_classes."; + with accunit_import_test_classes. +- If the module already has a test class, the draft name gets a number (e.g. modCalcTests1): create, import and run it, + then ask the developer whether to merge it into the existing class (accunit_export_test_classes, + accunit_remove_test_classes), replace the existing class or keep both."; } } diff --git a/mcp-server/AccUnit.McpServer/TestModuleExportService.cs b/mcp-server/AccUnit.McpServer/TestModuleExportService.cs new file mode 100644 index 0000000..3c6b2f2 --- /dev/null +++ b/mcp-server/AccUnit.McpServer/TestModuleExportService.cs @@ -0,0 +1,141 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using AccessCodeLib.AccUnit.Configuration; +using AccessCodeLib.Common.VBIDETools; +using Microsoft.Vbe.Interop; + +namespace AccessCodeLib.AccUnit.McpServer +{ + /// + /// Exports single test classes and test related modules to the AccUnit test folder and removes them from the + /// open database, with the functions of the AccUnit core. Other modules are never exported or removed. + /// + public sealed class TestModuleExportService + { + private readonly AccessSession _session; + + public TestModuleExportService(AccessSession session) + { + _session = session ?? throw new ArgumentNullException(nameof(session)); + } + + public ExportTestClassesResult ExportTestClasses(IList classNames, bool overwrite) + { + return _session.Execute(application => + ExportOnStaThread(VBProjectLocator.GetCurrentVBProject(application), classNames, overwrite)); + } + + public RemoveTestClassesResult RemoveTestClasses(IList classNames, bool exportBeforeRemoving) + { + var result = _session.Execute(application => + RemoveOnStaThread(VBProjectLocator.GetCurrentVBProject(application), classNames, exportBeforeRemoving)); + + if (result.RemovedModules.Count == 0) + { + result.Message = "Nothing was removed."; + return result; + } + + // Access keeps modules removed with VBComponents.Remove only if the VBA project is saved. + _session.SaveAndReopen(); + result.Message = "Removed and saved; the database was closed with saving and opened again."; + return result; + } + + private static ExportTestClassesResult ExportOnStaThread(VBProject vbProject, IList classNames, bool overwrite) + { + using (var testClassManager = new TestClassManager(new VBProjectOnlyApplicatonHelper(vbProject))) + { + var result = new ExportTestClassesResult { ExportDirectory = testClassManager.ExportDirectory }; + foreach (var module in SelectTestModules(vbProject, classNames, result.Rejected)) + { + var filePath = GetExportFilePath(result.ExportDirectory, module); + if (File.Exists(filePath) && !overwrite) + { + result.Rejected.Add(new RejectedTestModule + { + Name = module.Name, + Reason = "The file " + filePath + " exists already; export with overwrite = true (the file is kept as .bak)." + }); + continue; + } + + AddBackup(result.BackupFiles, SourceFileBackup.BackupIfExists(filePath)); + result.ExportedFiles.Add(testClassManager.ExportTestClass(module.Name)); + } + return result; + } + } + + private static RemoveTestClassesResult RemoveOnStaThread(VBProject vbProject, IList classNames, bool exportBeforeRemoving) + { + var componentsBefore = GetComponentNames(vbProject); + using (var testClassManager = new TestClassManager(new VBProjectOnlyApplicatonHelper(vbProject))) + { + var result = new RemoveTestClassesResult(); + foreach (var module in SelectTestModules(vbProject, classNames, result.Rejected)) + { + if (exportBeforeRemoving) + { + var filePath = GetExportFilePath(testClassManager.ExportDirectory, module); + AddBackup(result.BackupFiles, SourceFileBackup.BackupIfExists(filePath)); + result.ExportedFiles.Add(filePath); + } + // Exports to the AccUnit test folder first if requested; also removes AccUnit_TestClassFactory, + // which accunit_run_tests adds again. + testClassManager.RemoveTestClass(module.Name, exportBeforeRemoving); + } + + result.RemovedModules = componentsBefore.Except(GetComponentNames(vbProject), StringComparer.OrdinalIgnoreCase).ToList(); + return result; + } + } + + private static List SelectTestModules(VBProject vbProject, IList classNames, List rejected) + { + var testModules = new TestClassReader(vbProject).GetTestComponents().ToList(); + return TestModuleSelection.Select(classNames, testModules, GetComponentNames(vbProject), rejected); + } + + private static string GetExportFilePath(string directory, CodeModuleInfo module) + { + return Path.Combine(directory, module.Name + TestModuleSelection.GetFileExtension(module.ComponentType)); + } + + private static void AddBackup(List backupFiles, string backupFile) + { + if (backupFile != null) + backupFiles.Add(backupFile); + } + + private static List GetComponentNames(VBProject vbProject) + { + var names = new List(); + foreach (VBComponent component in vbProject.VBComponents) + names.Add(component.Name); + return names; + } + } + + public class ExportTestClassesResult + { + public string ExportDirectory { get; set; } + public List ExportedFiles { get; set; } = new List(); + + /// Copies (.bak) of files that the export wrote over. + public List BackupFiles { get; set; } = new List(); + public List Rejected { get; set; } = new List(); + } + + public class RemoveTestClassesResult + { + /// All removed modules, including AccUnit_TestClassFactory (added again by accunit_run_tests). + public List RemovedModules { get; set; } = new List(); + public List ExportedFiles { get; set; } = new List(); + public List BackupFiles { get; set; } = new List(); + public List Rejected { get; set; } = new List(); + public string Message { get; set; } + } +} diff --git a/mcp-server/AccUnit.McpServer/TestModuleSelection.cs b/mcp-server/AccUnit.McpServer/TestModuleSelection.cs new file mode 100644 index 0000000..245305c --- /dev/null +++ b/mcp-server/AccUnit.McpServer/TestModuleSelection.cs @@ -0,0 +1,70 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using AccessCodeLib.Common.VBIDETools; +using Microsoft.Vbe.Interop; + +namespace AccessCodeLib.AccUnit.McpServer +{ + /// + /// Selects the requested test classes and test related modules for export or removal; other modules are rejected, + /// so these tools never touch production code. + /// + public static class TestModuleSelection + { + private const string ClassModuleExtension = ".cls"; + private const string StandardModuleExtension = ".bas"; + + /// Module names from the client. + /// Test classes and test related modules of the VBA project. + /// All modules of the VBA project. + /// Receives the requested names that are not selected, with the reason. + public static List Select(IList requestedNames, IEnumerable testModules, + ICollection componentNames, List rejected) + { + if (requestedNames == null || requestedNames.Count == 0 || requestedNames.Any(string.IsNullOrWhiteSpace)) + throw new DatabaseSessionException("Name the test classes (classNames); empty names are not allowed."); + + var testModuleList = testModules.ToList(); + var selected = new List(); + foreach (var name in requestedNames.Select(n => n.Trim()).Distinct(StringComparer.OrdinalIgnoreCase)) + { + var testModule = testModuleList.FirstOrDefault(m => string.Equals(m.Name, name, StringComparison.OrdinalIgnoreCase)); + var reason = GetRejectReason(name, testModule, componentNames); + if (reason == null) + selected.Add(testModule); + else + rejected.Add(new RejectedTestModule { Name = name, Reason = reason }); + } + return selected; + } + + private static string GetRejectReason(string name, CodeModuleInfo testModule, ICollection componentNames) + { + if (testModule == null) + return componentNames.Contains(name, StringComparer.OrdinalIgnoreCase) + ? "Not a test module: the header has no comment 'AccUnit:TestClass or 'AccUnit:TestRelated." + : "No module with this name."; + if (GetFileExtension(testModule.ComponentType) == null) + return "Only class modules and standard modules are supported, not form or report modules."; + return null; + } + + /// File extension of the VBA export, or null for module types the tools do not support. + public static string GetFileExtension(vbext_ComponentType componentType) + { + switch (componentType) + { + case vbext_ComponentType.vbext_ct_ClassModule: return ClassModuleExtension; + case vbext_ComponentType.vbext_ct_StdModule: return StandardModuleExtension; + default: return null; + } + } + } + + public class RejectedTestModule + { + public string Name { get; set; } + public string Reason { get; set; } + } +} diff --git a/mcp-server/AccUnit.McpServer/TestTools.cs b/mcp-server/AccUnit.McpServer/TestTools.cs index c45534d..eb87aa1 100644 --- a/mcp-server/AccUnit.McpServer/TestTools.cs +++ b/mcp-server/AccUnit.McpServer/TestTools.cs @@ -12,14 +12,17 @@ public class TestTools private readonly TestClassDraftService _testClassDraftService; private readonly TestEnvironmentService _testEnvironmentService; private readonly TestClassImportService _testClassImportService; + private readonly TestModuleExportService _testModuleExportService; public TestTools(TestRunService testRunService, TestClassDraftService testClassDraftService, - TestEnvironmentService testEnvironmentService, TestClassImportService testClassImportService) + TestEnvironmentService testEnvironmentService, TestClassImportService testClassImportService, + TestModuleExportService testModuleExportService) { _testRunService = testRunService; _testClassDraftService = testClassDraftService; _testEnvironmentService = testEnvironmentService; _testClassImportService = testClassImportService; + _testModuleExportService = testModuleExportService; } [McpServerTool(Name = "accunit_generate_test_class", ReadOnly = true)] @@ -37,7 +40,9 @@ public TestTools(TestRunService testRunService, TestClassDraftService testClassD "no constants or enums of the own VBA project (use the numeric value), no VBA functions (dates: " + "System.Convert.ToDateTime(\"2014-05-16\")); see the server instructions for an example. " + "Save the finished class as a source file (e.g. .cls in the AccUnit test folder) and import it with " + - "accunit_import_test_classes.")] + "accunit_import_test_classes. If a test class for the module exists already, the proposed name gets a number " + + "(e.g. modCalcTests1): create, import and run it, then ask the developer whether to merge it into the existing class, " + + "replace the existing class or keep both.")] public TestClassDraft GenerateTestClass( [Description("Name of the standard module or class module under test.")] string moduleName, [Description("Only these public methods (optional, default: all public methods).")] string[] methodNames = null) @@ -73,6 +78,45 @@ public TestClassImportResult ImportTestClasses( } } + [McpServerTool(Name = "accunit_export_test_classes")] + [Description("Exports test classes and test related modules of the open database to the AccUnit test folder (VBA export " + + "format, ANSI), e.g. to edit an existing test class and import it again with accunit_import_test_classes. " + + "Only modules with 'AccUnit:TestClass or 'AccUnit:TestRelated are exported. An existing file is written over only " + + "with overwrite = true and is kept as .bak. Nothing is written to the database.")] + public ExportTestClassesResult ExportTestClasses( + [Description("Names of the test classes or test related modules.")] string[] classNames, + [Description("Write over an existing file in the test folder (kept as .bak).")] bool overwrite = false) + { + try + { + return _testModuleExportService.ExportTestClasses(classNames, overwrite); + } + catch (DatabaseSessionException ex) + { + throw new McpException(ex.Message); + } + } + + [McpServerTool(Name = "accunit_remove_test_classes", Destructive = true)] + [Description("Removes single test classes or test related modules from the open database, e.g. a second test class after it " + + "was merged into the existing one. Only modules with 'AccUnit:TestClass or 'AccUnit:TestRelated are removed; " + + "they are exported to the AccUnit test folder first by default (an existing file is kept as .bak). " + + "The module AccUnit_TestClassFactory is removed as well; accunit_run_tests adds it again. " + + "To keep the removal, Access is closed with saving and the database is opened again.")] + public RemoveTestClassesResult RemoveTestClasses( + [Description("Names of the test classes or test related modules.")] string[] classNames, + [Description("Export the modules to the AccUnit test folder before removing them.")] bool exportBeforeRemoving = true) + { + try + { + return _testModuleExportService.RemoveTestClasses(classNames, exportBeforeRemoving); + } + catch (DatabaseSessionException ex) + { + throw new McpException(ex.Message); + } + } + [McpServerTool(Name = "accunit_remove_test_environment", Destructive = true)] [Description("Removes the AccUnit test environment from the open database like the menu item of the VBE add-in: " + "the modules AccUnit_Factory and AccUnit_TestClassFactory and the AccUnit type library reference. " + diff --git a/mcp-server/README.md b/mcp-server/README.md index 7c88b4e..5b23931 100644 --- a/mcp-server/README.md +++ b/mcp-server/README.md @@ -59,6 +59,8 @@ Start `AccUnit.McpServer.exe` as a stdio server without arguments. Log output go | `accunit_run_tests` | `classNames`, `testNameFilter`, `tags`, `includePassed` (default `false`) | Runs the tests; returns a summary and the failed, error and ignored tests. | | `accunit_generate_test_class` | `moduleName`, `methodNames` | Draft of a test class for a module: code skeleton plus declaration and comment of each method under test, and the AccUnit test folder (`testFolder`). Writes nothing to the database. | | `accunit_import_test_classes` | `fileNameFilter`, `importPath` (default: AccUnit test folder) | Imports test classes and test related modules from source files with the import of the AccUnit core. | +| `accunit_export_test_classes` | `classNames`, `overwrite` (default `false`) | Exports single test classes or test related modules to the AccUnit test folder. | +| `accunit_remove_test_classes` | `classNames`, `exportBeforeRemoving` (default `true`) | Removes single test classes or test related modules from the database (exported first by default). | | `accunit_remove_test_environment` | `removeTestModules` (default `false`), `exportBeforeRemoving` (default `true`) | Removes the test environment like the VBE add-in menu item; optionally also the test classes (exported first). | | `accunit_install_skill` | `target` (`claude`/`agents`), `scope` (`project`/`user`), `projectPath`, `overwrite` (default `false`) | Installs the skill `accunit-tests` shipped with the server (see below). | @@ -115,8 +117,12 @@ A larger example of row tests: [SqlToolsBuildCriteriaTests.cls](https://github.c converted to the ANSI code page of the VBA editor (characters outside it are rejected), and code without export header gets the header the VBA editor writes. Default folder: the AccUnit test folder (`\Tests\` or the folder of the AccUnit setting `ImportExportFolder`). -- **`accunit_remove_test_environment`** and **`accunit_import_test_classes`** save the database and open it again: - Access keeps removed and imported modules only when the VBA project is saved. +- **`accunit_export_test_classes`** and **`accunit_remove_test_classes`** work only on test classes and test related + modules. They export to the AccUnit test folder; an existing file is written over only with `overwrite = true` (export) + or before removing, and is kept as `.bak`. Removing a test class also removes `AccUnit_TestClassFactory` + (core behavior); `accunit_run_tests` adds it again. +- **`accunit_remove_test_environment`**, **`accunit_import_test_classes`** and **`accunit_remove_test_classes`** save the + database and open it again: Access keeps removed and imported modules only when the VBA project is saved. - Tests never run in parallel; all calls to Access are serialized. ## Limitations diff --git a/mcp-server/Tests/AccUnit.McpServer.Tests/AccessCodeLib.AccUnit.McpServer.Tests.csproj b/mcp-server/Tests/AccUnit.McpServer.Tests/AccessCodeLib.AccUnit.McpServer.Tests.csproj index 4ce2e91..1f35787 100644 --- a/mcp-server/Tests/AccUnit.McpServer.Tests/AccessCodeLib.AccUnit.McpServer.Tests.csproj +++ b/mcp-server/Tests/AccUnit.McpServer.Tests/AccessCodeLib.AccUnit.McpServer.Tests.csproj @@ -18,4 +18,12 @@ + + + + ..\..\..\source\packages\ThammimTech.Microsoft.Vbe.Interop.15.0.0\lib\net20\Microsoft.Vbe.Interop.dll + false + + + diff --git a/mcp-server/Tests/AccUnit.McpServer.Tests/SourceFileBackupTests.cs b/mcp-server/Tests/AccUnit.McpServer.Tests/SourceFileBackupTests.cs new file mode 100644 index 0000000..069aec7 --- /dev/null +++ b/mcp-server/Tests/AccUnit.McpServer.Tests/SourceFileBackupTests.cs @@ -0,0 +1,55 @@ +using System; +using System.IO; +using NUnit.Framework; + +namespace AccessCodeLib.AccUnit.McpServer.Tests +{ + public class SourceFileBackupTests + { + private string _directory; + + [SetUp] + public void SetUp() + { + _directory = Path.Combine(Path.GetTempPath(), "AccUnitSourceFileBackupTests", Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(_directory); + } + + [TearDown] + public void TearDown() + { + Directory.Delete(_directory, true); + } + + [Test] + public void BackupIfExists_MissingFile_ReturnsNull() + { + Assert.That(SourceFileBackup.BackupIfExists(Path.Combine(_directory, "modCalcTests.cls")), Is.Null); + } + + [Test] + public void BackupIfExists_ExistingFile_CopiesToBak() + { + var filePath = Path.Combine(_directory, "modCalcTests.cls"); + File.WriteAllText(filePath, "work in progress"); + + var backupPath = SourceFileBackup.BackupIfExists(filePath); + + Assert.That(backupPath, Is.EqualTo(filePath + ".bak")); + Assert.That(File.ReadAllText(backupPath), Is.EqualTo("work in progress")); + Assert.That(File.Exists(filePath), Is.True); + } + + [Test] + public void BackupIfExists_BakExists_IsReplaced() + { + var filePath = Path.Combine(_directory, "modCalcTests.cls"); + File.WriteAllText(filePath, "new"); + File.WriteAllText(filePath + ".bak", "old"); + + SourceFileBackup.BackupIfExists(filePath); + + Assert.That(File.ReadAllText(filePath + ".bak"), Is.EqualTo("new")); + } + } +} diff --git a/mcp-server/Tests/AccUnit.McpServer.Tests/TestAuthoringGuideTests.cs b/mcp-server/Tests/AccUnit.McpServer.Tests/TestAuthoringGuideTests.cs index 8c08798..1544eb6 100644 --- a/mcp-server/Tests/AccUnit.McpServer.Tests/TestAuthoringGuideTests.cs +++ b/mcp-server/Tests/AccUnit.McpServer.Tests/TestAuthoringGuideTests.cs @@ -24,6 +24,7 @@ private static string ShippedSkillFile [TestCase("start with accunit_generate_test_class")] [TestCase("neither the exported source files nor through other tools")] [TestCase("with accunit_import_test_classes")] + [TestCase("whether to merge it into the existing class")] public void ServerInstructions_ContainSkillReferenceAndCoreRules(string text) { Assert.That(TestAuthoringGuide.Text, Does.Contain(text)); @@ -65,6 +66,8 @@ public void Skill_HasPortableFrontmatter() [TestCase("Use when the user asks to create unit tests for VBA code")] [TestCase("`accunit_import_test_classes` with the class name as `fileNameFilter`")] [TestCase("in the `testFolder` returned by the draft")] + [TestCase("Create, import and run this second class first")] + [TestCase("`accunit_remove_test_classes` for the second class")] public void Skill_ContainsExampleAndRules(string text) { Assert.That(File.ReadAllText(ShippedSkillFile), Does.Contain(text)); diff --git a/mcp-server/Tests/AccUnit.McpServer.Tests/TestModuleSelectionTests.cs b/mcp-server/Tests/AccUnit.McpServer.Tests/TestModuleSelectionTests.cs new file mode 100644 index 0000000..efffadd --- /dev/null +++ b/mcp-server/Tests/AccUnit.McpServer.Tests/TestModuleSelectionTests.cs @@ -0,0 +1,91 @@ +using System.Collections.Generic; +using System.Linq; +using AccessCodeLib.Common.VBIDETools; +using Microsoft.Vbe.Interop; +using NUnit.Framework; + +namespace AccessCodeLib.AccUnit.McpServer.Tests +{ + public class TestModuleSelectionTests + { + private static readonly List TestModules = new List + { + new CodeModuleInfo("modCalcTests", vbext_ComponentType.vbext_ct_ClassModule), + new CodeModuleInfo("TestHelper", vbext_ComponentType.vbext_ct_StdModule), + new CodeModuleInfo("Form_frmTestHost", vbext_ComponentType.vbext_ct_Document) + }; + + private static readonly List ComponentNames = new List + { + "modCalc", "modCalcTests", "TestHelper", "Form_frmTestHost" + }; + + [Test] + public void Select_TestClassAndTestRelatedModule_AreSelected() + { + var rejected = new List(); + + var selected = TestModuleSelection.Select(new[] { "modcalctests", "TestHelper" }, TestModules, ComponentNames, rejected); + + Assert.That(selected.Select(m => m.Name), Is.EqualTo(new[] { "modCalcTests", "TestHelper" })); + Assert.That(rejected, Is.Empty); + } + + [Test] + public void Select_ModuleThatIsNoTestModule_IsRejected() + { + var rejected = new List(); + + var selected = TestModuleSelection.Select(new[] { "modCalc" }, TestModules, ComponentNames, rejected); + + Assert.That(selected, Is.Empty); + Assert.That(rejected.Single().Reason, Does.Contain("Not a test module")); + } + + [Test] + public void Select_UnknownModule_IsRejected() + { + var rejected = new List(); + + TestModuleSelection.Select(new[] { "modMissing" }, TestModules, ComponentNames, rejected); + + Assert.That(rejected.Single().Reason, Does.Contain("No module with this name")); + } + + [Test] + public void Select_FormModule_IsRejected() + { + var rejected = new List(); + + TestModuleSelection.Select(new[] { "Form_frmTestHost" }, TestModules, ComponentNames, rejected); + + Assert.That(rejected.Single().Reason, Does.Contain("not form or report modules")); + } + + [Test] + public void Select_SameNameTwice_IsSelectedOnce() + { + var selected = TestModuleSelection.Select(new[] { "modCalcTests", "MODCALCTESTS" }, TestModules, ComponentNames, + new List()); + + Assert.That(selected.Count, Is.EqualTo(1)); + } + + private static readonly object[] MissingNames = { null, new string[0], new[] { " " } }; + + [TestCaseSource(nameof(MissingNames))] + public void Select_NoNames_Throws(string[] names) + { + Assert.Throws(() => + TestModuleSelection.Select(names, TestModules, ComponentNames, new List())); + } + + [TestCase(vbext_ComponentType.vbext_ct_ClassModule, ".cls")] + [TestCase(vbext_ComponentType.vbext_ct_StdModule, ".bas")] + [TestCase(vbext_ComponentType.vbext_ct_Document, null)] + public void GetFileExtension_ReturnsExtensionOfVbaExport(vbext_ComponentType componentType, string expected) + { + Assert.That(TestModuleSelection.GetFileExtension(componentType), Is.EqualTo(expected)); + } + } +} diff --git a/mcp-server/skills/accunit-tests/SKILL.md b/mcp-server/skills/accunit-tests/SKILL.md index 7aae025..ca91133 100644 --- a/mcp-server/skills/accunit-tests/SKILL.md +++ b/mcp-server/skills/accunit-tests/SKILL.md @@ -6,7 +6,7 @@ description: Write and run AccUnit unit tests for VBA code in Microsoft Access - # AccUnit tests AccUnit runs unit tests for VBA code in Microsoft Access. The AccUnit MCP server (tools `accunit_*`) lists and runs -the tests, creates drafts of test classes and imports test classes into the database. +the tests, creates drafts of test classes and imports, exports and removes test classes. ## Workflow @@ -23,6 +23,14 @@ the tests, creates drafts of test classes and imports test classes into the data error and ignored tests. Fix the file, import and run again. 6. `accunit_close` when done. +Existing test class: if the module already has a test class, the draft proposes a name with a number +(e.g. `modCalcTests1`). Create, import and run this second class first, so the developer can look at both. Then ask: +- **Merge:** `accunit_export_test_classes` for the existing class (to edit its current code), add the new tests, + import it, then `accunit_remove_test_classes` for the second class. +- **Replace:** save the new code under the name of the existing class, import it, then remove the second class. +- **Keep both:** nothing more to do. +`accunit_export_test_classes` writes over an existing file only with `overwrite = true` (kept as `.bak`). + Notes on running: - The tests run inside Access with the installed AccUnitLoader add-in; private test classes work unchanged. - The server inserts the module `AccUnit_Factory` and factory methods in `AccUnit_TestClassFactory` if needed and