diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 6b04dde..87d523c 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -1,5 +1,6 @@ -# Builds the AccUnit library and the VBE add-in, runs the unit tests and creates the -# library zip AccUnit..bin.zip as workflow artifact. +# Builds the AccUnit library, the VBE add-in and the MCP server, runs the unit tests and creates the +# library zip AccUnit..bin.zip and the MCP server zip +# AccUnit.McpServer..zip as workflow artifacts. # Runs for pushes and pull requests to dev/main and is called by the release workflow. name: Build @@ -61,6 +62,14 @@ jobs: if ($LASTEXITCODE -ne 0) { throw "Build failed for $solution" } } + # Own configuration (Release): the MCP server solution has no AzureCI configuration. + # /restore restores its PackageReference projects; the AccUnit projects were restored above. + - name: "Build MCP server" + shell: pwsh + run: | + msbuild mcp-server\AccessCodeLib.AccUnit.McpServer.sln /restore /p:Configuration=Release "/p:Platform=$env:BUILD_PLATFORM" /m /v:minimal /nologo + if ($LASTEXITCODE -ne 0) { throw "Build failed for the MCP server" } + - name: "Run unit tests" shell: pwsh run: | @@ -71,6 +80,9 @@ jobs: $excludedTestAssemblies = @('AccessTestClientTests.dll', 'AccessCodeLib.Common.VBIDETools.Tests.dll') $testAssemblies = @(Get-ChildItem -Recurse -Filter '*Tests.dll' -Path source, vbe-add-In | Where-Object { $_.FullName -match "\\bin\\$env:BUILD_CONFIGURATION\\" -and $_.Name -notin $excludedTestAssemblies }) + # MCP server tests need no Access (built with Release, see "Build MCP server") + $testAssemblies += @(Get-ChildItem -Recurse -Filter '*Tests.dll' -Path mcp-server | + Where-Object { $_.FullName -match '\\bin\\Release\\' }) if ($testAssemblies.Count -eq 0) { throw "No test assemblies found" } $testAssemblies.FullName & $vstest $testAssemblies.FullName '/TestCaseFilter:TestCategory!=AccessClientTests' '/logger:trx' '/ResultsDirectory:TestResults' @@ -114,3 +126,26 @@ jobs: name: "AccUnit-bin" path: build/AccUnit.*.bin.zip if-no-files-found: error + + # Same version as the AccUnit library: the MCP server is released together with AccUnit. + - name: "Create MCP server zip" + shell: pwsh + env: + VERSION: ${{ steps.zip.outputs.version }} + 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" + # 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" + uses: actions/upload-artifact@v7 + with: + name: "AccUnit-McpServer" + path: build/AccUnit.McpServer.*.zip + if-no-files-found: error diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 34dcad9..61557d8 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -1,6 +1,7 @@ # Creates the release assets when a release is published: -# 1. build: builds the AccUnit library from the release tag (build.yml) -> artifact AccUnit-bin -# 2. upload-library: attaches AccUnit..bin.zip to the release +# 1. build: builds the AccUnit library and the MCP server from the release tag (build.yml) +# -> artifacts AccUnit-bin and AccUnit-McpServer +# 2. upload-library: attaches AccUnit..bin.zip and AccUnit.McpServer..zip to the release # 3. build-access-add-in: builds the Access add-in (AccUnitLoader.accda) from access-add-in/source, # loads the library files into the table usys_AppFiles and attaches # AccUnitLoader..Access.zip to the release @@ -49,8 +50,14 @@ jobs: name: "AccUnit-bin" path: build - - name: "Upload library zip to release" - run: gh release upload "$RELEASE_TAG" build/AccUnit.*.bin.zip --repo "$GITHUB_REPOSITORY" --clobber + - name: "Download MCP server zip" + uses: actions/download-artifact@v8 + with: + name: "AccUnit-McpServer" + path: build + + - name: "Upload library and MCP server zip to release" + run: gh release upload "$RELEASE_TAG" build/AccUnit.*.bin.zip build/AccUnit.McpServer.*.zip --repo "$GITHUB_REPOSITORY" --clobber build-access-add-in: needs: build diff --git a/.gitignore b/.gitignore index 6d7193f..a9b69e5 100644 --- a/.gitignore +++ b/.gitignore @@ -12,3 +12,4 @@ AGENTS.md CLAUDE.md logs/ +.claude/ diff --git a/README.md b/README.md index f10883e..a1b0bc2 100644 --- a/README.md +++ b/README.md @@ -29,6 +29,9 @@ For more informations see [Wiki](https://github.com/AccessCodeLib/AccUnit/wiki) * Select tests to run * show test result in tree view * generate test procedures +* MCP server for AI agents (e.g. Claude Code) + * List and run tests, create drafts of test classes, remove the test environment + * See [mcp-server](https://github.com/AccessCodeLib/AccUnit/tree/main/mcp-server) ### Remarks Examples see [./examples/msaccess/](https://github.com/AccessCodeLib/AccUnit/blob/main/examples/msaccess/) diff --git a/access-add-in/source/forms/AccUnitUserSettings.cls b/access-add-in/source/forms/AccUnitUserSettings.cls index 127b0df..328a26e 100644 --- a/access-add-in/source/forms/AccUnitUserSettings.cls +++ b/access-add-in/source/forms/AccUnitUserSettings.cls @@ -53,6 +53,7 @@ End Sub Private Sub LoadDataFromSettings() With m_UserSettings Me.txtImportExportFolder.Value = .ImportExportFolder + Me.cboImportExportEncoding.Value = .ImportExportEncoding Me.txtTemplateFolder.Value = .TemplateFolder Me.txtTestClassNameFormat.Value = .TestClassNameFormat Me.txtTestMethodTemplate.Value = Replace(.TestMethodTemplate, vbTab, TabSpaces) @@ -62,6 +63,7 @@ End Sub Private Sub SaveDataToSettings() With m_UserSettings .ImportExportFolder = Me.txtImportExportFolder.Value + .ImportExportEncoding = Me.cboImportExportEncoding.Value .TemplateFolder = Me.txtTemplateFolder.Value .TestClassNameFormat = Me.txtTestClassNameFormat.Value .TestMethodTemplate = Replace(Me.txtTestMethodTemplate.Value, TabSpaces, vbTab) diff --git a/access-add-in/source/forms/AccUnitUserSettings.form b/access-add-in/source/forms/AccUnitUserSettings.form index 3db54e2..b9e9979 100644 --- a/access-add-in/source/forms/AccUnitUserSettings.form +++ b/access-add-in/source/forms/AccUnitUserSettings.form @@ -16,7 +16,7 @@ Begin Form GridY =10 Width =11520 DatasheetFontHeight =11 - ItemSuffix =209 + ItemSuffix =211 Left =1000 Top =1000 Right =50000 @@ -85,6 +85,14 @@ Begin Form BorderColor =12632256 FontName ="Calibri" End + Begin ComboBox + BorderLineStyle =0 + Width =1701 + LabelX =-1701 + FontSize =11 + BorderColor =12632256 + FontName ="Calibri" + End Begin ToggleButton Width =283 Height =283 @@ -99,7 +107,7 @@ Begin Form GridlineShade =65.0 End Begin Section - Height =5460 + Height =6060 Name ="Detail" Begin Begin TextBox @@ -196,20 +204,25 @@ Begin Form End End End - Begin TextBox + Begin ComboBox + LimitToList = NotDefault + RowSourceTypeInt =1 OverlapFlags =85 TextAlign =1 IMESentenceMode =3 + ColumnCount =2 Left =2340 Top =1320 Width =9060 Height =420 TabIndex =3 - Name ="txtTemplateFolder" + Name ="cboImportExportEncoding" + RowSourceType ="Value List" + RowSource ="0;\"UTF-8 with BOM\";1;\"ANSI\"" + ColumnWidths ="0;9060" GroupTable =2 BottomPadding =150 HorizontalAnchor =2 - ShowDatePicker =0 RowStart =2 RowEnd =2 @@ -227,8 +240,8 @@ Begin Form Top =1320 Width =2160 Height =420 - Name ="Label132" - Caption ="TemplateFolder:" + Name ="lblImportExportEncoding" + Caption ="ImportExportEncoding:" GroupTable =2 RightPadding =0 BottomPadding =150 @@ -244,14 +257,59 @@ Begin Form Begin TextBox OverlapFlags =85 TextAlign =1 - TextFontFamily =49 IMESentenceMode =3 Left =2340 Top =1920 Width =9060 + Height =420 + TabIndex =4 + Name ="txtTemplateFolder" + GroupTable =2 + BottomPadding =150 + HorizontalAnchor =2 + ShowDatePicker =0 + + RowStart =3 + RowEnd =3 + ColumnStart =1 + ColumnEnd =1 + LayoutGroup =1 + GridlineThemeColorIndex =1 + GridlineShade =65.0 + GroupTable =2 + Begin + Begin Label + OverlapFlags =85 + TextAlign =1 + Left =120 + Top =1920 + Width =2160 + Height =420 + Name ="Label132" + Caption ="TemplateFolder:" + GroupTable =2 + RightPadding =0 + BottomPadding =150 + RowStart =3 + RowEnd =3 + LayoutGroup =1 + GridlineThemeColorIndex =1 + GridlineShade =65.0 + GroupTable =2 + End + End + End + Begin TextBox + OverlapFlags =85 + TextAlign =1 + TextFontFamily =49 + IMESentenceMode =3 + Left =2340 + Top =2520 + Width =9060 Height =2820 FontSize =10 - TabIndex =5 + TabIndex =6 Name ="txtTestMethodTemplate" FontName ="Consolas" GroupTable =2 @@ -260,8 +318,8 @@ Begin Form VerticalAnchor =2 ShowDatePicker =0 - RowStart =3 - RowEnd =3 + RowStart =4 + RowEnd =4 ColumnStart =1 ColumnEnd =1 LayoutGroup =1 @@ -273,7 +331,7 @@ Begin Form OverlapFlags =85 TextAlign =1 Left =120 - Top =1920 + Top =2520 Width =2160 Height =2820 Name ="Label134" @@ -282,8 +340,8 @@ Begin Form RightPadding =0 BottomPadding =0 VerticalAnchor =2 - RowStart =3 - RowEnd =3 + RowStart =4 + RowEnd =4 LayoutGroup =1 GridlineThemeColorIndex =1 GridlineShade =65.0 @@ -294,9 +352,9 @@ Begin Form Begin CommandButton OverlapFlags =85 Left =9689 - Top =4860 + Top =5460 Height =454 - TabIndex =6 + TabIndex =7 Name ="cmdCommit" Caption ="Save" OnClick ="[Event Procedure]" @@ -307,9 +365,9 @@ Begin Form Cancel = NotDefault OverlapFlags =85 Left =113 - Top =4860 + Top =5460 Height =454 - TabIndex =4 + TabIndex =5 Name ="cmdCancel" Caption ="Cancel" OnClick ="[Event Procedure]" diff --git a/access-add-in/source/modules/TestSuite.cls b/access-add-in/source/modules/TestSuite.cls index 844aaeb..9e95048 100644 --- a/access-add-in/source/modules/TestSuite.cls +++ b/access-add-in/source/modules/TestSuite.cls @@ -42,6 +42,15 @@ End Property Public Property Set CodeCoverageTracker(ByVal NewRef As Object) Set m_CodeCoverageTracker = NewRef + Set m_TestSuite.CodeCoverageTracker = NewRef +End Property + +Private Property Set AccessTestSuite_CodeCoverageTracker(ByVal RHS As AccUnit.ICodeCoverageTracker) + Set CodeCoverageTracker = RHS +End Property + +Private Property Get AccessTestSuite_CodeCoverageTracker() As AccUnit.ICodeCoverageTracker + Set AccessTestSuite_CodeCoverageTracker = m_TestSuite.CodeCoverageTracker End Property Private Sub m_TestSuite_TestSuiteStarted(ByVal TestSuite As AccUnit.ITestSuite) diff --git a/access-add-in/source/modules/_config_Application.bas b/access-add-in/source/modules/_config_Application.bas index 9ad42c7..dfadfb1 100644 --- a/access-add-in/source/modules/_config_Application.bas +++ b/access-add-in/source/modules/_config_Application.bas @@ -18,7 +18,7 @@ Option Compare Text Option Explicit 'Version number -Private Const APPLICATION_VERSION As String = "0.10.0000.261114" +Private Const APPLICATION_VERSION As String = "0.11.0000.261118" Private Const APPLICATION_NAME As String = "ACLib AccUnit Loader" Private Const APPLICATION_FULLNAME As String = "Access Code Library - AccUnit Loader" diff --git a/mcp-server/.gitignore b/mcp-server/.gitignore new file mode 100644 index 0000000..3692944 --- /dev/null +++ b/mcp-server/.gitignore @@ -0,0 +1,341 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore + +# User-specific files +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUNIT +*.VisualState.xml +TestResult.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# JustCode is a .NET coding add-in +.JustCode + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!?*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser +*- Backup*.rdl + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# JetBrains Rider +.idea/ +*.sln.iml + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ + +# BeatPulse healthcheck temp database +healthchecksdb +/MsAccessFiles/lib diff --git a/mcp-server/AccUnit.McpServer/AccessCodeLib.AccUnit.McpServer.csproj b/mcp-server/AccUnit.McpServer/AccessCodeLib.AccUnit.McpServer.csproj new file mode 100644 index 0000000..4d17028 --- /dev/null +++ b/mcp-server/AccUnit.McpServer/AccessCodeLib.AccUnit.McpServer.csproj @@ -0,0 +1,47 @@ + + + + Exe + net48 + AccUnit.McpServer + AccessCodeLib.AccUnit.McpServer + AnyCPU + false + 7.3 + + + + + + + + + + ..\..\source\lib\access\Microsoft.Office.Interop.Access.dll + false + + + ..\..\source\lib\access\Microsoft.Office.interop.access.dao.dll + false + + + ..\..\source\packages\ThammimTech.Microsoft.Vbe.Interop.15.0.0\lib\net20\Microsoft.Vbe.Interop.dll + false + + + + + + + + + + + + + + + + + + diff --git a/mcp-server/AccUnit.McpServer/AccessInstanceOwnership.cs b/mcp-server/AccUnit.McpServer/AccessInstanceOwnership.cs new file mode 100644 index 0000000..52f4d61 --- /dev/null +++ b/mcp-server/AccUnit.McpServer/AccessInstanceOwnership.cs @@ -0,0 +1,23 @@ +using System.Collections.Generic; + +namespace AccessCodeLib.AccUnit.McpServer +{ + /// + /// Decides whether the Access instance returned by COM was started by this server. + /// While another automation (e.g. another MCP server) uses Access, COM may hand out that running instance + /// instead of starting a new one; the server must neither use nor quit it. + /// + public static class AccessInstanceOwnership + { + public const string ExistingInstanceMessage = + "Access returned an instance that was already running (probably used by another automation), " + + "so the database was not opened. Try again when the other Access automation has finished."; + + /// Process of the instance returned by COM. + /// Access processes that were running before the instance was requested. + public static bool IsStartedByServer(int processId, ICollection processIdsBeforeStart) + { + return !processIdsBeforeStart.Contains(processId); + } + } +} diff --git a/mcp-server/AccUnit.McpServer/AccessSession.cs b/mcp-server/AccUnit.McpServer/AccessSession.cs new file mode 100644 index 0000000..8535a8c --- /dev/null +++ b/mcp-server/AccUnit.McpServer/AccessSession.cs @@ -0,0 +1,414 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Runtime.InteropServices; +using Access = Microsoft.Office.Interop.Access; +using Dao = Microsoft.Office.Interop.Access.Dao; + +namespace AccessCodeLib.AccUnit.McpServer +{ + /// + /// Owns exactly one Access instance started by this server and the database opened in it. + /// All COM calls run on the ; the server never attaches to + /// an Access instance it did not start. + /// + public sealed class AccessSession : IDisposable + { + private const int QuitTimeoutMilliseconds = 10000; + private const bool OpenExclusive = true; + private const string AllowBypassKeyPropertyName = "AllowBypassKey"; + private const int DaoPropertyNotFoundHResult = unchecked((int)0x800A0CC6); // DAO error 3270 + private const string AccessProcessName = "MSACCESS"; + private const string DatabaseNotOpenedMessage = + "Access did not open the database, although it reported no error. This can happen while another Access automation " + + "is running; the Access instance of this server was closed. Try again."; + + private readonly StaComDispatcher _dispatcher; + private Access.Application _application; + private Process _accessProcess; + private string _databasePath; + private bool _bypassStartup; + + public AccessSession(StaComDispatcher dispatcher) + { + _dispatcher = dispatcher ?? throw new ArgumentNullException(nameof(dispatcher)); + } + + public SessionStatus Open(string databasePath, bool bypassStartup) + { + var fullPath = DatabasePathValidator.Validate(databasePath); + return _dispatcher.Invoke(() => OpenOnStaThread(fullPath, bypassStartup)); + } + + public CloseResult Close() + { + return _dispatcher.Invoke(() => CloseOnStaThread()); + } + + public SessionStatus GetStatus() + { + return _dispatcher.Invoke(() => GetStatusOnStaThread()); + } + + /// + /// Quits Access saving all changes and opens the database again (same startup bypass). + /// Needed after modules were removed with VBComponents.Remove: Access keeps the removal only if the + /// VBA project is saved, which "compile and save" does not do when the project does not compile. + /// + public SessionStatus SaveAndReopen() + { + return _dispatcher.Invoke(() => + { + if (!IsOpen()) + throw new DatabaseSessionException("No database is open. Call accunit_open first."); + + var databasePath = _databasePath; + var bypassStartup = _bypassStartup; + if (QuitAccess(Access.AcQuitOption.acQuitSaveAll)) + throw new DatabaseSessionException("Access did not quit in time and was terminated; the changes may not be saved."); + return OpenOnStaThread(databasePath, bypassStartup); + }); + } + + private SessionStatus OpenOnStaThread(string fullPath, bool bypassStartup) + { + if (IsOpen()) + { + if (string.Equals(_databasePath, fullPath, StringComparison.OrdinalIgnoreCase)) + return GetStatusOnStaThread(); + + throw new DatabaseSessionException( + "Another database is already open: " + _databasePath + ". Close it first."); + } + + ReleaseAccess(); + StartAccess(); + + StartupBypassDecision bypass; + try + { + bypass = StartupBypassDecision.Create(bypassStartup, bypassStartup ? ReadAllowBypassKey(fullPath) : null); + OpenCurrentDatabase(fullPath, bypass.PressShiftKey); + } + catch (COMException ex) + { + QuitAccess(); + throw new DatabaseSessionException("Access could not open the database: " + ex.Message, ex); + } + + // Seen while another Access automation was running: OpenCurrentDatabase returned without error, + // but no database was open (CurrentProject "closed or doesn't exist"). + if (!HasOpenDatabase()) + { + QuitAccess(); + throw new DatabaseSessionException(DatabaseNotOpenedMessage); + } + _databasePath = fullPath; + _bypassStartup = bypassStartup; + + var status = GetStatusOnStaThread(); + status.StartupBypassAttempted = bypass.PressShiftKey; + status.Warning = bypass.Warning; + return status; + } + + private bool HasOpenDatabase() + { + Access._CurrentProject currentProject = null; + try + { + currentProject = _application.CurrentProject; + return !string.IsNullOrEmpty(currentProject.FullName); + } + catch (COMException) + { + return false; + } + finally + { + ReleaseComObject(currentProject); + } + } + + private void OpenCurrentDatabase(string fullPath, bool pressShiftKey) + { + using (pressShiftKey ? new ShiftKeyScope() : null) + { + _application.OpenCurrentDatabase(fullPath, OpenExclusive); + } + } + + /// The value of AllowBypassKey (true if the property is not set), or null if it could not be read. + private bool? ReadAllowBypassKey(string fullPath) + { + // Uses the DAO engine of the own Access instance, so the bitness always matches. + Dao._DBEngine dbEngine = null; + Dao.Database database = null; + Dao.Properties properties = null; + Dao.Property property = null; + try + { + dbEngine = _application.DBEngine; + database = dbEngine.OpenDatabase(fullPath, false, true); + properties = database.Properties; + property = properties[AllowBypassKeyPropertyName]; + return Convert.ToBoolean(property.Value); + } + catch (COMException ex) when (ex.ErrorCode == DaoPropertyNotFoundHResult) + { + return true; + } + catch (COMException) + { + return null; + } + finally + { + ReleaseComObject(property); + ReleaseComObject(properties); + if (database != null) + { + database.Close(); + ReleaseComObject(database); + } + ReleaseComObject(dbEngine); + } + } + + private static void ReleaseComObject(object comObject) + { + if (comObject != null) + Marshal.ReleaseComObject(comObject); + } + + private void StartAccess() + { + var processIdsBeforeStart = GetAccessProcessIds(); + var application = new Access.Application(); + var process = GetProcess(application); + + if (!AccessInstanceOwnership.IsStartedByServer(process.Id, processIdsBeforeStart)) + { + // COM handed out a running instance (e.g. of another automation): release it, never quit or kill it. + process.Dispose(); + Marshal.FinalReleaseComObject(application); + throw new DatabaseSessionException(AccessInstanceOwnership.ExistingInstanceMessage); + } + + _application = application; + _accessProcess = process; + // Visible, so the user can see what happens and dialogs do not block unnoticed. + _application.Visible = true; + } + + private static HashSet GetAccessProcessIds() + { + var processIds = new HashSet(); + foreach (var process in Process.GetProcessesByName(AccessProcessName)) + { + using (process) + { + processIds.Add(process.Id); + } + } + return processIds; + } + + private CloseResult CloseOnStaThread() + { + if (_application == null) + return new CloseResult { WasOpen = false, Message = "No database is open." }; + + var closedPath = _databasePath; + var killed = QuitAccess(); + return new CloseResult + { + WasOpen = true, + FilePath = closedPath, + Message = killed + ? "Access did not quit in time and was terminated (no changes were saved)." + : "Database closed and Access quit." + }; + } + + /// true if the Access process had to be terminated. + private bool QuitAccess(Access.AcQuitOption quitOption = Access.AcQuitOption.acQuitSaveNone) + { + try + { + if (IsProcessAlive()) + { + ReleaseUnreferencedComObjects(); + // No CloseCurrentDatabase: with unsaved modules it shows a modal save prompt + // and blocks the automation. Quit with acQuitSaveNone/acQuitSaveAll does not ask. + _application.Quit(quitOption); + } + } + catch (COMException) + { + // Access is not reachable any more; the process check below decides what to do. + } + finally + { + ReleaseApplication(); + } + + ReleaseUnreferencedComObjects(); + return EnsureProcessEnded(); + } + + /// + /// The AccUnit core does not release every COM object it obtains (VBComponents, CodeModules, ...). + /// Access only quits when all references are gone, so collect the unreferenced wrappers. + /// + private static void ReleaseUnreferencedComObjects() + { + GC.Collect(); + GC.WaitForPendingFinalizers(); + GC.Collect(); + GC.WaitForPendingFinalizers(); + } + + /// + /// Runs work with the Access application of the open database on the STA thread. + /// + public T Execute(Func work) + { + return _dispatcher.Invoke(() => + { + if (!IsOpen()) + throw new DatabaseSessionException("No database is open. Call accunit_open first."); + return work(_application); + }); + } + + private bool EnsureProcessEnded() + { + var process = _accessProcess; + _accessProcess = null; + _databasePath = null; + + if (process == null) + return false; + + using (process) + { + if (process.WaitForExit(QuitTimeoutMilliseconds)) + return false; + + // Only the instance started by this server is terminated. + process.Kill(); + process.WaitForExit(QuitTimeoutMilliseconds); + return true; + } + } + + private void ReleaseAccess() + { + ReleaseApplication(); + if (_accessProcess != null) + { + _accessProcess.Dispose(); + _accessProcess = null; + } + _databasePath = null; + } + + private void ReleaseApplication() + { + if (_application == null) + return; + + Marshal.FinalReleaseComObject(_application); + _application = null; + } + + private SessionStatus GetStatusOnStaThread() + { + if (!IsOpen()) + { + var lostInstance = _application != null; + ReleaseAccess(); + return new SessionStatus + { + IsOpen = false, + Message = lostInstance ? "The Access instance was closed outside of this server." : "No database is open." + }; + } + + return new SessionStatus + { + IsOpen = true, + FilePath = _databasePath, + ApplicationVersion = _application.Version, + ProcessId = _accessProcess.Id, + IsTrusted = IsCurrentProjectTrusted() + }; + } + + private bool IsCurrentProjectTrusted() + { + // Every COM object obtained from Access must be released, otherwise Access does not quit. + var currentProject = _application.CurrentProject; + try + { + return currentProject.IsTrusted; + } + finally + { + Marshal.ReleaseComObject(currentProject); + } + } + + private bool IsOpen() + { + return _application != null && _databasePath != null && IsProcessAlive(); + } + + private bool IsProcessAlive() + { + if (_accessProcess == null) + return false; + _accessProcess.Refresh(); + return !_accessProcess.HasExited; + } + + private static Process GetProcess(Access.Application application) + { + int processId; + GetWindowThreadProcessId(new IntPtr(application.hWndAccessApp()), out processId); + return Process.GetProcessById(processId); + } + + [DllImport("user32.dll")] + private static extern uint GetWindowThreadProcessId(IntPtr hWnd, out int processId); + + public void Dispose() + { + _dispatcher.Invoke(() => + { + if (_application != null) + QuitAccess(); + }); + } + } + + public class SessionStatus + { + public bool IsOpen { get; set; } + public string FilePath { get; set; } + public string ApplicationVersion { get; set; } + public int? ProcessId { get; set; } + public bool? IsTrusted { get; set; } + public bool? StartupBypassAttempted { get; set; } + public string Warning { get; set; } + public string Message { get; set; } + } + + public class CloseResult + { + public bool WasOpen { get; set; } + public string FilePath { get; set; } + public string Message { get; set; } + } +} diff --git a/mcp-server/AccUnit.McpServer/DatabasePathValidator.cs b/mcp-server/AccUnit.McpServer/DatabasePathValidator.cs new file mode 100644 index 0000000..9ae69db --- /dev/null +++ b/mcp-server/AccUnit.McpServer/DatabasePathValidator.cs @@ -0,0 +1,68 @@ +using System; +using System.IO; +using System.Linq; + +namespace AccessCodeLib.AccUnit.McpServer +{ + /// + /// Checks a database path from the MCP client before Access is started. + /// + public static class DatabasePathValidator + { + // Only file types with readable VBA source; .accde/.mde contain compiled code only. + private static readonly string[] AllowedExtensions = { ".accdb", ".accda", ".mdb" }; + + private const string AccdbLockFileExtension = ".laccdb"; + private const string MdbLockFileExtension = ".ldb"; + private const string MdbExtension = ".mdb"; + + /// + /// Returns the normalized full path or throws a . + /// + public static string Validate(string databasePath) + { + if (string.IsNullOrWhiteSpace(databasePath)) + throw new DatabaseSessionException("The database path is empty."); + + var fullPath = GetAbsoluteFullPath(databasePath); + if (fullPath == null) + throw new DatabaseSessionException("The database path must be an absolute path."); + + var extension = Path.GetExtension(fullPath); + if (!AllowedExtensions.Contains(extension, StringComparer.OrdinalIgnoreCase)) + throw new DatabaseSessionException( + "Unsupported file type '" + extension + "'. Allowed: " + string.Join(", ", AllowedExtensions) + "."); + + if (!File.Exists(fullPath)) + throw new DatabaseSessionException("The database file does not exist: " + fullPath); + + var lockFilePath = GetLockFilePath(fullPath); + if (File.Exists(lockFilePath)) + throw new DatabaseSessionException( + "The database seems to be open in another Access instance (lock file found: " + lockFilePath + "). " + + "Close it there first. If no Access instance uses it, the lock file is stale and can be deleted."); + + return fullPath; + } + + private static string GetAbsoluteFullPath(string path) + { + try + { + return Path.IsPathRooted(path) ? Path.GetFullPath(path) : null; + } + catch (Exception ex) when (ex is ArgumentException || ex is NotSupportedException || ex is PathTooLongException) + { + throw new DatabaseSessionException("The database path is not a valid file path.", ex); + } + } + + public static string GetLockFilePath(string databasePath) + { + var lockExtension = string.Equals(Path.GetExtension(databasePath), MdbExtension, StringComparison.OrdinalIgnoreCase) + ? MdbLockFileExtension + : AccdbLockFileExtension; + return Path.ChangeExtension(databasePath, lockExtension); + } + } +} diff --git a/mcp-server/AccUnit.McpServer/DatabaseSessionException.cs b/mcp-server/AccUnit.McpServer/DatabaseSessionException.cs new file mode 100644 index 0000000..4ceb7e8 --- /dev/null +++ b/mcp-server/AccUnit.McpServer/DatabaseSessionException.cs @@ -0,0 +1,18 @@ +using System; + +namespace AccessCodeLib.AccUnit.McpServer +{ + /// + /// Error with a message that is safe to show to the MCP client. + /// + public class DatabaseSessionException : Exception + { + public DatabaseSessionException(string message) : base(message) + { + } + + public DatabaseSessionException(string message, Exception innerException) : base(message, innerException) + { + } + } +} diff --git a/mcp-server/AccUnit.McpServer/JUnitResultReader.cs b/mcp-server/AccUnit.McpServer/JUnitResultReader.cs new file mode 100644 index 0000000..08fe800 --- /dev/null +++ b/mcp-server/AccUnit.McpServer/JUnitResultReader.cs @@ -0,0 +1,67 @@ +using System.Collections.Generic; +using System.Globalization; +using System.Linq; +using System.Xml.Linq; + +namespace AccessCodeLib.AccUnit.McpServer +{ + /// + /// Reads the test results from the JUnit XML file written by AccUnit (JUnitXmlTestResultReporter). + /// + public static class JUnitResultReader + { + private const double MillisecondsPerSecond = 1000; + + public static List Read(string junitXml) + { + return XDocument.Parse(junitXml) + .Descendants("testcase") + .Select(ToTestResultInfo) + .ToList(); + } + + private static TestResultInfo ToTestResultInfo(XElement testCase) + { + var resultElement = testCase.Elements().FirstOrDefault(e => e.Name == "failure" || e.Name == "error" || e.Name == "skipped"); + return new TestResultInfo + { + Test = GetTestName(testCase), + Status = GetStatus(resultElement), + Message = GetMessage(resultElement), + ElapsedMilliseconds = GetElapsedMilliseconds(testCase) + }; + } + + private static string GetTestName(XElement testCase) + { + var className = (string)testCase.Attribute("classname"); + var name = (string)testCase.Attribute("name"); + return string.IsNullOrEmpty(className) ? name : className + "." + name; + } + + private static string GetStatus(XElement resultElement) + { + if (resultElement == null) return TestStatus.Passed; + switch (resultElement.Name.LocalName) + { + case "failure": return TestStatus.Failed; + case "error": return TestStatus.Error; + default: return TestStatus.Ignored; + } + } + + private static string GetMessage(XElement resultElement) + { + var message = (string)resultElement?.Attribute("message"); + return string.IsNullOrEmpty(message) ? null : message; + } + + private static double GetElapsedMilliseconds(XElement testCase) + { + double seconds; + return double.TryParse((string)testCase.Attribute("time"), NumberStyles.Float, CultureInfo.InvariantCulture, out seconds) + ? seconds * MillisecondsPerSecond + : 0; + } + } +} diff --git a/mcp-server/AccUnit.McpServer/LateBinding.cs b/mcp-server/AccUnit.McpServer/LateBinding.cs new file mode 100644 index 0000000..4b20f66 --- /dev/null +++ b/mcp-server/AccUnit.McpServer/LateBinding.cs @@ -0,0 +1,32 @@ +using System.Reflection; +using System.Runtime.ExceptionServices; + +namespace AccessCodeLib.AccUnit.McpServer +{ + /// Late bound calls (IDispatch) on COM objects of the Access process. + internal static class LateBinding + { + public static object GetProperty(object target, string name, params object[] args) + { + return Invoke(target, name, BindingFlags.GetProperty, args); + } + + public static object CallMethod(object target, string name, params object[] args) + { + return Invoke(target, name, BindingFlags.InvokeMethod, args); + } + + private static object Invoke(object target, string name, BindingFlags flags, object[] args) + { + try + { + return target.GetType().InvokeMember(name, flags, null, target, args); + } + catch (TargetInvocationException ex) when (ex.InnerException != null) + { + ExceptionDispatchInfo.Capture(ex.InnerException).Throw(); + throw; + } + } + } +} diff --git a/mcp-server/AccUnit.McpServer/ProcedureCommentFormatter.cs b/mcp-server/AccUnit.McpServer/ProcedureCommentFormatter.cs new file mode 100644 index 0000000..012888b --- /dev/null +++ b/mcp-server/AccUnit.McpServer/ProcedureCommentFormatter.cs @@ -0,0 +1,74 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace AccessCodeLib.AccUnit.McpServer +{ + /// + /// Extracts the comment above a VBA procedure (e.g. a NaturalDoc block as in the ACLib modules) + /// from the procedure header lines, i.e. the lines the VBE assigns to the procedure before its declaration. + /// + public static class ProcedureCommentFormatter + { + private const string CommentMarker = "'"; + private const string RemMarker = "Rem "; + private const int MinSeparatorLength = 3; + private static readonly char[] SeparatorChars = { '-', '=', '*', '#', '_', '~' }; + + /// The comment text without comment markers and separator lines, or null if there is none. + public static string Format(string procedureHeader) + { + if (string.IsNullOrWhiteSpace(procedureHeader)) + return null; + + var lines = procedureHeader + .Split(new[] { "\r\n", "\n" }, StringSplitOptions.None) + .Select(GetCommentText) + .Where(text => text != null && !IsSeparator(text)) + .ToList(); + + lines = RemoveCommonIndent(lines); + lines = CollapseEmptyLines(lines); + return lines.Count == 0 ? null : string.Join(Environment.NewLine, lines); + } + + /// The text after the comment marker, or null for code and blank lines. + private static string GetCommentText(string line) + { + var trimmed = line.Trim(); + if (trimmed.StartsWith(CommentMarker, StringComparison.Ordinal)) + return trimmed.Substring(CommentMarker.Length).TrimEnd(); + if (trimmed.StartsWith(RemMarker, StringComparison.OrdinalIgnoreCase)) + return trimmed.Substring(RemMarker.Length).TrimEnd(); + return null; + } + + private static bool IsSeparator(string text) + { + var trimmed = text.Trim(); + return trimmed.Length >= MinSeparatorLength && trimmed.All(c => SeparatorChars.Contains(c)); + } + + private static List RemoveCommonIndent(List lines) + { + var indents = lines.Where(line => line.Length > 0).Select(line => line.Length - line.TrimStart().Length).ToList(); + var commonIndent = indents.Count == 0 ? 0 : indents.Min(); + return lines.Select(line => line.Length == 0 ? line : line.Substring(commonIndent)).ToList(); + } + + private static List CollapseEmptyLines(List lines) + { + var result = new List(); + foreach (var line in lines) + { + var previousIsEmpty = result.Count == 0 || result[result.Count - 1].Length == 0; + if (line.Length == 0 && previousIsEmpty) + continue; + result.Add(line); + } + if (result.Count > 0 && result[result.Count - 1].Length == 0) + result.RemoveAt(result.Count - 1); + return result; + } + } +} diff --git a/mcp-server/AccUnit.McpServer/Program.cs b/mcp-server/AccUnit.McpServer/Program.cs new file mode 100644 index 0000000..e62a1d7 --- /dev/null +++ b/mcp-server/AccUnit.McpServer/Program.cs @@ -0,0 +1,47 @@ +using System.Threading.Tasks; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; +using ModelContextProtocol.Protocol; + +namespace AccessCodeLib.AccUnit.McpServer +{ + internal static class Program + { + private const string ServerName = "AccUnit.McpServer"; + + private static async Task Main(string[] args) + { + var builder = Host.CreateApplicationBuilder(args); + + // stdout carries the MCP protocol; all log output must go to stderr. + builder.Logging.AddConsole(options => options.LogToStandardErrorThreshold = LogLevel.Trace); + + builder.Services.AddSingleton(); + builder.Services.AddSingleton(); + builder.Services.AddSingleton(); + builder.Services.AddSingleton(); + builder.Services.AddSingleton(); + builder.Services.AddSingleton(); + builder.Services.AddSingleton(); + builder.Services.AddSingleton(_ => new SkillInstaller()); + builder.Services + .AddMcpServer(options => + { + 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(); + + await builder.Build().RunAsync(); + } + } +} diff --git a/mcp-server/AccUnit.McpServer/SessionTools.cs b/mcp-server/AccUnit.McpServer/SessionTools.cs new file mode 100644 index 0000000..7c65317 --- /dev/null +++ b/mcp-server/AccUnit.McpServer/SessionTools.cs @@ -0,0 +1,55 @@ +using System.ComponentModel; +using ModelContextProtocol; +using ModelContextProtocol.Server; + +namespace AccessCodeLib.AccUnit.McpServer +{ + /// + /// Opens and closes the file with the VBA project under test. The tool names are host neutral, + /// so further hosts (e.g. Excel) can be added later without changing the interface. + /// + [McpServerToolType] + public class SessionTools + { + private readonly AccessSession _session; + + public SessionTools(AccessSession session) + { + _session = session; + } + + [McpServerTool(Name = "accunit_open")] + [Description("Opens the file with the VBA project under test in a visible Office instance owned by this server. " + + "Currently supported: Microsoft Access databases (.accdb, .accda, .mdb), opened exclusively. " + + "Only one file can be open at a time. The file should be in a trusted location, otherwise VBA code does not run. " + + "By default the startup code (AutoExec, startup form) is skipped like opening with the Shift key held down.")] + public SessionStatus Open( + [Description("Absolute path of the file (.accdb, .accda or .mdb).")] string filePath, + [Description("Skip AutoExec and the startup form (Shift bypass). Set to false if the tests need the startup code. " + + "Has no effect if the database sets AllowBypassKey = False.")] bool bypassStartup = true) + { + try + { + return _session.Open(filePath, bypassStartup); + } + catch (DatabaseSessionException ex) + { + throw new McpException(ex.Message); + } + } + + [McpServerTool(Name = "accunit_close")] + [Description("Closes the open file without saving and quits the Office instance of this server.")] + public CloseResult Close() + { + return _session.Close(); + } + + [McpServerTool(Name = "accunit_status", ReadOnly = true)] + [Description("Returns whether a file is open, its path, the application version, the process id and whether the file is trusted.")] + public SessionStatus GetStatus() + { + return _session.GetStatus(); + } + } +} diff --git a/mcp-server/AccUnit.McpServer/ShiftKeyScope.cs b/mcp-server/AccUnit.McpServer/ShiftKeyScope.cs new file mode 100644 index 0000000..5902252 --- /dev/null +++ b/mcp-server/AccUnit.McpServer/ShiftKeyScope.cs @@ -0,0 +1,33 @@ +using System; +using System.Runtime.InteropServices; + +namespace AccessCodeLib.AccUnit.McpServer +{ + /// + /// Holds the Shift key down until disposed. Access skips AutoExec and the startup form + /// when Shift is down while a database opens; there is no automation switch for this. + /// The key state is system-wide, so keep the scope as short as possible. + /// + internal sealed class ShiftKeyScope : IDisposable + { + private const byte VirtualKeyShift = 0x10; + private const uint KeyEventKeyUp = 0x0002; + + private bool _released; + + public ShiftKeyScope() + { + keybd_event(VirtualKeyShift, 0, 0, UIntPtr.Zero); + } + + public void Dispose() + { + if (_released) return; + keybd_event(VirtualKeyShift, 0, KeyEventKeyUp, UIntPtr.Zero); + _released = true; + } + + [DllImport("user32.dll")] + private static extern void keybd_event(byte virtualKey, byte scanCode, uint flags, UIntPtr extraInfo); + } +} 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/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/StaComDispatcher.cs b/mcp-server/AccUnit.McpServer/StaComDispatcher.cs new file mode 100644 index 0000000..35b3f67 --- /dev/null +++ b/mcp-server/AccUnit.McpServer/StaComDispatcher.cs @@ -0,0 +1,86 @@ +using System; +using System.Collections.Concurrent; +using System.Runtime.ExceptionServices; +using System.Threading; + +namespace AccessCodeLib.AccUnit.McpServer +{ + /// + /// Runs all COM work on one dedicated STA thread, strictly one item after another. + /// Office automation and callbacks from VBA require an STA thread, and AccUnit must never + /// run tests or VBA calls in parallel against one Access instance. + /// + public sealed class StaComDispatcher : IDisposable + { + private const string ThreadName = "AccUnit.McpServer.STA"; + + private readonly BlockingCollection _workItems = new BlockingCollection(); + private readonly Thread _thread; + private bool _disposed; + + public StaComDispatcher() + { + _thread = new Thread(ProcessWorkItems) { Name = ThreadName, IsBackground = true }; + _thread.SetApartmentState(ApartmentState.STA); + _thread.Start(); + } + + public bool IsDispatcherThread + { + get { return Thread.CurrentThread == _thread; } + } + + public T Invoke(Func work) + { + if (work == null) throw new ArgumentNullException(nameof(work)); + if (_disposed) throw new ObjectDisposedException(nameof(StaComDispatcher)); + + // Re-entrant calls would dead-lock the queue; run them directly. + if (IsDispatcherThread) + return work(); + + var result = default(T); + ExceptionDispatchInfo error = null; + using (var done = new ManualResetEventSlim(false)) + { + _workItems.Add(() => + { + try { result = work(); } + catch (Exception ex) { error = ExceptionDispatchInfo.Capture(ex); } + finally { done.Set(); } + }); + done.Wait(); + } + + if (error != null) + error.Throw(); + + return result; + } + + public void Invoke(Action work) + { + if (work == null) throw new ArgumentNullException(nameof(work)); + Invoke(() => { work(); return null; }); + } + + private void ProcessWorkItems() + { + // Managed waits on an STA thread pump COM messages, so callbacks from VBA are delivered. + foreach (var workItem in _workItems.GetConsumingEnumerable()) + { + workItem(); + } + } + + public void Dispose() + { + if (_disposed) return; + _disposed = true; + _workItems.CompleteAdding(); + if (!IsDispatcherThread) + _thread.Join(); + _workItems.Dispose(); + } + } +} diff --git a/mcp-server/AccUnit.McpServer/StartupBypassDecision.cs b/mcp-server/AccUnit.McpServer/StartupBypassDecision.cs new file mode 100644 index 0000000..3ea1091 --- /dev/null +++ b/mcp-server/AccUnit.McpServer/StartupBypassDecision.cs @@ -0,0 +1,36 @@ +namespace AccessCodeLib.AccUnit.McpServer +{ + /// + /// Decides whether the Shift key is held while opening a database, to skip AutoExec and the startup form. + /// + public sealed class StartupBypassDecision + { + private StartupBypassDecision(bool pressShiftKey, string warning) + { + PressShiftKey = pressShiftKey; + Warning = warning; + } + + public bool PressShiftKey { get; } + + public string Warning { get; } + + /// The client asked to skip the startup code. + /// Value of the database property AllowBypassKey; null if it could not be read. + public static StartupBypassDecision Create(bool bypassRequested, bool? allowBypassKey) + { + if (!bypassRequested) + return new StartupBypassDecision(false, null); + + if (allowBypassKey == false) + return new StartupBypassDecision(false, + "The database disables the bypass key (AllowBypassKey = False). AutoExec and the startup form run."); + + if (allowBypassKey == null) + return new StartupBypassDecision(true, + "AllowBypassKey could not be read. The startup code is skipped only if the bypass key is allowed."); + + return new StartupBypassDecision(true, null); + } + } +} diff --git a/mcp-server/AccUnit.McpServer/TestAuthoringGuide.cs b/mcp-server/AccUnit.McpServer/TestAuthoringGuide.cs new file mode 100644 index 0000000..d3eed47 --- /dev/null +++ b/mcp-server/AccUnit.McpServer/TestAuthoringGuide.cs @@ -0,0 +1,38 @@ +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. + +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). + +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"")); arrays next to other values as {""a"", ""b""}, + Array(...) only as the only value of a row. +- Iz.EqualTo distinguishes vbNullString and """". +- 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). +- Save the test class as .cls in the testFolder returned by accunit_generate_test_class and import it + 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/TestClassDraft.cs b/mcp-server/AccUnit.McpServer/TestClassDraft.cs new file mode 100644 index 0000000..565cd5e --- /dev/null +++ b/mcp-server/AccUnit.McpServer/TestClassDraft.cs @@ -0,0 +1,30 @@ +using System.Collections.Generic; + +namespace AccessCodeLib.AccUnit.McpServer +{ + /// Draft of a test class: the AI fills the test methods from the specification. + 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(); + } + + public class MethodUnderTest + { + public string Name { get; set; } + + /// Procedure, Property Get, Property Let or Property Set. + public string Kind { get; set; } + + /// Declaration line(s) of the procedure as in the code. + public string Declaration { get; set; } + + /// Comment above the procedure (e.g. NaturalDoc), if any. + public string Comment { get; set; } + } +} diff --git a/mcp-server/AccUnit.McpServer/TestClassDraftService.cs b/mcp-server/AccUnit.McpServer/TestClassDraftService.cs new file mode 100644 index 0000000..3b6116a --- /dev/null +++ b/mcp-server/AccUnit.McpServer/TestClassDraftService.cs @@ -0,0 +1,112 @@ +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; + +namespace AccessCodeLib.AccUnit.McpServer +{ + /// + /// Creates the draft of a test class for a module of the open database with the AccUnit test code generator + /// (as the VBE add-in does). Reads the VBA project only; nothing is written to the database. + /// + public sealed class TestClassDraftService + { + private readonly AccessSession _session; + + public TestClassDraftService(AccessSession session) + { + _session = session ?? throw new ArgumentNullException(nameof(session)); + } + + public TestClassDraft CreateDraft(string moduleName, IList methodNames) + { + if (string.IsNullOrWhiteSpace(moduleName)) + throw new DatabaseSessionException("The name of the module under test is missing."); + + return _session.Execute(application => + CreateDraftOnStaThread(VBProjectLocator.GetCurrentVBProject(application), moduleName, methodNames)); + } + + private static TestClassDraft CreateDraftOnStaThread(VBProject vbProject, string moduleName, IList methodNames) + { + using (var modules = new CodeModuleContainer(vbProject)) + { + var codeModule = modules.TryGetCodeModule(moduleName); + if (codeModule == null) + throw new DatabaseSessionException("Module not found: " + moduleName); + + return CreateDraft(vbProject, new CodeModuleReader(codeModule), moduleName, methodNames); + } + } + + private static TestClassDraft CreateDraft(VBProject vbProject, CodeModuleReader reader, string moduleName, IList methodNames) + { + var members = SelectMembers(reader.Members.FindAll(true), methodNames); + + var generator = new TestCodeGenerator(); + generator.Add(members); + + return new TestClassDraft + { + TestClassName = new TestClassNameGenerator(vbProject).GetTestClassName(moduleName), + ModuleUnderTest = moduleName, + SourceCode = generator.GenerateSourceCode(), + TestFolder = GetTestFolder(vbProject), + MethodsUnderTest = members.Select(member => new MethodUnderTest + { + Name = member.Name, + Kind = GetKind(member.ProcKind), + Declaration = member.DeclarationString, + Comment = ProcedureCommentFormatter.Format(reader.GetProcedureHeader(member.Name, member.ProcKind)) + }).ToList() + }; + } + + 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) + return publicMembers; + + var unknown = methodNames.Where(name => !publicMembers.Any(m => string.Equals(m.Name, name, StringComparison.OrdinalIgnoreCase))).ToList(); + if (unknown.Count > 0) + throw new DatabaseSessionException("No public method with this name: " + string.Join(", ", unknown)); + + return publicMembers.Where(m => methodNames.Contains(m.Name, StringComparer.OrdinalIgnoreCase)).ToList(); + } + + private static string GetKind(vbext_ProcKind procKind) + { + switch (procKind) + { + case vbext_ProcKind.vbext_pk_Get: return "Property Get"; + case vbext_ProcKind.vbext_pk_Let: return "Property Let"; + case vbext_ProcKind.vbext_pk_Set: return "Property Set"; + default: return "Procedure"; + } + } + + /// Uses the naming of the AccUnit test class generator (setting TestClassNameFormat, e.g. "...Tests"). + private sealed class TestClassNameGenerator : TestClassGenerator + { + public TestClassNameGenerator(VBProject vbProject) : base(vbProject) + { + } + + public string GetTestClassName(string moduleUnderTest) + { + return GenerateTestClassName(moduleUnderTest, true); + } + } + } +} diff --git a/mcp-server/AccUnit.McpServer/TestClassImportService.cs b/mcp-server/AccUnit.McpServer/TestClassImportService.cs new file mode 100644 index 0000000..129b801 --- /dev/null +++ b/mcp-server/AccUnit.McpServer/TestClassImportService.cs @@ -0,0 +1,217 @@ +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. + private static Encoding AnsiEncoding + { + get { return VbaSourceFile.AnsiEncoding; } + } + + 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) + { + // Copies with export header, so code without header (e.g. the draft) is imported as class module; + // the core converts them to the ANSI code page. + var importDirectory = Path.Combine(Path.GetTempPath(), "AccUnitMcpServer", "Import-" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(importDirectory); + try + { + var copies = files.Select(file => new CodeModuleInfo(new FileInfo(file.WriteImportCopy(importDirectory)))).ToList(); + + // Same import as the VBE add-in: an existing module with the same name is replaced. + testClassManager.ImportTestComponents(copies, true); + result.ImportedModules.AddRange(files.Select(file => file.ModuleName)); + } + catch (UnsupportedSourceCharactersException ex) + { + // Not expected after the check per file; the core imports nothing in this case. + throw new DatabaseSessionException(ex.Message, ex); + } + finally + { + Directory.Delete(importDirectory, 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/TestEnvironment.cs b/mcp-server/AccUnit.McpServer/TestEnvironment.cs new file mode 100644 index 0000000..eeddfdb --- /dev/null +++ b/mcp-server/AccUnit.McpServer/TestEnvironment.cs @@ -0,0 +1,78 @@ +using System; +using System.Collections.Generic; +using AccessCodeLib.AccUnit.Configuration; +using Microsoft.Vbe.Interop; +using Access = Microsoft.Office.Interop.Access; + +namespace AccessCodeLib.AccUnit.McpServer +{ + /// + /// Prepares the VBA project of the open database so that the tests can be run from outside Access. + /// Must be used on the STA thread of the session. + /// + internal sealed class TestEnvironment + { + private const Access.AcCommand CompileAndSaveAllModules = (Access.AcCommand)126; // acCmdCompileAndSaveAllModules + private const string FactoryModuleName = "AccUnit_Factory"; + + private readonly Access.Application _application; + private readonly VBProject _vbProject; + + public TestEnvironment(Access.Application application, VBProject vbProject) + { + _application = application; + _vbProject = vbProject; + } + + public List Changes { get; } = new List(); + + /// Compiles and saves all modules. A compile error does not show a dialog. + public bool Compile() + { + _application.RunCommand(CompileAndSaveAllModules); + return _application.IsCompiled; + } + + /// + /// Test classes use Assert/Iz and the test suite from AccUnit_Factory, as in the Immediate window. + /// + public void EnsureFactoryModule() + { + if (ComponentExists(FactoryModuleName)) + return; + + using (var configurator = new Configurator()) + { + configurator.InsertAccUnitLoaderFactoryModule(false, false, _vbProject, _application); + } + Changes.Add("Inserted module " + FactoryModuleName + "."); + } + + /// + /// AccUnit creates the test class instances through factory methods in AccUnit_TestClassFactory and adds + /// missing methods while the tests are added. Changing the VBA project resets it after a call from outside + /// Access, which destroys the new instances. So the methods are created before the run. + /// + public void EnsureTestClassFactoryMethods(IEnumerable classNames) + { + var added = false; + using (var factoryManager = new TestClassFactoryManager(_vbProject, new TestClassReader(_vbProject))) + { + foreach (var className in classNames) + added |= factoryManager.EnsureFactoryMethodExists(className); + } + if (added) + Changes.Add("Added factory methods to module AccUnit_TestClassFactory."); + } + + private bool ComponentExists(string name) + { + foreach (VBComponent component in _vbProject.VBComponents) + { + if (string.Equals(component.Name, name, StringComparison.OrdinalIgnoreCase)) + return true; + } + return false; + } + } +} diff --git a/mcp-server/AccUnit.McpServer/TestEnvironmentService.cs b/mcp-server/AccUnit.McpServer/TestEnvironmentService.cs new file mode 100644 index 0000000..27d75b2 --- /dev/null +++ b/mcp-server/AccUnit.McpServer/TestEnvironmentService.cs @@ -0,0 +1,89 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using AccessCodeLib.AccUnit.Configuration; +using AccessCodeLib.Common.VBIDETools; +using Microsoft.Vbe.Interop; + +namespace AccessCodeLib.AccUnit.McpServer +{ + /// + /// Removes the AccUnit test environment from the open database, like the menu item of the VBE add-in. + /// + public sealed class TestEnvironmentService + { + private const string TestClassFactoryModuleName = "AccUnit_TestClassFactory"; + + private readonly AccessSession _session; + + public TestEnvironmentService(AccessSession session) + { + _session = session ?? throw new ArgumentNullException(nameof(session)); + } + + public RemoveTestEnvironmentResult RemoveTestEnvironment(bool removeTestModules, bool exportBeforeRemoving) + { + var result = _session.Execute(application => + RemoveOnStaThread(VBProjectLocator.GetCurrentVBProject(application), removeTestModules, exportBeforeRemoving)); + + // The modules are removed with VBComponents.Remove (AccUnit core). Access keeps that only if the + // VBA project is saved, as when closing Access interactively, so save and open the database again. + _session.SaveAndReopen(); + result.Message = "Removed and saved; the database was closed with saving and opened again."; + return result; + } + + private static RemoveTestEnvironmentResult RemoveOnStaThread(VBProject vbProject, bool removeTestModules, bool exportBeforeRemoving) + { + var componentsBefore = GetComponentNames(vbProject); + var exportFolder = removeTestModules && exportBeforeRemoving ? GetExportFolder(vbProject) : null; + + // Removes AccUnit_Factory and the AccUnit type library reference; with removeTestModules also the test classes. + using (var configurator = new Configurator(vbProject)) + { + configurator.RemoveTestEnvironment(removeTestModules, exportBeforeRemoving, vbProject); + } + + // The MCP server adds AccUnit_TestClassFactory for test runs; Configurator removes it only together with the test classes. + if (GetComponentNames(vbProject).Contains(TestClassFactoryModuleName, StringComparer.OrdinalIgnoreCase)) + { + using (var factoryManager = new TestClassFactoryManager(vbProject, new TestClassReader(vbProject))) + { + factoryManager.DeleteFactoryCodeModule(); + } + } + + return new RemoveTestEnvironmentResult + { + RemovedModules = componentsBefore.Except(GetComponentNames(vbProject), StringComparer.OrdinalIgnoreCase).ToList(), + ExportFolder = exportFolder + }; + } + + private static string GetExportFolder(VBProject vbProject) + { + using (var testClassManager = new TestClassManager(new VBProjectOnlyApplicatonHelper(vbProject))) + { + return testClassManager.ExportDirectory; + } + } + + private static List GetComponentNames(VBProject vbProject) + { + var names = new List(); + foreach (VBComponent component in vbProject.VBComponents) + names.Add(component.Name); + return names; + } + } + + public class RemoveTestEnvironmentResult + { + public List RemovedModules { get; set; } = new List(); + + /// Folder with the exported test classes (only if test classes were removed and exported). + public string ExportFolder { get; set; } + + public string Message { get; set; } + } +} diff --git a/mcp-server/AccUnit.McpServer/TestListing.cs b/mcp-server/AccUnit.McpServer/TestListing.cs new file mode 100644 index 0000000..b69c6af --- /dev/null +++ b/mcp-server/AccUnit.McpServer/TestListing.cs @@ -0,0 +1,22 @@ +using System.Collections.Generic; + +namespace AccessCodeLib.AccUnit.McpServer +{ + public class TestClassListing + { + public string ClassName { get; set; } + public List Tags { get; set; } = new List(); + public List Tests { get; set; } = new List(); + } + + public class TestMethodListing + { + public string Name { get; set; } + public List Tags { get; set; } = new List(); + public bool Ignored { get; set; } + public string IgnoreComment { get; set; } + + /// Number of data rows of a row test; 0 for a simple test. + public int RowCount { get; set; } + } +} 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/TestModuleSourceFile.cs b/mcp-server/AccUnit.McpServer/TestModuleSourceFile.cs new file mode 100644 index 0000000..e74c4e0 --- /dev/null +++ b/mcp-server/AccUnit.McpServer/TestModuleSourceFile.cs @@ -0,0 +1,121 @@ +using System; +using System.IO; +using System.Linq; +using System.Text; +using System.Text.RegularExpressions; +using AccessCodeLib.Common.VBIDETools; + +namespace AccessCodeLib.AccUnit.McpServer +{ + /// + /// A test class or test related module in a source file (VBA export format, UTF-8 or ANSI), checked before it is imported. + /// The encoding (VbaSourceFile) and the conversion to ANSI for VBComponents.Import are done by the AccUnit core; + /// this class adds the checks of the MCP server and the export header for code without header. + /// + 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 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, VbaSourceFile.ReadAllText(filePath, ansiEncoding)); + } + + /// 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 + "\")."; + + // Checked per file, so the other files are still imported (the core rejects the whole import). + if (!VbaSourceFile.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 as it is imported (with export header) in UTF-8 with BOM and CRLF line endings; + /// the core converts it to the ANSI code page for VBComponents.Import. + /// + /// Path of the copy (same file name). + public string WriteImportCopy(string directory) + { + var copyPath = Path.Combine(directory, Path.GetFileName(FilePath)); + File.WriteAllText(copyPath, VbaSourceFile.ToCrLf(GetImportSource()), VbaSourceFile.Utf8BomEncoding); + return copyPath; + } + + /// + /// 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 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; + } + } +} diff --git a/mcp-server/AccUnit.McpServer/TestResultMapper.cs b/mcp-server/AccUnit.McpServer/TestResultMapper.cs new file mode 100644 index 0000000..46876a8 --- /dev/null +++ b/mcp-server/AccUnit.McpServer/TestResultMapper.cs @@ -0,0 +1,38 @@ +using System.Collections.Generic; +using System.Linq; + +namespace AccessCodeLib.AccUnit.McpServer +{ + /// + /// Builds the result of the MCP tool accunit_run_tests from the single test results. + /// + public static class TestResultMapper + { + public static TestRunResult CreateRunResult(IEnumerable testResults, + IEnumerable notRunnableClasses, + bool includePassed) + { + var infos = testResults.ToList(); + var notRunnable = notRunnableClasses.ToList(); + + var summary = new TestRunSummary + { + Total = infos.Count, + Passed = infos.Count(i => i.Status == TestStatus.Passed), + Failed = infos.Count(i => i.Status == TestStatus.Failed), + Errors = infos.Count(i => i.Status == TestStatus.Error), + Ignored = infos.Count(i => i.Status == TestStatus.Ignored), + NotRunnable = notRunnable.Count, + ElapsedMilliseconds = infos.Sum(i => i.ElapsedMilliseconds) + }; + summary.Success = summary.Failed == 0 && summary.Errors == 0 && summary.NotRunnable == 0; + + return new TestRunResult + { + Summary = summary, + Results = infos.Where(i => includePassed || i.Status != TestStatus.Passed).ToList(), + NotRunnableClasses = notRunnable + }; + } + } +} diff --git a/mcp-server/AccUnit.McpServer/TestRunResult.cs b/mcp-server/AccUnit.McpServer/TestRunResult.cs new file mode 100644 index 0000000..4cfc0f7 --- /dev/null +++ b/mcp-server/AccUnit.McpServer/TestRunResult.cs @@ -0,0 +1,53 @@ +using System.Collections.Generic; + +namespace AccessCodeLib.AccUnit.McpServer +{ + public class TestRunResult + { + public TestRunSummary Summary { get; set; } + + /// Failed, error and ignored tests; passed tests only if requested. + public List Results { get; set; } = new List(); + + /// Test classes that could not be prepared for a run from the MCP server. + public List NotRunnableClasses { get; set; } = new List(); + + /// Changes the server made to the database to be able to run the tests. + public List EnvironmentChanges { get; set; } = new List(); + } + + public class TestRunSummary + { + public int Total { get; set; } + public int Passed { get; set; } + public int Failed { get; set; } + public int Errors { get; set; } + public int Ignored { get; set; } + public int NotRunnable { get; set; } + public double ElapsedMilliseconds { get; set; } + public bool Success { get; set; } + } + + public class TestResultInfo + { + public string Test { get; set; } + public string Status { get; set; } + public string Message { get; set; } + public double ElapsedMilliseconds { get; set; } + } + + public class NotRunnableTestClass + { + public string ClassName { get; set; } + public string Reason { get; set; } + } + + public static class TestStatus + { + public const string Passed = "passed"; + public const string Failed = "failed"; + public const string Error = "error"; + public const string Ignored = "ignored"; + public const string NotExecuted = "notExecuted"; + } +} diff --git a/mcp-server/AccUnit.McpServer/TestRunService.cs b/mcp-server/AccUnit.McpServer/TestRunService.cs new file mode 100644 index 0000000..284047d --- /dev/null +++ b/mcp-server/AccUnit.McpServer/TestRunService.cs @@ -0,0 +1,207 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Runtime.InteropServices; +using AccessCodeLib.AccUnit.Interfaces; +using Microsoft.Vbe.Interop; +using Access = Microsoft.Office.Interop.Access; + +namespace AccessCodeLib.AccUnit.McpServer +{ + /// + /// Lists and runs the AccUnit tests of the database opened in the . + /// + public sealed class TestRunService + { + private const string ProjectDoesNotCompileMessage = + "The VBA project does not compile. Open the database in Access and compile it (Debug > Compile) to see the error."; + private const string LoaderNotAvailableMessage = + "The tests run with the AccUnitLoader add-in, which was not found. Install AccUnit " + + "(AccUnitLoader.accda in %APPDATA%\\Microsoft\\AddIns) and run the tests again."; + private const string LoaderFileName = "AccUnitLoader"; + private const string LoaderFileExtension = ".accda"; + private const string LoaderFactoryProcedureName = "GetAccUnitFactory"; + private const int NoTestReportOutput = 0; // TestReportOutput: no DebugPrint/LogFile reporter + + private readonly AccessSession _session; + + public TestRunService(AccessSession session) + { + _session = session ?? throw new ArgumentNullException(nameof(session)); + } + + public List ListTests(IList classNames) + { + return _session.Execute(application => ListTestsOnStaThread(GetVBProject(application), classNames)); + } + + public TestRunResult RunTests(IList classNames, IList testNameFilter, IList tags, bool includePassed) + { + return _session.Execute(application => + { + try + { + return RunTestsOnStaThread(application, classNames, testNameFilter, tags, includePassed); + } + finally + { + // Release the COM objects of the loader and the test suite now; Access does not quit while they are referenced. + GC.Collect(); + GC.WaitForPendingFinalizers(); + } + }); + } + + private static List ListTestsOnStaThread(VBProject vbProject, IList classNames) + { + var reader = new TestClassReader(vbProject); + return reader.GetTestClasses(true) + .Where(testClass => IsSelected(testClass.Name, classNames)) + .Select(testClass => new TestClassListing + { + ClassName = testClass.Name, + Tags = GetTagNames(testClass.Tags), + Tests = testClass.Members.Select(member => new TestMethodListing + { + Name = member.Name, + Tags = GetTagNames(member.Tags), + Ignored = member.IgnoreInfo.Ignore, + IgnoreComment = string.IsNullOrEmpty(member.IgnoreInfo.Comment) ? null : member.IgnoreInfo.Comment, + // GetTestClasses does not read the data rows; only the member info of a single member does. + RowCount = reader.GetTestClassMemberInfo(testClass.Name, member.Name).TestRows.Count + }).ToList() + }) + .ToList(); + } + + private static TestRunResult RunTestsOnStaThread(Access.Application application, IList classNames, + IList testNameFilter, IList tags, bool includePassed) + { + // Check first, so the database is not changed when no test can run. + EnsureLoaderIsInstalled(); + + var vbProject = GetVBProject(application); + var environment = new TestEnvironment(application, vbProject); + + // Test classes use Assert/Iz from AccUnit_Factory, so the project only compiles with that module. + environment.EnsureFactoryModule(); + if (!environment.Compile()) + throw new DatabaseSessionException(ProjectDoesNotCompileMessage); + + var notRunnable = new List(); + var selectedClasses = SelectTestClasses(vbProject, classNames, notRunnable); + + var testResults = new List(); + if (selectedClasses.Count > 0) + { + environment.EnsureTestClassFactoryMethods(selectedClasses); + if (!environment.Compile()) + throw new DatabaseSessionException(ProjectDoesNotCompileMessage); + testResults = RunTestSuite(application, selectedClasses, testNameFilter, tags); + } + + var result = TestResultMapper.CreateRunResult(testResults, notRunnable, includePassed); + result.EnvironmentChanges.AddRange(environment.Changes); + return result; + } + + private static List SelectTestClasses(VBProject vbProject, IList classNames, List notRunnable) + { + var testClassNames = new TestClassReader(vbProject).GetTestClasses().Select(testClass => testClass.Name).ToList(); + if (classNames == null || classNames.Count == 0) + return testClassNames; + + foreach (var missing in classNames.Where(name => !testClassNames.Contains(name, StringComparer.OrdinalIgnoreCase))) + { + notRunnable.Add(new NotRunnableTestClass + { + ClassName = missing, + Reason = "No test class with this name. A test class needs the header comment: 'AccUnit:TestClass" + }); + } + return testClassNames.Where(name => IsSelected(name, classNames)).ToList(); + } + + /// + /// Same as TestSuite.AddByClassName("...").Run in the Immediate window, but with the test suite of the + /// AccUnitLoader factory that also writes a JUnit XML file: the suite runs inside Access, so private test + /// classes work, and the results are read from the file (the test objects are not reachable late bound). + /// + private static List RunTestSuite(Access.Application application, IEnumerable classNames, + IList testNameFilter, IList tags) + { + var junitXmlFilePath = PrepareJUnitXmlFile(); + var testSuite = LateBinding.GetProperty(GetLoaderFactory(application), "TestSuite", NoTestReportOutput, junitXmlFilePath); + + foreach (var className in classNames) + LateBinding.CallMethod(testSuite, "AddByClassName", className); + if (testNameFilter != null && testNameFilter.Count > 0) + LateBinding.CallMethod(testSuite, "SelectTests", testNameFilter.ToArray()); + if (tags != null && tags.Count > 0) + LateBinding.CallMethod(testSuite, "Filter", tags.ToArray()); + + LateBinding.CallMethod(testSuite, "Run"); + + if (!File.Exists(junitXmlFilePath)) + throw new DatabaseSessionException("AccUnit did not write the test results (" + junitXmlFilePath + ")."); + return JUnitResultReader.Read(File.ReadAllText(junitXmlFilePath)); + } + + private static string LoaderPath + { + get + { + return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), + "Microsoft", "AddIns", LoaderFileName); + } + } + + private static void EnsureLoaderIsInstalled() + { + if (!File.Exists(LoaderPath + LoaderFileExtension)) + throw new DatabaseSessionException(LoaderNotAvailableMessage); + } + + private static object GetLoaderFactory(Access.Application application) + { + try + { + // Application.Run has 30 ByRef parameters in the interop assembly; call it late bound. + return LateBinding.CallMethod(application, "Run", LoaderPath + "." + LoaderFactoryProcedureName); + } + catch (COMException ex) + { + throw new DatabaseSessionException(LoaderNotAvailableMessage + " (" + ex.Message + ")", ex); + } + } + + private static string PrepareJUnitXmlFile() + { + var directory = Path.Combine(Path.GetTempPath(), "AccUnitMcpServer"); + Directory.CreateDirectory(directory); + var filePath = Path.Combine(directory, "TestResults-" + Process.GetCurrentProcess().Id + ".xml"); + // A result file of an earlier run must never be read as the result of this run. + if (File.Exists(filePath)) + File.Delete(filePath); + return filePath; + } + + private static VBProject GetVBProject(Access.Application application) + { + return VBProjectLocator.GetCurrentVBProject(application); + } + + private static bool IsSelected(string className, IList classNames) + { + return classNames == null || classNames.Count == 0 || + classNames.Contains(className, StringComparer.OrdinalIgnoreCase); + } + + private static List GetTagNames(ITagList tags) + { + return tags == null ? new List() : tags.Select(tag => tag.Name).ToList(); + } + } +} diff --git a/mcp-server/AccUnit.McpServer/TestTools.cs b/mcp-server/AccUnit.McpServer/TestTools.cs new file mode 100644 index 0000000..d854ecf --- /dev/null +++ b/mcp-server/AccUnit.McpServer/TestTools.cs @@ -0,0 +1,176 @@ +using System.Collections.Generic; +using System.ComponentModel; +using ModelContextProtocol; +using ModelContextProtocol.Server; + +namespace AccessCodeLib.AccUnit.McpServer +{ + [McpServerToolType] + public class TestTools + { + private readonly TestRunService _testRunService; + 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, + TestModuleExportService testModuleExportService) + { + _testRunService = testRunService; + _testClassDraftService = testClassDraftService; + _testEnvironmentService = testEnvironmentService; + _testClassImportService = testClassImportService; + _testModuleExportService = testModuleExportService; + } + + [McpServerTool(Name = "accunit_generate_test_class", ReadOnly = true)] + [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: 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 " + + "(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. " + + "Save the finished class as a source file (e.g. .cls in the AccUnit test folder) and import it with " + + "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) + { + try + { + return _testClassDraftService.CreateDraft(moduleName, methodNames); + } + catch (DatabaseSessionException ex) + { + throw new McpException(ex.Message); + } + } + + [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_export_test_classes")] + [Description("Exports test classes and test related modules of the open database to the AccUnit test folder (VBA export " + + "format; encoding from the AccUnit setting ImportExportEncoding, default UTF-8 with BOM), 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. " + + "With removeTestModules = true the test classes are removed as well (exported to a folder first by default). " + + "To keep the removal, Access is closed with saving and the database is opened again.")] + public RemoveTestEnvironmentResult RemoveTestEnvironment( + [Description("Also remove the test classes and test related modules.")] bool removeTestModules = false, + [Description("Export the test classes before removing them.")] bool exportBeforeRemoving = true) + { + try + { + return _testEnvironmentService.RemoveTestEnvironment(removeTestModules, exportBeforeRemoving); + } + catch (DatabaseSessionException ex) + { + throw new McpException(ex.Message); + } + } + + [McpServerTool(Name = "accunit_list_tests", ReadOnly = true)] + [Description("Lists the AccUnit test classes of the open database with their test methods, tags, ignore info and number of data rows (row tests).")] + public List ListTests( + [Description("Only these test classes (optional).")] string[] classNames = null) + { + try + { + return _testRunService.ListTests(classNames); + } + catch (DatabaseSessionException ex) + { + throw new McpException(ex.Message); + } + } + + [McpServerTool(Name = "accunit_run_tests")] + [Description("Runs AccUnit tests in the open database and returns a summary plus all failed, error and ignored tests. " + + "The tests run inside Access with the test suite of the installed AccUnitLoader add-in, as TestSuite in the Immediate window; " + + "the results are read from the JUnit XML file AccUnit writes. If needed the server inserts the module AccUnit_Factory and " + + "adds factory methods to AccUnit_TestClassFactory; these changes are kept and listed in environmentChanges.")] + public TestRunResult RunTests( + [Description("Only these test classes (optional, default: all test classes).")] string[] classNames = null, + [Description("Only tests whose name matches one of these filters, wildcards * and ? allowed (optional).")] string[] testNameFilter = null, + [Description("Only tests with all of these tags (optional).")] string[] tags = null, + [Description("Also list passed tests in results.")] bool includePassed = false) + { + try + { + return _testRunService.RunTests(classNames, testNameFilter, tags, includePassed); + } + catch (DatabaseSessionException ex) + { + throw new McpException(ex.Message); + } + } + } +} diff --git a/mcp-server/AccUnit.McpServer/VBProjectLocator.cs b/mcp-server/AccUnit.McpServer/VBProjectLocator.cs new file mode 100644 index 0000000..9ec95e4 --- /dev/null +++ b/mcp-server/AccUnit.McpServer/VBProjectLocator.cs @@ -0,0 +1,52 @@ +using System; +using System.Runtime.InteropServices; +using Microsoft.Vbe.Interop; +using Access = Microsoft.Office.Interop.Access; + +namespace AccessCodeLib.AccUnit.McpServer +{ + internal static class VBProjectLocator + { + /// + /// VBE.ActiveVBProject can point to a loaded library (e.g. a protected Access wizard) after code ran, + /// so the project is found by the file name of the open database. + /// + public static VBProject GetCurrentVBProject(Access.Application application) + { + var databasePath = GetCurrentProjectFullName(application); + var vbe = (VBE)application.VBE; + foreach (VBProject vbProject in vbe.VBProjects) + { + if (string.Equals(GetFileNameOrNull(vbProject), databasePath, StringComparison.OrdinalIgnoreCase)) + return vbProject; + } + throw new DatabaseSessionException("The VBA project of the open database was not found: " + databasePath); + } + + private static string GetCurrentProjectFullName(Access.Application application) + { + var currentProject = application.CurrentProject; + try + { + return currentProject.FullName; + } + finally + { + Marshal.ReleaseComObject(currentProject); + } + } + + private static string GetFileNameOrNull(VBProject vbProject) + { + try + { + return vbProject.FileName; + } + catch (COMException) + { + // Protected or not yet saved projects do not expose their file name. + return null; + } + } + } +} diff --git a/mcp-server/AccessCodeLib.AccUnit.McpServer.sln b/mcp-server/AccessCodeLib.AccUnit.McpServer.sln new file mode 100644 index 0000000..cc41dd4 --- /dev/null +++ b/mcp-server/AccessCodeLib.AccUnit.McpServer.sln @@ -0,0 +1,103 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.0.31903.59 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "AccUnit.McpServer", "AccUnit.McpServer", "{77FE7D31-1D6E-EBBA-DE4E-5F401342AD31}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AccessCodeLib.AccUnit.McpServer", "AccUnit.McpServer\AccessCodeLib.AccUnit.McpServer.csproj", "{55D83F5B-15D0-4BC4-9A45-9CACACFA7D9E}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Tests", "Tests", "{0AB3BF05-4346-4AA6-1389-037BE0695223}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AccessCodeLib.AccUnit.McpServer.Tests", "Tests\AccUnit.McpServer.Tests\AccessCodeLib.AccUnit.McpServer.Tests.csproj", "{53D1D3C9-2E9A-4D2B-A575-9D1B8D17E14C}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "AccUnit", "AccUnit", "{4E945CC9-25F6-8B14-E954-ABBEBA8A0AC8}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AccessCodeLib.AccUnit", "..\source\AccUnit\AccessCodeLib.AccUnit.csproj", "{1575D69A-C503-4149-B3A9-2CE188B19C15}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AccessCodeLib.Common.Tools", "..\source\Common\Common.Tools\AccessCodeLib.Common.Tools.csproj", "{7AF24615-91B3-4775-BC6E-C8986F980B57}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AccessCodeLib.Common.VBIDETools", "..\source\Common\Common.VBIDETools\AccessCodeLib.Common.VBIDETools.csproj", "{9FA679C2-82C0-42DC-A34F-F78A9012EEEB}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Debug|x64 = Debug|x64 + Debug|x86 = Debug|x86 + Release|Any CPU = Release|Any CPU + Release|x64 = Release|x64 + Release|x86 = Release|x86 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {55D83F5B-15D0-4BC4-9A45-9CACACFA7D9E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {55D83F5B-15D0-4BC4-9A45-9CACACFA7D9E}.Debug|Any CPU.Build.0 = Debug|Any CPU + {55D83F5B-15D0-4BC4-9A45-9CACACFA7D9E}.Debug|x64.ActiveCfg = Debug|Any CPU + {55D83F5B-15D0-4BC4-9A45-9CACACFA7D9E}.Debug|x64.Build.0 = Debug|Any CPU + {55D83F5B-15D0-4BC4-9A45-9CACACFA7D9E}.Debug|x86.ActiveCfg = Debug|Any CPU + {55D83F5B-15D0-4BC4-9A45-9CACACFA7D9E}.Debug|x86.Build.0 = Debug|Any CPU + {55D83F5B-15D0-4BC4-9A45-9CACACFA7D9E}.Release|Any CPU.ActiveCfg = Release|Any CPU + {55D83F5B-15D0-4BC4-9A45-9CACACFA7D9E}.Release|Any CPU.Build.0 = Release|Any CPU + {55D83F5B-15D0-4BC4-9A45-9CACACFA7D9E}.Release|x64.ActiveCfg = Release|Any CPU + {55D83F5B-15D0-4BC4-9A45-9CACACFA7D9E}.Release|x64.Build.0 = Release|Any CPU + {55D83F5B-15D0-4BC4-9A45-9CACACFA7D9E}.Release|x86.ActiveCfg = Release|Any CPU + {55D83F5B-15D0-4BC4-9A45-9CACACFA7D9E}.Release|x86.Build.0 = Release|Any CPU + {53D1D3C9-2E9A-4D2B-A575-9D1B8D17E14C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {53D1D3C9-2E9A-4D2B-A575-9D1B8D17E14C}.Debug|Any CPU.Build.0 = Debug|Any CPU + {53D1D3C9-2E9A-4D2B-A575-9D1B8D17E14C}.Debug|x64.ActiveCfg = Debug|Any CPU + {53D1D3C9-2E9A-4D2B-A575-9D1B8D17E14C}.Debug|x64.Build.0 = Debug|Any CPU + {53D1D3C9-2E9A-4D2B-A575-9D1B8D17E14C}.Debug|x86.ActiveCfg = Debug|Any CPU + {53D1D3C9-2E9A-4D2B-A575-9D1B8D17E14C}.Debug|x86.Build.0 = Debug|Any CPU + {53D1D3C9-2E9A-4D2B-A575-9D1B8D17E14C}.Release|Any CPU.ActiveCfg = Release|Any CPU + {53D1D3C9-2E9A-4D2B-A575-9D1B8D17E14C}.Release|Any CPU.Build.0 = Release|Any CPU + {53D1D3C9-2E9A-4D2B-A575-9D1B8D17E14C}.Release|x64.ActiveCfg = Release|Any CPU + {53D1D3C9-2E9A-4D2B-A575-9D1B8D17E14C}.Release|x64.Build.0 = Release|Any CPU + {53D1D3C9-2E9A-4D2B-A575-9D1B8D17E14C}.Release|x86.ActiveCfg = Release|Any CPU + {53D1D3C9-2E9A-4D2B-A575-9D1B8D17E14C}.Release|x86.Build.0 = Release|Any CPU + {1575D69A-C503-4149-B3A9-2CE188B19C15}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {1575D69A-C503-4149-B3A9-2CE188B19C15}.Debug|Any CPU.Build.0 = Debug|Any CPU + {1575D69A-C503-4149-B3A9-2CE188B19C15}.Debug|x64.ActiveCfg = Debug|Any CPU + {1575D69A-C503-4149-B3A9-2CE188B19C15}.Debug|x64.Build.0 = Debug|Any CPU + {1575D69A-C503-4149-B3A9-2CE188B19C15}.Debug|x86.ActiveCfg = Debug|Any CPU + {1575D69A-C503-4149-B3A9-2CE188B19C15}.Debug|x86.Build.0 = Debug|Any CPU + {1575D69A-C503-4149-B3A9-2CE188B19C15}.Release|Any CPU.ActiveCfg = Release|Any CPU + {1575D69A-C503-4149-B3A9-2CE188B19C15}.Release|Any CPU.Build.0 = Release|Any CPU + {1575D69A-C503-4149-B3A9-2CE188B19C15}.Release|x64.ActiveCfg = Release|Any CPU + {1575D69A-C503-4149-B3A9-2CE188B19C15}.Release|x64.Build.0 = Release|Any CPU + {1575D69A-C503-4149-B3A9-2CE188B19C15}.Release|x86.ActiveCfg = Release|Any CPU + {1575D69A-C503-4149-B3A9-2CE188B19C15}.Release|x86.Build.0 = Release|Any CPU + {7AF24615-91B3-4775-BC6E-C8986F980B57}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {7AF24615-91B3-4775-BC6E-C8986F980B57}.Debug|Any CPU.Build.0 = Debug|Any CPU + {7AF24615-91B3-4775-BC6E-C8986F980B57}.Debug|x64.ActiveCfg = Debug|Any CPU + {7AF24615-91B3-4775-BC6E-C8986F980B57}.Debug|x64.Build.0 = Debug|Any CPU + {7AF24615-91B3-4775-BC6E-C8986F980B57}.Debug|x86.ActiveCfg = Debug|Any CPU + {7AF24615-91B3-4775-BC6E-C8986F980B57}.Debug|x86.Build.0 = Debug|Any CPU + {7AF24615-91B3-4775-BC6E-C8986F980B57}.Release|Any CPU.ActiveCfg = Release|Any CPU + {7AF24615-91B3-4775-BC6E-C8986F980B57}.Release|Any CPU.Build.0 = Release|Any CPU + {7AF24615-91B3-4775-BC6E-C8986F980B57}.Release|x64.ActiveCfg = Release|Any CPU + {7AF24615-91B3-4775-BC6E-C8986F980B57}.Release|x64.Build.0 = Release|Any CPU + {7AF24615-91B3-4775-BC6E-C8986F980B57}.Release|x86.ActiveCfg = Release|Any CPU + {7AF24615-91B3-4775-BC6E-C8986F980B57}.Release|x86.Build.0 = Release|Any CPU + {9FA679C2-82C0-42DC-A34F-F78A9012EEEB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {9FA679C2-82C0-42DC-A34F-F78A9012EEEB}.Debug|Any CPU.Build.0 = Debug|Any CPU + {9FA679C2-82C0-42DC-A34F-F78A9012EEEB}.Debug|x64.ActiveCfg = Debug|Any CPU + {9FA679C2-82C0-42DC-A34F-F78A9012EEEB}.Debug|x64.Build.0 = Debug|Any CPU + {9FA679C2-82C0-42DC-A34F-F78A9012EEEB}.Debug|x86.ActiveCfg = Debug|Any CPU + {9FA679C2-82C0-42DC-A34F-F78A9012EEEB}.Debug|x86.Build.0 = Debug|Any CPU + {9FA679C2-82C0-42DC-A34F-F78A9012EEEB}.Release|Any CPU.ActiveCfg = Release|Any CPU + {9FA679C2-82C0-42DC-A34F-F78A9012EEEB}.Release|Any CPU.Build.0 = Release|Any CPU + {9FA679C2-82C0-42DC-A34F-F78A9012EEEB}.Release|x64.ActiveCfg = Release|Any CPU + {9FA679C2-82C0-42DC-A34F-F78A9012EEEB}.Release|x64.Build.0 = Release|Any CPU + {9FA679C2-82C0-42DC-A34F-F78A9012EEEB}.Release|x86.ActiveCfg = Release|Any CPU + {9FA679C2-82C0-42DC-A34F-F78A9012EEEB}.Release|x86.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(NestedProjects) = preSolution + {55D83F5B-15D0-4BC4-9A45-9CACACFA7D9E} = {77FE7D31-1D6E-EBBA-DE4E-5F401342AD31} + {53D1D3C9-2E9A-4D2B-A575-9D1B8D17E14C} = {0AB3BF05-4346-4AA6-1389-037BE0695223} + {1575D69A-C503-4149-B3A9-2CE188B19C15} = {4E945CC9-25F6-8B14-E954-ABBEBA8A0AC8} + {7AF24615-91B3-4775-BC6E-C8986F980B57} = {4E945CC9-25F6-8B14-E954-ABBEBA8A0AC8} + {9FA679C2-82C0-42DC-A34F-F78A9012EEEB} = {4E945CC9-25F6-8B14-E954-ABBEBA8A0AC8} + EndGlobalSection +EndGlobal diff --git a/mcp-server/README.md b/mcp-server/README.md new file mode 100644 index 0000000..02d6198 --- /dev/null +++ b/mcp-server/README.md @@ -0,0 +1,143 @@ +# AccUnit MCP server + +MCP server (Model Context Protocol, stdio) that lets an AI agent such as Claude Code work with AccUnit tests +in a Microsoft Access database: list and run tests, create drafts of test classes and remove the test environment. + +The tests run inside Access with the test suite of the installed AccUnitLoader add-in, +the same way as `TestSuite.AddByClassName("...").Run` in the VBA Immediate window. + +## Requirements + +- Windows with Microsoft Access (32 or 64 bit) +- .NET Framework 4.8 +- AccUnit installed: the AccUnitLoader add-in `AccUnitLoader.accda` in `%APPDATA%\Microsoft\AddIns` + (see [How-to: Install AccUnit](https://github.com/AccessCodeLib/AccUnit/wiki/How%E2%80%90to:-Install-AccUnit)) +- The database is in a trusted location, otherwise Access does not run its VBA code. + +## Installation + +1. Download `AccUnit.McpServer..zip` from the [AccUnit release](https://github.com/AccessCodeLib/AccUnit/releases) + (same version as AccUnit). +2. Unblock the zip before extracting it (file properties, or `Unblock-File` in PowerShell); + otherwise Windows may block the DLLs that were downloaded from the internet. +3. Extract it to a local folder, e.g. `C:\Tools\AccUnit.McpServer`. The DLLs must not be on a network drive. + +## Configuration + +### Claude Code + +``` +claude mcp add accunit -- "C:\Tools\AccUnit.McpServer\AccUnit.McpServer.exe" +``` + +or in the `.mcp.json` of a project: + +```json +{ + "mcpServers": { + "accunit": { + "type": "stdio", + "command": "C:\\Tools\\AccUnit.McpServer\\AccUnit.McpServer.exe", + "args": [] + } + } +} +``` + +### Other MCP clients + +Start `AccUnit.McpServer.exe` as a stdio server without arguments. Log output goes to stderr. + +## Tools + +| Tool | Parameters | Purpose | +|---|---|---| +| `accunit_open` | `filePath`, `bypassStartup` (default `true`) | Opens the database (.accdb, .accda, .mdb) exclusively in a visible Access instance owned by the server. | +| `accunit_close` | | Closes the database without saving and quits Access. | +| `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, 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). | + +### 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 +(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 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` + +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. + +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`). + +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 + an Access instance it did not start. The instance is visible. If COM hands out an Access instance that was already + running (e.g. while another Access automation runs), `accunit_open` fails and leaves that instance untouched. + If Access reports no error but has no database open afterwards, the server quits its own instance and reports it. +- **Startup code** (AutoExec, startup form) is skipped by default like opening with the Shift key held down. + This does not work if the database sets `AllowBypassKey = False`; the result then contains a warning. +- **`accunit_run_tests`** inserts the module `AccUnit_Factory` if it is missing (test classes use `Assert`/`Iz` from it) + 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_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; the + AccUnit core converts them to the ANSI code page of the VBA editor (files with 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_export_test_classes`** and **`accunit_remove_test_classes`** work only on test classes and test related + modules. They export to the AccUnit test folder in the encoding of the AccUnit setting `ImportExportEncoding` + (default UTF-8 with BOM, or ANSI); 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 + +- Microsoft Access only. The tool names are host neutral, so other hosts (e.g. Excel) can be added later. +- The AccUnitLoader add-in must be installed; without it `accunit_run_tests` reports an error and does not change the database. + +## Build + +Solution `AccessCodeLib.AccUnit.McpServer.sln` (.NET Framework 4.8). It references the AccUnit projects in `../source`; +restore their NuGet packages first (`nuget restore ../source/AccessCodeLib.AccUnit.sln`), then build with MSBuild: + +``` +msbuild AccessCodeLib.AccUnit.McpServer.sln /restore /p:Configuration=Release +``` 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 new file mode 100644 index 0000000..1f35787 --- /dev/null +++ b/mcp-server/Tests/AccUnit.McpServer.Tests/AccessCodeLib.AccUnit.McpServer.Tests.csproj @@ -0,0 +1,29 @@ + + + + net48 + AccessCodeLib.AccUnit.McpServer.Tests + AccessCodeLib.AccUnit.McpServer.Tests + false + 7.3 + + + + + + + + + + + + + + + + ..\..\..\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/AccessInstanceOwnershipTests.cs b/mcp-server/Tests/AccUnit.McpServer.Tests/AccessInstanceOwnershipTests.cs new file mode 100644 index 0000000..8c03847 --- /dev/null +++ b/mcp-server/Tests/AccUnit.McpServer.Tests/AccessInstanceOwnershipTests.cs @@ -0,0 +1,25 @@ +using NUnit.Framework; + +namespace AccessCodeLib.AccUnit.McpServer.Tests +{ + public class AccessInstanceOwnershipTests + { + [Test] + public void IsStartedByServer_NewProcess_IsTrue() + { + Assert.That(AccessInstanceOwnership.IsStartedByServer(300, new[] { 100, 200 }), Is.True); + } + + [Test] + public void IsStartedByServer_NoAccessRunningBefore_IsTrue() + { + Assert.That(AccessInstanceOwnership.IsStartedByServer(300, new int[0]), Is.True); + } + + [Test] + public void IsStartedByServer_ProcessRunningBefore_IsFalse() + { + Assert.That(AccessInstanceOwnership.IsStartedByServer(200, new[] { 100, 200 }), Is.False); + } + } +} diff --git a/mcp-server/Tests/AccUnit.McpServer.Tests/DatabasePathValidatorTests.cs b/mcp-server/Tests/AccUnit.McpServer.Tests/DatabasePathValidatorTests.cs new file mode 100644 index 0000000..faef57c --- /dev/null +++ b/mcp-server/Tests/AccUnit.McpServer.Tests/DatabasePathValidatorTests.cs @@ -0,0 +1,94 @@ +using System; +using System.IO; +using NUnit.Framework; + +namespace AccessCodeLib.AccUnit.McpServer.Tests +{ + public class DatabasePathValidatorTests + { + private string _directory; + + [SetUp] + public void SetUp() + { + _directory = Path.Combine(Path.GetTempPath(), "AccUnitMcpServerTests", Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(_directory); + } + + [TearDown] + public void TearDown() + { + Directory.Delete(_directory, true); + } + + [TestCase("test.accdb")] + [TestCase("test.ACCDB")] + [TestCase("test.accda")] + [TestCase("test.mdb")] + public void Validate_ExistingSupportedFile_ReturnsFullPath(string fileName) + { + var path = CreateFile(fileName); + + Assert.That(DatabasePathValidator.Validate(path), Is.EqualTo(path)); + } + + [TestCase(null)] + [TestCase("")] + [TestCase(" ")] + public void Validate_EmptyPath_Throws(string path) + { + Assert.Throws(() => DatabasePathValidator.Validate(path)); + } + + [Test] + public void Validate_RelativePath_Throws() + { + var ex = Assert.Throws(() => DatabasePathValidator.Validate(@"folder\test.accdb")); + Assert.That(ex.Message, Does.Contain("absolute")); + } + + [TestCase("test.accde")] + [TestCase("test.mde")] + [TestCase("test.txt")] + public void Validate_UnsupportedExtension_Throws(string fileName) + { + var path = CreateFile(fileName); + + var ex = Assert.Throws(() => DatabasePathValidator.Validate(path)); + Assert.That(ex.Message, Does.Contain("Unsupported file type")); + } + + [Test] + public void Validate_MissingFile_Throws() + { + var path = Path.Combine(_directory, "missing.accdb"); + + var ex = Assert.Throws(() => DatabasePathValidator.Validate(path)); + Assert.That(ex.Message, Does.Contain("does not exist")); + } + + [TestCase("test.accdb", "test.laccdb")] + [TestCase("test.mdb", "test.ldb")] + public void Validate_LockFileExists_Throws(string fileName, string lockFileName) + { + var path = CreateFile(fileName); + CreateFile(lockFileName); + + var ex = Assert.Throws(() => DatabasePathValidator.Validate(path)); + Assert.That(ex.Message, Does.Contain("lock file")); + } + + [Test] + public void Validate_InvalidCharacters_Throws() + { + Assert.Throws(() => DatabasePathValidator.Validate("C:\\in.accdb")); + } + + private string CreateFile(string fileName) + { + var path = Path.Combine(_directory, fileName); + File.WriteAllText(path, string.Empty); + return path; + } + } +} diff --git a/mcp-server/Tests/AccUnit.McpServer.Tests/JUnitResultReaderTests.cs b/mcp-server/Tests/AccUnit.McpServer.Tests/JUnitResultReaderTests.cs new file mode 100644 index 0000000..728e2ef --- /dev/null +++ b/mcp-server/Tests/AccUnit.McpServer.Tests/JUnitResultReaderTests.cs @@ -0,0 +1,70 @@ +using System.Linq; +using NUnit.Framework; + +namespace AccessCodeLib.AccUnit.McpServer.Tests +{ + public class JUnitResultReaderTests + { + // Format of AccessCodeLib.AccUnit.Integration.JUnitXmlWriter + private const string JUnitXml = +@" + + + + + actual is less than expected (Expected: 2 but was: 1) + + + runtime error in test + + + + + + actual is less than expected (Expected: 3 but was: 2) + + +"; + + [Test] + public void Read_ReturnsOneResultPerTestCase() + { + var results = JUnitResultReader.Read(JUnitXml); + + Assert.That(results.Select(r => r.Test), Is.EqualTo(new[] + { + "clsSampleTests.PassingTest", "clsSampleTests.FailingTest", "clsSampleTests.ErrorTest", + "clsSampleTests.IgnoredTest", "clsSampleTests.RowTest.NotEqual" + })); + } + + [Test] + public void Read_MapsStatusFromResultElement() + { + var results = JUnitResultReader.Read(JUnitXml); + + Assert.That(results.Select(r => r.Status), Is.EqualTo(new[] + { + TestStatus.Passed, TestStatus.Failed, TestStatus.Error, TestStatus.Ignored, TestStatus.Failed + })); + } + + [Test] + public void Read_UsesMessageAttributeAndNullForEmptyMessage() + { + var results = JUnitResultReader.Read(JUnitXml); + + Assert.That(results[1].Message, Is.EqualTo("actual is less than expected (Expected: 2 but was: 1)")); + Assert.That(results[0].Message, Is.Null); + Assert.That(results[3].Message, Is.Null); + } + + [Test] + public void Read_ConvertsTimeInSecondsToMilliseconds() + { + var results = JUnitResultReader.Read(JUnitXml); + + Assert.That(results[0].ElapsedMilliseconds, Is.EqualTo(12).Within(0.0001)); + } + } +} diff --git a/mcp-server/Tests/AccUnit.McpServer.Tests/ProcedureCommentFormatterTests.cs b/mcp-server/Tests/AccUnit.McpServer.Tests/ProcedureCommentFormatterTests.cs new file mode 100644 index 0000000..013832e --- /dev/null +++ b/mcp-server/Tests/AccUnit.McpServer.Tests/ProcedureCommentFormatterTests.cs @@ -0,0 +1,69 @@ +using NUnit.Framework; + +namespace AccessCodeLib.AccUnit.McpServer.Tests +{ + public class ProcedureCommentFormatterTests + { + [TestCase(null)] + [TestCase("")] + [TestCase("\r\n\r\n")] + public void Format_NoHeader_ReturnsNull(string header) + { + Assert.That(ProcedureCommentFormatter.Format(header), Is.Null); + } + + [Test] + public void Format_NaturalDocBlock_RemovesMarkersAndSeparators() + { + const string header = + "'---------------------------------------------------------------------------------------\r\n" + + "' Function: CompareVersions\r\n" + + "'---------------------------------------------------------------------------------------\r\n" + + "'\r\n" + + "' Compares two version strings.\r\n" + + "'\r\n" + + "' Parameters:\r\n" + + "' Version1 - first version\r\n" + + "' Version2 - second version\r\n" + + "'\r\n" + + "' Returns:\r\n" + + "' -1, 0 or 1\r\n" + + "'\r\n" + + "'---------------------------------------------------------------------------------------\r\n"; + + var comment = ProcedureCommentFormatter.Format(header); + + Assert.That(comment, Is.EqualTo( + "Function: CompareVersions\r\n" + + "\r\n" + + "Compares two version strings.\r\n" + + "\r\n" + + "Parameters:\r\n" + + " Version1 - first version\r\n" + + " Version2 - second version\r\n" + + "\r\n" + + "Returns:\r\n" + + " -1, 0 or 1")); + } + + [Test] + public void Format_SimpleCommentWithBlankLines_KeepsTextOnly() + { + const string header = "\r\n\r\n' Returns the net price.\r\n\r\n"; + + Assert.That(ProcedureCommentFormatter.Format(header), Is.EqualTo("Returns the net price.")); + } + + [Test] + public void Format_RemComment_IsRecognized() + { + Assert.That(ProcedureCommentFormatter.Format("Rem Old style comment\r\n"), Is.EqualTo("Old style comment")); + } + + [Test] + public void Format_OnlySeparators_ReturnsNull() + { + Assert.That(ProcedureCommentFormatter.Format("'----------\r\n'==========\r\n"), Is.Null); + } + } +} 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/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/StaComDispatcherTests.cs b/mcp-server/Tests/AccUnit.McpServer.Tests/StaComDispatcherTests.cs new file mode 100644 index 0000000..b3fa2b9 --- /dev/null +++ b/mcp-server/Tests/AccUnit.McpServer.Tests/StaComDispatcherTests.cs @@ -0,0 +1,90 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using NUnit.Framework; + +namespace AccessCodeLib.AccUnit.McpServer.Tests +{ + public class StaComDispatcherTests + { + [Test] + public void Invoke_RunsWorkOnStaThread() + { + using (var dispatcher = new StaComDispatcher()) + { + var apartment = dispatcher.Invoke(() => Thread.CurrentThread.GetApartmentState()); + + Assert.That(apartment, Is.EqualTo(ApartmentState.STA)); + } + } + + [Test] + public void Invoke_AlwaysUsesTheSameThread() + { + using (var dispatcher = new StaComDispatcher()) + { + var firstThreadId = dispatcher.Invoke(() => Thread.CurrentThread.ManagedThreadId); + var secondThreadId = dispatcher.Invoke(() => Thread.CurrentThread.ManagedThreadId); + + Assert.That(secondThreadId, Is.EqualTo(firstThreadId)); + Assert.That(firstThreadId, Is.Not.EqualTo(Thread.CurrentThread.ManagedThreadId)); + } + } + + [Test] + public void Invoke_ConcurrentCallers_WorkNeverOverlaps() + { + using (var dispatcher = new StaComDispatcher()) + { + var running = 0; + var maxRunning = 0; + + var callers = Enumerable.Range(0, 8).Select(_ => Task.Run(() => dispatcher.Invoke(() => + { + var current = Interlocked.Increment(ref running); + maxRunning = Math.Max(maxRunning, current); + Thread.Sleep(10); + Interlocked.Decrement(ref running); + }))).ToArray(); + Task.WaitAll(callers); + + Assert.That(maxRunning, Is.EqualTo(1)); + } + } + + [Test] + public void Invoke_WorkThrows_ExceptionIsPassedToCaller() + { + using (var dispatcher = new StaComDispatcher()) + { + Assert.Throws(() => + dispatcher.Invoke(() => { throw new InvalidOperationException("expected"); })); + + // The dispatcher keeps working after an error. + Assert.That(dispatcher.Invoke(() => 42), Is.EqualTo(42)); + } + } + + [Test] + public void Invoke_FromDispatcherThread_RunsDirectly() + { + using (var dispatcher = new StaComDispatcher()) + { + var result = dispatcher.Invoke(() => dispatcher.Invoke(() => "nested")); + + Assert.That(result, Is.EqualTo("nested")); + } + } + + [Test] + public void Invoke_AfterDispose_Throws() + { + var dispatcher = new StaComDispatcher(); + dispatcher.Dispose(); + + Assert.Throws(() => dispatcher.Invoke(() => 1)); + } + } +} diff --git a/mcp-server/Tests/AccUnit.McpServer.Tests/StartupBypassDecisionTests.cs b/mcp-server/Tests/AccUnit.McpServer.Tests/StartupBypassDecisionTests.cs new file mode 100644 index 0000000..e68cf85 --- /dev/null +++ b/mcp-server/Tests/AccUnit.McpServer.Tests/StartupBypassDecisionTests.cs @@ -0,0 +1,45 @@ +using NUnit.Framework; + +namespace AccessCodeLib.AccUnit.McpServer.Tests +{ + public class StartupBypassDecisionTests + { + [TestCase(true)] + [TestCase(false)] + [TestCase(null)] + public void Create_BypassNotRequested_NoShiftKeyAndNoWarning(bool? allowBypassKey) + { + var decision = StartupBypassDecision.Create(false, allowBypassKey); + + Assert.That(decision.PressShiftKey, Is.False); + Assert.That(decision.Warning, Is.Null); + } + + [Test] + public void Create_BypassAllowed_PressesShiftKeyWithoutWarning() + { + var decision = StartupBypassDecision.Create(true, true); + + Assert.That(decision.PressShiftKey, Is.True); + Assert.That(decision.Warning, Is.Null); + } + + [Test] + public void Create_BypassKeyDisabled_NoShiftKeyAndWarning() + { + var decision = StartupBypassDecision.Create(true, false); + + Assert.That(decision.PressShiftKey, Is.False); + Assert.That(decision.Warning, Does.Contain("AllowBypassKey = False")); + } + + [Test] + public void Create_BypassKeyUnknown_PressesShiftKeyAndWarns() + { + var decision = StartupBypassDecision.Create(true, null); + + Assert.That(decision.PressShiftKey, Is.True); + Assert.That(decision.Warning, Does.Contain("could not be read")); + } + } +} 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..1544eb6 --- /dev/null +++ b/mcp-server/Tests/AccUnit.McpServer.Tests/TestAuthoringGuideTests.cs @@ -0,0 +1,76 @@ +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("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")] + [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)); + } + + [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("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")] + [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")] + [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/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/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/Tests/AccUnit.McpServer.Tests/TestModuleSourceFileTests.cs b/mcp-server/Tests/AccUnit.McpServer.Tests/TestModuleSourceFileTests.cs new file mode 100644 index 0000000..fa13296 --- /dev/null +++ b/mcp-server/Tests/AccUnit.McpServer.Tests/TestModuleSourceFileTests.cs @@ -0,0 +1,153 @@ +using System; +using System.IO; +using System.Linq; +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 Read_AnsiFile_KeepsUmlauts() + { + var file = CreateFile("modStringsTests.cls", TestClassCode + "' Gr\u00F6\u00DFe\r\n", Ansi); + + Assert.That(file.SourceCode, Does.EndWith("' Gr\u00F6\u00DFe\r\n")); + } + + [Test] + public void Read_Utf8FileWithBom_KeepsUmlauts() + { + var file = CreateFile("modStringsTests.cls", TestClassCode + "' Gr\u00F6\u00DFe\r\n", new UTF8Encoding(true)); + + Assert.That(file.SourceCode, Is.EqualTo(TestClassCode + "' Gr\u00F6\u00DFe\r\n")); + } + + [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 WriteImportCopy_Utf8WithLfWithoutHeader_WritesUtf8BomWithHeaderAndCrLf() + { + var file = CreateFile("modStringsTests.cls", "'AccUnit:TestClass\n' Gr\u00F6\u00DFe\n", Encoding.UTF8); + var targetDirectory = Path.Combine(_directory, "import"); + Directory.CreateDirectory(targetDirectory); + + var copyPath = file.WriteImportCopy(targetDirectory); + + Assert.That(copyPath, Is.EqualTo(Path.Combine(targetDirectory, "modStringsTests.cls"))); + var bytes = File.ReadAllBytes(copyPath); + Assert.That(bytes.Take(3), Is.EqualTo(new UTF8Encoding(true).GetPreamble())); + var text = new UTF8Encoding(true).GetString(bytes, 3, bytes.Length - 3); + Assert.That(text, Does.StartWith("VERSION 1.0 CLASS\r\n")); + Assert.That(text, Does.EndWith("'AccUnit:TestClass\r\n' Gr\u00F6\u00DFe\r\n")); + } + } +} diff --git a/mcp-server/Tests/AccUnit.McpServer.Tests/TestResultMapperTests.cs b/mcp-server/Tests/AccUnit.McpServer.Tests/TestResultMapperTests.cs new file mode 100644 index 0000000..8048d93 --- /dev/null +++ b/mcp-server/Tests/AccUnit.McpServer.Tests/TestResultMapperTests.cs @@ -0,0 +1,70 @@ +using System.Linq; +using NUnit.Framework; + +namespace AccessCodeLib.AccUnit.McpServer.Tests +{ + public class TestResultMapperTests + { + [Test] + public void CreateRunResult_CountsResultsAndListsOnlyNotPassed() + { + var results = new[] + { + Result("clsTests.PassingTest", TestStatus.Passed, 1), + Result("clsTests.FailingTest", TestStatus.Failed, 2), + Result("clsTests.ErrorTest", TestStatus.Error), + Result("clsTests.IgnoredTest", TestStatus.Ignored), + Result("clsTests.RowTest.Equal", TestStatus.Passed) + }; + + var runResult = TestResultMapper.CreateRunResult(results, new NotRunnableTestClass[0], includePassed: false); + + Assert.That(runResult.Summary.Total, Is.EqualTo(5)); + Assert.That(runResult.Summary.Passed, Is.EqualTo(2)); + Assert.That(runResult.Summary.Failed, Is.EqualTo(1)); + Assert.That(runResult.Summary.Errors, Is.EqualTo(1)); + Assert.That(runResult.Summary.Ignored, Is.EqualTo(1)); + Assert.That(runResult.Summary.ElapsedMilliseconds, Is.EqualTo(3)); + Assert.That(runResult.Summary.Success, Is.False); + Assert.That(runResult.Results.Select(r => r.Test), + Is.EquivalentTo(new[] { "clsTests.FailingTest", "clsTests.ErrorTest", "clsTests.IgnoredTest" })); + } + + [Test] + public void CreateRunResult_IncludePassed_ListsAllResults() + { + var results = new[] { Result("a", TestStatus.Passed), Result("b", TestStatus.Failed) }; + + var runResult = TestResultMapper.CreateRunResult(results, new NotRunnableTestClass[0], includePassed: true); + + Assert.That(runResult.Results.Count, Is.EqualTo(2)); + } + + [Test] + public void CreateRunResult_OnlyPassedAndIgnored_Success() + { + var results = new[] { Result("a", TestStatus.Passed), Result("b", TestStatus.Ignored) }; + + var runResult = TestResultMapper.CreateRunResult(results, new NotRunnableTestClass[0], includePassed: false); + + Assert.That(runResult.Summary.Success, Is.True); + } + + [Test] + public void CreateRunResult_NotRunnableClass_NoSuccess() + { + var notRunnable = new[] { new NotRunnableTestClass { ClassName = "clsX", Reason = "r" } }; + + var runResult = TestResultMapper.CreateRunResult(new[] { Result("a", TestStatus.Passed) }, notRunnable, includePassed: false); + + Assert.That(runResult.Summary.NotRunnable, Is.EqualTo(1)); + Assert.That(runResult.Summary.Success, Is.False); + Assert.That(runResult.NotRunnableClasses.Single().ClassName, Is.EqualTo("clsX")); + } + + private static TestResultInfo Result(string test, string status, double elapsed = 0) + { + return new TestResultInfo { Test = test, Status = status, ElapsedMilliseconds = elapsed }; + } + } +} diff --git a/mcp-server/skills/accunit-tests/SKILL.md b/mcp-server/skills/accunit-tests/SKILL.md new file mode 100644 index 0000000..ca91133 --- /dev/null +++ b/mcp-server/skills/accunit-tests/SKILL.md @@ -0,0 +1,100 @@ +--- +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 the user asks to create unit tests for VBA code, 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, creates drafts of test classes and imports, exports and removes 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. 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 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. + +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 + 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. +- 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, 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` + (only for tests whose expected behavior is still open; for expected errors use `Assert.Throws`), + `'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. +- 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 +`vbNullString`; compare `"" & Actual` or use `Iz.StringCompare(StringCompareMode_vbNullStringEqualEmptyString)`. diff --git a/source/AccUnit/AccessCodeLib.AccUnit.csproj b/source/AccUnit/AccessCodeLib.AccUnit.csproj index 9dbe47b..5399e75 100644 --- a/source/AccUnit/AccessCodeLib.AccUnit.csproj +++ b/source/AccUnit/AccessCodeLib.AccUnit.csproj @@ -225,6 +225,7 @@ + diff --git a/source/AccUnit/Assertions/Constraints/ComparerConstraint.cs b/source/AccUnit/Assertions/Constraints/ComparerConstraint.cs index 6e3807a..d9e3b24 100644 --- a/source/AccUnit/Assertions/Constraints/ComparerConstraint.cs +++ b/source/AccUnit/Assertions/Constraints/ComparerConstraint.cs @@ -92,11 +92,11 @@ protected override IMatchResult Compare(object actual) string compareInfo; if (result < 0) { - compareInfo = "actual is less then expected"; + compareInfo = "actual is less than expected"; } else if (result > 0) { - compareInfo = "actual is greather then expected"; + compareInfo = "actual is greater than expected"; } else { diff --git a/source/AccUnit/Assertions/Constraints/StringComparerConstraint.cs b/source/AccUnit/Assertions/Constraints/StringComparerConstraint.cs index 91fa8f9..86b6439 100644 --- a/source/AccUnit/Assertions/Constraints/StringComparerConstraint.cs +++ b/source/AccUnit/Assertions/Constraints/StringComparerConstraint.cs @@ -69,11 +69,11 @@ protected override IMatchResult Compare(object actual) string compareInfo; if (result < 0) { - compareInfo = "actual is less then expected"; + compareInfo = "actual is less than expected"; } else if (result > 0) { - compareInfo = "actual is greather then expected"; + compareInfo = "actual is greater than expected"; } else { diff --git a/source/AccUnit/CodeCoverage/CodeCoverageTracker.cs b/source/AccUnit/CodeCoverage/CodeCoverageTracker.cs index d1d5191..79884e3 100644 --- a/source/AccUnit/CodeCoverage/CodeCoverageTracker.cs +++ b/source/AccUnit/CodeCoverage/CodeCoverageTracker.cs @@ -20,9 +20,14 @@ public CodeCoverageTracker(VBProject vbProject) public void Clear(string codeModuleName = null) { - if (codeModuleName.Length > 0) + if (!string.IsNullOrEmpty(codeModuleName)) { RemoveCodeCoverageTracker(codeModuleName); + if (_codeModules.TryGetValue(codeModuleName, out var codeModuleTracker)) + { + codeModuleTracker.Procedures.Clear(); + _codeModules.Remove(codeModuleName); + } } else { diff --git a/source/AccUnit/Configuration/ErrorTrappingObserver.cs b/source/AccUnit/Configuration/ErrorTrappingObserver.cs index 59977eb..3d644bc 100644 --- a/source/AccUnit/Configuration/ErrorTrappingObserver.cs +++ b/source/AccUnit/Configuration/ErrorTrappingObserver.cs @@ -78,17 +78,19 @@ protected virtual void Dispose(bool disposing) try { - if (_applicationHelper != null) + // COM calls only on deterministic dispose, never from a finalizer thread: + // if Dispose is not called, the error trapping is not restored. + if (disposing) { - // set the error trapping back to the initial value - if (GetAccessErrorTrapping() != _initialErrorTrapping) + if (_applicationHelper != null) { - SetErrorTrapping(_initialErrorTrapping); + // set the error trapping back to the initial value + if (GetAccessErrorTrapping() != _initialErrorTrapping) + { + SetErrorTrapping(_initialErrorTrapping); + } } - } - if (disposing) - { DisposeManagedResources(); } DisposeUnmanagedResources(); @@ -115,11 +117,6 @@ void DisposeUnmanagedResources() _hostApplication = null; } - ~AccessErrorTrappingObserver() - { - Dispose(false); - } - #endregion } } diff --git a/source/AccUnit/Configuration/TestClassManager.cs b/source/AccUnit/Configuration/TestClassManager.cs index c02e4ac..941c01e 100644 --- a/source/AccUnit/Configuration/TestClassManager.cs +++ b/source/AccUnit/Configuration/TestClassManager.cs @@ -1,4 +1,5 @@ -using AccessCodeLib.Common.Tools.Logging; +using AccessCodeLib.AccUnit.Interfaces; +using AccessCodeLib.Common.Tools.Logging; using AccessCodeLib.Common.VBIDETools; using AccessCodeLib.Common.VBIDETools.Templates; using Microsoft.Vbe.Interop; @@ -6,6 +7,7 @@ using System.Collections.Generic; using System.IO; using System.Linq; +using System.Text; using System.Text.RegularExpressions; namespace AccessCodeLib.AccUnit.Configuration @@ -53,12 +55,23 @@ public string ExportTestClass(string name) private string ExportTestClass(string name, string exportdirectory) { - return CodeModuleManager.Export(name, exportdirectory); + return CodeModuleManager.Export(name, exportdirectory, ExportFileEncoding); } public string ExportTestClass(VBComponent component) { - return CodeModuleManager.Export(component, ExportDirectory); + return CodeModuleManager.Export(component, ExportDirectory, ExportFileEncoding); + } + + /// Encoding of exported .cls and .bas files (setting ImportExportEncoding); null keeps the ANSI file of the VBA editor. + private static Encoding ExportFileEncoding + { + get + { + return TestSuiteUserSettings.Current.ImportExportEncoding == ImportExportEncoding.Ansi + ? null + : VbaSourceFile.Utf8BomEncoding; + } } public void RemoveTestClass(string name, bool export = true) @@ -98,7 +111,7 @@ private void RemoveVbComponent(string name, bool export, string exportdirectory) { if (export) { - CodeModuleManager.ExportAndRemove(name, exportdirectory); + CodeModuleManager.ExportAndRemove(name, exportdirectory, ExportFileEncoding); } else { @@ -261,15 +274,76 @@ public void ImportTestComponents(string fileNameFilter = null, string importPath ImportTestComponents(importComponents, overwriteExistingComponent); } + /// + /// A .cls or .bas file contains characters that are not available in the ANSI code page of the VBA editor; nothing is imported. + /// public void ImportTestComponents(IEnumerable list, bool overwriteExistingComponent = false) { - foreach (var m in list) + var modules = list.ToList(); + ThrowIfSourceFilesCannotBeImported(modules); + + string ansiDirectory = null; + try { - if (overwriteExistingComponent) + foreach (var m in modules) { - RemoveComponentIfExists(m); + if (overwriteExistingComponent) + { + RemoveComponentIfExists(m); + } + + if (m.ComponentType == vbext_ComponentType.vbext_ct_Document) + { + ImportOfficeObject(new FileInfo(m.FileName)); + } + else + { + if (ansiDirectory is null) + { + ansiDirectory = CreateTempImportDirectory(); + } + // VBComponents.Import reads the ANSI code page: import an ANSI copy of the (UTF-8 or ANSI) source file + var ansiFile = VbaSourceFile.WriteAnsiCopy(m.FileName, ansiDirectory, VbaSourceFile.AnsiEncoding); + CodeModuleManager.Generator.Add(new FileInfo(ansiFile)); + } + } + } + finally + { + if (ansiDirectory != null) + { + DeleteTempImportDirectory(ansiDirectory); } - ImportTestComponent(new FileInfo(m.FileName), m.ComponentType); + } + } + + private static void ThrowIfSourceFilesCannotBeImported(IEnumerable modules) + { + var sourceFiles = modules.Where(m => m.ComponentType != vbext_ComponentType.vbext_ct_Document) + .Select(m => m.FileName); + var rejectedFiles = VbaSourceFile.GetFilesWithUnsupportedCharacters(sourceFiles, VbaSourceFile.AnsiEncoding).ToList(); + if (rejectedFiles.Count > 0) + { + throw new UnsupportedSourceCharactersException(rejectedFiles, VbaSourceFile.AnsiEncoding); + } + } + + private static string CreateTempImportDirectory() + { + var directory = Path.Combine(Path.GetTempPath(), "AccUnit", "Import-" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(directory); + return directory; + } + + private static void DeleteTempImportDirectory(string directory) + { + try + { + Directory.Delete(directory, true); + } + catch (Exception ex) + { + Logger.Log(ex); } } @@ -293,16 +367,6 @@ private void RemoveComponentIfExists(CodeModuleInfo codeModuleInfo) } - private void ImportTestComponent(FileInfo importFile, vbext_ComponentType type) - { - if (type == vbext_ComponentType.vbext_ct_Document) - ImportOfficeObject(importFile); - else - { - CodeModuleManager.Generator.Add(importFile); - } - } - private void ImportOfficeObject(FileSystemInfo importFile) { if (!(ApplicationHelper is AccessApplicationHelper accessApplication)) diff --git a/source/AccUnit/Configuration/UserSettings.cs b/source/AccUnit/Configuration/UserSettings.cs index dd1ebcc..35e9714 100644 --- a/source/AccUnit/Configuration/UserSettings.cs +++ b/source/AccUnit/Configuration/UserSettings.cs @@ -1,4 +1,5 @@ -using AccessCodeLib.AccUnit.Properties; +using AccessCodeLib.AccUnit.Interfaces; +using AccessCodeLib.AccUnit.Properties; using AccessCodeLib.AccUnit.Tools.Templates; using AccessCodeLib.Common.Tools.Logging; using System; @@ -19,6 +20,8 @@ public interface IUserSettings string TestMethodTemplate { get; set; } void Save(); + + ImportExportEncoding ImportExportEncoding { get; set; } } public class UserSettings : IUserSettings @@ -126,6 +129,15 @@ public string ImportExportFolder set { _testSuiteUserSettings.ImportExportFolder = value.TrimEnd('\\', ' ').TrimStart(); } } + [Category("Import/Export")] + [DefaultValue(ImportExportEncoding.Utf8Bom)] + [Description("Encoding of exported test classes (.cls, .bas): Utf8Bom (UTF-8 with BOM) or Ansi (code page of the VBA editor).\nThe import detects the encoding.")] + public ImportExportEncoding ImportExportEncoding + { + get { return _testSuiteUserSettings.ImportExportEncoding; } + set { _testSuiteUserSettings.ImportExportEncoding = value; } + } + [Category("Templates")] [DefaultValue(@"%APPDATA%\AccessCodeLib\AccUnit\Templates")] [Description("Location of template files")] diff --git a/source/AccUnit/Integration/TestSuiteUserSettings.cs b/source/AccUnit/Integration/TestSuiteUserSettings.cs index 1938bab..8b00e0b 100644 --- a/source/AccUnit/Integration/TestSuiteUserSettings.cs +++ b/source/AccUnit/Integration/TestSuiteUserSettings.cs @@ -1,4 +1,5 @@ -using AccessCodeLib.AccUnit.Properties; +using AccessCodeLib.AccUnit.Interfaces; +using AccessCodeLib.AccUnit.Properties; using AccessCodeLib.Common.Tools.Logging; using System; using System.ComponentModel; @@ -47,6 +48,7 @@ public TestSuiteUserSettings Clone() var clone = new TestSuiteUserSettings { ImportExportFolder = ImportExportFolder, + ImportExportEncoding = ImportExportEncoding, SeparatorChar = SeparatorChar, SeparatorMaxLength = SeparatorMaxLength }; @@ -60,6 +62,7 @@ private void Load() using (new BlockLogger()) { ImportExportFolder = Settings.Default.ImportExportFolder; + ImportExportEncoding = Settings.Default.ImportExportEncoding; SeparatorMaxLength = Settings.Default.SeparatorMaxLength; SeparatorChar = Settings.Default.SeparatorChar; } @@ -68,6 +71,7 @@ private void Load() public void Save() { Settings.Default.ImportExportFolder = ImportExportFolder; + Settings.Default.ImportExportEncoding = ImportExportEncoding; Settings.Default.SeparatorMaxLength = SeparatorMaxLength; Settings.Default.SeparatorChar = SeparatorChar; Settings.Default.Save(); @@ -90,6 +94,9 @@ public string ImportExportFolder } } + /// Encoding of exported .cls and .bas files; the import detects the encoding. + public ImportExportEncoding ImportExportEncoding { get; set; } + [Category("Text output")] [DefaultValue(60)] [Description("")] diff --git a/source/AccUnit/Integration/UserSettings.cs b/source/AccUnit/Integration/UserSettings.cs index 865a4ca..2c94e18 100644 --- a/source/AccUnit/Integration/UserSettings.cs +++ b/source/AccUnit/Integration/UserSettings.cs @@ -1,4 +1,5 @@ -using AccessCodeLib.AccUnit.Properties; +using AccessCodeLib.AccUnit.Interfaces; +using AccessCodeLib.AccUnit.Properties; using AccessCodeLib.Common.Tools.Logging; using System; using System.ComponentModel; @@ -47,6 +48,7 @@ public UserSettings Clone() var clone = new UserSettings { ImportExportFolder = ImportExportFolder, + ImportExportEncoding = ImportExportEncoding, SeparatorChar = SeparatorChar, SeparatorMaxLength = SeparatorMaxLength }; @@ -60,6 +62,7 @@ private void Load() using (new BlockLogger()) { ImportExportFolder = Settings.Default.ImportExportFolder; + ImportExportEncoding = Settings.Default.ImportExportEncoding; SeparatorMaxLength = Settings.Default.SeparatorMaxLength; SeparatorChar = Settings.Default.SeparatorChar; } @@ -68,6 +71,7 @@ private void Load() public void Save() { Settings.Default.ImportExportFolder = ImportExportFolder; + Settings.Default.ImportExportEncoding = ImportExportEncoding; Settings.Default.SeparatorMaxLength = SeparatorMaxLength; Settings.Default.SeparatorChar = SeparatorChar; Settings.Default.Save(); @@ -90,6 +94,9 @@ public string ImportExportFolder } } + /// Encoding of exported .cls and .bas files; the import detects the encoding. + public ImportExportEncoding ImportExportEncoding { get; set; } + [Category("Text output")] [DefaultValue(60)] [Description("")] diff --git a/source/AccUnit/Interfaces/ImportExportEncoding.cs b/source/AccUnit/Interfaces/ImportExportEncoding.cs new file mode 100644 index 0000000..c8edd0f --- /dev/null +++ b/source/AccUnit/Interfaces/ImportExportEncoding.cs @@ -0,0 +1,16 @@ +using System.Runtime.InteropServices; + +namespace AccessCodeLib.AccUnit.Interfaces +{ + /// + /// Encoding of exported test class files (.cls, .bas). + /// The import always detects the encoding (UTF-8 with or without BOM, otherwise ANSI). + /// + [ComVisible(true)] + [Guid("FA0E0FD9-F0F3-40CB-9D8D-D7FD4502A8C0")] + public enum ImportExportEncoding + { + Utf8Bom = 0, + Ansi = 1 + } +} diff --git a/source/AccUnit/Interop/AccessTestSuite.cs b/source/AccUnit/Interop/AccessTestSuite.cs index de8e7e2..2eb3861 100644 --- a/source/AccUnit/Interop/AccessTestSuite.cs +++ b/source/AccUnit/Interop/AccessTestSuite.cs @@ -29,6 +29,9 @@ public interface IAccessTestSuite : Interfaces.IVBATestSuite IAccessTestSuite SelectTests(object TestNameFilter); IAccessTestSuite Filter(object FilterTags); ITestClassGenerator TestClassGenerator { get; } + + // Hides the non-COM-visible ITestSuite.CodeCoverageTracker; keep as last member (vtable order). + new ICodeCoverageTracker CodeCoverageTracker { get; set; } } [ComVisible(true)] @@ -96,6 +99,12 @@ public ITestClassGenerator TestClassGenerator } } + public new ICodeCoverageTracker CodeCoverageTracker + { + get { return base.CodeCoverageTracker as ICodeCoverageTracker; } + set { base.CodeCoverageTracker = value; } + } + public new IAccessTestSuite AppendTestResultReporter(ITestResultReporter reporter) { base.AppendTestResultReporter(reporter); diff --git a/source/AccUnit/Properties/AssemblyInfo.cs b/source/AccUnit/Properties/AssemblyInfo.cs index 8e9c73c..656fe8c 100644 --- a/source/AccUnit/Properties/AssemblyInfo.cs +++ b/source/AccUnit/Properties/AssemblyInfo.cs @@ -31,5 +31,5 @@ // Sie können alle Werte angeben oder Standardwerte für die Build- und Revisionsnummern verwenden, // indem Sie "*" wie unten gezeigt eingeben: // [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("0.10.0.0")] -[assembly: AssemblyFileVersion("0.10.0.0")] +[assembly: AssemblyVersion("0.11.0.0")] +[assembly: AssemblyFileVersion("0.11.0.0")] diff --git a/source/AccUnit/Properties/Settings.Designer.cs b/source/AccUnit/Properties/Settings.Designer.cs index 64eba54..08939c9 100644 --- a/source/AccUnit/Properties/Settings.Designer.cs +++ b/source/AccUnit/Properties/Settings.Designer.cs @@ -59,6 +59,18 @@ public string ImportExportFolder { } } + [global::System.Configuration.UserScopedSettingAttribute()] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Configuration.DefaultSettingValueAttribute("Utf8Bom")] + public global::AccessCodeLib.AccUnit.Interfaces.ImportExportEncoding ImportExportEncoding { + get { + return ((global::AccessCodeLib.AccUnit.Interfaces.ImportExportEncoding)(this["ImportExportEncoding"])); + } + set { + this["ImportExportEncoding"] = value; + } + } + [global::System.Configuration.UserScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("%APPDATA%\\AccessCodeLib\\AccUnit\\Templates")] diff --git a/source/AccUnit/Properties/Settings.settings b/source/AccUnit/Properties/Settings.settings index 09583fc..4fe2040 100644 --- a/source/AccUnit/Properties/Settings.settings +++ b/source/AccUnit/Properties/Settings.settings @@ -11,6 +11,9 @@ %APPFOLDER%\Tests\%APPNAME% + + Utf8Bom + %APPDATA%\AccessCodeLib\AccUnit\Templates diff --git a/source/AccUnit/app.config b/source/AccUnit/app.config index 1a9070e..a8c9b9c 100644 --- a/source/AccUnit/app.config +++ b/source/AccUnit/app.config @@ -16,6 +16,9 @@ %APPFOLDER%\Tests\%APPNAME% + + Utf8Bom + %APPDATA%\AccessCodeLib\AccUnit\Templates diff --git a/source/Common/Common.VBIDETools/AccessCodeLib.Common.VBIDETools.csproj b/source/Common/Common.VBIDETools/AccessCodeLib.Common.VBIDETools.csproj index b8ea725..0154877 100644 --- a/source/Common/Common.VBIDETools/AccessCodeLib.Common.VBIDETools.csproj +++ b/source/Common/Common.VBIDETools/AccessCodeLib.Common.VBIDETools.csproj @@ -136,6 +136,8 @@ + + diff --git a/source/Common/Common.VBIDETools/CodeModuleContainer.cs b/source/Common/Common.VBIDETools/CodeModuleContainer.cs index 61b6b18..fb47224 100644 --- a/source/Common/Common.VBIDETools/CodeModuleContainer.cs +++ b/source/Common/Common.VBIDETools/CodeModuleContainer.cs @@ -2,6 +2,7 @@ using Microsoft.Vbe.Interop; using System; using System.Linq; +using System.Text; namespace AccessCodeLib.Common.VBIDETools { @@ -68,13 +69,35 @@ public string Export(string name, string exportfolder) return Export(c, exportfolder); } + public string Export(string name, string exportfolder, Encoding fileEncoding) + { + var c = _vbProject.VBComponents.Item(name); + return Export(c, exportfolder, fileEncoding); + } + public string Export(VBComponent component, string exportfolder) + { + return Export(component, exportfolder, null); + } + + /// Encoding of .cls and .bas files; null keeps the ANSI file of the VBA editor. + public string Export(VBComponent component, string exportfolder, Encoding fileEncoding) { var fileName = $"{exportfolder.TrimEnd(' ', '\\')}\\{component.Name}{GetVbComponentTypeFileExtension(component.Type)}"; component.Export(fileName); + if (fileEncoding != null && IsConvertibleComponentType(component.Type)) + { + VbaSourceFile.ConvertExportedFile(fileName, fileEncoding, VbaSourceFile.AnsiEncoding); + } return fileName; } + private static bool IsConvertibleComponentType(vbext_ComponentType componenttype) + { + return componenttype == vbext_ComponentType.vbext_ct_ClassModule || + componenttype == vbext_ComponentType.vbext_ct_StdModule; + } + private static string GetVbComponentTypeFileExtension(vbext_ComponentType componenttype) { string fileExtension; @@ -107,7 +130,18 @@ public string ExportAndRemove(string name, string exportfolder) public string ExportAndRemove(VBComponent component, string exportfolder) { - var fileName = Export(component, exportfolder); + return ExportAndRemove(component, exportfolder, null); + } + + public string ExportAndRemove(string name, string exportfolder, Encoding fileEncoding) + { + var c = _vbProject.VBComponents.Item(name); + return ExportAndRemove(c, exportfolder, fileEncoding); + } + + public string ExportAndRemove(VBComponent component, string exportfolder, Encoding fileEncoding) + { + var fileName = Export(component, exportfolder, fileEncoding); Remove(component); return fileName; } diff --git a/source/Common/Common.VBIDETools/Commandbar/VbeCommandBarAdapter.cs b/source/Common/Common.VBIDETools/Commandbar/VbeCommandBarAdapter.cs index 8df5198..45b4c85 100644 --- a/source/Common/Common.VBIDETools/Commandbar/VbeCommandBarAdapter.cs +++ b/source/Common/Common.VBIDETools/Commandbar/VbeCommandBarAdapter.cs @@ -113,73 +113,63 @@ protected virtual void Dispose(bool disposing) using (new BlockLogger()) { - DisposeUnmanagedResources(); + if (disposing) + { + RemoveCommandBarButtonClickHandlers(); + ReleaseVbe(); + } _disposed = true; } } - private void DisposeUnmanagedResources() + /// + /// Unadvises the COM event sinks of the command bar buttons. + /// + /// + /// Must run while the VBE is still alive (never from a finalizer). + /// If the sinks stay advised, the CLR finalizer unadvises them during process shutdown, + /// which crashes the host (access violation in combase.dll/clr.dll) and lets Office restart Access. + /// The buttons are not deleted here (issue #77: http://accunit.access-codelib.net/bugs/view.php?id=77). + /// + protected void RemoveCommandBarButtonClickHandlers() { using (new BlockLogger()) { - Marshal.ReleaseComObject(VBE); - VBE = null; - - // issue #77: (http://accunit.access-codelib.net/bugs/view.php?id=77) - return; - /* - try + while (_commandBarButtons.Count > 0) { - while (_commandBarButtons.Count > 0) + var button = _commandBarButtons.Pop(); + try { - var button = _commandBarButtons.Pop(); - try - { - Logger.Log(string.Format("Button: {0}, -ClickEventHandler", button.Button.Caption)); - button.Button.Click -= button.ClickEventHandler; - } - catch (Exception ex) - { - Logger.Log(ex); - } - try - { - Logger.Log(string.Format("Button: {0}, Delete", button.Button.Caption)); - button.Button.Delete(); - } - catch (Exception ex) - { - Logger.Log(ex); - } - try - { - button.Dispose(); - } - catch (Exception ex) - { - Logger.Log(ex); - } + button.Button.Click -= button.ClickEventHandler; + } + catch (Exception ex) + { + Logger.Log(ex); } - Logger.Log("_commandBarButtons.Clear"); - _commandBarButtons.Clear(); - } - catch (Exception ex) - { - Logger.Log(ex); } - */ } } - public void Dispose() + /// + /// Only called from Dispose(true): there is no finalizer, because COM objects must not be + /// touched on the finalizer thread (the STA may already be gone during process exit). + /// + private void ReleaseVbe() { - Dispose(true); - GC.SuppressFinalize(this); + using (new BlockLogger()) + { + if (VBE is null) + return; + + Marshal.ReleaseComObject(VBE); + VBE = null; + } } - ~VbeCommandBarAdapter() + public void Dispose() { - Dispose(false); + Dispose(true); + GC.SuppressFinalize(this); } #endregion @@ -244,11 +234,6 @@ public void Dispose() GC.SuppressFinalize(this); } - ~CommandBarButtonAndClickHandler() - { - Dispose(false); - } - #endregion } } diff --git a/source/Common/Common.VBIDETools/HotKey.cs b/source/Common/Common.VBIDETools/HotKey.cs index 247e521..8715651 100644 --- a/source/Common/Common.VBIDETools/HotKey.cs +++ b/source/Common/Common.VBIDETools/HotKey.cs @@ -4,7 +4,7 @@ namespace AccessCodeLib.Common.VBIDETools { - public class HotKey + public class HotKey : IDisposable { [Flags] public enum ModKeys @@ -50,14 +50,24 @@ public HotKey(ModKeys modKeys, uint key, IntPtr hOwner) public ModKeys Modifiers { get; private set; } public uint Key { get; private set; } - ~HotKey() + bool _disposed; + + /// + /// UnregisterHotKey only works on the thread that registered the hot key, + /// so this must be called on deterministic dispose (not from a finalizer). + /// + public void Dispose() { + if (_disposed) + return; + try { - if ((int)_hwnd != 0) + Pressed = null; + if (_hwnd != IntPtr.Zero) { UnregisterHotKey(_hwnd, HotKeyAtom); - _hwnd = (IntPtr)0; + _hwnd = IntPtr.Zero; } GlobalDeleteAtom(HotKeyAtom); } @@ -65,6 +75,8 @@ public HotKey(ModKeys modKeys, uint key, IntPtr hOwner) { Logger.Log(ex); } + + _disposed = true; } } diff --git a/source/Common/Common.VBIDETools/HotKeys.cs b/source/Common/Common.VBIDETools/HotKeys.cs index 1bddb84..fba6ea7 100644 --- a/source/Common/Common.VBIDETools/HotKeys.cs +++ b/source/Common/Common.VBIDETools/HotKeys.cs @@ -3,7 +3,7 @@ namespace AccessCodeLib.Common.VBIDETools { - public class HotKeys : List + public class HotKeys : List, IDisposable { private readonly IntPtr _hWnd; public HotKeys(IntPtr hWnd) @@ -17,5 +17,17 @@ public HotKey RegisterHotKey(HotKey.ModKeys modKeys, uint key) Add(hotKey); return hotKey; } + + /// + /// Unregisters all hot keys. + /// + public void Dispose() + { + foreach (var hotKey in this) + { + hotKey.Dispose(); + } + Clear(); + } } } \ No newline at end of file diff --git a/source/Common/Common.VBIDETools/Integration/ComTools.cs b/source/Common/Common.VBIDETools/Integration/ComTools.cs index 77e145a..a27271e 100644 --- a/source/Common/Common.VBIDETools/Integration/ComTools.cs +++ b/source/Common/Common.VBIDETools/Integration/ComTools.cs @@ -15,6 +15,9 @@ public static class ComTools [DllImport("ole32.dll")] private static extern int CreateBindCtx(uint reserved, out IBindCtx pctx); + [DllImport("ole32.dll")] + private static extern int CreateFileMoniker([MarshalAs(UnmanagedType.LPWStr)] string lpszPathName, out IMoniker ppmk); + private static IRunningObjectTable RunningObjectTable { get @@ -45,12 +48,16 @@ public static object GetOfficeComObjectByProgIDAndVBE(string progID, VBE vbe) if (progID.Equals("Access.Application", StringComparison.CurrentCultureIgnoreCase) && vbe.VBProjects.Count == 1) { var fileName = vbe.ActiveVBProject.FileName; - using (new BlockLogger($"Marshal.BindToMoniker({fileName})")) + using (new BlockLogger($"GetComObjectFromROTByFileName({fileName})")) { - comInstance = Marshal.BindToMoniker(fileName); + comInstance = GetComObjectFromROTByFileName(fileName); if (comInstance != null) { - return comInstance; + if (BelongsToVbe(comInstance, vbe)) + { + return comInstance; + } + ReleaseComObject(comInstance); } } } @@ -73,22 +80,59 @@ public static object GetOfficeComObjectByProgIDAndVBE(string progID, VBE vbe) } } - private static object GetOfficeComObjectByProgIDAndVBEfromFirstObjectInROT(string progID, VBE vbe) + /// + /// Looks up a file moniker in the running object table. + /// + /// + /// Unlike Marshal.BindToMoniker, IRunningObjectTable.GetObject never activates the object, + /// so no new instance of the host application is started if the file is not open. + /// + private static object GetComObjectFromROTByFileName(string fileName) { - var comInstance = Marshal.GetActiveObject(progID); - if (comInstance is null) + if (string.IsNullOrEmpty(fileName)) + return null; + + var runningObjectTable = RunningObjectTable; + if (runningObjectTable is null) return null; + IMoniker fileMoniker = null; try { - var appVbe = comInstance.GetType().InvokeMember("VBE", BindingFlags.GetProperty, null, comInstance, null); - return vbe.Equals(appVbe) ? comInstance : null; + if (CreateFileMoniker(fileName, out fileMoniker) != 0 || fileMoniker is null) + return null; + + return runningObjectTable.GetObject(fileMoniker, out object comInstance) == 0 ? comInstance : null; + } + finally + { + ReleaseComObject(fileMoniker); + ReleaseComObject(runningObjectTable); + } + } + + private static object GetOfficeComObjectByProgIDAndVBEfromFirstObjectInROT(string progID, VBE vbe) + { + object comInstance; + try + { + comInstance = Marshal.GetActiveObject(progID); } catch (Exception ex) { + // e.g. MK_E_UNAVAILABLE: no active object registered for this ProgID => continue with the ROT search Logger.Log(ex); return null; } + + if (comInstance is null) + return null; + + if (BelongsToVbe(comInstance, vbe)) + return comInstance; + + ReleaseComObject(comInstance); + return null; } private static object GetOfficeComObjectByProgIDAndVBEfromROT(string progID, VBE vbe) @@ -99,49 +143,147 @@ private static object GetOfficeComObjectByProgIDAndVBEfromROT(string progID, VBE if (runningObjectTable is null) return null; - runningObjectTable.EnumRunning(out IEnumMoniker monikerList); - - var monikerContainer = new IMoniker[1]; - var pointerFetchedMonikers = IntPtr.Zero; - monikerList.Reset(); - while (monikerList.Next(1, monikerContainer, pointerFetchedMonikers) == 0) + IEnumMoniker monikerList = null; + try { - CreateBindCtx(0, out IBindCtx binder); + runningObjectTable.EnumRunning(out monikerList); - monikerContainer[0].GetDisplayName(binder, null, out string displayName); - Logger.Log($"displayName: {displayName}"); - - runningObjectTable.GetObject(monikerContainer[0], out object comInstance); - if (GetTypeForComObject(comInstance, progID) is null) continue; - object appVbe; - try - { - appVbe = comInstance.GetType().InvokeMember("VBE", BindingFlags.GetProperty, null, comInstance, null); - } - catch (Exception ex) + var monikerContainer = new IMoniker[1]; + var pointerFetchedMonikers = IntPtr.Zero; + monikerList.Reset(); + while (monikerList.Next(1, monikerContainer, pointerFetchedMonikers) == 0) { - Logger.Log($"VBE error => attempt: Application / Error: {ex.Message}"); + var moniker = monikerContainer[0]; + monikerContainer[0] = null; try { - comInstance = comInstance.GetType().InvokeMember("Application", BindingFlags.GetProperty, null, comInstance, null); - // Microsoft Word & Co.: enable option 'Trust access to the VBA project object model'! - appVbe = comInstance.GetType().InvokeMember("VBE", BindingFlags.GetProperty, null, comInstance, null); - Logger.Log($"VBE: {comInstance.GetType()}"); + var comInstance = GetComObjectFromROTIfOfficeApplicationOfVbe(runningObjectTable, moniker, progID, vbe); + if (comInstance != null) + { + Logger.Log($"found: {comInstance}"); + return comInstance; + } } - catch (Exception ex2) + catch (Exception ex) { - Logger.Log(ex2); - appVbe = comInstance = null; + // a faulty ROT entry must not abort the search + Logger.Log(ex); + } + finally + { + ReleaseComObject(moniker); } } + return null; + } + finally + { + ReleaseComObject(monikerList); + ReleaseComObject(runningObjectTable); + } + } + } + + private static object GetComObjectFromROTIfOfficeApplicationOfVbe(IRunningObjectTable runningObjectTable, IMoniker moniker, string progID, VBE vbe) + { + IBindCtx binder = null; + try + { + CreateBindCtx(0, out binder); + moniker.GetDisplayName(binder, null, out string displayName); + Logger.Log($"displayName: {displayName}"); + } + catch (Exception ex) + { + Logger.Log(ex); + } + finally + { + ReleaseComObject(binder); + } - if (appVbe is null || !vbe.Equals(appVbe)) continue; + if (runningObjectTable.GetObject(moniker, out object comInstance) != 0 || comInstance is null) + return null; - Logger.Log($"found: {comInstance}"); - return comInstance; - } + if (GetTypeForComObject(comInstance, progID) is null) + { + ReleaseComObject(comInstance); return null; } + + if (BelongsToVbe(comInstance, vbe)) + return comInstance; + + // Microsoft Word & Co.: enable option 'Trust access to the VBA project object model'! + Logger.Log("VBE does not match or is not accessible => attempt: Application"); + object application = null; + try + { + application = comInstance.GetType().InvokeMember("Application", BindingFlags.GetProperty, null, comInstance, null); + } + catch (Exception ex) + { + Logger.Log(ex); + } + finally + { + // each marshalled reference increments the RCW count, so this is balanced + // even if Application returns the same RCW + ReleaseComObject(comInstance); + } + + if (application is null) + return null; + + if (BelongsToVbe(application, vbe)) + { + Logger.Log($"VBE: {application.GetType()}"); + return application; + } + + ReleaseComObject(application); + return null; + } + + /// + /// Checks whether the VBE property of the COM object is the given VBE. + /// + private static bool BelongsToVbe(object comInstance, VBE vbe) + { + object appVbe = null; + try + { + appVbe = comInstance.GetType().InvokeMember("VBE", BindingFlags.GetProperty, null, comInstance, null); + return appVbe != null && vbe.Equals(appVbe); + } + catch (Exception ex) + { + Logger.Log(ex); + return false; + } + finally + { + // the matching VBE is the RCW shared with the add-in => do not release it + if (!ReferenceEquals(appVbe, vbe)) + { + ReleaseComObject(appVbe); + } + } + } + + private static void ReleaseComObject(object comObject) + { + if (comObject is null || !Marshal.IsComObject(comObject)) + return; + + try + { + Marshal.ReleaseComObject(comObject); + } + catch (Exception ex) + { + Logger.Log(ex); + } } /// @@ -156,39 +298,48 @@ public static Type GetTypeForComObject(object comObject, string progID) using (new BlockLogger("comObject: " + comObject.GetType().Name)) { var comType = Type.GetTypeFromProgID(progID); + if (comType is null) + return null; // ProgID not registered // get the com object and fetch its IUnknown var iunkwn = Marshal.GetIUnknownForObject(comObject); - - // enum all the types defined in the interop assembly - var comAssembly = Assembly.GetAssembly(comType); - var comTypes = comAssembly.GetTypes(); - - using (new BlockLogger("foreach loop, comTypes.Count = " + comTypes.Length)) + try { - // find the first implemented interop type - foreach (var currType in comTypes) + // enum all the types defined in the interop assembly + var comAssembly = Assembly.GetAssembly(comType); + var comTypes = comAssembly.GetTypes(); + + using (new BlockLogger("foreach loop, comTypes.Count = " + comTypes.Length)) { - // get the iid of the current type - var iid = currType.GUID; - if (!currType.IsInterface || iid == Guid.Empty) + // find the first implemented interop type + foreach (var currType in comTypes) { - // com interop type must be an interface with valid iid - continue; - } + // get the iid of the current type + var iid = currType.GUID; + if (!currType.IsInterface || iid == Guid.Empty) + { + // com interop type must be an interface with valid iid + continue; + } - // query supportability of current interface on object - Marshal.QueryInterface(iunkwn, ref iid, out IntPtr ipointer); + // query supportability of current interface on object + Marshal.QueryInterface(iunkwn, ref iid, out IntPtr ipointer); - if (ipointer != IntPtr.Zero) - { - // yeah, that’s the one we’re after - return currType; + if (ipointer != IntPtr.Zero) + { + Marshal.Release(ipointer); + // yeah, that’s the one we’re after + return currType; + } } } + // no implemented type found + return null; + } + finally + { + Marshal.Release(iunkwn); } - // no implemented type found - return null; } } diff --git a/source/Common/Common.VBIDETools/OfficeApplicationHelper.cs b/source/Common/Common.VBIDETools/OfficeApplicationHelper.cs index 9e33c54..019df25 100644 --- a/source/Common/Common.VBIDETools/OfficeApplicationHelper.cs +++ b/source/Common/Common.VBIDETools/OfficeApplicationHelper.cs @@ -67,7 +67,7 @@ protected virtual VBProject GetCheckedVbProject() try { var activeDocumentFullName = FileTools.ConvertPathToUNC(GetDocumentFullName()); - if (string.IsNullOrEmpty(activeDocumentFullName) && !VbProjectMatchWithFullName(activeVBProject, activeDocumentFullName)) + if (IsProjectLookupRequired(activeDocumentFullName, fullName => VbProjectMatchWithFullName(activeVBProject, fullName))) { activeVBProject = FindVbProjectEqualsFullName(activeDocumentFullName); } @@ -80,6 +80,15 @@ protected virtual VBProject GetCheckedVbProject() } } + /// + /// The active VBProject has to be replaced only if the active document is known + /// and the active VBProject does not belong to it. + /// + public static bool IsProjectLookupRequired(string activeDocumentFullName, Func activeVbProjectMatches) + { + return !string.IsNullOrEmpty(activeDocumentFullName) && !activeVbProjectMatches(activeDocumentFullName); + } + private string GetDocumentFullName() { // TODO: The strings are not sufficient to be able to invoke the infos. We also need the kind of invocation (method or getter call). @@ -138,17 +147,17 @@ protected virtual void Dispose(bool disposing) _invocationHelper.Dispose(); _invocationHelper = null; } - } - if (_application != null) - { - if (_releaseApplicationComObjectOnDispose) + // COM release only on deterministic dispose, never from the finalizer thread + if (_application != null) { - Marshal.ReleaseComObject(_application); + if (_releaseApplicationComObjectOnDispose) + { + Marshal.ReleaseComObject(_application); + } + _application = null; } - _application = null; - } - + } } catch (Exception ex) { @@ -169,11 +178,6 @@ public void Dispose() GC.SuppressFinalize(this); } - ~OfficeApplicationHelper() - { - Dispose(false); - } - #endregion } diff --git a/source/Common/Common.VBIDETools/Properties/AssemblyInfo.cs b/source/Common/Common.VBIDETools/Properties/AssemblyInfo.cs index e4a993d..1ac5fee 100644 --- a/source/Common/Common.VBIDETools/Properties/AssemblyInfo.cs +++ b/source/Common/Common.VBIDETools/Properties/AssemblyInfo.cs @@ -28,5 +28,5 @@ // Build Number // Revision // -[assembly: AssemblyVersion("0.9.19.0")] -[assembly: AssemblyFileVersion("0.9.19.0")] +[assembly: AssemblyVersion("0.9.20.0")] +[assembly: AssemblyFileVersion("0.9.20.0")] diff --git a/source/Common/Common.VBIDETools/UnsupportedSourceCharactersException.cs b/source/Common/Common.VBIDETools/UnsupportedSourceCharactersException.cs new file mode 100644 index 0000000..9398741 --- /dev/null +++ b/source/Common/Common.VBIDETools/UnsupportedSourceCharactersException.cs @@ -0,0 +1,33 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace AccessCodeLib.Common.VBIDETools +{ + /// + /// Source files contain characters that are not available in the ANSI code page of the VBA editor. + /// + [Serializable] + public class UnsupportedSourceCharactersException : Exception + { + public UnsupportedSourceCharactersException(IEnumerable filePaths, Encoding ansiEncoding) + : this(filePaths.ToList(), ansiEncoding) + { + } + + private UnsupportedSourceCharactersException(IList filePaths, Encoding ansiEncoding) + : base(CreateMessage(filePaths, ansiEncoding)) + { + FilePaths = filePaths; + } + + public IList FilePaths { get; } + + private static string CreateMessage(IEnumerable filePaths, Encoding ansiEncoding) + { + return "The following files contain characters that are not available in the ANSI code page " + + ansiEncoding.WebName + " used by the VBA editor:\r\n" + string.Join("\r\n", filePaths); + } + } +} diff --git a/source/Common/Common.VBIDETools/VbaSourceFile.cs b/source/Common/Common.VBIDETools/VbaSourceFile.cs new file mode 100644 index 0000000..495f1ea --- /dev/null +++ b/source/Common/Common.VBIDETools/VbaSourceFile.cs @@ -0,0 +1,91 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; + +namespace AccessCodeLib.Common.VBIDETools +{ + /// + /// Encoding of VBA source files (.cls, .bas). + /// VBComponent.Export and VBComponents.Import always use the ANSI code page of the system, + /// source files in a repository are usually UTF-8. + /// + public static class VbaSourceFile + { + private static readonly string[] LineSeparators = { "\r\n", "\n" }; + private static readonly byte[] Utf8Preamble = Encoding.UTF8.GetPreamble(); + + /// Code page used by VBComponent.Export and VBComponents.Import (Encoding.Default on .NET Framework). + public static Encoding AnsiEncoding + { + get { return Encoding.Default; } + } + + public static Encoding Utf8BomEncoding + { + get { return new UTF8Encoding(true); } + } + + /// UTF-8 with BOM, valid UTF-8 without BOM, 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); + } + } + + public static string ReadAllText(string filePath, Encoding ansiEncoding) + { + return Decode(File.ReadAllBytes(filePath), ansiEncoding); + } + + public static bool CanBeEncoded(string sourceCode, Encoding ansiEncoding) + { + return ansiEncoding.GetString(ansiEncoding.GetBytes(sourceCode)) == sourceCode; + } + + public static string ToCrLf(string sourceCode) + { + return string.Join("\r\n", sourceCode.Split(LineSeparators, StringSplitOptions.None)); + } + + /// Rewrites a file exported by the VBA editor (ANSI) in the target encoding with CRLF line endings. + public static void ConvertExportedFile(string filePath, Encoding targetEncoding, Encoding ansiEncoding) + { + var sourceCode = ansiEncoding.GetString(File.ReadAllBytes(filePath)); + File.WriteAllText(filePath, ToCrLf(sourceCode), targetEncoding); + } + + /// + /// Writes the source file in the ANSI code page with CRLF line endings into the target directory, + /// as VBComponents.Import expects it. + /// + /// Path of the ANSI copy (same file name as the source file). + /// The file contains characters that are not available in the ANSI code page. + public static string WriteAnsiCopy(string sourceFilePath, string targetDirectory, Encoding ansiEncoding) + { + var sourceCode = ReadAllText(sourceFilePath, ansiEncoding); + if (!CanBeEncoded(sourceCode, ansiEncoding)) + throw new UnsupportedSourceCharactersException(new[] { sourceFilePath }, ansiEncoding); + + var targetFilePath = Path.Combine(targetDirectory, Path.GetFileName(sourceFilePath)); + File.WriteAllText(targetFilePath, ToCrLf(sourceCode), ansiEncoding); + return targetFilePath; + } + + /// Files that contain characters which are not available in the ANSI code page. + public static IEnumerable GetFilesWithUnsupportedCharacters(IEnumerable filePaths, Encoding ansiEncoding) + { + return filePaths.Where(filePath => !CanBeEncoded(ReadAllText(filePath, ansiEncoding), ansiEncoding)).ToList(); + } + } +} diff --git a/source/Common/Common.VBIDETools/VbeAdapter.cs b/source/Common/Common.VBIDETools/VbeAdapter.cs index 4074de2..2a604e7 100644 --- a/source/Common/Common.VBIDETools/VbeAdapter.cs +++ b/source/Common/Common.VBIDETools/VbeAdapter.cs @@ -112,6 +112,7 @@ private int NewWndProc(IntPtr hWnd, int wMsg, int wParam, int lParam) } } + // when re-enabled: call HotKeys.Dispose() in DisposeManagedResources (unregisters the hot keys) public HotKeys HotKeys { get; private set; } private void CheckHotKeys(int wParam) diff --git a/source/Tests/AccUnit.Assertions.Tests/AccessCodeLib.AccUnit.Assertions.Tests.csproj b/source/Tests/AccUnit.Assertions.Tests/AccessCodeLib.AccUnit.Assertions.Tests.csproj index 660bc3c..c03c8a2 100644 --- a/source/Tests/AccUnit.Assertions.Tests/AccessCodeLib.AccUnit.Assertions.Tests.csproj +++ b/source/Tests/AccUnit.Assertions.Tests/AccessCodeLib.AccUnit.Assertions.Tests.csproj @@ -105,6 +105,9 @@ prompt + + ..\..\libvbide\Microsoft.Vbe.Interop.dll + ..\..\packages\NUnit.3.13.3\lib\net45\nunit.framework.dll @@ -114,6 +117,7 @@ + diff --git a/source/Tests/AccUnit.Assertions.Tests/CodeCoverageTrackerTests.cs b/source/Tests/AccUnit.Assertions.Tests/CodeCoverageTrackerTests.cs new file mode 100644 index 0000000..20e99aa --- /dev/null +++ b/source/Tests/AccUnit.Assertions.Tests/CodeCoverageTrackerTests.cs @@ -0,0 +1,34 @@ +using AccessCodeLib.AccUnit.CodeCoverage; +using NUnit.Framework; + +namespace AccessCodeLib.AccUnit.Assertions.Tests +{ + public class CodeCoverageTrackerTests + { + // An empty tracker needs no VBProject: nothing has to be removed from a code module. + + [Test] + public void Clear_WithoutArgument_ClearsAllModulesWithoutException() + { + var tracker = new CodeCoverageTracker(null); + + Assert.DoesNotThrow(() => tracker.Clear()); + } + + [Test] + public void Clear_WithNull_ClearsAllModulesWithoutException() + { + var tracker = new CodeCoverageTracker(null); + + Assert.DoesNotThrow(() => tracker.Clear(null)); + } + + [Test] + public void Clear_WithEmptyString_ClearsAllModulesWithoutException() + { + var tracker = new CodeCoverageTracker(null); + + Assert.DoesNotThrow(() => tracker.Clear("")); + } + } +} diff --git a/source/Tests/AccessCodeLib.Common.VBIDETools.Tests/AccessCodeLib.Common.VBIDETools.Tests.csproj b/source/Tests/AccessCodeLib.Common.VBIDETools.Tests/AccessCodeLib.Common.VBIDETools.Tests.csproj index a7b338e..17608d8 100644 --- a/source/Tests/AccessCodeLib.Common.VBIDETools.Tests/AccessCodeLib.Common.VBIDETools.Tests.csproj +++ b/source/Tests/AccessCodeLib.Common.VBIDETools.Tests/AccessCodeLib.Common.VBIDETools.Tests.csproj @@ -126,6 +126,10 @@ + + ..\..\packages\ThammimTech.Microsoft.Vbe.Interop.15.0.0\lib\net20\Microsoft.Vbe.Interop.dll + False + False True @@ -149,6 +153,7 @@ + diff --git a/source/Tests/AccessCodeLib.Common.VBIDETools.Tests/HostLookupTests.cs b/source/Tests/AccessCodeLib.Common.VBIDETools.Tests/HostLookupTests.cs new file mode 100644 index 0000000..03597ad --- /dev/null +++ b/source/Tests/AccessCodeLib.Common.VBIDETools.Tests/HostLookupTests.cs @@ -0,0 +1,39 @@ +using AccessCodeLib.Common.VBIDETools.Integration; +using NUnit.Framework; + +namespace AccessCodeLib.Common.VBIDETools.Tests +{ + [TestFixture] + public class HostLookupTests + { + [TestCase(null, false, ExpectedResult = false, Description = "unknown document: keep active project")] + [TestCase("", false, ExpectedResult = false, Description = "unknown document: keep active project")] + [TestCase(@"C:\Test\a.xlsm", true, ExpectedResult = false, Description = "active project matches: keep it")] + [TestCase(@"C:\Test\a.xlsm", false, ExpectedResult = true, Description = "active project does not match: look up")] + public bool IsProjectLookupRequired_ReturnsExpected(string fullName, bool activeProjectMatches) + { + return OfficeApplicationHelper.IsProjectLookupRequired(fullName, _ => activeProjectMatches); + } + + [Test] + public void IsProjectLookupRequired_EmptyName_DoesNotEvaluateMatch() + { + var evaluated = false; + + OfficeApplicationHelper.IsProjectLookupRequired(string.Empty, _ => evaluated = true); + + Assert.That(evaluated, Is.False); + } + + [Test] + public void GetOfficeComObjectByProgIDAndVBE_ProgIdNotRegistered_ReturnsNullInsteadOfThrowing() + { + // not "Access.Application" => the VBE is not touched; Marshal.GetActiveObject throws for an unknown ProgID + object result = null; + + Assert.DoesNotThrow(() => result = ComTools.GetOfficeComObjectByProgIDAndVBE("AccUnit.NotRegistered.Application", null)); + + Assert.That(result, Is.Null); + } + } +} diff --git a/source/Tests/AccessTestClientTests/AccessTestClientTests.csproj b/source/Tests/AccessTestClientTests/AccessTestClientTests.csproj index 7da7e50..14c8cb3 100644 --- a/source/Tests/AccessTestClientTests/AccessTestClientTests.csproj +++ b/source/Tests/AccessTestClientTests/AccessTestClientTests.csproj @@ -142,6 +142,7 @@ + diff --git a/source/Tests/AccessTestClientTests/AccessTestSuiteCodeCoverageTrackerTests.cs b/source/Tests/AccessTestClientTests/AccessTestSuiteCodeCoverageTrackerTests.cs new file mode 100644 index 0000000..cd2f90a --- /dev/null +++ b/source/Tests/AccessTestClientTests/AccessTestSuiteCodeCoverageTrackerTests.cs @@ -0,0 +1,60 @@ +using AccessCodeLib.AccUnit.CodeCoverage; +using NUnit.Framework; +using System.Linq; +using System.Reflection; +using System.Runtime.InteropServices; + +namespace AccessCodeLib.AccUnit.AccessTestClientTests +{ + internal class AccessTestSuiteCodeCoverageTrackerTests + { + private class TestableAccessTestSuite : Interop.AccessTestSuite + { + public TestableAccessTestSuite() : base(null, null, null, null) + { + } + + public void Trace(string text) + { + RaiseTraceMessage(text); + } + } + + [Test] + public void CodeCoverageTracker_SetViaInteropInterface_IsPassedToTraceMessageEvent() + { + ICodeCoverageTracker received = null; + var tracker = new Interop.CodeCoverageTracker(); + using (var suite = new TestableAccessTestSuite()) + { + ((Interop.IAccessTestSuite)suite).CodeCoverageTracker = tracker; + suite.TestTraceMessage += (message, codeCoverageTracker) => received = codeCoverageTracker; + + suite.Trace("Total"); + } + + Assert.That(received, Is.SameAs(tracker)); + } + + [Test] + public void CodeCoverageTracker_NotSet_ReturnsNull() + { + using (var suite = new TestableAccessTestSuite()) + { + Assert.That(((Interop.IAccessTestSuite)suite).CodeCoverageTracker, Is.Null); + } + } + + [Test] + public void IAccessTestSuite_CodeCoverageTracker_IsComVisible() + { + var property = typeof(Interop.IAccessTestSuite).GetProperty(nameof(Interop.IAccessTestSuite.CodeCoverageTracker), + BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly); + + Assert.That(property, Is.Not.Null, "Property must be declared on IAccessTestSuite"); + Assert.That(property.CanRead && property.CanWrite, Is.True); + Assert.That(property.GetCustomAttributes(typeof(ComVisibleAttribute), true) + .Cast().Any(a => !a.Value), Is.False); + } + } +} diff --git a/source/Tests/TestGeneratorTests/VbaSourceFileTests.cs b/source/Tests/TestGeneratorTests/VbaSourceFileTests.cs new file mode 100644 index 0000000..7375e23 --- /dev/null +++ b/source/Tests/TestGeneratorTests/VbaSourceFileTests.cs @@ -0,0 +1,136 @@ +using AccessCodeLib.Common.VBIDETools; +using NUnit.Framework; +using System; +using System.IO; +using System.Linq; +using System.Text; + +namespace TestGeneratorTests +{ + public class VbaSourceFileTests + { + private static readonly Encoding Ansi1252 = Encoding.GetEncoding(1252); + private const string GermanText = "' Größe ändern: äöüß €"; + private const string NonAnsiText = "' Pfeil → und 中"; + + private string _directory; + + [SetUp] + public void SetUp() + { + _directory = Path.Combine(Path.GetTempPath(), "AccUnitVbaSourceFileTests-" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(_directory); + } + + [TearDown] + public void TearDown() + { + Directory.Delete(_directory, true); + } + + [Test] + public void Decode_Utf8WithBom_ReturnsTextWithoutBom() + { + var bytes = new UTF8Encoding(true).GetPreamble().Concat(Encoding.UTF8.GetBytes(GermanText)).ToArray(); + + Assert.That(VbaSourceFile.Decode(bytes, Ansi1252), Is.EqualTo(GermanText)); + } + + [Test] + public void Decode_Utf8WithoutBom_ReturnsText() + { + var bytes = Encoding.UTF8.GetBytes(GermanText); + + Assert.That(VbaSourceFile.Decode(bytes, Ansi1252), Is.EqualTo(GermanText)); + } + + [Test] + public void Decode_Ansi_ReturnsText() + { + var bytes = Ansi1252.GetBytes(GermanText); + + Assert.That(VbaSourceFile.Decode(bytes, Ansi1252), Is.EqualTo(GermanText)); + } + + [TestCase(GermanText, true)] + [TestCase(NonAnsiText, false)] + public void CanBeEncoded_ReturnsExpected(string text, bool expected) + { + Assert.That(VbaSourceFile.CanBeEncoded(text, Ansi1252), Is.EqualTo(expected)); + } + + [Test] + public void ToCrLf_MixedLineEndings_ReturnsCrLf() + { + Assert.That(VbaSourceFile.ToCrLf("a\nb\r\nc\n"), Is.EqualTo("a\r\nb\r\nc\r\n")); + } + + [Test] + public void WriteAnsiCopy_Utf8FileWithLf_WritesAnsiWithCrLf() + { + var sourceFile = Path.Combine(_directory, "Test1.cls"); + File.WriteAllText(sourceFile, "Option Explicit\n" + GermanText + "\n", new UTF8Encoding(true)); + var targetDirectory = Directory.CreateDirectory(Path.Combine(_directory, "ansi")).FullName; + + var ansiFile = VbaSourceFile.WriteAnsiCopy(sourceFile, targetDirectory, Ansi1252); + + Assert.That(ansiFile, Is.EqualTo(Path.Combine(targetDirectory, "Test1.cls"))); + Assert.That(File.ReadAllBytes(ansiFile), Is.EqualTo(Ansi1252.GetBytes("Option Explicit\r\n" + GermanText + "\r\n"))); + } + + [Test] + public void WriteAnsiCopy_AnsiFile_WritesSameText() + { + var sourceFile = Path.Combine(_directory, "Test2.bas"); + var ansiBytes = Ansi1252.GetBytes("Option Explicit\r\n" + GermanText + "\r\n"); + File.WriteAllBytes(sourceFile, ansiBytes); + var targetDirectory = Directory.CreateDirectory(Path.Combine(_directory, "ansi")).FullName; + + var ansiFile = VbaSourceFile.WriteAnsiCopy(sourceFile, targetDirectory, Ansi1252); + + Assert.That(File.ReadAllBytes(ansiFile), Is.EqualTo(ansiBytes)); + } + + [Test] + public void WriteAnsiCopy_NonAnsiCharacters_ThrowsAndWritesNothing() + { + var sourceFile = Path.Combine(_directory, "Test3.cls"); + File.WriteAllText(sourceFile, NonAnsiText, new UTF8Encoding(true)); + var targetDirectory = Directory.CreateDirectory(Path.Combine(_directory, "ansi")).FullName; + + var ex = Assert.Throws( + () => VbaSourceFile.WriteAnsiCopy(sourceFile, targetDirectory, Ansi1252)); + + Assert.That(ex.FilePaths, Is.EqualTo(new[] { sourceFile })); + Assert.That(Directory.GetFiles(targetDirectory), Is.Empty); + } + + [Test] + public void GetFilesWithUnsupportedCharacters_ReturnsOnlyRejectedFiles() + { + var ansiFile = Path.Combine(_directory, "Ansi.cls"); + File.WriteAllBytes(ansiFile, Ansi1252.GetBytes(GermanText)); + var utf8File = Path.Combine(_directory, "Utf8.cls"); + File.WriteAllText(utf8File, GermanText, new UTF8Encoding(false)); + var rejectedFile = Path.Combine(_directory, "Rejected.cls"); + File.WriteAllText(rejectedFile, NonAnsiText, new UTF8Encoding(true)); + + var result = VbaSourceFile.GetFilesWithUnsupportedCharacters(new[] { ansiFile, utf8File, rejectedFile }, Ansi1252); + + Assert.That(result, Is.EqualTo(new[] { rejectedFile })); + } + + [Test] + public void ConvertExportedFile_AnsiFile_WritesUtf8WithBomAndCrLf() + { + var file = Path.Combine(_directory, "Exported.cls"); + File.WriteAllBytes(file, Ansi1252.GetBytes("Option Explicit\r\n" + GermanText + "\n")); + + VbaSourceFile.ConvertExportedFile(file, VbaSourceFile.Utf8BomEncoding, Ansi1252); + + var expected = new UTF8Encoding(true).GetPreamble() + .Concat(Encoding.UTF8.GetBytes("Option Explicit\r\n" + GermanText + "\r\n")).ToArray(); + Assert.That(File.ReadAllBytes(file), Is.EqualTo(expected)); + } + } +} diff --git a/vbe-add-In/AccUnit.VbeAddIn/AccUnitCommandBarAdapter.cs b/vbe-add-In/AccUnit.VbeAddIn/AccUnitCommandBarAdapter.cs index 8573af8..2a9c6a0 100644 --- a/vbe-add-In/AccUnit.VbeAddIn/AccUnitCommandBarAdapter.cs +++ b/vbe-add-In/AccUnit.VbeAddIn/AccUnitCommandBarAdapter.cs @@ -111,7 +111,8 @@ protected override void Dispose(bool disposing) { if (disposing) { - // managed resources: + // unadvise COM event sinks before the command bars are deleted + RemoveCommandBarButtonClickHandlers(); } // unmanaged resources: diff --git a/vbe-add-In/AccUnit.VbeAddIn/AddInManager.cs b/vbe-add-In/AccUnit.VbeAddIn/AddInManager.cs index 496f32b..1bfc274 100644 --- a/vbe-add-In/AccUnit.VbeAddIn/AddInManager.cs +++ b/vbe-add-In/AccUnit.VbeAddIn/AddInManager.cs @@ -238,9 +238,27 @@ private void CreateAddInManagerBridge() _addInManagerBridge.HostApplicationInitialized += AddInBridgeHostApplicationInitialized; _addInManagerBridge.ConstraintBuilderRequest += AddInBridgeConstraintBuilderRequest; _addInManagerBridge.AssertRequest += AddInBridgeAssertRequest; + _addInManagerBridge.AccUnitFactoryRequest += AddInBridgeAccUnitFactoryRequest; + _addInManagerBridge.CodeCoverageTrackerRequest += AddInBridgeCodeCoverageTrackerRequest; + _addInManagerBridge.ErrorTrappingObserverRequest += AddInBridgeErrorTrappingObserverRequest; } } + private void AddInBridgeAccUnitFactoryRequest(out Interop.IAccUnitFactory accUnitFactory) + { + accUnitFactory = _testSuiteManager.AccUnitFactory; + } + + private void AddInBridgeCodeCoverageTrackerRequest(out Interop.ICodeCoverageTracker codeCoverageTracker) + { + codeCoverageTracker = _testSuiteManager.CodeCoverageTracker; + } + + private void AddInBridgeErrorTrappingObserverRequest(out IErrorTrappingObserver errorTrappingObserver) + { + errorTrappingObserver = _testSuiteManager.ErrorTrappingObserver; + } + private void AddInBridgeAssertRequest(out Interop.IAssert assert) { assert = _testSuiteManager.Assert; @@ -266,9 +284,17 @@ private void InitOfficeApplicationHelper(object hostApplication = null) using (new BlockLogger()) { // Note: if load RubberDuck, an instance of Access stay in memory after close => HostApplicationTools.GetOfficeApplicationHelper(..., ..., true); + var previousHelper = _officeApplicationHelper; _officeApplicationHelper = HostApplicationTools.GetOfficeApplicationHelper(VBE, ref hostApplication, true); _vbeIntegrationManager.OfficeApplicationHelper = _officeApplicationHelper; _testSuiteManager.OfficeApplicationHelper = _officeApplicationHelper; + + // Dispose the previous helper only after the new one exists: both may wrap the same + // application RCW, whose reference count must not drop to 0 in between. + if (previousHelper != null) + { + DisposeManagedResource(previousHelper); + } } } @@ -401,6 +427,7 @@ protected virtual void Dispose(bool disposing) { if (_disposed) return; + // COM objects are only released on deterministic dispose, never from a finalizer thread if (disposing) { try @@ -411,15 +438,15 @@ protected virtual void Dispose(bool disposing) { Logger.Log(ex); } - } - try - { - DisposeUnmanagedResources(); - } - catch (Exception ex) - { - Logger.Log(ex); + try + { + DisposeUnmanagedResources(); + } + catch (Exception ex) + { + Logger.Log(ex); + } } _disposed = true; @@ -428,11 +455,9 @@ protected virtual void Dispose(bool disposing) private void DisposeUnmanagedResources() { - if (_addIn != null) - { - Marshal.ReleaseComObject(_addIn); - _addIn = null; - } + // The AddIn RCW is owned by Connect (it receives it in OnConnection and releases it once in Dispose), + // so it is only dereferenced here. A second ReleaseComObject would throw InvalidComObjectException. + _addIn = null; } private void DisposeManagedResources() @@ -492,6 +517,9 @@ private void RemoveEventHandler(AddInManagerBridge addInManagerBridge) addInManagerBridge.HostApplicationInitialized -= AddInBridgeHostApplicationInitialized; addInManagerBridge.ConstraintBuilderRequest -= AddInBridgeConstraintBuilderRequest; addInManagerBridge.AssertRequest -= AddInBridgeAssertRequest; + addInManagerBridge.AccUnitFactoryRequest -= AddInBridgeAccUnitFactoryRequest; + addInManagerBridge.CodeCoverageTrackerRequest -= AddInBridgeCodeCoverageTrackerRequest; + addInManagerBridge.ErrorTrappingObserverRequest -= AddInBridgeErrorTrappingObserverRequest; } public void Dispose() @@ -503,13 +531,6 @@ public void Dispose() } } - ~AddInManager() - { - Logger.Log("~AddInManager"); - Dispose(false); - Logger.Log("~AddInManager completed"); - } - #endregion } } diff --git a/vbe-add-In/AccUnit.VbeAddIn/AddInManagerBridge.cs b/vbe-add-In/AccUnit.VbeAddIn/AddInManagerBridge.cs index 81a26ce..82d9467 100644 --- a/vbe-add-In/AccUnit.VbeAddIn/AddInManagerBridge.cs +++ b/vbe-add-In/AccUnit.VbeAddIn/AddInManagerBridge.cs @@ -1,4 +1,5 @@ -using AccessCodeLib.AccUnit.Interop; +using AccessCodeLib.AccUnit.Configuration; +using AccessCodeLib.AccUnit.Interop; using System.Runtime.InteropServices; namespace AccessCodeLib.AccUnit.VbeAddIn @@ -18,6 +19,15 @@ public class AddInManagerBridge : IAddInManagerBridge public delegate void AssertRequestEventHandler(out IAssert assert); public event AssertRequestEventHandler AssertRequest; + public delegate void AccUnitFactoryRequestEventHandler(out IAccUnitFactory accUnitFactory); + public event AccUnitFactoryRequestEventHandler AccUnitFactoryRequest; + + public delegate void CodeCoverageTrackerRequestEventHandler(out ICodeCoverageTracker codeCoverageTracker); + public event CodeCoverageTrackerRequestEventHandler CodeCoverageTrackerRequest; + + public delegate void ErrorTrappingObserverRequestEventHandler(out IErrorTrappingObserver errorTrappingObserver); + public event ErrorTrappingObserverRequestEventHandler ErrorTrappingObserverRequest; + public delegate void HostApplicationInitializedEventHandler(object hostapplication); public event HostApplicationInitializedEventHandler HostApplicationInitialized; @@ -30,7 +40,8 @@ public object Application } } - public Interfaces.IVBATestSuite TestSuite(TestReportOutput OutputTo = TestReportOutput.DebugPrint) + [return: MarshalAs(UnmanagedType.IDispatch)] + public object TestSuite(TestReportOutput OutputTo = TestReportOutput.DebugPrint) { Interfaces.IVBATestSuite suite = null; TestSuiteRequest?.Invoke(out suite); @@ -56,6 +67,36 @@ public IAssert Assert return assert; } } + + public IAccUnitFactory AccUnitFactory + { + get + { + IAccUnitFactory accUnitFactory = null; + AccUnitFactoryRequest?.Invoke(out accUnitFactory); + return accUnitFactory; + } + } + + public ICodeCoverageTracker CodeCoverageTracker + { + get + { + ICodeCoverageTracker codeCoverageTracker = null; + CodeCoverageTrackerRequest?.Invoke(out codeCoverageTracker); + return codeCoverageTracker; + } + } + + public IErrorTrappingObserver ErrorTrappingObserver + { + get + { + IErrorTrappingObserver errorTrappingObserver = null; + ErrorTrappingObserverRequest?.Invoke(out errorTrappingObserver); + return errorTrappingObserver; + } + } } [ComVisible(true)] @@ -63,9 +104,13 @@ public IAssert Assert public interface IAddInManagerBridge { object Application { set; } - Interfaces.IVBATestSuite TestSuite(TestReportOutput OutputTo = TestReportOutput.DebugPrint); + [return: MarshalAs(UnmanagedType.IDispatch)] + object TestSuite(TestReportOutput OutputTo = TestReportOutput.DebugPrint); IConstraintBuilder ConstraintBuilder { get; } IAssert Assert { get; } + IAccUnitFactory AccUnitFactory { get; } + ICodeCoverageTracker CodeCoverageTracker { get; } + IErrorTrappingObserver ErrorTrappingObserver { get; } } public enum TestReportOutput diff --git a/vbe-add-In/AccUnit.VbeAddIn/Connect.cs b/vbe-add-In/AccUnit.VbeAddIn/Connect.cs index bd18a00..c6a01d0 100644 --- a/vbe-add-In/AccUnit.VbeAddIn/Connect.cs +++ b/vbe-add-In/AccUnit.VbeAddIn/Connect.cs @@ -179,37 +179,40 @@ protected virtual void Dispose(bool disposing) return; } - try - { - _addInInstance.Object = null; - } - catch (Exception ex) - { - Logger.Log(ex); - } - + // COM objects are only touched on deterministic dispose (OnDisconnection/OnBeginShutdown). + // There is no finalizer: during process exit the STA may already be gone. if (disposing) { Logger.Log("disposing == true"); + + try + { + _addInInstance.Object = null; + } + catch (Exception ex) + { + Logger.Log(ex); + } + if (AddInManager != null) { Logger.Log("Start AddInManager.Dispose ..."); AddInManager.Dispose(); AddInManager = null; } - } - if (_addInInstance != null) - { - Logger.Log("Start Marshal.ReleaseComObject(_addInInstance) ..."); - Marshal.ReleaseComObject(_addInInstance); - _addInInstance = null; + if (_addInInstance != null) + { + Logger.Log("Start Marshal.ReleaseComObject(_addInInstance) ..."); + Marshal.ReleaseComObject(_addInInstance); + _addInInstance = null; + } + + GC.Collect(); + GC.WaitForPendingFinalizers(); + GC.Collect(); + GC.WaitForPendingFinalizers(); } - - GC.Collect(); - GC.WaitForPendingFinalizers(); - GC.Collect(); - GC.WaitForPendingFinalizers(); _disposed = true; @@ -223,13 +226,6 @@ public void Dispose() GC.SuppressFinalize(this); } - ~Connect() - { - Logger.Log("~Connect"); - Dispose(false); - Logger.Log("~Connect completed"); - } - #endregion } } diff --git a/vbe-add-In/AccUnit.VbeAddIn/Properties/AssemblyInfo.cs b/vbe-add-In/AccUnit.VbeAddIn/Properties/AssemblyInfo.cs index fd11951..e0f2782 100644 --- a/vbe-add-In/AccUnit.VbeAddIn/Properties/AssemblyInfo.cs +++ b/vbe-add-In/AccUnit.VbeAddIn/Properties/AssemblyInfo.cs @@ -1,4 +1,5 @@ using System.Reflection; +using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // Allgemeine Informationen über eine Assembly werden über die folgenden @@ -16,6 +17,7 @@ // Durch Festlegen von ComVisible auf FALSE werden die Typen in dieser Assembly // für COM-Komponenten unsichtbar. Wenn Sie auf einen Typ in dieser Assembly von // COM aus zugreifen müssen, sollten Sie das ComVisible-Attribut für diesen Typ auf "True" festlegen. +[assembly: InternalsVisibleTo("AccUnit.VbeAddIn.Tests")] [assembly: ComVisible(false)] // Die folgende GUID bestimmt die ID der Typbibliothek, wenn dieses Projekt für COM verfügbar gemacht wird @@ -31,5 +33,5 @@ // Sie können alle Werte angeben oder Standardwerte für die Build- und Revisionsnummern verwenden, // indem Sie "*" wie unten gezeigt eingeben: // [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("0.10.0000.0")] -[assembly: AssemblyFileVersion("0.10.0000.0")] +[assembly: AssemblyVersion("0.11.0000.0")] +[assembly: AssemblyFileVersion("0.11.0000.0")] diff --git a/vbe-add-In/AccUnit.VbeAddIn/TestExplorer/TestListAndResultManager.cs b/vbe-add-In/AccUnit.VbeAddIn/TestExplorer/TestListAndResultManager.cs index 4a36963..2cfe321 100644 --- a/vbe-add-In/AccUnit.VbeAddIn/TestExplorer/TestListAndResultManager.cs +++ b/vbe-add-In/AccUnit.VbeAddIn/TestExplorer/TestListAndResultManager.cs @@ -79,7 +79,14 @@ public VbideUserControl TestListAndResultWindow { _testListAndResultVbideControl = new VbideUserControl(AddIn, Resources.UserControls.TestResultUserControlInfoCaption, TestListAndResultViewUserControlInfo.PositionGuid); _testListAndResultView = _testListAndResultVbideControl.Control; - _testListAndResultView.RunBreakOnErrorMenuItemEnabled = (TestSuiteManager.TestSuite is AccessTestSuite); + try + { + _testListAndResultView.RunBreakOnErrorMenuItemEnabled = (TestSuiteManager.TestSuite is AccessTestSuite); + } + catch (Exception ex) + { + UITools.ShowException(ex); + } _testListAndResultView.RunTests += TestListAndResultViewRunTests; _testListAndResultView.ShowSourceCodeInvoked += TestListAndResultViewShowSourceCodeInvoked; diff --git a/vbe-add-In/AccUnit.VbeAddIn/TestStarter.cs b/vbe-add-In/AccUnit.VbeAddIn/TestStarter.cs index 126f2e6..8dbd67c 100644 --- a/vbe-add-In/AccUnit.VbeAddIn/TestStarter.cs +++ b/vbe-add-In/AccUnit.VbeAddIn/TestStarter.cs @@ -507,7 +507,19 @@ protected virtual void Dispose(bool disposing) _codeWindowRunCurrentTestButton = null; _projectWindowRunCurrentTestButton = null; - _accUnitSubMenuEvents = null; + if (_accUnitSubMenuEvents != null) + { + try + { + // unadvise COM event sink while the VBE is still alive + _accUnitSubMenuEvents.Click -= OnAccUnitSubMenuEventsClick; + } + catch (Exception ex) + { + Logger.Log(ex); + } + _accUnitSubMenuEvents = null; + } if (VbeIntegrationManager != null) { diff --git a/vbe-add-In/AccUnit.VbeAddIn/TestSuiteManager.cs b/vbe-add-In/AccUnit.VbeAddIn/TestSuiteManager.cs index 84fcbbf..b0e5638 100644 --- a/vbe-add-In/AccUnit.VbeAddIn/TestSuiteManager.cs +++ b/vbe-add-In/AccUnit.VbeAddIn/TestSuiteManager.cs @@ -1,4 +1,5 @@ -using AccessCodeLib.AccUnit.Interfaces; +using AccessCodeLib.AccUnit.Configuration; +using AccessCodeLib.AccUnit.Interfaces; using AccessCodeLib.AccUnit.Interop; using AccessCodeLib.Common.Tools.Logging; using AccessCodeLib.Common.VBIDETools; @@ -60,14 +61,15 @@ private void InitTestSuite() try { _vbaTestSuite = CreateVbaTestSuite(OfficeApplicationHelper); + TestSuiteInitialized?.Invoke(_vbaTestSuite); } catch (Exception ex) { - UITools.ShowException(ex); - } - finally - { - TestSuiteInitialized?.Invoke(_vbaTestSuite); + // Do not hand out a silent null: VBA would fail later with a meaningless message. + // The exception reaches VBA as COM error (Err.Description contains the message); + // UI callers show it themselves. + Logger.Log(ex); + throw new InvalidOperationException("AccUnit test suite could not be initialized: " + ex.Message, ex); } } } @@ -117,6 +119,35 @@ public IConstraintBuilder ConstraintBuilder } } + public IAccUnitFactory AccUnitFactory + { + get + { + return new Interop.AccUnitFactory(); + } + } + + public Interop.ICodeCoverageTracker CodeCoverageTracker + { + get + { + return new Interop.CodeCoverageTracker(OfficeApplicationHelper.CurrentVBProject); + } + } + + public IErrorTrappingObserver ErrorTrappingObserver + { + get + { + if (!(OfficeApplicationHelper is AccessApplicationHelper)) + { + throw new NotSupportedException("ErrorTrappingObserver is only supported in Microsoft Access."); + } + + return new AccessErrorTrappingObserver(OfficeApplicationHelper.Application); + } + } + #region IDisposable Support bool _disposed; diff --git a/vbe-add-In/AccUnit.VbeAddIn/UserSettings.cs b/vbe-add-In/AccUnit.VbeAddIn/UserSettings.cs index d93c51f..69e6350 100644 --- a/vbe-add-In/AccUnit.VbeAddIn/UserSettings.cs +++ b/vbe-add-In/AccUnit.VbeAddIn/UserSettings.cs @@ -1,4 +1,5 @@ -using AccessCodeLib.AccUnit.Tools.Templates; +using AccessCodeLib.AccUnit.Interfaces; +using AccessCodeLib.AccUnit.Tools.Templates; using AccessCodeLib.Common.Tools.Logging; using System; using System.ComponentModel; @@ -84,6 +85,8 @@ public void Save() { AccUnit.UserSettings.Current = _testSuiteUserSettings; AccUnit.UserSettings.Current.Save(); + // TestClassManager reads TestSuiteUserSettings: reload it from the saved settings + TestSuiteUserSettings.UnloadCurrent(); Tools.UserSettings.Current = _toolsUserSettings; Tools.UserSettings.Current.Save(); /* @@ -121,6 +124,15 @@ public string ImportExportFolder set { _testSuiteUserSettings.ImportExportFolder = value.TrimEnd('\\', ' ').TrimStart(); } } + [Category("Import/Export")] + [DefaultValue(ImportExportEncoding.Utf8Bom)] + [Description("Encoding of exported test classes (.cls, .bas): Utf8Bom (UTF-8 with BOM) or Ansi (code page of the VBA editor).\nThe import detects the encoding.")] + public ImportExportEncoding ImportExportEncoding + { + get { return _testSuiteUserSettings.ImportExportEncoding; } + set { _testSuiteUserSettings.ImportExportEncoding = value; } + } + [Category("Templates")] [DefaultValue(@"%APPDATA%\AccessCodeLib\AccUnit\Templates")] [Description("Location of template files")] diff --git a/vbe-add-In/AccessCodeLib.AccUnit.VbeAddIn.sln b/vbe-add-In/AccessCodeLib.AccUnit.VbeAddIn.sln index c257fd3..75a7492 100644 --- a/vbe-add-In/AccessCodeLib.AccUnit.VbeAddIn.sln +++ b/vbe-add-In/AccessCodeLib.AccUnit.VbeAddIn.sln @@ -15,6 +15,8 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Tests", "Tests", "{21839B1B EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "WpfUserControlsTests", "Tests\WpfUserControlsTests\WpfUserControlsTests.csproj", "{C63CF654-F59C-4F98-9DB1-3DE62BF99ECF}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AccUnit.VbeAddIn.Tests", "Tests\AccUnit.VbeAddIn.Tests\AccUnit.VbeAddIn.Tests.csproj", "{0724661E-2C65-4AA6-BD2B-999583B70B39}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution AzureCI|Any CPU = AzureCI|Any CPU @@ -117,12 +119,31 @@ Global {C63CF654-F59C-4F98-9DB1-3DE62BF99ECF}.Release|x64.Build.0 = Release|Any CPU {C63CF654-F59C-4F98-9DB1-3DE62BF99ECF}.Release|x86.ActiveCfg = Release|Any CPU {C63CF654-F59C-4F98-9DB1-3DE62BF99ECF}.Release|x86.Build.0 = Release|Any CPU + {0724661E-2C65-4AA6-BD2B-999583B70B39}.AzureCI|Any CPU.ActiveCfg = AzureCI|Any CPU + {0724661E-2C65-4AA6-BD2B-999583B70B39}.AzureCI|Any CPU.Build.0 = AzureCI|Any CPU + {0724661E-2C65-4AA6-BD2B-999583B70B39}.AzureCI|x64.ActiveCfg = AzureCI|Any CPU + {0724661E-2C65-4AA6-BD2B-999583B70B39}.AzureCI|x64.Build.0 = AzureCI|Any CPU + {0724661E-2C65-4AA6-BD2B-999583B70B39}.AzureCI|x86.ActiveCfg = AzureCI|Any CPU + {0724661E-2C65-4AA6-BD2B-999583B70B39}.AzureCI|x86.Build.0 = AzureCI|Any CPU + {0724661E-2C65-4AA6-BD2B-999583B70B39}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {0724661E-2C65-4AA6-BD2B-999583B70B39}.Debug|Any CPU.Build.0 = Debug|Any CPU + {0724661E-2C65-4AA6-BD2B-999583B70B39}.Debug|x64.ActiveCfg = Debug|Any CPU + {0724661E-2C65-4AA6-BD2B-999583B70B39}.Debug|x64.Build.0 = Debug|Any CPU + {0724661E-2C65-4AA6-BD2B-999583B70B39}.Debug|x86.ActiveCfg = Debug|Any CPU + {0724661E-2C65-4AA6-BD2B-999583B70B39}.Debug|x86.Build.0 = Debug|Any CPU + {0724661E-2C65-4AA6-BD2B-999583B70B39}.Release|Any CPU.ActiveCfg = Release|Any CPU + {0724661E-2C65-4AA6-BD2B-999583B70B39}.Release|Any CPU.Build.0 = Release|Any CPU + {0724661E-2C65-4AA6-BD2B-999583B70B39}.Release|x64.ActiveCfg = Release|Any CPU + {0724661E-2C65-4AA6-BD2B-999583B70B39}.Release|x64.Build.0 = Release|Any CPU + {0724661E-2C65-4AA6-BD2B-999583B70B39}.Release|x86.ActiveCfg = Release|Any CPU + {0724661E-2C65-4AA6-BD2B-999583B70B39}.Release|x86.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection GlobalSection(NestedProjects) = preSolution {C63CF654-F59C-4F98-9DB1-3DE62BF99ECF} = {21839B1B-5233-411F-8993-9631D5A5BA34} + {0724661E-2C65-4AA6-BD2B-999583B70B39} = {21839B1B-5233-411F-8993-9631D5A5BA34} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {7937BEBA-24F9-4A3C-987E-8801C4C58F6C} diff --git a/vbe-add-In/Tests/AccUnit.VbeAddIn.Tests/AccUnit.VbeAddIn.Tests.csproj b/vbe-add-In/Tests/AccUnit.VbeAddIn.Tests/AccUnit.VbeAddIn.Tests.csproj new file mode 100644 index 0000000..8163c49 --- /dev/null +++ b/vbe-add-In/Tests/AccUnit.VbeAddIn.Tests/AccUnit.VbeAddIn.Tests.csproj @@ -0,0 +1,34 @@ + + + + net48 + + false + + False + + + x86 + + False + + + + + + + + + + + + + + + + ..\..\packages\ThammimTech.Microsoft.Vbe.Interop.15.0.0\lib\net20\Microsoft.Vbe.Interop.dll + False + + + + diff --git a/vbe-add-In/Tests/AccUnit.VbeAddIn.Tests/AddInManagerBridgeTests.cs b/vbe-add-In/Tests/AccUnit.VbeAddIn.Tests/AddInManagerBridgeTests.cs new file mode 100644 index 0000000..6e60519 --- /dev/null +++ b/vbe-add-In/Tests/AccUnit.VbeAddIn.Tests/AddInManagerBridgeTests.cs @@ -0,0 +1,230 @@ +using NUnit.Framework; +using System; +using System.Runtime.InteropServices; +using System.Runtime.Serialization; +using ComTypes = System.Runtime.InteropServices.ComTypes; + +namespace AccessCodeLib.AccUnit.VbeAddIn.Tests +{ + /// + /// VBA uses late binding on the object returned by AddInManagerBridge.TestSuite. + /// These tests call the bridge through its IDispatch, like VBA does, and check that + /// the members used by the AccUnit_Factory module can be resolved on the returned object. + /// + public class AddInManagerBridgeTests + { + private static readonly string[] TestSuiteMemberNames = + { + "Reset", "Add", "AddByClassName", "AddFromVBProject", + "SelectTests", "Filter", "Run", "Summary", "Name", "AppendTestResultReporter" + }; + + [TestCase(typeof(Interop.AccessTestSuite))] + [TestCase(typeof(Interop.VBATestSuite))] + public void TestSuite_CalledViaIDispatch_ReturnedObjectSupportsTestSuiteMembers(Type testSuiteType) + { + var suite = CreateTestSuiteWithoutHostApplication(testSuiteType); + var bridge = new AddInManagerBridge(); + bridge.TestSuiteRequest += (out Interfaces.IVBATestSuite testSuite) => testSuite = suite; + + var bridgeDispatch = Marshal.GetIDispatchForObject(bridge); + try + { + var suiteDispatch = DispatchHelper.InvokeReturningDispatch(bridgeDispatch, "TestSuite", (int)TestReportOutput.DebugPrint); + try + { + foreach (var memberName in TestSuiteMemberNames) + { + Assert.That(DispatchHelper.TryGetDispId(suiteDispatch, memberName), Is.True, + $"Member '{memberName}' is not available via IDispatch"); + } + } + finally + { + Marshal.Release(suiteDispatch); + } + } + finally + { + Marshal.Release(bridgeDispatch); + } + } + + private static readonly string[] FactoryMemberNamesUsedByTemplates = + { + "Assert", "ConstraintBuilder", "TestSuite", "AccUnitFactory", "CodeCoverageTracker", "ErrorTrappingObserver" + }; + + [Test] + public void BridgeViaIDispatch_ProvidesAllFactoryMembersUsedByTemplates() + { + var bridgeDispatch = Marshal.GetIDispatchForObject(new AddInManagerBridge()); + try + { + foreach (var memberName in FactoryMemberNamesUsedByTemplates) + { + Assert.That(DispatchHelper.TryGetDispId(bridgeDispatch, memberName), Is.True, + $"Member '{memberName}' is not available via IDispatch"); + } + } + finally + { + Marshal.Release(bridgeDispatch); + } + } + + [Test] + public void AccUnitFactory_CalledViaIDispatch_ReturnsDispatchWithFactoryMembers() + { + var bridge = new AddInManagerBridge(); + bridge.AccUnitFactoryRequest += (out Interop.IAccUnitFactory accUnitFactory) => accUnitFactory = new Interop.AccUnitFactory(); + + AssertBridgeMemberReturnsDispatchWithMembers(bridge, "AccUnitFactory", + "Assert", "ConstraintBuilder", "CodeCoverageTracker", "AccessErrorTrappingObserver"); + } + + [Test] + public void CodeCoverageTracker_CalledViaIDispatch_ReturnsDispatchWithTrackerMembers() + { + var bridge = new AddInManagerBridge(); + bridge.CodeCoverageTrackerRequest += (out Interop.ICodeCoverageTracker tracker) => tracker = new Interop.CodeCoverageTracker(); + + AssertBridgeMemberReturnsDispatchWithMembers(bridge, "CodeCoverageTracker", + "Add", "Track", "GetReport", "Clear", "Dispose"); + } + + [Test] + public void ErrorTrappingObserver_CalledViaIDispatch_ReturnsDispatchWithObserverMembers() + { + // A real observer reads the Access option "Error Trapping"; only the COM type information is needed here. + var observer = FormatterServices.GetUninitializedObject(typeof(Configuration.AccessErrorTrappingObserver)); + GC.SuppressFinalize(observer); + var bridge = new AddInManagerBridge(); + bridge.ErrorTrappingObserverRequest += (out Configuration.IErrorTrappingObserver errorTrappingObserver) => + errorTrappingObserver = (Configuration.IErrorTrappingObserver)observer; + + AssertBridgeMemberReturnsDispatchWithMembers(bridge, "ErrorTrappingObserver", + "SetErrorTrapping", "Dispose"); + } + + private static void AssertBridgeMemberReturnsDispatchWithMembers(AddInManagerBridge bridge, string bridgeMemberName, params string[] expectedMemberNames) + { + var bridgeDispatch = Marshal.GetIDispatchForObject(bridge); + try + { + var resultDispatch = DispatchHelper.InvokeReturningDispatch(bridgeDispatch, bridgeMemberName); + try + { + foreach (var memberName in expectedMemberNames) + { + Assert.That(DispatchHelper.TryGetDispId(resultDispatch, memberName), Is.True, + $"Member '{memberName}' of '{bridgeMemberName}' is not available via IDispatch"); + } + } + finally + { + Marshal.Release(resultDispatch); + } + } + finally + { + Marshal.Release(bridgeDispatch); + } + } + + private static Interfaces.IVBATestSuite CreateTestSuiteWithoutHostApplication(Type testSuiteType) + { + // Only the COM type information is needed; a real suite would require an Office host application. + var suite = FormatterServices.GetUninitializedObject(testSuiteType); + GC.SuppressFinalize(suite); + return (Interfaces.IVBATestSuite)suite; + } + + private static class DispatchHelper + { + private const int GetIDsOfNamesVtableSlot = 5; + private const int InvokeVtableSlot = 6; + private const short DispatchMethodOrPropertyGet = 1 | 2; + private const short VariantTypeDispatch = 9; + private static readonly int VariantSize = IntPtr.Size == 8 ? 24 : 16; // sizeof(VARIANT) + private const int LocaleUserDefault = 0x0400; + + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + private delegate int GetIDsOfNamesDelegate(IntPtr dispatch, ref Guid riid, + [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.LPWStr)] string[] names, + int nameCount, int lcid, [Out] int[] dispIds); + + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + private delegate int InvokeDelegate(IntPtr dispatch, int dispId, ref Guid riid, int lcid, short flags, + ref ComTypes.DISPPARAMS dispParams, IntPtr result, IntPtr excepInfo, IntPtr argErr); + + [DllImport("oleaut32.dll")] + private static extern int VariantClear(IntPtr variant); + + public static bool TryGetDispId(IntPtr dispatch, string name) + { + return GetIDsOfNames(dispatch, name, out _) == 0; + } + + public static IntPtr InvokeReturningDispatch(IntPtr dispatch, string name, params object[] arguments) + { + Marshal.ThrowExceptionForHR(GetIDsOfNames(dispatch, name, out var dispId)); + + var argumentVariants = Marshal.AllocCoTaskMem(VariantSize * Math.Max(arguments.Length, 1)); + var resultVariant = Marshal.AllocCoTaskMem(VariantSize); + try + { + // IDispatch::Invoke expects the arguments in reverse order. + for (var i = 0; i < arguments.Length; i++) + { + Marshal.GetNativeVariantForObject(arguments[arguments.Length - 1 - i], argumentVariants + i * VariantSize); + } + Marshal.GetNativeVariantForObject(null, resultVariant); + + var dispParams = new ComTypes.DISPPARAMS + { + cArgs = arguments.Length, + rgvarg = arguments.Length > 0 ? argumentVariants : IntPtr.Zero + }; + var riid = Guid.Empty; + var invoke = GetVtableFunction(dispatch, InvokeVtableSlot); + Marshal.ThrowExceptionForHR(invoke(dispatch, dispId, ref riid, LocaleUserDefault, + DispatchMethodOrPropertyGet, ref dispParams, + resultVariant, IntPtr.Zero, IntPtr.Zero)); + + Assert.That(Marshal.ReadInt16(resultVariant), Is.EqualTo(VariantTypeDispatch), "Result is not VT_DISPATCH"); + var resultDispatch = Marshal.ReadIntPtr(resultVariant, 8); + Marshal.AddRef(resultDispatch); + return resultDispatch; + } + finally + { + for (var i = 0; i < arguments.Length; i++) + { + VariantClear(argumentVariants + i * VariantSize); + } + VariantClear(resultVariant); + Marshal.FreeCoTaskMem(argumentVariants); + Marshal.FreeCoTaskMem(resultVariant); + } + } + + private static int GetIDsOfNames(IntPtr dispatch, string name, out int dispId) + { + var riid = Guid.Empty; + var dispIds = new int[1]; + var getIDsOfNames = GetVtableFunction(dispatch, GetIDsOfNamesVtableSlot); + var hresult = getIDsOfNames(dispatch, ref riid, new[] { name }, 1, LocaleUserDefault, dispIds); + dispId = dispIds[0]; + return hresult; + } + + private static T GetVtableFunction(IntPtr comInterface, int slot) where T : class + { + var vtable = Marshal.ReadIntPtr(comInterface); + var function = Marshal.ReadIntPtr(vtable, slot * IntPtr.Size); + return Marshal.GetDelegateForFunctionPointer(function); + } + } + } +} diff --git a/vbe-add-In/Tests/AccUnit.VbeAddIn.Tests/TestSuiteManagerTests.cs b/vbe-add-In/Tests/AccUnit.VbeAddIn.Tests/TestSuiteManagerTests.cs new file mode 100644 index 0000000..ffb0b23 --- /dev/null +++ b/vbe-add-In/Tests/AccUnit.VbeAddIn.Tests/TestSuiteManagerTests.cs @@ -0,0 +1,25 @@ +using NUnit.Framework; +using System; + +namespace AccessCodeLib.AccUnit.VbeAddIn.Tests +{ + public class TestSuiteManagerTests + { + [Test] + public void TestSuite_WhenInitializationFails_ThrowsWithOriginalMessageInsteadOfReturningNull() + { + using (var manager = new TestSuiteManager()) + { + manager.TestResultReporterRequest += (ref System.Collections.Generic.IList reporters) => + throw new InvalidOperationException("reporter failure"); + // no OfficeApplicationHelper => the suite cannot be created + + var exception = Assert.Throws(() => { var _ = manager.TestSuite; }); + + Assert.That(exception.Message, Does.StartWith("AccUnit test suite could not be initialized")); + Assert.That(exception.InnerException, Is.Not.Null); + Assert.That(exception.Message, Does.Contain(exception.InnerException.Message)); + } + } + } +}