### Build Project and Create VSIX Installer Source: https://github.com/microsoft/vscode-powerquery-sdk/blob/main/build.md Execute this command to compile the project and package it into a .vsix file for installation. ```msdos npm run vsix ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/microsoft/vscode-powerquery-sdk/blob/main/build.md Run this command to install all necessary Node.js dependencies for the project. ```msdos npm install ``` -------------------------------- ### Install Extension from Command Line Source: https://github.com/microsoft/vscode-powerquery-sdk/blob/main/build.md Use this command to install the generated .vsix file into your VS Code instance. ```msdos npm run code-install ``` -------------------------------- ### PQTest.exe Run-Compare Invocation Example Source: https://context7.com/microsoft/vscode-powerquery-sdk/llms.txt Demonstrates the equivalent PQTest.exe command-line invocation for running and comparing tests, including all flags passed by the extension. ```bash // Equivalent PQTest.exe run-compare invocation (with all flags the extension passes): // PQTest.exe run-compare \ // --extension C:/project/bin/Debug/MyConnector.mez \ // --settingsFile C:/project/tests/MyConnector.testsettings.json \ // --persistIntermediateTestResults \ // --intermediateTestResultsFolder C:/project/TestResults ``` -------------------------------- ### Build and Install Power Query Connector Extension Source: https://context7.com/microsoft/vscode-powerquery-sdk/llms.txt Commands to package the Power Query connector extension for distribution and install it into VS Code. ```bash # From the terminal — build and package the extension for distribution: npm run vsix # Produces: vscode-powerquery-sdk-0.7.2.vsix (win32-x64 target) # Install the built extension into VS Code: code --install-extension vscode-powerquery-sdk-0.7.2.vsix ``` -------------------------------- ### Focused Test Setup Source: https://github.com/microsoft/vscode-powerquery-sdk/blob/main/TESTING.md Highlights the benefit of minimal and focused setup in tests. Avoid overly complex `beforeEach` blocks that can make tests brittle and hard to maintain. ```typescript // Bad - complex, brittle setup beforeEach(() => { // 50 lines of setup code... }); // Good - focused, minimal setup beforeEach(() => { mockService = { operation: sinon.stub() }; service = new ServiceUnderTest(mockService); }); ``` -------------------------------- ### Run All Power Query SDK Tests Source: https://github.com/microsoft/vscode-powerquery-sdk/blob/main/README.md Execute all unit and integration tests for the Power Query SDK. Ensure all dependencies are installed before running. ```bash npm test ``` -------------------------------- ### Service Testing with Dependency Injection (Sinon Stubs) Source: https://context7.com/microsoft/vscode-powerquery-sdk/llms.txt This example demonstrates service testing using dependency injection with Sinon stubs. It tests the `DeleteCredentialHandler` by mocking the `IPQTestService` dependency, allowing for isolated testing of the handler's logic and verifying interactions with its dependencies. ```typescript import sinon from "sinon"; import { DeleteCredentialHandler } from "../src/commands/handlers/DeleteCredentialHandler"; describe("DeleteCredentialHandler", () => { let mockPqTestService: Partial; let handler: DeleteCredentialHandler; beforeEach(() => { mockPqTestService = { DeleteCredential: sinon.stub().resolves({ Status: "Success", Message: "Deleted", Details: null }), }; handler = new DeleteCredentialHandler(mockPqTestService as IPQTestService); }); it("returns formatted output on success", async () => { const result = await handler.execute({}); expect(result.success).to.equal(true); expect(result.data?.formattedOutput).to.be.a("string"); expect(mockPqTestService.DeleteCredential).to.have.been.calledOnce; }); }); ``` -------------------------------- ### Arrange-Act-Assert Test Example Source: https://github.com/microsoft/vscode-powerquery-sdk/blob/main/TESTING.md Demonstrates the Arrange-Act-Assert pattern for testing asynchronous operations. Ensure mocks are set up before the act phase and assertions validate the final state. ```typescript it("should return success result when operation succeeds", async () => { // Arrange const input = { value: "test" }; const expectedOutput = { success: true }; mockService.performOperation.resolves(expectedOutput); // Act const result = await handler.execute(input); // Assert expect(result.success).to.equal(true); expect(result.data).to.deep.equal(expectedOutput); }); ``` -------------------------------- ### Service Testing with Dependency Injection and Mocking Source: https://github.com/microsoft/vscode-powerquery-sdk/blob/main/TESTING.md Test services by mocking their dependencies using Sinon. This example demonstrates testing a service's successful operation handling by mocking its dependency. ```typescript describe("ServiceClass", () => { let mockDependency: Partial; let service: ServiceClass; beforeEach(() => { mockDependency = { performOperation: sinon.stub(), }; service = new ServiceClass(mockDependency as IDependencyService); }); it("should handle successful operations", async () => { // Arrange const expectedResult = { success: true, data: "test" }; (mockDependency.performOperation as sinon.SinonStub).resolves(expectedResult); // Act const result = await service.execute({ input: "test" }); // Assert expect(result.success).to.equal(true); expect(mockDependency.performOperation).to.have.been.calledOnceWith("test"); }); }); ``` -------------------------------- ### Configure Private NuGet Feed Source: https://context7.com/microsoft/vscode-powerquery-sdk/llms.txt Provides an example of VS Code settings to configure a private NuGet feed and specify a custom version for the Power Query SDK tools. ```json { "powerquery.sdk.externals.nugetFeed": "https://pkgs.dev.azure.com/myorg/_packaging/myfeed/nuget/v3/index.json", "powerquery.sdk.externals.versionTag": "Custom", "powerquery.sdk.tools.version": "2.150.4" } ``` -------------------------------- ### Single Concern Test Example Source: https://github.com/microsoft/vscode-powerquery-sdk/blob/main/TESTING.md Emphasizes testing a single, focused concern per test case. Avoid tests that attempt to validate multiple behaviors simultaneously, which makes debugging difficult. ```typescript // Bad - testing multiple behaviors it("should validate input and save to database and send notification", () => { // Tests too many things at once }); // Good - focused single concern it("should validate input correctly", () => { // Tests only validation logic }); ``` -------------------------------- ### Build Power Query SDK for Production Source: https://github.com/microsoft/vscode-powerquery-sdk/blob/main/README.md Compile the Power Query SDK for production deployment. This command performs a full build without watch mode. ```bash npm run compile ``` -------------------------------- ### SDK Tools Version Configuration Source: https://context7.com/microsoft/vscode-powerquery-sdk/llms.txt Explains how to configure the version of SDK tools used by the extension, supporting 'Recommended', 'Latest', and 'Custom' options. ```typescript // Version tag configuration controls which version is used: // "Recommended" → uses the version pinned in extension constants (stable) // "Latest" → queries NuGet feed for highest available version // "Custom" → uses the version specified in powerquery.sdk.tools.version ``` -------------------------------- ### Package Power Query SDK Extension Source: https://github.com/microsoft/vscode-powerquery-sdk/blob/main/README.md Package the Power Query SDK extension for distribution. This command creates a distributable VSIX file. ```bash npm run package ``` -------------------------------- ### Run Test Battery Command Source: https://context7.com/microsoft/vscode-powerquery-sdk/llms.txt Executes an M query against a connector and displays results in a webview panel. Can be triggered from the editor or programmatically. ```typescript // Trigger via right-click in editor on a .pq file, or Command Palette: "Power query: Run test battery" await vscode.commands.executeCommand("powerquery.sdk.tools.RunTestBatteryCommand"); ``` ```typescript // Or programmatically with a specific query file URI: const queryFileUri = vscode.Uri.file("C:/project/MyConnector.query.pq"); await vscode.commands.executeCommand("powerquery.sdk.tools.RunTestBatteryCommand", queryFileUri); ``` ```plaintext // The result is passed to the webview panel: // SimplePqTestResultViewBroker.values.latestPqTestResult.emit(result) ``` ```plaintext // Equivalent PQTest.exe CLI: // PQTest.exe run-test --extension <.mez> --queryFile <.query.pq> --prettyPrint ``` ```plaintext // Example query file (MyConnector.query.pq): // MyConnector.Contents("Hello World") // → Result webview shows: "Hello from MyConnector: Hello World" ``` -------------------------------- ### Create New Power Query Connector Project Source: https://context7.com/microsoft/vscode-powerquery-sdk/llms.txt Scaffold a new connector project using the `CreateNewProjectCommand`. This command generates all necessary files for a new connector project based on a template. ```typescript // Trigger via VS Code Command Palette: "Power query: Create new project" // Programmatic equivalent (inside extension/test code): await vscode.commands.executeCommand("powerquery.sdk.tools.CreateNewProjectCommand"); ``` ```plaintext // Generated project structure: // MyConnector/ // ├── .vscode/ // │ └── settings.json ← pre-configured defaultExtension and defaultQueryFile paths // ├── MyConnector.pq ← main connector logic (M language) // ├── MyConnector.query.pq ← sample test query // ├── MyConnector.proj ← MSBuild project file // ├── resources.resx ← localization resources // └── MyConnector16..80.png ← connector icon assets ``` ```powerquery // Generated MyConnector.pq (template output with ProjectName = "MyConnector"): // [Version = "1.0.0"] // section MyConnector; // // [DataSource.Kind="MyConnector", Publish="MyConnector.Publish"] // shared MyConnector.Contents = (optional message as text) => // let // _message = if (message <> null) then message else "(no message)", // a = "Hello from MyConnector: " & _message // in // a; // // MyConnector = [ // Authentication = [ // // Key = [], // // UsernamePassword = [], // Anonymous = [] // ] // ]; // // MyConnector.Publish = [ // Beta = true, // Category = "Other", // ButtonText = { Extension.LoadString("ButtonTitle"), Extension.LoadString("ButtonHelp") }, // LearnMoreUrl = "https://powerbi.microsoft.com/", // SourceImage = MyConnector.Icons, // SourceTypeImage = MyConnector.Icons // ]; ``` -------------------------------- ### Build Power Query SDK in Watch Mode Source: https://github.com/microsoft/vscode-powerquery-sdk/blob/main/README.md Compile the Power Query SDK with watch mode enabled for development. This command recompiles automatically on file changes. ```bash npm run watch ``` -------------------------------- ### Test Settings File Configuration Source: https://context7.com/microsoft/vscode-powerquery-sdk/llms.txt Drives automated test discovery and execution via VS Code Test Explorer. This JSON file is passed directly to PQTest.exe. ```json // MyConnector.testsettings.json { "QueryFilePath": "./tests", "ExtensionPaths": ["./bin/AnyCPU/Debug/MyConnector.mez"], "AuthenticationKind": "Anonymous", "DataSourceKind": "MyConnector", "OutputFolderPath": "./tests/expected", "IntermediateTestResultsFolder": "../TestResults", "PersistIntermediateTestResults": true, "PrettyPrint": true, "FailOnFoldingFailure": false, "FailOnMissingOutputFile": false, "TestFilters": ["**/BasicTests/*", "!**/SkippedTests/*"], "TestCredentials": [ { "Kind": "MyConnector", "Pattern": "*", "Type": "Anonymous", "Settings": null } ], "LogMashupEngineTraceLevel": "user", "ApplicationProperties": { "MyCustomProperty": "PropertyValue" }, "MashupVariables": { "currentWorkspaceId": "test-workspace" }, "EnvironmentConfiguration": { "Cloud": "global", "Region": "us-east-1" } } ``` -------------------------------- ### PQTest Execution Command Log Source: https://github.com/microsoft/vscode-powerquery-sdk/blob/main/PQTestVSCodeUIIntegration.md This log output shows the PQTest command being executed. It is useful for verifying command arguments and execution paths when troubleshooting. ```text Executing: C:\...\PQTest.exe run-compare --extension --settingsFile ... ``` -------------------------------- ### Define VS Code Build Tasks for Power Query Connectors Source: https://context7.com/microsoft/vscode-powerquery-sdk/llms.txt Configure tasks.json to compile Power Query connectors into .mez files using either the Power Query SDK's compile operation or MSBuild. ```json // .vscode/tasks.json — manually define a build task: { "version": "2.0.0", "tasks": [ { "type": "powerquery", "operation": "compile", "label": "Build connector (.mez)", "group": { "kind": "build", "isDefault": true } }, { "type": "powerquery", "operation": "msbuild", "label": "Build connector project using MSBuild", "additionalArgs": ["/restore", "/consoleloggerparameters:NoSummary", "/property:GenerateFullPaths=true"], "group": "build" } ] } ``` -------------------------------- ### Trigger Manual SDK Tools Update Source: https://context7.com/microsoft/vscode-powerquery-sdk/llms.txt This command allows users to manually trigger the download and update of the Power Query SDK tools (PQTest.exe) via the VS Code Command Palette. ```APIDOC ## Downloading and Updating PQTest (SDK Tools) Users can manually trigger an update of the SDK tools through the VS Code Command Palette. ### Command - **Command Palette**: `Power query: Download/Update PQTest tool` - **Execute Command**: `await vscode.commands.executeCommand("powerquery.sdk.tools.SeizePqTestCommand");` ### Update Process The extension performs the following steps to update the tools: 1. Queries the configured NuGet feed (defaults to nuget.org). 2. Downloads the `Microsoft.PowerQuery.SdkTools` package and extracts `PQTest.exe` and `MakePQX.exe`. 3. Updates the `powerquery.sdk.tools.location` and `powerquery.sdk.tools.version` settings. 4. Copies the updated `UserSettings.schema.json` for `.testsettings.json` IntelliSense. ### Version Configuration - **Recommended**: Uses the version pinned in extension constants (stable). - **Latest**: Queries the NuGet feed for the highest available version. - **Custom**: Uses the version specified in the `powerquery.sdk.tools.version` setting. ### Private NuGet Feed Configuration Example ```json { "powerquery.sdk.externals.nugetFeed": "https://pkgs.dev.azure.com/myorg/_packaging/myfeed/nuget/v3/index.json", "powerquery.sdk.externals.versionTag": "Custom", "powerquery.sdk.tools.version": "2.150.4" } ``` ``` -------------------------------- ### Display Extension Info Command Source: https://context7.com/microsoft/vscode-powerquery-sdk/llms.txt Use this command to inspect metadata of loaded .mez files. It's triggered automatically on file modification. ```typescript // Trigger via Command Palette: "Power query: Display extension info" await vscode.commands.executeCommand("powerquery.sdk.tools.DisplayExtensionInfoCommand"); ``` ```typescript // The ExtensionInfo interface returned by PQTest: interface ExtensionInfo { Source: string; // path to the .mez LibraryId: string; Name: string | null; Version: string | null; Members: Array<{ Name: string; // e.g., "MyConnector.Contents" Type: string; DataSourceKind: string; IsDataSource: boolean; DataTypeOrReturnType: string; FunctionParameters?: Array<{ Name: string; ParameterType: string; IsRequired: boolean; IsNullable: boolean; DefaultValue?: string | number; AllowedValues?: ReadonlyArray; }>; Publish: { Beta?: boolean; Category: string; SupportsDirectQuery?: boolean }; }>; DataSources: Array<{ DataSourceKind: string; AuthenticationInfos: Array<{ Kind: string; Properties: any[] }>; }>; } ``` ```plaintext // Sample output channel log: // [Info] Display extension info result: // [{"Source":"C:/project/bin/Debug/MyConnector.mez","LibraryId":"...","Name":"MyConnector", // "DataSources":[{"DataSourceKind":"MyConnector","AuthenticationInfos":[{"Kind":"Anonymous"}]}], // "Members":[{"Name":"MyConnector.Contents","IsDataSource":true,...}]}] ``` -------------------------------- ### Running Test Suites in Power Query SDK Source: https://context7.com/microsoft/vscode-powerquery-sdk/llms.txt Commands to execute different types of tests within the project. Use `npm run test:unit-test` for fast, VS Code-independent unit tests, `npm run test:e2e` for integration tests requiring a VS Code host, or `npm test` for all tests. ```typescript // Running the test suite: // npm run test:unit-test → unit tests only (152 tests, fast, no VS Code) // npm run test:e2e → integration tests (13 tests, requires VS Code host) // npm test → all tests ``` -------------------------------- ### Trigger Manual SDK Tools Update Source: https://context7.com/microsoft/vscode-powerquery-sdk/llms.txt Initiates a manual download or update of the PQTest tool via the VS Code Command Palette. This command ensures the latest SDK tools are available. ```typescript // Trigger manual SDK tools update via Command Palette: "Power query: Download/Update PQTest tool" await vscode.commands.executeCommand("powerquery.sdk.tools.SeizePqTestCommand"); ``` -------------------------------- ### Generate and Set Connector Credentials via VS Code Command Source: https://context7.com/microsoft/vscode-powerquery-sdk/llms.txt Initiate a multi-step wizard to create and store connector credentials using the 'Power query: Set credential' command. Supports various authentication types. ```typescript // Trigger via Command Palette: "Power query: Set credential" await vscode.commands.executeCommand("powerquery.sdk.tools.GenerateAndSetCredentialCommand"); // Step 1: Select or enter DataSourceKind (e.g., "MyConnector") // Step 2: Select query file (e.g., "MyConnector.query.pq") // Step 3: Select AuthenticationKind (e.g., "UsernamePassword") // Step 4+: Enter auth-specific values (username, password, key, etc.) // The CreateAuthState interface used internally: interface CreateAuthState { DataSourceKind: string; // e.g., "MyConnector" AuthenticationKind: string; // e.g., "UsernamePassword" PathToConnectorFile?: string; // e.g., "C:/project/bin/Debug/MyConnector.mez" PathToQueryFile: string; // e.g., "C:/project/MyConnector.query.pq" $$KEY$$?: string; // for Key auth $$USERNAME$$?: string; // for UsernamePassword auth $$PASSWORD$$?: string; // for UsernamePassword auth } // Validation logic (also exposed for testing): import { LifecycleCommands } from "./src/commands/LifecycleCommands"; const errorMessage = lifecycleCommands.validateCreateAuthState({ DataSourceKind: "MyConnector", AuthenticationKind: "UsernamePassword", PathToQueryFile: "C:/project/MyConnector.query.pq", $$USERNAME$$: "admin", $$PASSWORD$$: "secret", }); // errorMessage === undefined → valid // errorMessage === "Username and password are required..." → invalid // Corresponding PQTest.exe CLI call generated internally: // PQTest.exe set-credential --interactive --extension --queryFile ``` -------------------------------- ### IPQTestService Interface Operations Source: https://context7.com/microsoft/vscode-powerquery-sdk/llms.txt This section details the operations available through the IPQTestService interface, which allows interaction with the PQTest.exe process for building, testing, and managing credentials. ```APIDOC ## IPQTestService Interface The `IPQTestService` interface defines operations for interacting with the `PQTest.exe` process. ### Methods - **ExecuteBuildTaskAndAwaitIfNeeded**: Builds the connector project. - **Returns**: `Promise` - **DeleteCredential**: Deletes a credential. - **Returns**: `Promise` - **ListCredentials**: Lists all stored credentials. - **Returns**: `Promise` - **GenerateCredentialTemplate**: Generates a template for new credentials. - **Returns**: `Promise` - **SetCredential**: Sets a credential using a string payload. - **Parameters**: - `payloadStr` (string) - The credential payload. - **Returns**: `Promise` - **SetCredentialFromCreateAuthState**: Sets a credential from a CreateAuthState object. - **Parameters**: - `state` (CreateAuthState) - The authentication state. - **Returns**: `Promise` - **RefreshCredential**: Refreshes an existing credential. - **Returns**: `Promise` - **RunTestBattery**: Runs a battery of tests, optionally specifying a query file. - **Parameters**: - `pathToQueryFile` (string, optional) - The path to the query file to test. - **Returns**: `Promise` - **TestConnection**: Tests the connection. - **Returns**: `Promise` - **DisplayExtensionInfo**: Displays information about the extension. - **Returns**: `Promise` ### Properties - **pqTestReady**: `boolean` - Indicates if PQTest.exe is located and ready. - **pqTestLocation**: `string` - The directory containing PQTest.exe. - **pqTestFullPath**: `string` - The full path to PQTest.exe. - **currentExtensionInfos**: `ValueEventEmitter` - Reactive state for current extension information. - **currentCredentials**: `ValueEventEmitter` - Reactive state for current credentials. - **onPowerQueryTestLocationChanged**: `() => void` - Triggered when the PQTest location configuration changes. ``` -------------------------------- ### VS Code Workspace Settings for Power Query SDK Source: https://context7.com/microsoft/vscode-powerquery-sdk/llms.txt Configure paths for the connector file, query file, PQTest tool, and test adapter behavior within your VS Code workspace settings. These settings control various aspects of the SDK's operation. ```json // .vscode/settings.json (workspace-level) { // Path to the compiled connector (.mez) file "powerquery.sdk.defaultExtension": "${workspaceFolder}\\bin\\AnyCPU\\Debug\\${workspaceFolderBasename}.mez", // Path to the default query file to evaluate "powerquery.sdk.defaultQueryFile": "${workspaceFolder}\\${workspaceFolderBasename}.query.pq", // Absolute path to the PQTest tool installation folder (containing PQTest.exe) "powerquery.sdk.tools.location": "C:\\Users\\user\\.nuget\\packages\\microsoft.powerquery.sdktools\\2.150.4\\tools", // Track which SDK tools version is in use "powerquery.sdk.tools.version": "2.150.4", // Control which NuGet version tag to use: "Recommended", "Latest", or "Custom" "powerquery.sdk.externals.versionTag": "Recommended", // Paths to .testsettings.json files (or directories containing them) for the Test Explorer "powerquery.sdk.test.settingsFiles": [ "${workspaceFolder}/tests/MyConnector.testsettings.json" ], // Paths to connector .mez files for the Test Explorer (overrides defaultExtension for tests) "powerquery.sdk.test.extensionPaths": [ "${workspaceFolder}/bin/AnyCPU/Debug/${workspaceFolderBasename}.mez" ], // Folder where intermediate test results are stored (relative to .testsettings.json) "powerquery.sdk.test.defaultIntermediateResultsFolder": "../TestResults", // Hours after which intermediate test results are auto-deleted (0 = disabled) "powerquery.sdk.test.cleanupIntermediateResultsAfterHours": 24, // Auto-detect Power Query files and prompt to configure workspace "powerquery.sdk.features.autoDetection": true } ``` -------------------------------- ### Configure Power Query Test Settings Source: https://github.com/microsoft/vscode-powerquery-sdk/blob/main/PQTestVSCodeUIIntegration.md Configure VS Code settings to specify paths for test settings files and connector files. Relative paths are resolved against the workspace folder. Supports VS Code variable substitution. ```json "powerquery.sdk.test.settingsFiles": "path/to/your/.testsettings.json", "powerquery.sdk.test.extensionPaths": "${workspaceFolder}/connectors/*.mez" ``` ```json "powerquery.sdk.tools.location": "C:\\...\\Microsoft.PowerQuery.SdkTools.2.150.4\\tools", "powerquery.sdk.tools.version": "2.150.4" ``` -------------------------------- ### Run Only Power Query SDK Unit Tests Source: https://github.com/microsoft/vscode-powerquery-sdk/blob/main/README.md Execute only the unit tests for the Power Query SDK. These tests are fast and do not require VS Code dependencies. ```bash npm run test:unit-test ``` -------------------------------- ### Build PQTest Arguments Source: https://context7.com/microsoft/vscode-powerquery-sdk/llms.txt Constructs the CLI argument array for PQTest tasks, specifying operation type, connector path, query file path, and additional arguments. ```typescript import { buildPqTestArgs } from "./src/common/PQTestService"; const args = buildPqTestArgs({ type: "powerquery", operation: "run-test", label: "Evaluate query", pathToConnector: "C:/project/bin/Debug/MyConnector.mez", pathToQueryFile: "C:/project/MyConnector.query.pq", additionalArgs: [], }); // → ["run-test", "--extension", "C:/project/bin/.../MyConnector.mez", // "--queryFile", "C:/project/MyConnector.query.pq", "--prettyPrint"] ``` -------------------------------- ### SDK Tools Update Process Source: https://context7.com/microsoft/vscode-powerquery-sdk/llms.txt Describes the automatic process the extension uses to check for and download SDK tool updates via NuGet, including configuration of feeds and versioning. ```typescript // The extension checks for updates and downloads via NuGet: // 1. Queries the configured NuGet feed (or nuget.org by default) // 2. Downloads the .nupkg and extracts PQTest.exe + MakePQX.exe // 3. Updates powerquery.sdk.tools.location and powerquery.sdk.tools.version settings // 4. Copies the updated UserSettings.schema.json for .testsettings.json IntelliSense ``` -------------------------------- ### Run Only Power Query SDK Integration Tests Source: https://github.com/microsoft/vscode-powerquery-sdk/blob/main/README.md Execute only the integration (end-to-end) tests for the Power Query SDK. These tests require VS Code to be available. ```bash npm run test:e2e ``` -------------------------------- ### IPQTestService Interface Definition Source: https://context7.com/microsoft/vscode-powerquery-sdk/llms.txt Defines the contract for operations dispatched to the PQTest.exe process. Includes properties for tool status and methods for build, credential management, and testing. ```typescript import { IPQTestService, GenericResult, ExtensionInfo, Credential, CreateAuthState } from "./src/common/PQTestService"; // Full interface contract: interface IPQTestService { readonly pqTestReady: boolean; // true if PQTest.exe is located and ready readonly pqTestLocation: string; // directory containing PQTest.exe readonly pqTestFullPath: string; // full path to PQTest.exe // Reactive state (subscribers get notified on changes) readonly currentExtensionInfos: ValueEventEmitter; readonly currentCredentials: ValueEventEmitter; // Triggers when PQTest.exe location config changes readonly onPowerQueryTestLocationChanged: () => void; // Build the connector project readonly ExecuteBuildTaskAndAwaitIfNeeded: () => Promise; // Credential operations readonly DeleteCredential: () => Promise; readonly ListCredentials: () => Promise; readonly GenerateCredentialTemplate: () => Promise; readonly SetCredential: (payloadStr: string) => Promise; readonly SetCredentialFromCreateAuthState: (state: CreateAuthState) => Promise; readonly RefreshCredential: () => Promise; // Query and test operations readonly RunTestBattery: (pathToQueryFile?: string) => Promise; readonly TestConnection: () => Promise; readonly DisplayExtensionInfo: () => Promise; } ``` -------------------------------- ### Check Power Query Test File Naming Convention Source: https://context7.com/microsoft/vscode-powerquery-sdk/llms.txt Verify if a given string adheres to the expected file naming convention for Power Query test files, specifically checking for the `.query.pq` ending. ```typescript // Check file naming convention for test query files: hasValidTestFileEnding("BasicQuery.query.pq", ".query.pq"); // → true hasValidTestFileEnding("BasicQuery.m", ".query.pq"); // → false hasValidTestFileEnding("", ".query.pq"); // → false ``` -------------------------------- ### Lint Power Query SDK Code Source: https://github.com/microsoft/vscode-powerquery-sdk/blob/main/README.md Check the Power Query SDK code for style and potential errors using a linter. This command helps maintain code quality. ```bash npm run lint ``` -------------------------------- ### Abstracting VS Code Dependencies for Testability Source: https://github.com/microsoft/vscode-powerquery-sdk/blob/main/TESTING.md Illustrates how to abstract VS Code API interactions behind an interface for easier testing. Pure business logic should be extracted into separate, testable functions. ```typescript // Abstract VS Code interactions export interface IUIService { showInformationMessage(message: string): Promise; showErrorMessage(message: string): Promise; } // Business logic remains testable export class NotificationService { constructor(private readonly ui: IUIService) {} async notifyResult(result: OperationResult): Promise { const message = this.formatMessage(result); // Pure function - testable if (result.success) { await this.ui.showInformationMessage(message); } else { await this.ui.showErrorMessage(message); } } private formatMessage(result: OperationResult): string { // Pure business logic - unit testable return result.success ? `Operation completed: ${result.data}` : `Operation failed: ${result.error}`; } } ``` -------------------------------- ### Configure VS Code Test Explorer for Power Query Source: https://context7.com/microsoft/vscode-powerquery-sdk/llms.txt Configure VS Code settings to enable the Test Explorer to discover and run Power Query tests. Ensure the correct paths for settings files, extensions, and tools are specified. ```typescript // VS Code settings to enable Test Explorer discovery: { "powerquery.sdk.test.settingsFiles": "${workspaceFolder}/tests", "powerquery.sdk.test.extensionPaths": [ "${workspaceFolder}/bin/AnyCPU/Debug/${workspaceFolderBasename}.mez" ], "powerquery.sdk.tools.location": "C:\\...\\Microsoft.PowerQuery.SdkTools.2.150.4\\tools", "powerquery.sdk.tools.version": "2.150.4" } ``` -------------------------------- ### Testable Service Interface and Implementation Source: https://github.com/microsoft/vscode-powerquery-sdk/blob/main/TESTING.md Defines an interface for dependency injection and provides a concrete implementation. This pattern separates business logic, making it easier to test without direct dependencies on file system or validation modules. ```typescript // Interface for dependency injection export interface IDataProcessor { processData(input: string): Promise; } // Implementation with dependencies export class DataProcessor implements IDataProcessor { constructor( private readonly fileSystem: IFileSystem, private readonly validator: IValidator, ) {} async processData(input: string): Promise { // Pure business logic - easily testable const validationResult = this.validator.validate(input); if (!validationResult.isValid) { return { success: false, error: validationResult.error }; } const data = await this.fileSystem.readFile(input); return { success: true, data: this.transformData(data) }; } private transformData(data: string): string { // Pure function - easily unit tested return data.trim().toUpperCase(); } } ``` -------------------------------- ### Test Connection Command Source: https://context7.com/microsoft/vscode-powerquery-sdk/llms.txt Validates the connector's TestConnection function, crucial for refresh verification in cloud environments. Results are logged to the output channel. ```typescript // Trigger via Command Palette: "Power query: Test connection" await vscode.commands.executeCommand("powerquery.sdk.tools.TestConnectionCommand"); ``` ```typescript // Returns a GenericResult: interface GenericResult { Status: "Success" | "Failure"; Message: string; Details: any; } ``` ```plaintext // Output channel example: // [Info] Test connection result: {"Status":"Success","Message":"Connection succeeded","Details":null} ``` ```plaintext // Equivalent PQTest.exe CLI: // PQTest.exe test-connection --extension <.mez> --queryFile <.query.pq> --prettyPrint ``` -------------------------------- ### Manage Power Query Credentials via VS Code Commands Source: https://context7.com/microsoft/vscode-powerquery-sdk/llms.txt Commands to list, refresh, and delete stored connector credentials within the Power Query SDK. These operations are logged to the Output channel. ```typescript // List all stored credentials → shown in the Power Query SDK output channel await vscode.commands.executeCommand("powerquery.sdk.tools.ListCredentialCommand"); // Output channel logs: // [Info] List credentials result: [{"DataSource":{"kind":"MyConnector","path":"..."},"AuthenticationKind":"Anonymous",...}] // Refresh OAuth/AAD access tokens for stored credentials await vscode.commands.executeCommand("powerquery.sdk.tools.RefreshCredentialCommand"); // Output: {"Status":"Success","Message":"Credentials refreshed","Details":null} // Delete all stored credentials await vscode.commands.executeCommand("powerquery.sdk.tools.DeleteCredentialCommand"); // Output: {"Status":"Success","Message":"All credentials deleted","Details":null} // Equivalent PQTest.exe CLI commands: // PQTest.exe list-credential --prettyPrint // PQTest.exe refresh-credential --extension <.mez> --queryFile <.query.pq> --prettyPrint // PQTest.exe delete-credential --ALL --prettyPrint ``` -------------------------------- ### Debug Mock Calls with Sinon Source: https://github.com/microsoft/vscode-powerquery-sdk/blob/main/TESTING.md Use Sinon's `getCall` method to inspect arguments passed to mocked functions. This helps in verifying interactions with dependencies. ```typescript // Use Sinon call history for debugging console.log("Mock was called with:", mockService.method.getCall(0).args); ``` -------------------------------- ### Testing Observable Behavior vs. Implementation Details Source: https://github.com/microsoft/vscode-powerquery-sdk/blob/main/TESTING.md Contrasts testing internal state (bad) with testing observable behavior (good). Focus tests on the public API and expected outcomes rather than internal implementation. ```typescript // Bad - testing internal state expect(service.internalCache.size).to.equal(1); // Good - testing observable behavior expect(await service.getData("key")).to.equal(expectedValue); ``` -------------------------------- ### Power Query Test ID Utilities Source: https://context7.com/microsoft/vscode-powerquery-sdk/llms.txt Utilize core utility functions for creating and parsing composite test IDs, which combine original test IDs with settings file URIs. These functions have no VS Code dependencies. ```typescript // Test IDs use a composite format: "originalTestId|settingsFileUri" // Core utility functions (no VS Code dependencies): import { createCompositeId, parseCompositeId } from "./src/testing/pqtest-adapter/core/compositeId"; const id = createCompositeId("test:BasicQuery", "file:///project/tests/MyConnector.testsettings.json"); // → "test:BasicQuery|file:///project/tests/MyConnector.testsettings.json" const parts = parseCompositeId(id); // → { originalTestId: "test:BasicQuery", settingsFileUri: "file:///project/tests/MyConnector.testsettings.json" } ``` -------------------------------- ### Validate Power Query File Path Fields Source: https://context7.com/microsoft/vscode-powerquery-sdk/llms.txt Use pure validation utilities to check the validity of `QueryFilePath` values from parsed `.testsettings.json` files. These utilities are unit-testable and have no VS Code dependencies. ```typescript import { validateQueryFilePathField, hasValidTestFileEnding } from "./src/testing/pqtest-adapter/core/queryFilePathValidation"; // Validate QueryFilePath values from parsed .testsettings.json: validateQueryFilePathField(undefined); // → { isValid: false, errorCode: "missing", error: "QueryFilePath property is missing" } validateQueryFilePathField(42); // → { isValid: false, errorCode: "invalid-type", error: "QueryFilePath must be a string, got number" } validateQueryFilePathField(""); // → { isValid: false, errorCode: "empty", error: "QueryFilePath cannot be empty" } validateQueryFilePathField(" "); // → { isValid: false, errorCode: "whitespace-only", error: "QueryFilePath cannot be whitespace-only" } validateQueryFilePathField("./tests/BasicQuery.query.pq"); // → { isValid: true } ``` -------------------------------- ### VS Code Power Query Test Explorer Commands Source: https://context7.com/microsoft/vscode-powerquery-sdk/llms.txt Execute VS Code commands to interact with the Power Query Test Explorer. These commands allow for refreshing tests, clearing discovered tests, and opening expected output files. ```typescript // Manually refresh all tests in the Test Explorer: await vscode.commands.executeCommand("powerquery.sdk.test.refreshTests"); // Clear all discovered tests: await vscode.commands.executeCommand("powerquery.sdk.test.clearTests"); // Open the expected output file for a test (the .pqout reference file): await vscode.commands.executeCommand("powerquery.sdk.test.openOutputFile"); ``` -------------------------------- ### Edge Case Testing for Boundary Conditions Source: https://github.com/microsoft/vscode-powerquery-sdk/blob/main/TESTING.md Systematically test boundary conditions and edge cases for the validation service. Includes tests for empty strings, max length, and unicode characters. ```typescript describe("Edge Case Testing", () => { it("should handle boundary conditions correctly", () => { const edgeCases = [ { input: "", expected: false, reason: "empty string" }, { input: "a".repeat(255), expected: true, reason: "max length" }, { input: "a".repeat(256), expected: false, reason: "over max length" }, { input: "🚀💻📊", expected: false, reason: "unicode characters" }, ]; for (const testCase of edgeCases) { const result = ValidationService.validate(testCase.input); expect(result.isValid).to.equal(testCase.expected, `${testCase.reason}: "${testCase.input}"`); } }); }); ``` -------------------------------- ### Property-Based Test for File Path Validation Source: https://context7.com/microsoft/vscode-powerquery-sdk/llms.txt This property-based test validates the `validateQueryFilePathField` function. It ensures that the function correctly identifies valid and invalid file paths, including edge cases like null, undefined, empty strings, and non-string inputs. Requires `chai` for assertions. ```typescript import { validateQueryFilePathField } from "../src/testing/pqtest-adapter/core/queryFilePathValidation"; import { expect } from "chai"; describe("validateQueryFilePathField - property-based", () => { it("always accepts non-empty, non-whitespace strings", () => { const validPaths = ["./tests", "/absolute/path", "relative/file.pq", "C:\\Windows\\path.pq"]; for (const p of validPaths) { expect(validateQueryFilePathField(p).isValid).to.equal(true, `Should accept: "${p}"`); } }); it("always rejects null, undefined, empty, non-string", () => { const invalidInputs = [null, undefined, "", " ", 0, false, [], {}]; for (const input of invalidInputs) { expect(validateQueryFilePathField(input).isValid).to.equal(false, `Should reject: ${JSON.stringify(input)}`); } }); }); ``` -------------------------------- ### Log Test Data for Debugging Source: https://github.com/microsoft/vscode-powerquery-sdk/blob/main/TESTING.md Log test data using `console.log` and `JSON.stringify` to inspect values during test execution. This is useful for understanding the state of test inputs. ```typescript // Log test data for debugging console.log(`Testing with input: ${JSON.stringify(testData)}`); ``` -------------------------------- ### Performance Testing for Critical Operations Source: https://github.com/microsoft/vscode-powerquery-sdk/blob/main/TESTING.md Include performance tests with realistic thresholds for critical operations. Asserts that a loop of operations completes within a specified time. ```typescript describe("Performance Testing", () => { it("should handle operations quickly under load", () => { const startTime = Date.now(); const iterations = 1000; for (let i = 0; i < iterations; i++) { const result = CriticalService.performOperation(`input${i}`); expect(result).to.be.defined; } const duration = Date.now() - startTime; expect(duration).to.be.lessThan(100, `${iterations} operations took ${duration}ms, should be < 100ms`); }); }); ``` -------------------------------- ### Random Data Generator for Property-Based Testing Source: https://github.com/microsoft/vscode-powerquery-sdk/blob/main/TESTING.md Provides a TypeScript function to generate random, valid project names for property-based testing. This helps in creating diverse test inputs. ```typescript function generateValidProjectName(): string { const letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; const validChars = letters + "0123456789_"; let name = letters[Math.floor(Math.random() * letters.length)]; const length = Math.floor(Math.random() * 50) + 1; for (let i = 0; i < length; i++) { name += validChars[Math.floor(Math.random() * validChars.length)]; } return name; } ``` -------------------------------- ### Add Detailed Failure Messages in Tests Source: https://github.com/microsoft/vscode-powerquery-sdk/blob/main/TESTING.md Enhance test assertions with detailed failure messages to aid debugging. Include relevant context like input values and error details. ```typescript // Add detailed failure messages expect(result.isValid).to.equal(true, `Validation failed for: "${input}" - ${result.error}`); ``` -------------------------------- ### Property-Based Testing for Validation Rules Source: https://github.com/microsoft/vscode-powerquery-sdk/blob/main/TESTING.md Use for validation logic and business rules. Generates random valid inputs to test the validation service. ```typescript describe("Property-Based Testing - Validation Rules", () => { it("should always validate valid inputs regardless of case", () => { for (let i = 0; i < 100; i++) { const validInput = generateValidInput(); const result = ValidationService.validate(validInput); expect(result.isValid).to.equal(true, `Valid input should pass: "${validInput}"`); } }); }); ``` -------------------------------- ### Edge Case Test Data Collection Source: https://github.com/microsoft/vscode-powerquery-sdk/blob/main/TESTING.md An array of strings representing various edge cases, including empty strings, whitespace, long strings, Unicode characters, control characters, null, and undefined. Useful for comprehensive testing. ```typescript const EDGE_CASE_STRINGS = [ "", // Empty " ", // Whitespace "a".repeat(1000), // Very long "🚀💻📊", // Unicode "test\n\r\t", // Control characters null as any, // Null undefined as any, // Undefined ]; ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.