diff --git a/README.md b/README.md index 4bf4ced..332ea07 100644 --- a/README.md +++ b/README.md @@ -18,6 +18,14 @@ dotnet docfx docfx.json --serve # http://localhost:8080 | Guides, CI setup, concepts | this repo | written here | | Exit codes, release verification, command reference, rule pages, `.xping.yml` reference | `xping-dev/xping` (`docs/reference/`) | `scripts/import-reference.sh `, never edited here | | `session.schema.json`, `history.schema.json` | `xping-dev/xping` (`schema/`) | same script, published under `/schema/` | -| SDK guides | moved from `xping-dev/sdk-dotnet` (`docs/`) | one-time move, see the migration plan in xping-dev/xping | +| SDK guides (`sdk/`) | moved from `xping-dev/sdk-dotnet@dc64c02` (`docs/`) | edited here from now on. The Cloud and 1.0.0-rc CLI parts carry notes until the SDK drops them. | Pages generated from code are imported at the release tag in `xping-version.txt`, so the site always describes a released version. Bump the file to publish docs for a new release. Until the first release (`v2.0.0-alpha.1`) it names `main`. + +## Old URLs + +docs.xping.io used to serve the SDK site from xping-dev/sdk-dotnet. The paths released packages +link (for example `/getting-started/quickstart-nunit.html`, `/configuration/configuration-reference.html`, +`/known-limitations.html`, `/cli/command-reference.html`, `/api/...`) are redirect pages +(`redirect_url` front matter) at their old locations. Keep them. + diff --git a/api/Xping.Sdk.Core.Collection.md b/api/Xping.Sdk.Core.Collection.md new file mode 100644 index 0000000..603f8f0 --- /dev/null +++ b/api/Xping.Sdk.Core.Collection.md @@ -0,0 +1,3 @@ +--- +redirect_url: ../sdk/index.html +--- diff --git a/api/Xping.Sdk.Core.md b/api/Xping.Sdk.Core.md new file mode 100644 index 0000000..603f8f0 --- /dev/null +++ b/api/Xping.Sdk.Core.md @@ -0,0 +1,3 @@ +--- +redirect_url: ../sdk/index.html +--- diff --git a/cli/cloud-data.md b/cli/cloud-data.md new file mode 100644 index 0000000..cd1b32a --- /dev/null +++ b/cli/cloud-data.md @@ -0,0 +1,3 @@ +--- +redirect_url: ../index.html +--- diff --git a/cli/command-reference.md b/cli/command-reference.md new file mode 100644 index 0000000..cd1b32a --- /dev/null +++ b/cli/command-reference.md @@ -0,0 +1,3 @@ +--- +redirect_url: ../index.html +--- diff --git a/cli/reading-the-report.md b/cli/reading-the-report.md new file mode 100644 index 0000000..cd1b32a --- /dev/null +++ b/cli/reading-the-report.md @@ -0,0 +1,3 @@ +--- +redirect_url: ../index.html +--- diff --git a/cloud/confidence-scores.md b/cloud/confidence-scores.md new file mode 100644 index 0000000..603f8f0 --- /dev/null +++ b/cloud/confidence-scores.md @@ -0,0 +1,3 @@ +--- +redirect_url: ../sdk/index.html +--- diff --git a/cloud/connect.md b/cloud/connect.md new file mode 100644 index 0000000..603f8f0 --- /dev/null +++ b/cloud/connect.md @@ -0,0 +1,3 @@ +--- +redirect_url: ../sdk/index.html +--- diff --git a/cloud/plans-and-retention.md b/cloud/plans-and-retention.md new file mode 100644 index 0000000..603f8f0 --- /dev/null +++ b/cloud/plans-and-retention.md @@ -0,0 +1,3 @@ +--- +redirect_url: ../sdk/index.html +--- diff --git a/cloud/read-api.md b/cloud/read-api.md new file mode 100644 index 0000000..603f8f0 --- /dev/null +++ b/cloud/read-api.md @@ -0,0 +1,3 @@ +--- +redirect_url: ../sdk/index.html +--- diff --git a/cloud/reading-the-pr-comment.md b/cloud/reading-the-pr-comment.md new file mode 100644 index 0000000..603f8f0 --- /dev/null +++ b/cloud/reading-the-pr-comment.md @@ -0,0 +1,3 @@ +--- +redirect_url: ../sdk/index.html +--- diff --git a/cloud/session-reliability-score.md b/cloud/session-reliability-score.md new file mode 100644 index 0000000..603f8f0 --- /dev/null +++ b/cloud/session-reliability-score.md @@ -0,0 +1,3 @@ +--- +redirect_url: ../sdk/index.html +--- diff --git a/configuration/collected-data.md b/configuration/collected-data.md new file mode 100644 index 0000000..1b853ad --- /dev/null +++ b/configuration/collected-data.md @@ -0,0 +1,3 @@ +--- +redirect_url: ../sdk/configuration/collected-data.html +--- diff --git a/configuration/configuration-reference.md b/configuration/configuration-reference.md new file mode 100644 index 0000000..6d45816 --- /dev/null +++ b/configuration/configuration-reference.md @@ -0,0 +1,3 @@ +--- +redirect_url: ../sdk/configuration/configuration-reference.html +--- diff --git a/configuration/local-store.md b/configuration/local-store.md new file mode 100644 index 0000000..3da1946 --- /dev/null +++ b/configuration/local-store.md @@ -0,0 +1,3 @@ +--- +redirect_url: ../sdk/configuration/local-store.html +--- diff --git a/docfx.json b/docfx.json index fbc24f9..8348f1e 100644 --- a/docfx.json +++ b/docfx.json @@ -2,21 +2,48 @@ "$schema": "https://raw.githubusercontent.com/dotnet/docfx/main/schemas/docfx.schema.json", "build": { "content": [ - { "files": ["**/*.{md,yml}"], "exclude": ["_site/**", "README.md", "obj/**", ".github/**", "scripts/**"] } + { + "files": [ + "**/*.{md,yml}" + ], + "exclude": [ + "_site/**", + "README.md", + "obj/**", + ".github/**", + "scripts/**" + ] + } ], "resource": [ - { "files": ["media/**", "schema/**"] } + { + "files": [ + "media/**", + "schema/**", + "public/**" + ] + } ], "output": "_site", - "template": ["default", "modern"], + "template": [ + "default", + "modern" + ], "globalMetadata": { "_appName": "Xping", "_appTitle": "Xping", "_appFooter": "MIT licensed. Source: xping-dev/docs", "_enableSearch": true, "_disableContribution": false, - "_gitContribute": { "repo": "https://github.com/xping-dev/docs", "branch": "main" } + "_gitContribute": { + "repo": "https://github.com/xping-dev/docs", + "branch": "main" + }, + "_appLogoPath": "media/logo.svg", + "_appFaviconPath": "media/favicon.ico" }, - "sitemap": { "baseUrl": "https://docs.xping.io" } + "sitemap": { + "baseUrl": "https://docs.xping.io" + } } } diff --git a/flaky-tests/finding-flaky-tests.md b/flaky-tests/finding-flaky-tests.md new file mode 100644 index 0000000..cd1b32a --- /dev/null +++ b/flaky-tests/finding-flaky-tests.md @@ -0,0 +1,3 @@ +--- +redirect_url: ../index.html +--- diff --git a/flaky-tests/patterns-and-fixes.md b/flaky-tests/patterns-and-fixes.md new file mode 100644 index 0000000..cd1b32a --- /dev/null +++ b/flaky-tests/patterns-and-fixes.md @@ -0,0 +1,3 @@ +--- +redirect_url: ../index.html +--- diff --git a/getting-started/ci-cd-setup.md b/getting-started/ci-cd-setup.md new file mode 100644 index 0000000..09090bf --- /dev/null +++ b/getting-started/ci-cd-setup.md @@ -0,0 +1,3 @@ +--- +redirect_url: ../sdk/getting-started/ci-cd-setup.html +--- diff --git a/getting-started/local-first.md b/getting-started/local-first.md new file mode 100644 index 0000000..e723fe0 --- /dev/null +++ b/getting-started/local-first.md @@ -0,0 +1,3 @@ +--- +redirect_url: ../sdk/getting-started/local-first.html +--- diff --git a/getting-started/quickstart-mstest.md b/getting-started/quickstart-mstest.md new file mode 100644 index 0000000..cb2c4fa --- /dev/null +++ b/getting-started/quickstart-mstest.md @@ -0,0 +1,3 @@ +--- +redirect_url: ../sdk/getting-started/quickstart-mstest.html +--- diff --git a/getting-started/quickstart-nunit.md b/getting-started/quickstart-nunit.md new file mode 100644 index 0000000..1883a93 --- /dev/null +++ b/getting-started/quickstart-nunit.md @@ -0,0 +1,3 @@ +--- +redirect_url: ../sdk/getting-started/quickstart-nunit.html +--- diff --git a/getting-started/quickstart-xunit.md b/getting-started/quickstart-xunit.md new file mode 100644 index 0000000..d7a6400 --- /dev/null +++ b/getting-started/quickstart-xunit.md @@ -0,0 +1,3 @@ +--- +redirect_url: ../sdk/getting-started/quickstart-xunit.html +--- diff --git a/guides/working-with-tests/common-flaky-patterns.md b/guides/working-with-tests/common-flaky-patterns.md new file mode 100644 index 0000000..586dbe6 --- /dev/null +++ b/guides/working-with-tests/common-flaky-patterns.md @@ -0,0 +1,3 @@ +--- +redirect_url: ../../index.html +--- diff --git a/known-limitations.md b/known-limitations.md new file mode 100644 index 0000000..1e44725 --- /dev/null +++ b/known-limitations.md @@ -0,0 +1,3 @@ +--- +redirect_url: sdk/troubleshooting/known-limitations.html +--- diff --git a/media/favicon.ico b/media/favicon.ico new file mode 100644 index 0000000..9b13c33 Binary files /dev/null and b/media/favicon.ico differ diff --git a/media/logo.svg b/media/logo.svg new file mode 100644 index 0000000..57b77e9 --- /dev/null +++ b/media/logo.svg @@ -0,0 +1,3 @@ + + + \ No newline at end of file diff --git a/performance/performance.md b/performance/performance.md new file mode 100644 index 0000000..fd66b9f --- /dev/null +++ b/performance/performance.md @@ -0,0 +1,3 @@ +--- +redirect_url: ../sdk/performance/performance.html +--- diff --git a/public/main.css b/public/main.css new file mode 100644 index 0000000..e6434fd --- /dev/null +++ b/public/main.css @@ -0,0 +1,7 @@ +/* Xping SDK Documentation Custom Styles */ + +/* Target logo by ID (DocFX modern template) */ +#logo { + height: 32px !important; + width: auto !important; +} diff --git a/sdk/configuration/collected-data.md b/sdk/configuration/collected-data.md new file mode 100644 index 0000000..591ae13 --- /dev/null +++ b/sdk/configuration/collected-data.md @@ -0,0 +1,332 @@ +--- +uid: configuration-collected-data +title: Data Xping collects +--- + +# Data Xping collects + +> [!NOTE] +> This page describes the **Xping SDK for .NET, 1.0.0-rc series**. The SDK can upload to Xping Cloud, and these pages refer to the 1.0.0-rc `xping report` CLI. The Xping CLI 2.x is a different tool: it does not use Xping Cloud and has no `report` command. See the [Xping overview](../../index.md). + +This page lists every field the Xping SDK records, where it goes, and the switch that controls it. +It is for developers and for anyone who reviews what a test run sends to Xping Cloud. + +--- + +## Where the data goes + +- A **run** is one `dotnet test` invocation that the SDK records, for one test assembly or more. + The SDK's API (`TestSession`, `SessionId`) and the read API call it a + session. A run holds one execution for + each test that ran. +- An **execution** is one test's result within a run. A retried test has one execution for + each attempt that the framework reports. + +| [Mode](configuration-reference.md#mode) | Local store | Xping Cloud | +|---|---|---| +| `LocalOnly` (the `Auto` mode without an API key) | The full run | Nothing. The SDK makes no network calls. | +| `Cloud` (the `Auto` mode with an API key) | The full run | The run, without the stack trace text unless you turn on [UploadStackTraces](configuration-reference.md#uploadstacktraces) | +| `Disabled` | Nothing | Nothing | + +The SDK writes the local store before it uploads. The [local store](local-store.md) page says where +the store is and how to delete it. + +--- + +## Personal data and other sensitive fields + +| Field | When the SDK records it | Switch | Default | +|---|---|---|---| +| Machine name (`MachineName`) | Always | None | On | +| CI login or name of the person behind the run (`CI.Actor`, `CI.ActorId`) | On CI, when the platform gives one. See [Who is behind the run](#who-is-behind-the-run). | None | On | +| CI email of that person (`CI.ActorEmail`) | On Azure Pipelines, GitLab, Jenkins and AppVeyor | [CollectCiActorEmail](configuration-reference.md#collectciactoremail) | Off | +| GitLab commit author (`CI.CommitAuthor`) | On GitLab. GitLab gives it as `Name `. | None | On | +| PR author (`PullRequestContext.Author`) | On a PR build with PR context | [EnablePullRequestDetection](configuration-reference.md#enablepullrequestdetection) | On | +| Local git author name (`Git.Actor`) | Outside CI, from `user.name` in the repository's git config, or else in your global git config (`~/.gitconfig` or `$XDG_CONFIG_HOME/git/config`) | [CollectLocalGitAuthor](configuration-reference.md#collectlocalgitauthor) | Off | +| Error message (`ErrorMessage`) | When a test fails | None | On | +| Stack trace text (`StackTrace`) | When a test fails. The local store always keeps it. | [UploadStackTraces](configuration-reference.md#uploadstacktraces), for the upload only | Not uploaded | +| NUnit author tag (`Tags`, `author:`) | For each `[Author]` attribute. `[Author(name, email)]` gives `author:Name `. | None | On | +| Test arguments (`CustomAttributes["Arguments"]`) | For each data row of a parameterized test | None | On | +| xUnit test output (`CustomAttributes["Output"]`) | When an xUnit test writes to `ITestOutputHelper` | None | On | +| MSTest `TestContext` properties | Always on MSTest. Some of them are folder paths on the machine, which can contain the user name. | None | On | +| Source file path (`SourceFile`) | When the test assembly has a Portable PDB. Outside a git repository, the path is absolute and can contain the user name. | None | On | + +**The SDK stores and uploads the error message word for word.** It contains whatever your test or +your code put in it, for example an assertion value or a connection string. The SDK does not redact +it. It also sends a hash of the message, with numbers, GUIDs, paths and times replaced, so that +Xping Cloud can group repeats of the same failure. + +**Without the stack trace text**, the upload still carries a hash of the method names in the +trace, without file paths or line numbers. Xping Cloud groups failures by it. + +The SDK does not read or send your source code. + +To record nothing at all, set [Enabled](configuration-reference.md#enabled) to `false` +(`XPING_ENABLED=false`). + +--- + +## Each run + +| Field | What it holds | +|---|---| +| `SessionId` | A new GUID for each run | +| `StartedAt`, `EndedAt` | UTC times of the first and last record | +| `Assemblies` | The names of the test assemblies in the run | +| `SdkVersion` | The version of the Xping SDK | +| `SessionState` | Which upload this is: `Initial` (the first batch), `Partial` (a later batch) or `Finalized` (the last one, at the end of the run) | +| `EnvironmentInfo` | The machine and the CI build. See [The environment](#the-environment). | +| `PullRequestContext` | The pull request, on a PR build. See [Pull request context](#pull-request-context). | +| `QuickStatistics`, `StatisticsByAssembly` | Counts of executions by outcome, for the whole run and for each assembly | + +--- + +## Each execution + +### Identity + +| Field | What it holds | +|---|---| +| `TestFingerprint` | The test's stable id: a SHA-256 hash of the fully qualified name and the parameter hash, or the value of `[XpingFingerprint]` | +| `FullyQualifiedName`, `Assembly`, `Namespace`, `ClassName`, `MethodName` | Where the test is declared | +| `DisplayName` | The name the framework shows | +| `ParameterHash` | A hash of the arguments, for a data row of a parameterized test | +| `SourceFile`, `SourceLineNumber` | The file and the line of the test method, read from the Portable PDB. The path is relative to the repository root when the SDK finds one, and absolute otherwise. Both are empty when the assembly has no PDB. | + +### Result + +| Field | What it holds | +|---|---| +| `ExecutionId` | A new GUID for each execution | +| `TestName` | The test's name | +| `Outcome` | `Passed`, `Failed`, `Timeout`, `Skipped`, `Inconclusive` or `NotExecuted` | +| `Duration`, `StartTimeUtc`, `EndTimeUtc` | How long the test ran, and when | +| `ExceptionType` | The full type name of the exception that failed the test | +| `ErrorMessage` | The exception message, word for word | +| `ErrorMessageHash` | A SHA-256 hash of the message, with run-specific detail replaced | +| `StackTrace` | The stack trace text. Left out of the upload unless `UploadStackTraces` is on. | +| `StackTraceHash` | A SHA-256 hash of the method names in the trace | +| `StackTraceOmitted` | `true` on the uploaded copy when the SDK left out the trace text | +| `TimeoutBudget`, `TimeoutBudgetSource` | The timeout the test declared. `TimeoutBudgetSource` is `Declared` for a finite timeout and `Infinite` when the test declared no limit. Both are empty when the test declared nothing. | +| `Site` | Where a failing test failed: `TestBody`, `TestSetup`, `TestTeardown`, `FixtureSetup`, `FixtureTeardown`, `AssemblySetup`, `AssemblyTeardown` or `Unknown`. Empty when the test did not fail. | +| `FailureSiteMember` | The setup or teardown member that failed, such as `OrdersFixture.OneTimeSetUp`, when the framework names one | + +### Categories, tags and attributes + +| Field | NUnit | xUnit v2 and v3 | MSTest | +|---|---|---|---| +| `Categories` | `[Category]` | `[Trait("Category", …)]` | `TestCategory` from `TestContext.Properties` | +| `Description` | `[Description]` | The first `[Trait("Description", …)]` | `Description` from `TestContext.Properties` | +| `Tags` | `framework:NUnit`, `type:test` or `type:suite`, and `author:` for `[Author]` | `framework:xUnit`, `type:fact` or `type:theory`, and `key:value` for every other trait | `framework:MSTest`, `type:test` or `type:datatest` | +| `CustomAttributes` | `FixtureType`, and `Arguments` for a `[TestCase]` | `Arguments` for a theory, and `Output` for the test output | Every other `TestContext.Properties` entry, `Arguments` for a `[DataRow]`, and `ResultsDirectory` | + +Xping Cloud stores these fields with each execution and returns them from its API. Scoring and +flaky-test detection do not use them, and the test list does not filter by them. Xping Cloud reads +only one tag itself: `framework:`. + +### Test order and concurrency + +| Field | What it holds | +|---|---| +| `PositionInSuite` | The test's position on its worker | +| `GlobalPosition` | The test's position across all workers | +| `PreviousTestId`, `PreviousTestName`, `PreviousTestOutcome` | The test that ran just before this one on the same worker | +| `WasParallelized`, `ConcurrentTestCount` | Whether other tests ran at the same time, and how many | +| `ThreadId`, `WorkerId` | The thread and the worker that ran the test | +| `SuiteElapsedTime` | The time from the start of the run to the start of the test | +| `CollectionName` | The xUnit test collection, the NUnit fixture or the MSTest test class | + +### Retries + +The SDK records retry fields when a test has a retry attribute: + +| Field | What it holds | +|---|---| +| `AttemptNumber` | `1` for the first attempt, `2` and up for retries | +| `MaxRetries` | The count the attribute declares | +| `PassedOnRetry` | `true` when an attempt after the first passed | +| `DelayBetweenRetries` | The delay the attribute declares | +| `RetryReason` | The reason the attribute declares | +| `RetryAttributeName` | The name of the retry attribute | +| `AdditionalMetadata` | The attribute's other properties | + +The SDK recognizes these attributes, by name: + +| Framework | Attributes | +|---|---| +| NUnit | `Retry` | +| xUnit | `RetryFact`, `RetryTheory`, `Retry`, `XunitRetry` | +| MSTest | `TestRetry`, `Retry`, `DataTestMethodWithRetry` | + +To add your own attribute, call `RetryAttributeRegistry.RegisterCustomRetryAttribute` before the +run starts. The framework name is `xunit`, `nunit` or `mstest`: + +```csharp +using Xping.Sdk.Core.Services.Retry; + +RetryAttributeRegistry.RegisterCustomRetryAttribute("nunit", "RetryOnDeadlock"); +``` + +On xUnit v3, xRetry.v3 reports only the last attempt. See +[Known limitations](../troubleshooting/known-limitations.md#xunit-v3-records-only-the-last-retry-attempt). + +--- + +## The environment + +`EnvironmentInfo` describes the machine, once for each run. + +| Field | What it holds | +|---|---| +| `MachineName` | The machine name | +| `OperatingSystem` | The OS name and version | +| `RuntimeVersion`, `Framework` | The .NET runtime | +| `EnvironmentName` | The value of [Environment](configuration-reference.md#environment), or `Default` | +| `IsCIEnvironment` | `true` when the SDK detects a CI platform | +| `TimeZoneId`, `UtcOffset` | The machine's time zone and its UTC offset at the start of the run | +| `CustomProperties` | The properties below, and the CI properties in [CI metadata](#ci-metadata) | + +| Custom property | When it is set | +|---|---| +| `ExecutionContext` | Always: `CI` or `Local` | +| `IsDeveloperMachine` | `true` outside CI and outside a container | +| `IsContainer` | `true` when `/.dockerenv` exists, `KUBERNETES_SERVICE_HOST` is set, or on Linux `/proc/1/cgroup` names `docker` or `kubepods` | +| `IsInsideGitRepository` | Always: `true` or `false` | +| `Platform` | `Windows`, `Linux`, `macOS`, `Android` or `iOS` | +| `IsMobile`, `DeviceType` | On Android and iOS | +| `ProcessorArchitecture`, `ProcessorCount` | Always | +| `Git.Branch`, `Git.SHA` | Outside CI, from the local git repository | +| `IsDetachedHead`, `HasStagedChanges` | Outside CI, from the local git repository | +| `Git.Actor` | Outside CI, only with [CollectLocalGitAuthor](configuration-reference.md#collectlocalgitauthor) | + +--- + +## CI metadata + +### Detected CI platforms + +The SDK checks for each platform in this order and uses the first match. It sets `CIPlatform` to +the name in the first column. + +| `CIPlatform` | Detected by | PR context | +|---|---|---| +| `GitHubActions` | `GITHUB_ACTIONS=true` | Yes | +| `AzureDevOps` | `TF_BUILD` | Yes, for Azure Repos and GitHub repositories | +| `Jenkins` | `JENKINS_URL` | Yes, for multibranch (Branch Source) PR builds of GitHub, GitLab and Azure DevOps repositories | +| `GitLabCI` | `GITLAB_CI=true` | Yes, in merge request pipelines | +| `CircleCI` | `CIRCLECI=true` | No | +| `TravisCI` | `TRAVIS=true` | No | +| `TeamCity` | `TEAMCITY_VERSION` | No | +| `BitbucketPipelines` | `BITBUCKET_PIPELINE_UUID` | No | +| `AppVeyor` | `APPVEYOR=True` | No | +| `Generic` | `CI=true` or `CI=True` | No | + +CircleCI, Travis CI, TeamCity, Bitbucket Pipelines, AppVeyor and a generic CI upload without PR +context. They are not targeted for it. Most of them still send the PR flag (`CI.IsPullRequest`). + +### Properties for each platform + +| Property | GitHub Actions | Azure Pipelines | Jenkins | GitLab | CircleCI | Travis CI | TeamCity | Bitbucket | AppVeyor | +|---|---|---|---|---|---|---|---|---|---| +| `CI.CommitSha` | `GITHUB_SHA` (see [Which commit is recorded](#which-commit-is-recorded)) | `BUILD_SOURCEVERSION` | `GIT_COMMIT` | `CI_COMMIT_SHA` | `CIRCLE_SHA1` | `TRAVIS_COMMIT` | `BUILD_VCS_NUMBER` | `BITBUCKET_COMMIT` | `APPVEYOR_REPO_COMMIT` | +| `CI.IsPullRequest` | `GITHUB_EVENT_NAME`, `GITHUB_REF` | `BUILD_REASON` | `CHANGE_ID` or `ghprbPullId` | `CI_MERGE_REQUEST_IID` | `CIRCLE_PULL_REQUEST` | `TRAVIS_PULL_REQUEST` | Not sent | `BITBUCKET_PR_ID` | `APPVEYOR_PULL_REQUEST_NUMBER` | +| `CI.Branch` | `GITHUB_HEAD_REF`, else `GITHUB_REF_NAME`, else the branch in `GITHUB_REF` | `SYSTEM_PULLREQUEST_SOURCEBRANCH` on a PR, else `BUILD_SOURCEBRANCH` without `refs/heads/` | `CHANGE_BRANCH` or `ghprbSourceBranch` on a PR, else `BRANCH_NAME`, else `GIT_BRANCH` without `origin/` | `CI_COMMIT_BRANCH`, else `CI_COMMIT_REF_NAME` | `CIRCLE_BRANCH` | `TRAVIS_BRANCH` | — | `BITBUCKET_BRANCH` | `APPVEYOR_REPO_BRANCH` | +| `CI.DefaultBranch` | `repository.default_branch` from the event file | — | — | `CI_DEFAULT_BRANCH` | — | — | — | — | — | +| `CI.ServerUrl` | `GITHUB_SERVER_URL` | `SYSTEM_COLLECTIONURI` (Azure Repos) or `BUILD_REPOSITORY_URI` | — | `CI_SERVER_URL` | — | — | — | — | — | +| `CI.Repository` | `GITHUB_REPOSITORY` | `BUILD_REPOSITORY_NAME` | — | `CI_PROJECT_PATH` (as `CI.ProjectPath`) | `CIRCLE_PROJECT_REPONAME` (as `CI.ProjectName`) | `TRAVIS_REPO_SLUG` | `TEAMCITY_PROJECT_NAME` (as `CI.ProjectName`) | `BITBUCKET_REPO_FULL_NAME` | `APPVEYOR_REPO_NAME` | +| Build ids | `CI.RunId` (`GITHUB_RUN_ID`), `CI.RunNumber` (`GITHUB_RUN_NUMBER`) | `CI.BuildId` (`BUILD_BUILDID`), `CI.BuildNumber` (`BUILD_BUILDNUMBER`) | `CI.BuildNumber` (`BUILD_NUMBER`), `CI.JobName` (`JOB_NAME`), `CI.BuildUrl` (`BUILD_URL`) | `CI.JobId` (`CI_JOB_ID`), `CI.PipelineId` (`CI_PIPELINE_ID`) | `CI.BuildNumber` (`CIRCLE_BUILD_NUM`), `CI.WorkflowId` (`CIRCLE_WORKFLOW_ID`) | `CI.BuildNumber` (`TRAVIS_BUILD_NUMBER`), `CI.JobNumber` (`TRAVIS_JOB_NUMBER`) | `CI.BuildId` (`TEAMCITY_BUILD_ID`), `CI.Version` (`TEAMCITY_VERSION`) | `CI.BuildNumber` (`BITBUCKET_BUILD_NUMBER`) | `CI.BuildNumber` (`APPVEYOR_BUILD_NUMBER`), `CI.BuildVersion` (`APPVEYOR_BUILD_VERSION`) | +| Other | `CI.Ref` (`GITHUB_REF`), `CI.HeadBranch` (`GITHUB_HEAD_REF`), `CI.BaseBranch` (`GITHUB_BASE_REF`), `CI.Workflow` (`GITHUB_WORKFLOW`) | `CI.SourceBranch` (`BUILD_SOURCEBRANCH`) | `CI.GitBranch` (`GIT_BRANCH`) | `CI.CommitBranch` (`CI_COMMIT_BRANCH`), `CI.CommitAuthor` (`CI_COMMIT_AUTHOR`) | — | — | — | — | — | + +A generic CI (`CI=true` or `CI=True`) sends only `CIPlatform`, and `CI.DefaultBranch` when you set DefaultBranch. The actor properties are in +[Who is behind the run](#who-is-behind-the-run). + +[DefaultBranch](configuration-reference.md#defaultbranch) (`XPING_DEFAULTBRANCH`) replaces +`CI.DefaultBranch` on every platform. When it differs from what the platform reports, the SDK logs +a warning. + +### Which commit is recorded + +A pull request build can carry two commits, and the SDK records both: + +- **`CI.CommitSha`** is the commit the build checked out and tested. On a pull request build, it is + often a merge commit that the platform made for the run. +- **The PR context's commit** is the head commit the author pushed. It stays the same when the + build runs again, and it is the commit your code host shows on the PR. + +| Build | PR context commit | `CI.CommitSha` | +|---|---|---| +| GitHub `push`, `schedule`, `workflow_dispatch`, `merge_group`, `release`, `create`, `deployment`, `deployment_status` | — | `GITHUB_SHA` | +| GitHub `pull_request` | `pull_request.head.sha` | `GITHUB_SHA` (the merge commit) | +| GitHub `pull_request_target` | `pull_request.head.sha` | Not sent: `GITHUB_SHA` is the tip of the base branch | +| GitHub, any other event (`issue_comment`, `workflow_run`, `repository_dispatch`, …) | — | Not sent: `GITHUB_SHA` is the tip of the default branch, not what the workflow checked out | +| Azure Pipelines PR | `SYSTEM_PULLREQUEST_SOURCECOMMITID` | `BUILD_SOURCEVERSION` (the merge commit) | +| GitLab merged-results pipeline or merge train | `CI_MERGE_REQUEST_SOURCE_BRANCH_SHA` | `CI_COMMIT_SHA` (the merge result) | +| Jenkins Branch Source PR | `refs/remotes/origin/$BRANCH_NAME`, checked against `GIT_COMMIT` | `GIT_COMMIT` (the merge commit, with the merge strategy) | + +On GitHub Actions, the SDK sets `CI.IsPullRequest` to `true` for `pull_request`, +`pull_request_target` and any run on `refs/pull/*`. It sets it to `false` for the push-like events +in the first row. For any other event, it sends neither `CI.IsPullRequest` nor `CI.CommitSha`, +because a `/retest` comment or a `workflow_run` usually tests PR code. + +Xping Cloud files a run under the PR context's commit when there is one. It uses `CI.CommitSha` only +when `CI.IsPullRequest` is `false`. Xping Cloud does not file these runs under a commit, so it never +takes them for a run on your main branch: + +- A run without the flag (TeamCity, a generic CI, or the GitHub events above). It may be a pull + request build. +- A pull request build without PR context, such as a Jenkins GHPRB job. + +### Who is behind the run + +Xping Cloud counts a workspace's active committers from each uploaded CI run. It counts the PR +author when there is PR context, and `CI.Actor` otherwise. `CI.Actor` is the person the platform +names for the run. On most platforms, that is the person who started it. On Jenkins, it is the PR's +author. On AppVeyor, it is the author of the commit. + +| Platform | `CI.Actor` | `CI.ActorId` | `CI.ActorEmail` (only with `CollectCiActorEmail`) | +|---|---|---|---| +| GitHub Actions | `GITHUB_ACTOR` | `GITHUB_ACTOR_ID` | — | +| Azure Pipelines | `BUILD_REQUESTEDFOR` (a display name). Not sent on scheduled builds or for a service identity. | — | `BUILD_REQUESTEDFOREMAIL` | +| GitLab | `GITLAB_USER_LOGIN` | — | `GITLAB_USER_EMAIL` | +| Jenkins | `CHANGE_AUTHOR` (Branch Source PR builds), `ghprbPullAuthorLogin` (GHPRB PR builds). Not sent on push builds. | — | `CHANGE_AUTHOR_EMAIL`, `ghprbPullAuthorEmail` | +| CircleCI | `CIRCLE_USERNAME` | — | — | +| Bitbucket Pipelines | `BITBUCKET_STEP_TRIGGERER_UUID` (an account UUID) | — | — | +| AppVeyor | `APPVEYOR_REPO_COMMIT_AUTHOR` (the commit author's git name) | — | `APPVEYOR_REPO_COMMIT_AUTHOR_EMAIL` | +| TeamCity, Travis CI, generic CI | — | — | — | + +A run with neither a PR author nor `CI.Actor` adds no committer. Local runs never add one: they send +no `CI.Actor`, and Xping Cloud does not count `Git.Actor`. + +`CollectCiActorEmail` is off by default, because an email address is personal data. It does not +change how Xping Cloud counts committers: Xping Cloud counts by platform and login only. The email +lets Xping Cloud link a committer to a workspace member automatically on Azure Pipelines, GitLab, +Jenkins and AppVeyor. Without it, an Owner or Admin links them by hand. GitHub Actions links by the +actor id and login, so the switch does not affect it. + +### Pull request context + +On a PR build, the SDK records the pull request once for each run. Set +[EnablePullRequestDetection](configuration-reference.md#enablepullrequestdetection) to `false` to +turn it off. + +| Field | What it holds | +|---|---| +| `Platform` | `GitHub`, `GitLab` or `AzureDevOps`: the code host, not the CI | +| `ServerUrl` | The code host's server, such as `https://github.com` or `https://gitlab.example.com:8443` | +| `RepositoryOwner`, `RepositoryName` | The repository | +| `PullRequestNumber` | The PR or merge request number | +| `CommitSha` | The PR head commit. See [Which commit is recorded](#which-commit-is-recorded). | +| `BaseBranch`, `HeadBranch` | The target branch and the source branch | +| `Author` | `GITHUB_ACTOR` (GitHub Actions), `BUILD_REQUESTEDFOR` (Azure Pipelines), `GITLAB_USER_LOGIN` (GitLab) or `CHANGE_AUTHOR` (Jenkins) | + +GitHub Enterprise Server, GHE.com, self-managed GitLab and Azure DevOps Server get PR context in the +same way as the cloud services. [Set up CI](../getting-started/ci-cd-setup.md) lists what each +platform needs. + +--- + +## See also + +- [Configuration reference](configuration-reference.md) +- [Local store](local-store.md) +- [Set up CI](../getting-started/ci-cd-setup.md) diff --git a/sdk/configuration/configuration-reference.md b/sdk/configuration/configuration-reference.md new file mode 100644 index 0000000..43964ab --- /dev/null +++ b/sdk/configuration/configuration-reference.md @@ -0,0 +1,848 @@ +--- +uid: configuration-reference +title: Configuration reference +--- + +# Configuration reference + +> [!NOTE] +> This page describes the **Xping SDK for .NET, 1.0.0-rc series**. The SDK can upload to Xping Cloud, and these pages refer to the 1.0.0-rc `xping report` CLI. The Xping CLI 2.x is a different tool: it does not use Xping Cloud and has no `report` command. See the [Xping overview](../../index.md). + +This page lists every setting of the Xping SDK and the `xping` CLI, with its environment variable, +its default and its rules. It is for developers who configure the SDK in a test project or in CI. + +--- + +## Configuration methods + +How you initialize decides which sources the SDK reads. + +**`XpingContext.Initialize()`**, without an argument, reads these sources. The first one that sets +a value wins: + +1. `XPING_*` environment variables, for example `XPING_APIKEY` +2. `Xping__*` environment variables, the .NET nested format, for example `Xping__ApiKey` +3. The `"Xping"` section of `appsettings.{environment}.json` +4. The `"Xping"` section of `appsettings.json` +5. The defaults + +**`XpingContext.Initialize(configuration)`** reads these sources: + +1. `XPING_*` environment variables +2. The `XpingConfiguration` object you pass +3. The defaults + +On this path, the SDK reads only one setting from `appsettings.json` and `Xping__*`: +[StrictMode](#strictmode). It turns strict mode on when the object, `XPING_STRICTMODE`, +`Xping__StrictMode` or `"Xping": { "StrictMode": true }` in `appsettings.json` asks for it. +`XPING_STRICTMODE=false` turns it off whatever the other sources say. + +`XPING_*` variables win on both paths. A pipeline can change a value without a rebuild, even when +the code passes a configuration object. The SDK applies them to its own copy, so your object does +not change. + +Once a process has called `Initialize(configuration)`, a later `Initialize()` in the same process +reuses that configuration. This matters in a process that records several runs, such as an IDE's +test server. `XpingContext.ShutdownAsync()` forgets it. + +You cannot combine a configuration object with `appsettings.json`. To use the file, call +`Initialize()` and override values with `XPING_*` variables. + +### Files and environment variables + +- The SDK reads `appsettings.json` and `appsettings.{environment}.json` from the current directory + of the test process. With `dotnet test`, that is the test project's output folder, so set + `` on the files. +- `{environment}` is the value of `ASPNETCORE_ENVIRONMENT`, else `DOTNET_ENVIRONMENT`, else + `Production`. These variables only choose the file. They do not set the + [Environment](#environment) setting. +- Section and key names are not case-sensitive: `"Xping"`, `"xping"` and `"XPING"` are the same + section. +- Write a `TimeSpan` as whole seconds (`30`) or as `"hh:mm:ss"` (`"00:00:30"`), in JSON, in an + `Xping__*` variable and in an `XPING_*` variable alike. A value in another form, such as `"1.5"` or + `"30s"`, is ignored and the setting keeps its default. The SDK prints a warning that names it: + `[Xping 16:39:12 WRN] XPING_RETRYDELAY '1.5' is not a duration and was ignored. Use whole seconds (30) or a time with colons (00:00:30).` + From `appsettings.json` or an `Xping__*` variable, the warning names the setting as + `Xping:RetryDelay`. +- An `XPING_*` variable that is blank, or whose value does not parse, is ignored. So a missing + secret, such as `XPING_APIKEY: ${{ secrets.XPING_APIKEY }}`, does not clear a key set elsewhere. + +--- + +## Quick reference + +### SDK settings + +| Setting | Type | Default | Environment variable | Description | +|---|---|---|---|---| +| [`ApiEndpoint`](#apiendpoint) | string | `https://upload.xping.io/v1` | `XPING_APIENDPOINT` | The upload address of Xping Cloud | +| [`ApiKey`](#apikey) | string | *(none)* | `XPING_APIKEY` | The key that authorizes uploads. Without it, the SDK runs local-only. | +| [`ProjectId`](#projectid) | string | *(none)* | `XPING_PROJECTID` | Sends every test assembly to one project | +| [`Mode`](#mode) | `XpingMode` | `Auto` | `XPING_MODE` | `Auto`, `LocalOnly`, `Cloud` or `Disabled` | +| [`BatchSize`](#batchsize) | int | `100` | `XPING_BATCHSIZE` | Cloud mode only. Executions in each upload during the run. | +| [`FlushInterval`](#flushinterval) | TimeSpan | `00:00:30` | `XPING_FLUSHINTERVAL` | Cloud mode only. Time between uploads during the run. | +| [`UploadTimeout`](#uploadtimeout) | TimeSpan | `00:00:30` | `XPING_UPLOADTIMEOUT` | Time limit of one upload attempt | +| [`MaxRetries`](#maxretries) | int | `3` | `XPING_MAXRETRIES` | Retries of a failed upload | +| [`RetryDelay`](#retrydelay) | TimeSpan | `00:00:02` | `XPING_RETRYDELAY` | Base delay between retries | +| [`EnableCompression`](#enablecompression) | bool | `true` | `XPING_ENABLECOMPRESSION` | Compresses uploads with gzip | +| [`Environment`](#environment) | string | `Default` | `XPING_ENVIRONMENT` | The deployed environment the tests target | +| [`DefaultBranch`](#defaultbranch) | string | *(none)* | `XPING_DEFAULTBRANCH` | The branch Xping Cloud treats as the default branch | +| [`Enabled`](#enabled) | bool | `true` | `XPING_ENABLED` | Turns the SDK on or off | +| [`UploadStackTraces`](#uploadstacktraces) | bool | `false` | `XPING_UPLOADSTACKTRACES` | Uploads the stack trace text of failed tests | +| [`EnablePullRequestDetection`](#enablepullrequestdetection) | bool | `true` | `XPING_ENABLEPULLREQUESTDETECTION` | Records the pull request a CI build belongs to | +| [`CollectLocalGitAuthor`](#collectlocalgitauthor) | bool | `false` | `XPING_COLLECTLOCALGITAUTHOR` | Records the git author name on local runs | +| [`CollectCiActorEmail`](#collectciactoremail) | bool | `false` | `XPING_COLLECTCIACTOREMAIL` | Records the email of the person behind a CI run | +| [`LogLevel`](#loglevel) | `LogLevel` | `Information` | `XPING_LOGLEVEL` | The lowest level of SDK message that is printed | +| [`StrictMode`](#strictmode) | bool | `false` | `XPING_STRICTMODE` | Fails the test run when the SDK cannot record or upload | +| [`LocalStorePath`](#localstorepath) | string | *(none)* | `XPING_LOCAL_STORE` | Moves the [local store](local-store.md) | + +### CLI and shared settings + +> [!NOTE] +> This describes the 1.0.0-rc `xping` CLI. The Xping CLI 2.x is a different tool and has no `report`, `where`, `clear` or `login` commands. + +| Setting | Read by | Default | Description | +|---|---|---|---| +| [`CloudUrl`](#cloudurl) / `XPING_CLOUDURL` | CLI | `https://app.xping.io` | The Xping Cloud address for `xping login` and for Xping Cloud data in `xping report` | +| `XPING_APIKEY`, `XPING_PROJECTID` | SDK and CLI | *(none)* | The CLI reads them for Xping Cloud data. See Credentials. | +| [`XPING_LOCAL_STORE`](#localstorepath) | SDK and CLI | *(none)* | Moves the local store for both | +| [`XPING_SHELL`](#xping_shell) | CLI | `powershell` on Windows, `posix` elsewhere | The shell syntax of the commands `xping report` prints | +| `XPING_NO_BANNER` | SDK and CLI | *(unset)* | Any non-empty value hides the SDK's retry hint and the CLI's Xping Cloud invitation | + +--- + +## Mode + +### Mode + +**Type:** `XpingMode` +**Default:** `Auto` +**Environment variable:** `XPING_MODE` (not case-sensitive) + +The **mode** says what the SDK does with the runs it records. The SDK resolves it once, when it +starts. It decides whether the SDK uploads, writes the +local store, or does nothing. + +| Value | What the SDK does | +|---|---| +| `Auto` | Resolves to one of the modes below. See the next table. | +| `LocalOnly` | Writes the [local store](local-store.md). It makes no network calls and creates no HTTP client. | +| `Cloud` | Writes the local store and uploads to Xping Cloud | +| `Disabled` | Records nothing. The same as `Enabled = false`. | + +`Auto` resolves in this order. The first row that matches wins: + +| Condition | Resolved mode | +|---|---| +| `Enabled` is `false` | `Disabled` | +| `StrictMode` is `true` | `Cloud` | +| `ApiKey` is set | `Cloud` | +| Otherwise | `LocalOnly` | + +A `Mode` other than `Auto` wins over `StrictMode` and over the key. To keep a run local while a key +is set in your environment, set `XPING_MODE=LocalOnly`. + +**A missing key is not an error in `Auto` mode.** The SDK runs local-only, as on a developer +machine without an account. See [Run without an account](../getting-started/local-first.md). + +**A missing key is an error in two cases:** + +- `Mode` is `Cloud`. The SDK logs the error and records nothing, not even to the local store. +- `StrictMode` is on and `Mode` is `Auto`. The test run fails. Strict mode does not fall back to + local-only, so a pipeline that must upload fails when its key is missing. + +--- + +## Upload settings + +### ApiEndpoint + +> [!NOTE] +> Xping Cloud only. The Xping CLI 2.x does not use Xping Cloud. + +**Type:** `string` +**Default:** `https://upload.xping.io/v1` +**Environment variable:** `XPING_APIENDPOINT` + +The address the SDK uploads to. Change it only when you were given another Xping Cloud address. It +must be an absolute `http` or `https` URL. + +```bash +export XPING_APIENDPOINT="https://upload.xping.io/v1" +``` + +### ApiKey + +> [!NOTE] +> Xping Cloud only. The Xping CLI 2.x does not use Xping Cloud. + +**Type:** `string` +**Default:** *(none)* +**Environment variable:** `XPING_APIKEY` + +The key that authorizes uploads to Xping Cloud. Without a key, the SDK runs [local-only](#mode). + +To create one, open **Settings → API keys** in Xping Cloud. Create it with only the Upload scope. See API keys. + +Set the key as an environment variable or a CI secret: + +```bash +export XPING_APIKEY="your-api-key" +``` + +Do not put it in `appsettings.json` or in code: the file is committed and copied into the build +output. + +**In the `xping` CLI:** the CLI uses the key to read Xping Cloud data when you have not signed in +with `xping login`. `--api-key` wins over a sign-in. `XPING_APIKEY` and `appsettings.json` do not, +because on a developer machine they usually hold the upload key. A key with only the Upload scope +cannot read. See Credentials. + +### ProjectId + +> [!NOTE] +> Xping Cloud only. The Xping CLI 2.x does not use Xping Cloud. + +**Type:** `string` +**Default:** *(none: one project for each test assembly)* +**Environment variable:** `XPING_PROJECTID` + +You usually do not set this. Without it, Xping Cloud creates one project for each test assembly, on +its first upload: + +| Test assembly | Project | +|---|---| +| `Billing.Tests` | `billing-tests` | +| `Api.Tests` | `api-tests` | + +Set `ProjectId` to send every test assembly of the run to one project, for example in a +monorepo where several test assemblies test one product: + +```bash +export XPING_PROJECTID="payment-service" +``` + +Xping Cloud applies these rules to the value: + +- Only ASCII letters, digits, `-` and `_`. It starts with a letter or a digit. +- At most 128 characters. No spaces. +- It is converted to lowercase, so `My-App` and `my-app` are one project. +- A blank value counts as unset. + +Xping Cloud identifies a project by its name. Renaming a test assembly, or changing `ProjectId`, +starts a new project, and the old history stays in the old one. On a plan with a low project +limit, a solution-wide run can reach the limit on its first upload. Set `ProjectId` to use one +project instead. + +**In the `xping` CLI:** the CLI uses the same value to find the Xping Cloud project of a local run. + +### BatchSize + +**Type:** `int` +**Default:** `100` +**Valid range:** `1` to `1000` +**Environment variable:** `XPING_BATCHSIZE` + +**Cloud mode only.** In Cloud mode, the SDK uploads during the run as well as at its end: + +1. When `BatchSize` executions are waiting +2. When the [FlushInterval](#flushinterval) timer fires +3. When the run ends: the rest, in the final upload + +A smaller batch shows results in Xping Cloud sooner and makes more uploads. A larger batch makes +fewer uploads. In every mode, the SDK keeps every execution in memory until the run ends, +because it writes the whole run to the local store. + +```bash +export XPING_BATCHSIZE="200" +``` + +### FlushInterval + +**Type:** `TimeSpan` +**Default:** `00:00:30` +**Valid range:** greater than zero +**Environment variable:** `XPING_FLUSHINTERVAL` (whole seconds or `hh:mm:ss`) + +**Cloud mode only.** The time between uploads during the run. The upload at the end of the +run does not wait for it. In `LocalOnly` mode, the SDK starts no timer. + +```bash +export XPING_FLUSHINTERVAL="60" +``` + +### UploadTimeout + +**Type:** `TimeSpan` +**Default:** `00:00:30` +**Valid range:** 1 second to 1 day +**Environment variable:** `XPING_UPLOADTIMEOUT` (whole seconds or `hh:mm:ss`) + +The time limit of one upload attempt. An attempt that takes longer is retried, as +[MaxRetries](#maxretries) allows. The whole upload, retries and delays included, stops after +`2 × UploadTimeout` (60 seconds by default), so a failing upload cannot hold up the end of a test +run. + +```bash +export XPING_UPLOADTIMEOUT="60" +``` + +### MaxRetries + +**Type:** `int` +**Default:** `3` +**Valid range:** `0` to `10` +**Environment variable:** `XPING_MAXRETRIES` + +How many times the SDK retries a failed upload. `0` turns off retries. + +The SDK retries: + +- HTTP 5xx responses and HTTP 429 +- Network errors and timeouts + +It does not retry any other 4xx response, such as 400, 401 or 403. + +When at least half of the upload attempts in 30 seconds fail with a 5xx response, a network error +or a timeout, and there were at least 10 attempts, the SDK stops uploading for 30 seconds. Retries +count as attempts. It logs +`Circuit breaker is open: Too many consecutive failures`. + +```bash +export XPING_MAXRETRIES="5" +``` + +### RetryDelay + +**Type:** `TimeSpan` +**Default:** `00:00:02` +**Valid range:** 0 to 1 day +**Environment variable:** `XPING_RETRYDELAY` (whole seconds or `hh:mm:ss`) + +The base delay between retries. The delay doubles with each retry, and the SDK adds a random part, +so that parallel runs do not retry at the same moment. With the defaults, the retries come after +about 2, 4 and 8 seconds. The `2 × UploadTimeout` limit still applies, so a long delay can leave +fewer retries than `MaxRetries`. + +```bash +export XPING_RETRYDELAY="5" +``` + +### EnableCompression + +**Type:** `bool` +**Default:** `true` +**Environment variable:** `XPING_ENABLECOMPRESSION` + +Compresses each upload with gzip. Turn it off only to read the uploaded requests while you debug a +network problem, or when a proxy rejects compressed requests. + +```bash +export XPING_ENABLECOMPRESSION="false" +``` + +--- + +## Environment and branches + +### Environment + +**Type:** `string` +**Default:** `Default` +**Environment variable:** `XPING_ENVIRONMENT` + +The **deployed environment your tests target**, such as `Staging` or `Production`. Xping Cloud +scores each test separately for each environment. + +It is not a name for where the tests ran. A developer's run and the CI run of the same suite +against the same deployment belong to one environment. The SDK records whether a run is on CI, and +which branch and commit it tested, in other fields. See +[Data Xping collects](collected-data.md#the-environment). + +- Set it only when a pipeline tests a different deployment. +- Use a few stable names. Do not use a name that changes from run to run, such as one for each pull + request, branch or build agent: each new name splits the history of every test. +- When you test one deployment, leave it unset. + +```bash +export XPING_ENVIRONMENT="Staging" +``` + +**The SDK does not read `ASPNETCORE_ENVIRONMENT` or `DOTNET_ENVIRONMENT` for this setting.** These +variables tell the application how to configure itself, and a container image often sets them. To +use one, pass it in the shell of the test step: + +```yaml +- name: Run tests + shell: bash + run: XPING_ENVIRONMENT="$ASPNETCORE_ENVIRONMENT" dotnet test +``` + +On GitHub Actions, `${{ env.ASPNETCORE_ENVIRONMENT }}` does not work for this. The `env` context +holds only the variables that the workflow declares, not the ones the runner image or a container +sets. + +### DefaultBranch + +**Type:** `string` +**Default:** *(none)* +**Environment variable:** `XPING_DEFAULTBRANCH` + +The branch Xping Cloud treats as the repository's default branch for this pipeline's runs. Xping +Cloud counts a CI push to the default branch as a Canonical run, the strongest evidence behind a +confidence score. + +The default branch of a run comes from the first of these that has a value: + +1. `DefaultBranch` / `XPING_DEFAULTBRANCH` +2. The value the CI platform reports. Only GitHub Actions and GitLab CI/CD report one. +3. The project's default branch setting in Xping Cloud +4. `main` or `master` + +- The SDK sends it only from CI. +- The SDK removes a leading `refs/heads/`, `refs/remotes/origin/` or `origin/`, so you can pass + Jenkins' `GIT_BRANCH` (`origin/main`) as it is. Branch names are case-sensitive. +- On TeamCity it has no effect, because the SDK reports no branch there. +- It applies to new runs only. + +**Use it with care.** It replaces the value GitHub Actions and GitLab CI/CD report, and it wins +over the project's setting in Xping Cloud. A stale value, for example in a shared pipeline +template, stops every Canonical run. When the value differs from what the platform reports, the SDK +logs a warning that names both. + +```bash +export XPING_DEFAULTBRANCH="develop" +``` + +--- + +## What the SDK records + +[Data Xping collects](collected-data.md) lists every field, and which of these switches controls +it. + +### Enabled + +**Type:** `bool` +**Default:** `true` +**Environment variable:** `XPING_ENABLED` + +Turns the SDK off without removing it from the test project. With `false`, the tests run as usual. +The SDK records nothing and prints +`SDK is disabled via configuration (Enabled=false). Tests will run without observability tracking.` +With `Mode = Disabled`, the line says `(Mode=Disabled)` instead. + +```bash +export XPING_ENABLED="false" +``` + +### UploadStackTraces + +**Type:** `bool` +**Default:** `false` +**Environment variable:** `XPING_UPLOADSTACKTRACES` + +Uploads the stack trace text of failed tests to Xping Cloud. It is off by default, because a stack +trace can contain source paths, file names and details of your code. + +- The local store always keeps the full stack trace. `xping report` needs it to group failures. +- The upload always carries a hash of the stack trace. The hash covers the method names of up to + five of your own frames, without file paths or line numbers. Xping Cloud groups failures by it. +- With `false`, a failed test with a trace is uploaded with `stackTraceOmitted: true` and no trace + text. +- With `true`, the SDK uploads the trace text too. The Xping Cloud features that read it, such as + the failure frames in pull request comments and AI failure summaries, need it. + +```bash +export XPING_UPLOADSTACKTRACES="true" +``` + +### EnablePullRequestDetection + +**Type:** `bool` +**Default:** `true` +**Environment variable:** `XPING_ENABLEPULLREQUESTDETECTION` + +Records the pull request a CI build belongs to: its number, branches, head commit and author. Xping +Cloud uses it to file the run under the PR and to post the +pull request comment. Turn it off to send no PR context. + +The SDK detects PR context on: + +- GitHub Actions, on github.com, GHE.com and GitHub Enterprise Server +- GitLab CI/CD merge request pipelines, on gitlab.com and self-managed instances +- Azure Pipelines PR builds, for Azure Repos and GitHub repositories +- Jenkins multibranch PR builds, for GitHub, GitLab and Azure DevOps repositories + +[Which commit is recorded](collected-data.md#which-commit-is-recorded) lists the variables each +platform reads. [Set up CI](../getting-started/ci-cd-setup.md#jenkins) says what Jenkins needs. + +```bash +export XPING_ENABLEPULLREQUESTDETECTION="false" +``` + +### CollectLocalGitAuthor + +**Type:** `bool` +**Default:** `false` +**Environment variable:** `XPING_COLLECTLOCALGITAUTHOR` + +On a run outside CI, inside a git repository, records the git author name as the `Git.Actor` +property. The SDK reads `[user] name` from the repository's `.git/config`, or else from your global +git config (`~/.gitconfig`, then `$XDG_CONFIG_HOME/git/config`). + +It is off by default, because the git author name is usually a person's full name. Turn it on only +when your team agrees to share it. + +It has no effect on CI, where the person behind the run comes from the CI platform, or outside a +git repository. + +```bash +export XPING_COLLECTLOCALGITAUTHOR="true" +``` + +### CollectCiActorEmail + +**Type:** `bool` +**Default:** `false` +**Environment variable:** `XPING_COLLECTCIACTOREMAIL` + +On a CI run, records the email address that the platform gives for the person behind the run, as +the `CI.ActorEmail` property. The SDK reads it from `BUILD_REQUESTEDFOREMAIL` (Azure Pipelines), +`GITLAB_USER_EMAIL` (GitLab), `CHANGE_AUTHOR_EMAIL` or `ghprbPullAuthorEmail` (Jenkins) and +`APPVEYOR_REPO_COMMIT_AUTHOR_EMAIL` (AppVeyor). + +It is off by default, because an email address is personal data. Xping Cloud does not count +committers by it. It uses it only to link a committer to a workspace member automatically on Azure +Pipelines, GitLab, Jenkins and AppVeyor. Without it, an Owner or Admin links them by hand. GitHub +Actions is not affected. See [Who is behind the run](collected-data.md#who-is-behind-the-run). + +It has no effect on local runs, or on `CI.Actor` and `CI.ActorId`, which the SDK sends either way. + +```bash +export XPING_COLLECTCIACTOREMAIL="true" +``` + +--- + +## Logging and errors + +### LogLevel + +**Type:** `Microsoft.Extensions.Logging.LogLevel` +**Default:** `Information` +**Environment variable:** `XPING_LOGLEVEL` (not case-sensitive) + +The lowest level of SDK message that is printed: `Trace`, `Debug`, `Information`, `Warning`, +`Error`, `Critical` or `None`. The SDK prints messages below `Warning` to stdout, and `Warning` and +higher to stderr. + +Set it to `Debug` when the SDK is quieter than you expect. Debug messages explain failures that the +SDK absorbs so that it never breaks your test run, such as a local store that it could not write. +`None` silences the SDK. + +```bash +export XPING_LOGLEVEL="Debug" +``` + +```csharp +using Microsoft.Extensions.Logging; +using Xping.Sdk.Core.Configuration; +using Xping.Sdk.NUnit; // your adapter's namespace + +XpingContext.Initialize(new XpingConfiguration { LogLevel = LogLevel.Debug }); +``` + +### StrictMode + +**Type:** `bool` +**Default:** `false` +**Environment variable:** `XPING_STRICTMODE` + +By default, the SDK never fails your test run. When it cannot start or cannot upload, it logs the +error and the tests run as usual. In strict mode, the same errors fail the test run, so a CI +pipeline fails when it cannot record its tests. + +| What goes wrong | Default | Strict mode | +|---|---|---| +| No API key, `Mode` is `Auto` | The SDK runs local-only | The test run fails before any test runs | +| No API key, `Mode` is `Cloud` | The SDK logs the error and records nothing | The test run fails before any test runs | +| An invalid setting, such as `BatchSize = 2000` | The SDK logs the error and records nothing. See [What the SDK prints](#what-the-sdk-prints). | The test run fails before any test runs | +| The SDK fails to start, for example because `appsettings.json` does not parse | The SDK prints `[Xping] SDK initialization failed`, and the tests run unrecorded | The test run fails before any test runs | +| An upload fails | The SDK logs the error. The local store still gets the run. | The test run fails at its end | + +When the SDK cannot start in strict mode, the test process stops (`Environment.FailFast`) before +any test runs. Strict mode must then come from `XPING_STRICTMODE`, `Xping__StrictMode` or code, +because the SDK cannot read it from a file that does not parse. + +When an upload fails in strict mode, each adapter fails the run in its own way. Every test that ran +stays in the TRX file and the other reports, and `dotnet test` exits with a non-zero code. + +| Adapter and runner | What you see | +|---|---| +| xUnit v2 | An error from the runner: `Catastrophic failure: XpingNetworkException` | +| xUnit v3 on vstest | An error from the runner, which fails the run | +| xUnit v3 on Microsoft.Testing.Platform | The runner reports the error, and the test executable exits with code 1 after it writes its reports | +| MSTest | `[AssemblyCleanup]` fails, and MSTest reports it on the last test result | +| NUnit on vstest | The test process stops about two seconds after the upload fails, once every result has reached `dotnet test`. `dotnet test` reports the run as aborted. | +| NUnit on Microsoft.Testing.Platform | The test executable exits with code 1 after it writes its reports | + +On NUnit and MSTest, the upload error appears when the run ends, so the `[OneTimeTearDown]` or +`[AssemblyCleanup]` method must call `XpingContext.FinalizeAndShutdownAsync()`. On NUnit, that call +is what fails the run: NUnit reports an exception from `[OneTimeTearDown]` only as a warning. + +```bash +XPING_STRICTMODE=true dotnet test +``` + +### What the SDK prints + +These lines come from an NUnit project on vstest, with +`dotnet test --logger "console;verbosity=normal"`: + +``` +# Default: a configuration error, here XPING_MODE=Cloud without a key +[Xping 10:43:01 ERR] Configuration validation failed: ApiKey is required in Cloud mode. SDK disabled - tests will run without observability tracking. + +# Strict mode: a configuration error +[Xping] Strict mode configuration error: Xping configuration invalid: ApiKey is required when StrictMode is enabled. + +# Default: an upload error +[Xping 10:00:08 ERR] Network error occurred → HttpRequestException: Connection refused (127.0.0.1:9) + +# Strict mode: an upload error +[Xping] Xping network error in strict mode: HTTP request failed: Connection refused (127.0.0.1:9) +``` + +An invalid value in the configuration object you pass to `Initialize(configuration)` gives another +line, because the SDK rejects the object before it starts: + +``` +[Xping] SDK initialization failed: Xping configuration invalid: BatchSize cannot exceed 1000. Tests run without Xping tracking. +``` + +An invalid value from an `XPING_*` variable or from `appsettings.json` gives the +`Configuration validation failed:` line above. + +When the SDK fails to start for any other reason, and strict mode is off, it prints this line once +and the tests run unrecorded: + +``` +[Xping] SDK initialization failed: . Tests run without Xping tracking. +``` + +Where that line appears depends on the runner: + +| Runner | Where to look | +|---|---| +| NUnit | The `dotnet test` output, at the default verbosity | +| xUnit (v2 and v3) | `dotnet test -v n`, or the runner's diagnostics with `"diagnosticMessages": true` in `xunit.runner.json` | +| MSTest | The output of the first test that ran, in the TRX file (`dotnet test --logger trx`) | + +The next run in the same process tries again, so an IDE's test server recovers once you fix the +cause. + +### Validation rules + +The SDK checks the configuration when it starts. It reports every rule that fails, in one line: + +| Setting | Rule | Message | +|---|---|---| +| `Mode` | A defined value | `Mode has an undefined value (N). Valid values are Auto, LocalOnly, Cloud, and Disabled.` | +| `LogLevel` | A defined value | `LogLevel has an undefined value (N). Valid values are Trace, Debug, Information, Warning, Error, Critical, and None.` | +| `ApiKey` | Set, when the mode resolves to `Cloud` | `ApiKey is required in Cloud mode.` With `StrictMode` on and `Mode` set to `Auto`: `ApiKey is required when StrictMode is enabled.` | +| `ApiEndpoint` | Set, and an absolute `http` or `https` URL | `ApiEndpoint is required.` / `ApiEndpoint must be a valid HTTP or HTTPS URL.` | +| `BatchSize` | 1 to 1000 | `BatchSize must be greater than zero.` / `BatchSize cannot exceed 1000.` | +| `FlushInterval` | Greater than zero | `FlushInterval must be greater than zero.` | +| `MaxRetries` | 0 to 10 | `MaxRetries cannot be negative.` / `MaxRetries cannot exceed 10.` | +| `RetryDelay` | 0 to 1 day | `RetryDelay cannot be negative.` / `RetryDelay cannot exceed 1 day.` | +| `UploadTimeout` | 1 second to 1 day | `UploadTimeout must be at least 1 second.` / `UploadTimeout cannot exceed 1 day.` | + +To check a configuration in code, use `XpingConfigurationBuilder.TryBuild`: + +```csharp +using System; +using Xping.Sdk.Core.Configuration; +using Xping.Sdk.NUnit; // your adapter's namespace + +var builder = new XpingConfigurationBuilder() + .WithMode(XpingMode.Cloud) + .WithBatchSize(2000); + +if (builder.TryBuild(out XpingConfiguration? configuration, out string[] errors)) +{ + XpingContext.Initialize(configuration!); +} +else +{ + foreach (string error in errors) + Console.WriteLine(error); +} + +// Prints: +// ApiKey is required in Cloud mode. +// BatchSize cannot exceed 1000. +``` + +`TryBuild` and `Build` check only the values you set on the builder. They do not read `XPING_*` +variables, which the SDK applies later. So `Build` fails for a builder that sets +`WithStrictMode(true)` and relies on `XPING_APIKEY` for the key. + +--- + +## Local store and CLI + +### LocalStorePath + +**Type:** `string` +**Default:** *(none: `.xping/` at the repository root)* +**Environment variable:** `XPING_LOCAL_STORE` + +Moves the [local store](local-store.md). Leave it unset to use `.xping/` at the repository root, +where `xping report` looks. Set it when the repository is not writable, or when the history must +live outside a workspace that is deleted between builds. + +```bash +export XPING_LOCAL_STORE="/var/tmp/xping-store" +``` + +- The SDK reads `XPING_LOCAL_STORE` once, when it starts. A change during the run does not move + where the run is recorded. +- The CLI reads the same variable, so an exported `XPING_LOCAL_STORE` moves both. +- An absolute path is used as it is. A relative path, such as `.xping-ci`, is read from the + repository root: the nearest folder above the test assembly that holds `.git`, a `*.sln` file or + a `*.slnx` file. Without a repository root, it is read from the nearest folder that holds a + `.csproj`, `.fsproj` or `.vbproj` file, and without one of those, from the current directory. So + the SDK and the CLI find the same folder when the CLI runs anywhere inside the repository. +- On Windows, a path is absolute only with a drive and a separator (`C:\xping-store`) or as a UNC + path. `\xping-store` and `C:xping-store` are relative, and are read as above. +- When the SDK cannot write to the folder, the run has no local history: the SDK does not fall + back to another folder. +- A path set in code or in `appsettings.json` moves only the SDK. Export the variable for the CLI + too. The CLI's `--directory` option changes where the CLI starts looking for the repository, and + so the folder a relative path is read from. + +### CloudUrl + +> [!NOTE] +> Xping Cloud only. The Xping CLI 2.x does not use Xping Cloud. + +**Type:** `string` +**Default:** `https://app.xping.io` +**Environment variable:** `XPING_CLOUDURL` + +CLI only. The Xping Cloud address that `xping login` signs in to, and that `xping report` reads +Xping Cloud data from. Leave it unset unless you were given another address. + +The first of these that has a value wins: the `--cloud-url` option, `XPING_CLOUDURL`, +`Xping__CloudUrl`, then `Xping:CloudUrl` in `appsettings.{environment}.json` and `appsettings.json`. +The CLI reads the files from the current directory, or from the folder that `--directory` names. + +The value must be an absolute `https` URL without a path, query or fragment. `http` is accepted +only for `localhost` and `127.0.0.1`. Case, a default port and a trailing slash are ignored. + +```bash +export XPING_CLOUDURL="https://app.xping.io" +``` + +### XPING_SHELL + +> [!NOTE] +> This describes the 1.0.0-rc `xping` CLI. The Xping CLI 2.x is a different tool and has no `report`, `where`, `clear` or `login` commands. + +CLI only. The shell syntax of the commands that `xping report` prints, such as the command that +runs a test again: `posix` or `powershell`. Without it, the CLI uses PowerShell syntax on Windows +and POSIX syntax elsewhere. Set it when your shell differs, for example Git Bash on Windows. For +any other value, the CLI prints a warning and uses the default. See +[Known limitations](../troubleshooting/known-limitations.md). + +```bash +export XPING_SHELL="posix" +``` + +--- + +## Examples + +### appsettings.json + +The SDK reads this file only with `XpingContext.Initialize()`, without an argument. Keep the API key +out of it. + +```json +{ + "Xping": { + "ProjectId": "my-application", + "Environment": "Staging", + "BatchSize": 200, + "FlushInterval": "00:01:00", + "UploadStackTraces": false, + "LogLevel": "Information" + } +} +``` + +### CI variables (GitHub Actions) + +```yaml +env: + XPING_APIKEY: ${{ secrets.XPING_APIKEY }} + XPING_PROJECTID: "my-application" + XPING_STRICTMODE: "true" +``` + +[Set up CI](../getting-started/ci-cd-setup.md) has a full pipeline for each CI platform. + +### In code + +```csharp +using System; +using Xping.Sdk.Core.Configuration; +using Xping.Sdk.NUnit; // your adapter's namespace + +// XPING_APIKEY still applies on top of this object. +XpingContext.Initialize(new XpingConfiguration +{ + ProjectId = "my-application", + BatchSize = 200, + FlushInterval = TimeSpan.FromMinutes(1), +}); +``` + +`XpingContext` is in your adapter's namespace: `Xping.Sdk.NUnit`, `Xping.Sdk.XUnit`, +`Xping.Sdk.XUnit.V3` or `Xping.Sdk.MSTest`. Each [quick start](../getting-started/quickstart-nunit.md) +shows where to call it. + +--- + +## Troubleshooting + +**The SDK ignores `appsettings.json`:** + +- Check that the SDK starts with `XpingContext.Initialize()`, without an argument. With a + configuration object, it reads only `StrictMode` from the file. +- Check that the file is in the test project's output folder (``). +- Check that the JSON parses. A file that does not parse stops the SDK from starting, and the SDK + prints `[Xping] SDK initialization failed`. + +**An environment variable has no effect:** + +- Check the name: `XPING_` with one underscore, then the setting name in capitals, such as + `XPING_BATCHSIZE`. The local store variable is `XPING_LOCAL_STORE`. +- Check the value. A value that does not parse, such as `XPING_ENABLED=yes`, is ignored. Use `true` + or `false`. + A duration that does not parse is ignored too, and the SDK prints a warning that names it. +- Check that the test process gets it. An IDE reads the environment when it starts. + +**The SDK disabled itself:** the line after `Configuration validation failed:`, or after +`Xping configuration invalid:` for a configuration object, names each setting that broke a rule. +See [Validation rules](#validation-rules). + +--- + +## See also + +- [Data Xping collects](collected-data.md) +- [Local store](local-store.md) +- [Set up CI](../getting-started/ci-cd-setup.md) +- [Common issues](../troubleshooting/common-issues.md) diff --git a/sdk/configuration/local-store.md b/sdk/configuration/local-store.md new file mode 100644 index 0000000..17d4049 --- /dev/null +++ b/sdk/configuration/local-store.md @@ -0,0 +1,198 @@ +--- +uid: configuration-local-store +title: Local store +--- + +# Local store + +> [!NOTE] +> This page describes the **Xping SDK for .NET, 1.0.0-rc series**. The SDK can upload to Xping Cloud, and these pages refer to the 1.0.0-rc `xping report` CLI. The Xping CLI 2.x is a different tool: it does not use Xping Cloud and has no `report` command. See the [Xping overview](../../index.md). + +This page says where the Xping SDK keeps the test history on your machine, what it keeps, and how +long. It is for developers who use the `xping` CLI, and for anyone who reviews what stays on disk. + +The **local store** is the folder where the SDK writes each run and where the CLI reads it. The SDK +writes every run to the local store, in `LocalOnly` and in `Cloud` mode. The +CLI reads it, so `xping report` works with or without an account. +In `Disabled` mode, the SDK writes nothing. + +--- + +## Location + +The SDK uses the first of these locations: + +1. The path in the `XPING_LOCAL_STORE` environment variable, or in the + [LocalStorePath](configuration-reference.md#localstorepath) setting. The SDK does not check that + it can write there. A relative path is read from the repository root, else from the test + project's folder. +2. A `.xping` folder at the **repository root**: the nearest folder above the test assembly that + holds `.git`, a `*.sln` file or a `*.slnx` file. +3. A folder under your user profile, `Xping/stores/`, when there is no repository root or the + SDK cannot write to it. The profile folder is `%LOCALAPPDATA%` on Windows, + `~/Library/Application Support` on macOS, and `$XDG_DATA_HOME` or else `~/.local/share` on Linux. + +The `` of the profile folder comes from the repository root when there is one. Otherwise it +comes from the nearest folder above that holds a `.csproj`, `.fsproj` or `.vbproj` file. So +`xping report` and `xping where` find the folder the tests wrote to when you run them inside the +repository or, without one, in the test project's folder. + +To see where the store is: + +```bash +xping where +``` + +The SDK starts its search at the test assembly, not at the current directory, because the current +directory of `dotnet test` differs between the CLI, IDEs and CI agents. + +--- + +## Layout + +``` +/.xping/ +├── .gitignore +├── sessions/ +│ ├── session-0639309348082804300-00b189fd-47e6952c.json.gz +│ └── … +└── state.json +``` + +- Each run is one gzipped JSON file in `sessions/`. The name holds the start time, the first 8 + characters of the `SessionId`, and a short hash of each test assembly the run covers (up to + 8). +- Test projects that run at the same time write separate files, so they never wait for a lock. +- The SDK writes each file under a `.tmp` name first and renames it when it is complete. A killed + test run can leave a `session-*.json.gz.tmp` file. The SDK deletes such a file once it is ten + minutes old, and it counts toward the size limit until then. +- `state.json` is the CLI's own state, such as when it last showed the Xping Cloud invitation. + +--- + +## Git + +The store keeps itself out of git. `.xping/.gitignore` holds a comment line and `*`, so git ignores +the whole folder. The SDK does not change your repository's own `.gitignore`. You do not need to +add `.xping/` to it, but an entry there does no harm. + +--- + +## What is stored + +The store keeps the **full run**: every field on +[Data Xping collects](collected-data.md), for every execution. That includes: + +- the error message and the full stack trace of each failure, whatever + [UploadStackTraces](configuration-reference.md#uploadstacktraces) says. That setting decides + only what the SDK uploads. `xping report` reads the stack traces to group failures. +- the machine name, the source file paths and the CI metadata, including `CI.ActorEmail` when + [CollectCiActorEmail](configuration-reference.md#collectciactoremail) is on. + +These switches limit what the SDK records, and so what the store keeps: + +| Switch | What it removes | +|---|---| +| [CollectLocalGitAuthor](configuration-reference.md#collectlocalgitauthor) off (the default) | The git author name of local runs | +| [CollectCiActorEmail](configuration-reference.md#collectciactoremail) off (the default) | The email of the person behind a CI run | +| [EnablePullRequestDetection](configuration-reference.md#enablepullrequestdetection) off | The pull request context, including its author | +| [Enabled](configuration-reference.md#enabled) off, or `Mode` set to `Disabled` | Everything: the SDK writes no run | + +The store never leaves your machine, and the SDK never uploads a run from it again. It is not +a backup of what Xping Cloud holds. To delete it, run `xping clear`. + +### How the run was recorded + +Each run also records how it was recorded, as properties of its environment. The CLI reads +them. The SDK writes them to the local store only, never to the upload. + +| Property | Value | Missing when | +|---|---|---| +| `Xping.Mode` | `LocalOnly` or `Cloud` | Never | +| `Xping.ProjectId` | The [ProjectId](configuration-reference.md#projectid) of the run | No project is set | +| `Xping.TestFramework` | `NUnit`, `MSTest`, `xUnit` (v2) or `xUnit.v3` | Never | +| `Xping.Runner` | `VSTest` or `MTP` (Microsoft.Testing.Platform) | The tests ran in another host, such as the xUnit console runner, or an xUnit v3 test executable without Microsoft.Testing.Platform | +| `Xping.ProjectPath` | The test project's path from the repository root, such as `tests/Shop.Tests/Shop.Tests.csproj` | The project was built outside a git repository or with `GenerateAssemblyInfo=false`, or the run covered test assemblies of more than one project | + +The project path comes from an MSBuild file that the Xping packages add to your test project's +build. It stamps the path into the test assembly as +`[assembly: AssemblyMetadata("Xping.ProjectPath", "...")]`. In a git submodule, the path is +relative to the submodule. + +--- + +## Retention + +After each write, the SDK deletes old runs until these limits hold. The limits are fixed: no +setting changes them. + +| Limit | Value | Applies to | +|---|---|---| +| Maximum age | 30 days, by the file's last write time | The whole store | +| Maximum runs | 50 | Each test assembly | +| Maximum size | 100 MB | The whole store | + +The SDK applies them in this order: + +1. It deletes runs older than 30 days. +2. It keeps the newest 50 runs of each test assembly, so a busy project never pushes another + project's runs out. A run that covers several test assemblies counts for each of them. + The SDK keeps it while any of them still needs it. +3. If the store is still over 100 MB, it deletes the oldest runs, first those outside the newest + 20 of every test assembly. It deletes from those 20 only if the store is still too big. + +The run the SDK just wrote is never deleted. + +The size of a run grows with the number of tests, and with the length of the error messages +and stack traces of failed tests. + +`xping report` reads the newest 20 runs from the last 14 days by default. The store keeps more, +so that `--runs`, `--since` and `--test` can look further back. + +--- + +## When the store is written + +The SDK writes the run once, when it ends, after the last test. During the run, it only keeps +each execution in memory. The CLI reads and analyses the history, so your test run does not pay for +it. + +--- + +## Failures + +**The local store never fails your test run.** When the SDK cannot write the run, for example +because the disk is full or because `XPING_LOCAL_STORE` names a folder it cannot write to, the run +has no local history. A repository root that is not writable is not such a case: the SDK then uses +the profile folder, so run `xping where` to find it. The SDK +logs the reason at the `Debug` level. To see it, set +[`XPING_LOGLEVEL=Debug`](configuration-reference.md#loglevel). + +When the CLI reads the store, it skips a run file that it cannot read or that does not parse, +and reads the rest. + +--- + +## Environment variables + +| Variable | Read by | Effect | +|---|---|---| +| `XPING_LOCAL_STORE` | SDK and CLI | Moves the store. See [LocalStorePath](configuration-reference.md#localstorepath). | +| `XPING_NO_BANNER` | SDK and CLI | Any non-empty value hides the SDK's retry hint after a test run and the CLI's Xping Cloud invitation | + +If you set `XPING_LOCAL_STORE` for the test run, set it for `xping report` too, to the same value. +Otherwise the CLI looks in another place and finds nothing. A relative value names the same folder +for both, as long as you run `xping report` inside the repository. + +```bash +export XPING_LOCAL_STORE=/var/tmp/xping-store +``` + +--- + +## See also + +- [Run without an account](../getting-started/local-first.md) +- [Data Xping collects](collected-data.md) +- [Configuration reference](configuration-reference.md) +- CLI reference diff --git a/sdk/configuration/toc.yml b/sdk/configuration/toc.yml new file mode 100644 index 0000000..a12d483 --- /dev/null +++ b/sdk/configuration/toc.yml @@ -0,0 +1,6 @@ +- name: Configuration reference + href: configuration-reference.md +- name: Local store + href: local-store.md +- name: Data Xping collects + href: collected-data.md diff --git a/sdk/getting-started/ci-cd-setup.md b/sdk/getting-started/ci-cd-setup.md new file mode 100644 index 0000000..6a6617e --- /dev/null +++ b/sdk/getting-started/ci-cd-setup.md @@ -0,0 +1,386 @@ +--- +uid: getting-started-ci-cd-setup +title: Set up CI +--- + +# Set up CI + +> [!NOTE] +> This page describes the **Xping SDK for .NET, 1.0.0-rc series**. The SDK can upload to Xping Cloud, and these pages refer to the 1.0.0-rc `xping report` CLI. The Xping CLI 2.x is a different tool: it does not use Xping Cloud and has no `report` command. See the [Xping overview](../../index.md). + +This page shows how to upload test results to Xping Cloud from a CI pipeline, and how to fail a +build on what `xping report` finds. It is for developers who already have the SDK in a test +project. If you do not, start with a quick start for +[NUnit](quickstart-nunit.md), [xUnit](quickstart-xunit.md) or [MSTest](quickstart-mstest.md). + +--- + +## What every pipeline needs + +1. In Xping Cloud, open **Settings → API keys** and create a key. Create it with only the Upload + scope. See API keys. +2. Store the key as a secret in your CI platform. Do not store it as a plain variable, and do not + put it in `appsettings.json`. +3. Pass the secret to the test step as the `XPING_APIKEY` environment variable. +4. Run `dotnet test` as usual. + +You do not name a project. Xping Cloud creates one project for each test assembly, on the first +upload. To send several test assemblies to one project, set `XPING_PROJECTID`. See +[ProjectId](../configuration/configuration-reference.md#projectid). + +The SDK detects the CI platform and records the build, the branch, the commit and the person behind +the run. You do not configure this. [Data Xping collects](../configuration/collected-data.md#ci-metadata) +lists each field and the variable it comes from. + +**A failed upload does not fail the build.** The SDK logs the error, and your tests pass or fail as +usual. To fail the build when the upload fails, turn on +[strict mode](../configuration/configuration-reference.md#strictmode). + +**To see the SDK's lines in a CI log**, run `dotnet test` with +`--logger "console;verbosity=normal"`. On xUnit v3, run the test project with `dotnet run` instead. + +--- + +## Supported platforms + +| Platform | Detected | PR context | Setup | +|---|---|---|---| +| GitHub Actions | Yes | Yes | [GitHub Actions](#github-actions) | +| Azure Pipelines | Yes | Yes, for Azure Repos and GitHub repositories | [Azure Pipelines](#azure-pipelines) | +| GitLab CI/CD | Yes | Yes, in merge request pipelines | [GitLab CI/CD](#gitlab-cicd) | +| Jenkins | Yes | Yes, for multibranch PR builds | [Jenkins](#jenkins) | +| CircleCI | Yes | No | [CircleCI](#circleci) | +| Travis CI, TeamCity, Bitbucket Pipelines, AppVeyor | Yes | No | [Other platforms](#other-platforms) | +| Any CI that sets `CI=true` | Yes | No | [Other platforms](#other-platforms) | + +**PR context** is the pull request a build belongs to: its number, branches and head commit. With +it, Xping Cloud files the run under the PR, and can post a +pull request comment. Travis CI, TeamCity, Bitbucket +Pipelines, AppVeyor and a generic CI upload without PR context. They are not targeted for it. + +--- + +## GitHub Actions + +Add the key under **Settings → Secrets and variables → Actions** in your repository, as a secret +named `XPING_APIKEY`. + +```yaml +name: Test + +on: + push: + branches: [main] + pull_request: + branches: [main] + +jobs: + test: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-dotnet@v4 + with: + dotnet-version: '10.0.x' + + - name: Run tests + env: + XPING_APIKEY: ${{ secrets.XPING_APIKEY }} + run: dotnet test --configuration Release --logger "console;verbosity=normal" +``` + +**Tests in a container.** When the tests run in `docker run`, pass the `GITHUB_*` variables, +including `GITHUB_SERVER_URL` and `GITHUB_EVENT_NAME`. Also mount the runner's temp folder, so that +the file at `GITHUB_EVENT_PATH` is readable. Without them, the SDK still records the run, but it +skips the PR context and logs a warning. Without `GITHUB_EVENT_NAME`, Xping Cloud also files the +run under no commit. + +--- + +## Azure Pipelines + +Create a variable group named `Xping` under **Pipelines → Library**, add a variable `XpingApiKey` +and mark it as secret. Azure Pipelines does not pass a secret to a step by itself, so map it in the +step's `env:`. + +```yaml +trigger: + branches: + include: + - main + +pool: + vmImage: 'ubuntu-latest' + +variables: + - group: Xping + +steps: + - task: UseDotNet@2 + inputs: + version: '10.0.x' + + - script: dotnet test --configuration Release --logger "console;verbosity=normal" + displayName: 'Run tests' + env: + XPING_APIKEY: $(XpingApiKey) +``` + +On a pull request build, the SDK records the PR context for repositories in Azure Repos and on +GitHub. Repositories on other providers get no PR context. + +--- + +## GitLab CI/CD + +Add the key under **Settings → CI/CD → Variables**, as a masked variable named `XPING_APIKEY`. +GitLab passes it to every job as an environment variable. + +```yaml +image: mcr.microsoft.com/dotnet/sdk:10.0 + +test: + stage: test + script: + - dotnet test --configuration Release --logger "console;verbosity=normal" +``` + +In a merge request pipeline, the SDK records the MR context, on gitlab.com and on a self-managed +instance. A branch pipeline gets no MR context. + +--- + +## Jenkins + +Add the key under **Manage Jenkins → Credentials**, as a **Secret text** credential with the ID +`xping-api-key`. + +```groovy +pipeline { + agent any + + environment { + XPING_APIKEY = credentials('xping-api-key') + } + + stages { + stage('Test') { + steps { + sh 'dotnet test --configuration Release --logger "console;verbosity=normal"' + } + } + } +} +``` + +**Pull request builds.** On a multibranch pipeline, the SDK records the PR context for GitHub, +GitLab and Azure DevOps repositories, with the merge strategy and with the head strategy. Jenkins has +no variable for the PR head commit when it merges the PR, so the SDK reads it from the `.git` +folder of the workspace: + +- Run the tests in the checked-out workspace. With `skipDefaultCheckout`, run `checkout scm` before + the test stage. +- Keep `git` on the agent's `PATH`. The SDK runs `git rev-parse` when `git gc` has packed the + commit. +- Shallow clones work. + +GitHub Pull Request Builder (GHPRB) jobs are marked as PR builds, but get no PR context. + +--- + +## CircleCI + +Add the key under **Project Settings → Environment Variables**, as `XPING_APIKEY`. CircleCI passes +it to every job. + +```yaml +version: 2.1 + +jobs: + test: + docker: + - image: mcr.microsoft.com/dotnet/sdk:10.0 + steps: + - checkout + - run: + name: Run tests + command: dotnet test --configuration Release --logger "console;verbosity=normal" + +workflows: + test: + jobs: + - test +``` + +--- + +## Other platforms + +On these platforms, store the key as a secret environment variable named `XPING_APIKEY`, then run +`dotnet test`. The SDK detects the platform and records its build metadata. + +| Platform | Where to store the key | +|---|---| +| Travis CI | Repository **Settings → Environment Variables**, with **Display value in build log** off | +| TeamCity | A build parameter `env.XPING_APIKEY` of type **Password** | +| Bitbucket Pipelines | **Repository settings → Repository variables**, with **Secured** on | +| AppVeyor | A secure variable in `appveyor.yml` (`XPING_APIKEY: { secure: … }`), or in the project's **Environment** settings | +| Any other CI | Any secret that the CI passes to the test step as an environment variable. The SDK detects the CI when `CI=true` is set. | + +On TeamCity and a generic CI, the SDK cannot tell a pull request build from a push. Xping Cloud +then files no run from them under a commit. See +[Which commit is recorded](../configuration/collected-data.md#which-commit-is-recorded). + +--- + +## Fail the build on findings + +`xping report --fail-on ` exits with code `1` when a finding of that severity or higher +appears in any test assembly. Add it as a step after the tests. It reads the [local store](../configuration/local-store.md) that the +SDK wrote in the same job, so it works with or without an API key. + +```yaml +- name: Install the Xping CLI + run: dotnet tool install -g Xping.Cli --prerelease + +- name: Run tests + env: + XPING_APIKEY: ${{ secrets.XPING_APIKEY }} + run: dotnet test --configuration Release + +- name: Check findings + if: always() + run: xping report --fail-on high +``` + +- `--fail-on` takes `high`, `medium` or `low`. +- The CLI needs the .NET 10 SDK or runtime on the agent. The SDK packages do not. +- The step reads only the runs in the local store on that agent. A new CI agent starts with an + empty store. `xping report` shows findings only after 5 runs, so on an agent that keeps no store + between jobs, `--fail-on` does not fail. +- When the store has no runs at all, for example because the SDK did not record, `xping report` + exits with code `2`. + +Exit codes lists every code. These options help in a CI +log: + +```bash +xping report --summary # one line for each assembly +xping report --format json # the findings as JSON, for a script or a coding agent +xping report --no-color --ascii # for log viewers that do not show color codes +``` + +### Add Xping Cloud data to the report + +> [!NOTE] +> Xping Cloud only. The Xping CLI 2.x does not use Xping Cloud. + +`xping report` adds Xping Cloud's confidence for each test when its key can read Xping Cloud data. +A key with only the Upload scope cannot. In a pipeline, create a second key with the Read scope, and +pass it only to the report step. Reading also needs a plan that includes API access. See +Credentials. + + +```yaml +- name: Check findings + if: always() + env: + XPING_APIKEY: ${{ secrets.XPING_READ_APIKEY }} + run: xping report --fail-on high +``` + +`xping login` does not work in a pipeline: it needs a terminal, and it does not run when `CI` is +set. When the key cannot read, the report says so on stderr and shows only local data. Xping Cloud +data never changes the exit code. See Credentials. + +--- + +## The default branch and canonical branches + +Xping Cloud counts a CI push to the default branch as a Canonical run. Canonical runs are the +strongest evidence behind a confidence score. A push to one of the project's canonical branches, +such as `release/*`, counts too. You set the canonical branch patterns in the project's settings in +Xping Cloud. A pull request build never counts as Canonical, whatever its branch. + +GitHub Actions and GitLab CI/CD report the default branch. On other platforms, Xping Cloud uses the +project's default branch setting, then `main` or `master`. To name the default branch from the +pipeline, set `XPING_DEFAULTBRANCH`: + +```yaml +- script: dotnet test --configuration Release + env: + XPING_APIKEY: $(XpingApiKey) + XPING_DEFAULTBRANCH: develop +``` + +The value replaces what the platform reports, and wins over the project's setting. See +[DefaultBranch](../configuration/configuration-reference.md#defaultbranch). + +--- + +## Environments and projects + +**Name environments after deployments.** Set `XPING_ENVIRONMENT` only when a pipeline tests a +different deployment, such as `Staging`. Xping Cloud scores each test for each environment. A name +that changes from run to run, such as `PR-123` or `CI`, splits each test's history. The SDK already +records whether a run is on CI and which commit and branch it tested. When you test one deployment, +leave `XPING_ENVIRONMENT` unset: CI runs and local runs then share the `Default` environment. + +The SDK does not read `ASPNETCORE_ENVIRONMENT`. To reuse it, pass it in the shell of the test step: + +```yaml +- name: Run tests + shell: bash + run: XPING_ENVIRONMENT="$ASPNETCORE_ENVIRONMENT" dotnet test +``` + +On GitHub Actions, `${{ env.ASPNETCORE_ENVIRONMENT }}` does not work for this. The `env` context +holds only the variables that the workflow declares, not the ones the runner image or a container +sets. + +**Use one project for one product.** With `XPING_PROJECTID`, every execution in the run goes to +that project, whatever its assembly. Do not split branches or environments into projects: the SDK +records both, and separate projects split the history that the confidence score needs. + +--- + +## Troubleshooting + +**No results in Xping Cloud:** + +1. Check that the test step gets the key: + + ```bash + echo "API key set: $([ -n "$XPING_APIKEY" ] && echo yes || echo no)" + ``` + +2. Run `dotnet test` with `--logger "console;verbosity=normal"`. On xUnit v3, run the test project + with `dotnet run` instead. The SDK's start line says + `Initialized in local-only mode` when it has no key. With a key, it prints one line for each + upload that Xping Cloud accepts, or an error that says why the upload failed. +3. Check that the agent can reach the upload endpoint: + + ```bash + curl -I https://upload.xping.io/v1 + ``` + +**Some results are missing:** + +- Check that the run ends. On NUnit, the `[OneTimeTearDown]` method must call + `FinalizeAndShutdownAsync`. On MSTest, the `[AssemblyCleanup]` method must call it. See the + quick starts. +- On MSTest with vstest, a run that no `[AssemblyCleanup]` method ends often loses its upload. + See [Known limitations](../troubleshooting/known-limitations.md#mstest-a-run-finalized-by-the-process-exit-safety-net-loses-its-upload-on-vstest). +- To fail the build when an upload fails, set `XPING_STRICTMODE: "true"`. + +[Common issues](../troubleshooting/common-issues.md) covers more problems. + +--- + +## See also + +- [Data Xping collects](../configuration/collected-data.md) +- [Configuration reference](../configuration/configuration-reference.md) +- CLI reference +- Reading the PR comment diff --git a/sdk/getting-started/local-first.md b/sdk/getting-started/local-first.md new file mode 100644 index 0000000..4402f3f --- /dev/null +++ b/sdk/getting-started/local-first.md @@ -0,0 +1,333 @@ +--- +uid: getting-started-local-first +title: Run without an account +--- + +# Run without an account + +> [!NOTE] +> This page describes the **Xping SDK for .NET, 1.0.0-rc series**. The SDK can upload to Xping Cloud, and these pages refer to the 1.0.0-rc `xping report` CLI. The Xping CLI 2.x is a different tool: it does not use Xping Cloud and has no `report` command. See the [Xping overview](../../index.md). + +This page shows how to record your test runs and read a reliability report with no Xping account, +no API key and no network access. It is for anyone who wants to try Xping on their own machine first. + +Without an API key, the SDK runs in **local-only mode**. Everything stays on your machine. + +--- + +## What you will learn + +- How to record test history with no Xping account +- How to read the local report +- Where the local data is stored and how to delete it +- What local-only mode can and cannot tell you + +--- + +## Prerequisites + +- A test project that uses **NUnit**, **xUnit** (v2 or v3) or **MSTest** 3.8 or later +- A test project that targets .NET Framework 4.6.2 or later, or .NET 8 or later +- The .NET 10 SDK or runtime, for the CLI + +No account. No API key. + +--- + +## Step 1: Add the SDK + +Install the adapter for your test framework: + +```bash +dotnet add package Xping.Sdk.NUnit --prerelease # or Xping.Sdk.XUnit (xUnit v2), Xping.Sdk.XUnit.V3 (xUnit v3), Xping.Sdk.MSTest +``` + +All Xping packages are prereleases, so the command needs `--prerelease`. + +Set up the adapter as the quick start for your framework describes +([NUnit](quickstart-nunit.md), [xUnit](quickstart-xunit.md), [MSTest](quickstart-mstest.md)). +Skip the API key step. + +With no API key, the SDK starts in local-only mode. When you run `dotnet test` in a terminal, the +SDK prints this line: + +``` +[Xping 17:28:04 INF] Initialized in local-only mode. SessionId: "6bec32b0-922b-4b9b-bcb9-fb4e1056180f", Environment: Default. No API key configured - results stay on this machine. +``` + +When the output goes to a file or a pipe instead of a terminal, for example in a CI log, +`dotnet test` shows this line only with `--logger "console;verbosity=normal"`. + +--- + +## Step 2: Run your tests several times + +```bash +dotnet test +``` + +The SDK writes each run to a local store. `xping report` shows no findings until the store holds at +least **5 runs**, and each test needs at least 5 runs of its own. With fewer runs, the report shows +the counts but no findings. Fewer runs cannot tell a flaky test from a test that just broke. +From the second run on, the report does show the failures of the latest run. See +The latest run. + +--- + +## Step 3: Install the CLI + +> [!NOTE] +> This describes the 1.0.0-rc `xping` CLI. The Xping CLI 2.x is a different tool and has no `report`, `where`, `clear` or `login` commands. + +> **The CLI needs the .NET 10 SDK or runtime.** The tool targets `net10.0` and does not start on +> older runtimes. The SDK packages target `netstandard2.0`, so your test projects do not need +> .NET 10. + +```bash +dotnet tool install -g Xping.Cli --prerelease +``` + +This adds the `xping` command to your `PATH`, for every repository. If your shell answers +`command not found: xping`, add `~/.dotnet/tools` to your `PATH` and open a new terminal. + +To pin the CLI version in your repository instead, install it into a tool manifest. See +Installation in the command reference. + +--- + +## Step 4: Read the report + +> [!NOTE] +> This describes the 1.0.0-rc `xping` CLI. The Xping CLI 2.x is a different tool and has no `report`, `where`, `clear` or `login` commands. + +```bash +xping report +``` + + +```` +Xping · Checkout.Tests · 20 runs · 2026-08-05 → 2026-08-19 · main@a3f9c2e +412 tests · 409 healthy · 3 flagged · 41 awaiting more runs · 6 not significant +◷ nothing to measure: concurrency 108 · slower 32 + +``` +NEEDS ATTENTION (1 high, 1 medium, 1 low) most severe first +──────────────────────────────────────────────────────────────────────── + +1. HIGH flaky + SummaryTests.GenerateMonthlySummary + failed 7 of 20 executions (35%) in 5 of 20 runs, 3 failure modes + evidence adequate | -env-cluster | f_2a91c0de | ...ummaryTests.cs:88 + +2. MED slower + FlowTests.CheckoutFlow_Completes + 3.51x slower (95% CI 1.94-5.87x), 340ms -> 1.2s on the clock + evidence robust | -env | f_8c04b71a | .../Checkout/FlowTests.cs:214 + +3. LOW stopped running + LegacyImport.Roundtrip + ran in 12 of 17 earlier runs, absent from the last 3 + evidence adequate | -partial | f_1d77e3f5 | .../ImportTests.cs:41 +``` + +rates: the marker on each finding says which runs its percentage was +counted out of; compare two only where the markers match. +https://docs.xping.io/cli/reading-the-report.html#the-population-marker + +Detail of row 1: xping report --id f_2a91c0de --assembly Checkout.Tests +```` + +### How to read it + +Each finding has four parts: a **severity**, a **kind**, the **test**, and the **evidence** behind it. + +| Part | Meaning | +|---|---| +| `HIGH` / `MED` / `LOW` | The severity. The report lists the most severe findings first. | +| `flaky`, `slower`, `stopped running` | The *kind*: what the report observed. There are 13 kinds. Reading the report lists them all. | +| The counts line | The measurement behind the finding, in plain numbers. | +| `evidence sparse\|adequate\|robust` | How many runs support *this finding*. A finding can count only the runs it could measure, so this is not always every run of the test. Treat a finding with `sparse` evidence as a lead, not a verdict. | +| `f_2a91c0de` | The finding id. It stays the same between reports, so you can use it in a ticket or compare two reports. | + +The report sits inside a fenced code block and is at most 72 columns wide. When you paste it into +Slack, a pull request or a ticket, the columns stay aligned. The report shows the top ten findings. +Add `--all` to see the rest. + +The report keeps **flaky** and **always failing** apart on purpose. A test that never passes is +not unreliable. It is broken, and it needs a different fix. + +--- + +## What gets flagged + +The report has 13 finding kinds. These are the ones you see most often: + +| Printed as | `--kind` value | What the report observed | +|---|---|---| +| masked by retry | `RetryMasked` | The test failed, then passed on a retry, so the run's outcome hid the failure. | +| flaky | `Flaky` | The test both passes and fails, or fails in different ways. | +| always failing | `AlwaysFailing` | The test fails in almost every run, in one main way. This is more likely a real bug than a flaky test. | +| timing out | `TimingOut` | The framework stops the test for running past its timeout in most runs. | +| slower | `DurationRegression` | The recent runs of the test are slower than its earlier runs, by more than its usual variation. The headline gives the factor and its interval, and the evidence gives the spread on each side. See [Known limitations](../troubleshooting/known-limitations.md). | +| stopped running | `Vanished` | The test ran regularly in the earlier runs and has stopped. | + +The other kinds are deeper retries (`RetryDeepening`), out of retries (`RetryExhausted`), unstable +timing (`DurationUnstable`), concurrency (`ParallelSensitive`), broken fixture (`BrokenFixture`), +shared failure (`SharedFailure`) and time sensitive (`TimeSensitive`). +Reading the report describes each one. + +Every kind needs the 5-run minimum. Before that, the SDK still tells you about a retry in the run +that just finished. Outside CI, it writes this line to your terminal when the run ends: + +``` +[Xping] 1 test flaked on retry this run - run `xping report` for local history +``` + +To show only some kinds, use `--kind`. With a store that holds one test assembly: + +```bash +xping report --kind Flaky --kind AlwaysFailing +``` + +The report ignores skipped tests and tests that did not run. They say nothing about reliability. + +--- + +## Multiple test projects + +All test projects in a repository share one store. When the store holds more than one assembly, +`xping report` lists them, one row each, most severe first: + +``` +Xping · 3 assemblies + +Checkout.Tests 4 findings (1 high, 3 medium) + 412 tests · 4 flagged · 20 runs · last 2026-11-08 16:45 +Billing.Tests no findings + 96 tests · 0 flagged · 20 runs · last 2026-11-08 16:44 +Search.Tests no findings + 57 tests · 0 flagged · 6 runs · last 2026-11-02 09:12 + +Details: xping report --assembly Checkout.Tests +``` + +To see the findings of one assembly: + +```bash +xping report --assembly Billing.Tests +``` + +`--kind`, `--top` and `--all` select findings from one assembly, so they need `--assembly` when the +store holds several. Without it, the CLI writes `--kind needs --assembly` to stderr and exits with +code 2. + +`--fail-on` checks every assembly. A CI step fails when any assembly has a finding at the +threshold. + +The CLI analyses each assembly against **its own** run history. An assembly with 3 runs is never +compared with the 12-run window of another assembly. + +--- + +## Where your data lives + +```bash +xping where +``` + +``` +/Users/you/src/my-repo/.xping + 36 runs · 1.2 MB on disk + Checkout.Tests 12 runs last 2026-08-08 09:14 UTC + Billing.Tests 12 runs last 2026-08-08 09:13 UTC + Api.Tests 12 runs last 2026-08-08 09:11 UTC +``` + +The store is the `.xping` folder at the root of your repository. It **ignores itself**: it contains +a `.gitignore` that hides the whole folder. Nothing appears in `git status`, and the SDK does not +change your own `.gitignore`. + +The store keeps at most 50 runs of each test assembly, runs up to 30 days old, and 100 MB in +total. It deletes older runs automatically. These limits are fixed. To move the store, see +[Local store](../configuration/local-store.md). + +To delete history: + +```bash +xping clear # asks before it deletes +xping clear --assembly Billing.Tests # only one assembly +``` + +--- + +## What local-only mode cannot tell you + +The local history holds only **your** runs, on **your** machine. It cannot include: + +- CI runs +- the runs of your teammates +- differences between operating systems or environments +- more history than the store keeps + +This is why the local report shows no confidence score. The +confidence score of Xping Cloud uses data that one machine does not +have, such as how a test behaves in different environments. A local number that looked like the +Xping Cloud score but did not match it would mislead you. + +Local-only mode answers the question *"what is unstable on my machine, in my last runs?"*. Xping +Cloud answers *"what is unstable across CI, every branch and every machine, over months?"*. + +--- + +## Connect later + +You lose nothing by starting locally. Add an API key when you want to. It is the only variable you +need, and your test code stays the same: + +```bash +export XPING_APIKEY="your-key" +``` + +Create the key in Xping Cloud under **Settings → API keys**, with only the Upload scope. See API keys. + +You do not name a project. Xping Cloud creates one project for each test assembly, on the first +upload. `XPING_PROJECTID` is optional. It sends several assemblies to one project. See +[ProjectId](../configuration/configuration-reference.md#projectid). + +Keep the key out of your repository. Set it in your shell or in a secret store, never in +`appsettings.json`. That file is committed and copied into the build output. + +With the key, the SDK switches to Cloud mode and uploads each run. It **keeps writing the local +store**, so `xping report` still works offline on your own machine. + +To see the Xping Cloud data in the same report, sign in once on your machine: + +```bash +xping login +``` + +`xping report` then adds the Xping Cloud confidence score to the rows it prints, with a label so you +cannot mistake it for a local number. Under `FLAGGED IN CLOUD`, it lists the tests that Xping Cloud +calls flaky, broken or unstable but that passed here. Neither changes the local counts or the exit +code. When you are offline, it prints the local report. See +Cloud data. + +To stop the SDK from uploading when credentials are present, set the mode: + +```bash +export XPING_MODE=LocalOnly +``` + +`XPING_MODE` is an SDK setting. The CLI does not read it. Without a sign-in, `xping report` tries +the `XPING_APIKEY` in your shell. A key with only the Upload scope cannot read Xping Cloud data, so +the report stays local. In a terminal, the report says so in one line. After `xping login`, the +report shows the Xping Cloud data instead. + +--- + +## See also + +- Command reference: every command and option +- [Local store](../configuration/local-store.md): the location and the limits +- [Configuration reference](../configuration/configuration-reference.md): every SDK setting +- Finding flaky tests diff --git a/sdk/getting-started/quickstart-mstest.md b/sdk/getting-started/quickstart-mstest.md new file mode 100644 index 0000000..8468bf1 --- /dev/null +++ b/sdk/getting-started/quickstart-mstest.md @@ -0,0 +1,295 @@ +--- +uid: getting-started-quickstart-mstest +title: "Quick start: MSTest" +--- + +# Quick start: MSTest + +> [!NOTE] +> This page describes the **Xping SDK for .NET, 1.0.0-rc series**. The SDK can upload to Xping Cloud, and these pages refer to the 1.0.0-rc `xping report` CLI. The Xping CLI 2.x is a different tool: it does not use Xping Cloud and has no `report` command. See the [Xping overview](../../index.md). + +This page shows how to add the Xping SDK to an MSTest test project and read your first report. It +is for developers who use MSTest 3.8 or later. + +--- + +## Prerequisites + +- A test project that uses **MSTest 3.8** or later. To create one, run + `dotnet new mstest -n MyTestProject`. MSTest 3.7 skips `[AssemblyCleanup]` when tests run in + parallel at method level, and that method ends the run. +- A test project that targets .NET Framework 4.6.2 or later, or .NET 8 or later. +- The .NET 10 SDK or runtime, for the `xping` CLI. + +You do not need an Xping account. Without an API key, the SDK runs in +[local-only mode](local-first.md): it writes every run to `.xping/` in your repository and makes no +network calls. + +--- + +## Step 1: Install the package + +```bash +dotnet add package Xping.Sdk.MSTest --prerelease +``` + +All Xping packages are prereleases, so the command needs `--prerelease`. To add the package to the +`.csproj` file instead: + +```xml + + + +``` + +--- + +## Step 2: Start and end the run + +Add one class to your test project, for example `XpingSetup.cs`: + +```csharp +using System.Threading.Tasks; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Xping.Sdk.MSTest; + +[TestClass] +public static class XpingSetup +{ + [AssemblyInitialize] + public static void AssemblyInit(TestContext context) => XpingContext.Initialize(); + + [AssemblyCleanup] + public static async Task AssemblyCleanup() => await XpingContext.FinalizeAndShutdownAsync(); +} +``` + +MSTest runs assembly hooks only from the test assembly itself, so this class must be in your test +project. `FinalizeAndShutdownAsync` ends the run, writes it to the [local store](../configuration/local-store.md) and uploads what +is left. + +When no `[AssemblyCleanup]` method ends the run, the SDK ends it when the test process exits, +and prints a warning. The local store still gets the run. On vstest, the upload to Xping Cloud +usually does not finish, because vstest stops the test process 100 ms after the run. See +[Known limitations](../troubleshooting/known-limitations.md#mstest-a-run-finalized-by-the-process-exit-safety-net-loses-its-upload-on-vstest). + +--- + +## Step 3: Track your tests + +Make each test class inherit from `XpingTestBase`: + +```csharp +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Xping.Sdk.MSTest; + +[TestClass] +public class CalculatorTests : XpingTestBase +{ + [TestMethod] + public void Add_TwoNumbers_ReturnsSum() + { + Assert.AreEqual(5, 2 + 3); + } +} +``` + +`XpingTestBase` records each test in its `[TestInitialize]` and `[TestCleanup]` methods. The SDK +records only the tests of classes that inherit from it. + +--- + +## Step 4: Run your tests + +```bash +dotnet test +``` + +When you run `dotnet test` in a terminal, the SDK prints one line when the run starts: + +``` +[Xping 17:28:04 INF] Initialized in local-only mode. SessionId: "6bec32b0-922b-4b9b-bcb9-fb4e1056180f", Environment: Default. No API key configured - results stay on this machine. +``` + +When the output goes to a file or a pipe, for example in a CI log, `dotnet test` shows the SDK's +lines only with `--logger "console;verbosity=normal"`. + +### On Microsoft.Testing.Platform + +The adapter hooks into MSTest, not into the test runner, so it works the same on +[Microsoft.Testing.Platform](https://learn.microsoft.com/dotnet/core/testing/microsoft-testing-platform-intro). +Turn on MSTest's runner in the test project: + +```xml + + Exe + true + +``` + +Then run the test executable, or run `dotnet test` with this `global.json` next to your solution +(.NET 10 SDK): + +```json +{ "test": { "runner": "Microsoft.Testing.Platform" } } +``` + +For a TRX report, reference `Microsoft.Testing.Extensions.TrxReport` and pass `--report-trx`. + +Microsoft.Testing.Platform lets the SDK finish the upload when the process exits, so a run +that no `[AssemblyCleanup]` ended still reaches Xping Cloud. + +--- + +## Step 5: Read the report + +> [!NOTE] +> This describes the 1.0.0-rc `xping` CLI. The Xping CLI 2.x is a different tool and has no `report`, `where`, `clear` or `login` commands. + +Run your tests at least **5 times**. Each test also needs at least 5 runs of its own. With fewer +runs, the report shows the counts but no findings. + +Install the CLI, then read the report: + +```bash +dotnet tool install -g Xping.Cli --prerelease +xping report +``` + + +```` +Xping · MyTestProject · 9 runs · 2026-08-20 07:52 → 09:02 · main@bdbafba +17 tests · 15 healthy · 2 flagged + +``` +NEEDS ATTENTION (2 high) most severe first +──────────────────────────────────────────────────────────────────────── + +1. HIGH flaky + SampleTests.FlakyTest_PassesOnRetry + failed 9 of 18 executions (50%) in 9 of 9 runs, 1 failure mode + evidence adequate | -env-cluster | f_2b84a621 | ...SampleTests.cs:96 + +2. HIGH always failing + SampleTests.ThrowingTestIsTracked + failed 9 of 9 executions (100%), one failure mode: + System.InvalidOperationException + evidence sparse | -env-cluster | f_c1774d82 | .../SampleTests.cs:65 +``` + +rates: the marker on each finding says which runs its percentage was +counted out of; compare two only where the markers match. +https://docs.xping.io/cli/reading-the-report.html#the-population-marker + +Detail of row 1: xping report --id f_2b84a621 --assembly MyTestProject +```` + +[Run without an account](local-first.md#how-to-read-it) explains each part of a finding. +`xping report --format json` gives the same findings as JSON, for a script or a coding agent. The +command reference lists every option. + +--- + +## Upload to Xping Cloud + +> [!NOTE] +> Xping Cloud only. The Xping CLI 2.x does not use Xping Cloud. + +Xping Cloud adds confidence scores, flaky-test detection and pull request comments, across CI and +every machine. Access is by invitation. + +1. In Xping Cloud, open **Settings → API keys** and create a key with only the Upload scope. See API keys. +2. Set the key as an environment variable: + + ```bash + export XPING_APIKEY="your-api-key" # Linux and macOS + $env:XPING_APIKEY="your-api-key" # PowerShell + set XPING_APIKEY=your-api-key # Command Prompt + ``` + +3. Run `dotnet test`. The start line does not say local-only: + + ``` + [Xping 09:14:02 INF] Initialized. SessionId: "0f3c9a1e-5b7d-4c2a-9e61-2d8b4f7a3c10", Environment: Default + ``` + + The SDK prints one line for each upload that Xping Cloud accepts. The upload at the end of the + run prints: + + ``` + [Xping 09:14:05 INF] Finalization receipt 7c1e04b2 (312ms, 4.6 KB) + ``` + + An upload during the run prints `Published 100 tests in 287ms (38.2 KB) · receipt 3a9d51f0`. + When an upload fails, the SDK prints an error that says why. The test run does not fail, unless + you turn on [strict mode](#strict-mode). + +Keep the key out of your repository. Do not put it in `appsettings.json`: that file is committed +and copied into the build output. In CI, store it as a secret. See [Set up CI](ci-cd-setup.md). + +The SDK keeps writing the local store in Xping Cloud mode, so `xping report` still works. + +You do not name a project. Xping Cloud creates one project for each test assembly, on the first +upload. To send several assemblies to one project, set +[ProjectId](../configuration/configuration-reference.md#projectid). + +### Configure in code + +To build the configuration at run time, pass it to `Initialize` in the `[AssemblyInitialize]` +method: + +```csharp +[AssemblyInitialize] +public static void AssemblyInit(TestContext context) => XpingContext.Initialize(new XpingConfiguration +{ + BatchSize = 200, +}); +``` + +`XpingConfiguration` is in the `Xping.Sdk.Core.Configuration` namespace. With a configuration +object, the SDK reads no `appsettings.json` file. `XPING_*` environment variables still win over +the values you pass. See [Configuration methods](../configuration/configuration-reference.md#configuration-methods). + +--- + +## What the adapter records + +- **Data rows**: each `[DataRow]` is a separate test, with its arguments. +- **Ignored tests**: MSTest skips a test with `[Ignore]` before its `[TestInitialize]` method runs, + so the SDK does not record it. See + [Known limitations](../troubleshooting/known-limitations.md#mstest). + +### Keep a test's history when you rename it + +Xping identifies a test by a hash of its fully qualified name. When you rename the method, the +class or the namespace, Xping sees a new test, and the history of the old name stops. + +To keep the history, pin a fingerprint. Use only letters, digits, `_` and `-`, at most 100 +characters: + +```csharp +using Xping.Sdk.Core.Attributes; + +[XpingFingerprint("checkout-happy-path-v1")] +[TestMethod] +public void PlaceOrder_WithValidCart_Succeeds() { } +``` + +For a data-driven test, the SDK adds the arguments to the fingerprint, so each data row stays a +separate test. Do not change the value after the first run: a new value starts a new history. + +### Strict mode + +In [strict mode](../configuration/configuration-reference.md#strictmode), a failed upload makes +`FinalizeAndShutdownAsync` throw. MSTest then fails the run and reports the error on the last test +result. + +--- + +## See also + +- [Set up CI](ci-cd-setup.md) +- [Configuration reference](../configuration/configuration-reference.md) +- [Known limitations](../troubleshooting/known-limitations.md#mstest) +- [Common issues](../troubleshooting/common-issues.md) +- Sample project: [samples/SampleApp.MSTest](https://github.com/xping-dev/sdk-dotnet/tree/main/samples/SampleApp.MSTest) diff --git a/sdk/getting-started/quickstart-nunit.md b/sdk/getting-started/quickstart-nunit.md new file mode 100644 index 0000000..99347a4 --- /dev/null +++ b/sdk/getting-started/quickstart-nunit.md @@ -0,0 +1,291 @@ +--- +uid: getting-started-quickstart-nunit +title: "Quick start: NUnit" +--- + +# Quick start: NUnit + +> [!NOTE] +> This page describes the **Xping SDK for .NET, 1.0.0-rc series**. The SDK can upload to Xping Cloud, and these pages refer to the 1.0.0-rc `xping report` CLI. The Xping CLI 2.x is a different tool: it does not use Xping Cloud and has no `report` command. See the [Xping overview](../../index.md). + +This page shows how to add the Xping SDK to an NUnit test project and read your first report. It +is for developers who use NUnit 3.14 or later. + +--- + +## Prerequisites + +- A test project that uses **NUnit 3.14** or later. To create one, run + `dotnet new nunit -n MyTestProject`. +- A test project that targets .NET Framework 4.6.2 or later, or .NET 8 or later. +- The .NET 10 SDK or runtime, for the `xping` CLI. + +You do not need an Xping account. Without an API key, the SDK runs in +[local-only mode](local-first.md): it writes every run to `.xping/` in your repository and makes no +network calls. + +--- + +## Step 1: Install the package + +```bash +dotnet add package Xping.Sdk.NUnit --prerelease +``` + +All Xping packages are prereleases, so the command needs `--prerelease`. To add the package to the +`.csproj` file instead: + +```xml + + + +``` + +--- + +## Step 2: Start and end the run + +Add one file to the root of your test project, for example `XpingSetup.cs`: + +```csharp +using System.Threading.Tasks; +using NUnit.Framework; +using Xping.Sdk.NUnit; + +[assembly: XpingTrack] + +[SetUpFixture] +public class XpingSetup +{ + [OneTimeSetUp] + public void BeforeAllTests() => XpingContext.Initialize(); + + [OneTimeTearDown] + public async Task AfterAllTests() => await XpingContext.FinalizeAndShutdownAsync(); +} +``` + +- `[assembly: XpingTrack]` tracks every test in the assembly. +- The setup fixture has no namespace, so it runs once for the whole assembly. +- `FinalizeAndShutdownAsync` ends the run, writes it to the [local store](../configuration/local-store.md) and uploads what is + left. **Without the `[OneTimeTearDown]` method, the run never ends:** the local store gets + nothing, and Xping Cloud gets only the batches the SDK uploaded during the run. + +The project includes the file by default. Do not add a `` item for it: an +SDK-style project already compiles every `.cs` file, and a second item stops the build with +`NETSDK1022`. + +### Track only some tests + +To track less than the whole assembly, leave out `[assembly: XpingTrack]` and put `[XpingTrack]` +on a test class or a test method: + +```csharp +using NUnit.Framework; +using Xping.Sdk.NUnit; + +[TestFixture] +[XpingTrack] // tracks every test in this class +public class CalculatorTests +{ + [Test] + public void Add_TwoNumbers_ReturnsSum() => Assert.That(2 + 3, Is.EqualTo(5)); +} +``` + +The setup fixture is still needed. + +--- + +## Step 3: Run your tests + +```bash +dotnet test +``` + +When you run `dotnet test` in a terminal, the SDK prints one line when the run starts: + +``` +[Xping 17:28:04 INF] Initialized in local-only mode. SessionId: "6bec32b0-922b-4b9b-bcb9-fb4e1056180f", Environment: Default. No API key configured - results stay on this machine. +``` + +When the output goes to a file or a pipe, for example in a CI log, `dotnet test` shows the SDK's +lines only with `--logger "console;verbosity=normal"`. + +### On Microsoft.Testing.Platform + +The adapter hooks into NUnit, not into the test runner, so it works the same on +[Microsoft.Testing.Platform](https://learn.microsoft.com/dotnet/core/testing/microsoft-testing-platform-intro). +Turn on NUnit's runner (NUnit3TestAdapter 5.0 or later) in the test project: + +```xml + + Exe + true + +``` + +Then run the test executable, or run `dotnet test` with this `global.json` next to your solution +(.NET 10 SDK): + +```json +{ "test": { "runner": "Microsoft.Testing.Platform" } } +``` + +For a TRX report, reference `Microsoft.Testing.Extensions.TrxReport` and pass `--report-trx`. + +--- + +## Step 4: Read the report + +> [!NOTE] +> This describes the 1.0.0-rc `xping` CLI. The Xping CLI 2.x is a different tool and has no `report`, `where`, `clear` or `login` commands. + +Run your tests at least **5 times**. Each test also needs at least 5 runs of its own. With fewer +runs, the report shows the counts but no findings. + +Install the CLI, then read the report: + +```bash +dotnet tool install -g Xping.Cli --prerelease +xping report +``` + + +```` +Xping · MyTestProject · 9 runs · 2026-08-20 07:52 → 09:02 · main@bdbafba +17 tests · 15 healthy · 2 flagged + +``` +NEEDS ATTENTION (2 high) most severe first +──────────────────────────────────────────────────────────────────────── + +1. HIGH flaky + SampleTests.FlakyTest_PassesOnRetry + failed 9 of 18 executions (50%) in 9 of 9 runs, 1 failure mode + evidence adequate | -env-cluster | f_2b84a621 | ...SampleTests.cs:96 + +2. HIGH always failing + SampleTests.ThrowingTestIsTracked + failed 9 of 9 executions (100%), one failure mode: + System.InvalidOperationException + evidence sparse | -env-cluster | f_c1774d82 | .../SampleTests.cs:65 +``` + +rates: the marker on each finding says which runs its percentage was +counted out of; compare two only where the markers match. +https://docs.xping.io/cli/reading-the-report.html#the-population-marker + +Detail of row 1: xping report --id f_2b84a621 --assembly MyTestProject +```` + +[Run without an account](local-first.md#how-to-read-it) explains each part of a finding. +`xping report --format json` gives the same findings as JSON, for a script or a coding agent. The +command reference lists every option. + +--- + +## Upload to Xping Cloud + +> [!NOTE] +> Xping Cloud only. The Xping CLI 2.x does not use Xping Cloud. + +Xping Cloud adds confidence scores, flaky-test detection and pull request comments, across CI and +every machine. Access is by invitation. + +1. In Xping Cloud, open **Settings → API keys** and create a key with only the Upload scope. See API keys. +2. Set the key as an environment variable: + + ```bash + export XPING_APIKEY="your-api-key" # Linux and macOS + $env:XPING_APIKEY="your-api-key" # PowerShell + set XPING_APIKEY=your-api-key # Command Prompt + ``` + +3. Run `dotnet test`. The start line does not say local-only: + + ``` + [Xping 09:14:02 INF] Initialized. SessionId: "0f3c9a1e-5b7d-4c2a-9e61-2d8b4f7a3c10", Environment: Default + ``` + + The SDK prints one line for each upload that Xping Cloud accepts. The upload at the end of the + run prints: + + ``` + [Xping 09:14:05 INF] Finalization receipt 7c1e04b2 (312ms, 4.6 KB) + ``` + + An upload during the run prints `Published 100 tests in 287ms (38.2 KB) · receipt 3a9d51f0`. + When an upload fails, the SDK prints an error that says why. The test run does not fail, unless + you turn on [strict mode](#strict-mode). + +Keep the key out of your repository. Do not put it in `appsettings.json`: that file is committed +and copied into the build output. In CI, store it as a secret. See [Set up CI](ci-cd-setup.md). + +The SDK keeps writing the local store in Xping Cloud mode, so `xping report` still works. + +You do not name a project. Xping Cloud creates one project for each test assembly, on the first +upload. To send several assemblies to one project, set +[ProjectId](../configuration/configuration-reference.md#projectid). + +### Configure in code + +To build the configuration at run time, pass it to `Initialize` in the setup fixture: + +```csharp +[OneTimeSetUp] +public void BeforeAllTests() => XpingContext.Initialize(new XpingConfiguration +{ + BatchSize = 200, +}); +``` + +`XpingConfiguration` is in the `Xping.Sdk.Core.Configuration` namespace. With a configuration +object, the SDK reads no `appsettings.json` file. `XPING_*` environment variables still win over +the values you pass. See [Configuration methods](../configuration/configuration-reference.md#configuration-methods). + +--- + +## What the adapter records + +- **Parameterized tests**: each `[TestCase]` is a separate test, with its arguments. +- **Categories**: `[Category]` values are stored with each execution. +- **Ignored tests**: NUnit skips a test with `[Ignore]` before it runs, so the SDK does not record + it. See [Known limitations](../troubleshooting/known-limitations.md#nunit). + +### Keep a test's history when you rename it + +Xping identifies a test by a hash of its fully qualified name. When you rename the method, the +class or the namespace, Xping sees a new test, and the history of the old name stops. + +To keep the history, pin a fingerprint. Use only letters, digits, `_` and `-`, at most 100 +characters: + +```csharp +using Xping.Sdk.Core.Attributes; + +[XpingFingerprint("checkout-happy-path-v1")] +[Test] +public void PlaceOrder_WithValidCart_Succeeds() { } +``` + +For a parameterized test, the SDK adds the arguments to the fingerprint, so each case stays a +separate test. Do not change the value after the first run: a new value starts a new history. + +### Strict mode + +In [strict mode](../configuration/configuration-reference.md#strictmode), a failed upload fails the +test run. NUnit reports an exception from `[OneTimeTearDown]` only as a warning and exits with +code 0. So on vstest the SDK ends the test process about two seconds later, after every result has +reached `dotnet test`. On Microsoft.Testing.Platform, it sets exit code 1 after the platform writes +its reports. + +--- + +## See also + +- [Set up CI](ci-cd-setup.md) +- [Configuration reference](../configuration/configuration-reference.md) +- [Known limitations](../troubleshooting/known-limitations.md#nunit) +- [Common issues](../troubleshooting/common-issues.md) +- Sample project: [samples/SampleApp.NUnit](https://github.com/xping-dev/sdk-dotnet/tree/main/samples/SampleApp.NUnit) diff --git a/sdk/getting-started/quickstart-xunit.md b/sdk/getting-started/quickstart-xunit.md new file mode 100644 index 0000000..05fec8b --- /dev/null +++ b/sdk/getting-started/quickstart-xunit.md @@ -0,0 +1,311 @@ +--- +uid: getting-started-quickstart-xunit +title: "Quick start: xUnit" +--- + +# Quick start: xUnit + +> [!NOTE] +> This page describes the **Xping SDK for .NET, 1.0.0-rc series**. The SDK can upload to Xping Cloud, and these pages refer to the 1.0.0-rc `xping report` CLI. The Xping CLI 2.x is a different tool: it does not use Xping Cloud and has no `report` command. See the [Xping overview](../../index.md). + +This page shows how to add the Xping SDK to an xUnit test project and read your first report. It +is for developers who use xUnit v2 (2.9.2 or later) or xUnit v3 (4.0.2 or later). + +--- + +## Prerequisites + +- A test project that uses **xUnit v2** 2.9.2 or later, or **xUnit v3** 4.0.2 or later. + `dotnet new xunit -n MyTestProject` creates an xUnit v2 project. For xUnit v3, run + `dotnet new install xunit.v3.templates`, then `dotnet new xunit3 -n MyTestProject`. +- A test project that targets .NET Framework 4.6.2 or later, or .NET 8 or later. xUnit v3 itself + needs .NET Framework 4.7.2 or later. +- The .NET 10 SDK or runtime, for the `xping` CLI. + +You do not need an Xping account. Without an API key, the SDK runs in +[local-only mode](local-first.md): it writes every run to `.xping/` in your repository and makes no +network calls. + +--- + +## Which package + +Xping has one adapter for each xUnit version. Choose the one that matches the xUnit package your +test project references: + +| Your project references | Install | Test runner | +|---|---|---| +| `xunit` (2.x) | `Xping.Sdk.XUnit` | vstest | +| `xunit.v3`, `xunit.v3.mtp-off` or another `xunit.v3.*` package | `Xping.Sdk.XUnit.V3` | Microsoft.Testing.Platform or vstest | + +To check, look for ` + +``` + +# [xUnit v3](#tab/xunit-v3) + +```bash +dotnet add package Xping.Sdk.XUnit.V3 --prerelease +``` + +Or in the `.csproj` file: + +```xml + + + +``` + +*** + +All Xping packages are prereleases, so the command needs `--prerelease`. + +--- + +## Step 2: Turn on the Xping test framework + +Add one line to an `AssemblyInfo.cs` file at the root of your test project. Create the file if you +do not have one. + +# [xUnit v2](#tab/xunit-v2) + +```csharp +using Xunit; + +[assembly: TestFramework("Xping.Sdk.XUnit.XpingTestFramework", "Xping.Sdk.XUnit")] +``` + +# [xUnit v3](#tab/xunit-v3) + +```csharp +using Xunit; + +[assembly: TestFramework(typeof(Xping.Sdk.XUnit.V3.XpingTestFramework))] +``` + +xUnit v3 takes the type of the framework, not its name. + +*** + +xUnit then runs your tests through the Xping test framework, which records every test in the +assembly. You do not add attributes to your tests, and you do not write a setup class: the +framework starts the run before the first test and ends it after the last one. + +--- + +## Step 3: Run your tests + +```bash +dotnet test +``` + +When you run `dotnet test` in a terminal, the SDK prints one line when the run starts: + +``` +[Xping 17:28:04 INF] Initialized in local-only mode. SessionId: "6bec32b0-922b-4b9b-bcb9-fb4e1056180f", Environment: Default. No API key configured - results stay on this machine. +``` + +When the output goes to a file or a pipe, for example in a CI log, `dotnet test` shows the SDK's +lines only with `--logger "console;verbosity=normal"`. + +On xUnit v3, `dotnet test` does not show the SDK's lines. To see them, run the test project +itself with `dotnet run`. + +### xUnit v3 test runners + +An xUnit v3 test project is an executable. The SDK records it on each runner: + +- **Microsoft.Testing.Platform**: run `dotnet test` with + `{ "test": { "runner": "Microsoft.Testing.Platform" } }` in `global.json`. Or run the project with + `dotnet run` when it sets `true`. +- **vstest**: run `dotnet test` without that `global.json` setting, through + `xunit.runner.visualstudio`. On the .NET 10 SDK, vstest does not run a Microsoft.Testing.Platform + app, so reference `xunit.v3.mtp-off` instead of `xunit.v3`. + +--- + +## Step 4: Read the report + +> [!NOTE] +> This describes the 1.0.0-rc `xping` CLI. The Xping CLI 2.x is a different tool and has no `report`, `where`, `clear` or `login` commands. + +Run your tests at least **5 times**. Each test also needs at least 5 runs of its own. With fewer +runs, the report shows the counts but no findings. + +Install the CLI, then read the report: + +```bash +dotnet tool install -g Xping.Cli --prerelease +xping report +``` + + +```` +Xping · MyTestProject · 9 runs · 2026-08-20 07:52 → 09:02 · main@bdbafba +17 tests · 15 healthy · 2 flagged + +``` +NEEDS ATTENTION (2 high) most severe first +──────────────────────────────────────────────────────────────────────── + +1. HIGH flaky + SampleTests.FlakyTest_PassesOnRetry + failed 9 of 18 executions (50%) in 9 of 9 runs, 1 failure mode + evidence adequate | -env-cluster | f_2b84a621 | ...SampleTests.cs:96 + +2. HIGH always failing + SampleTests.ThrowingTestIsTracked + failed 9 of 9 executions (100%), one failure mode: + System.InvalidOperationException + evidence sparse | -env-cluster | f_c1774d82 | .../SampleTests.cs:65 +``` + +rates: the marker on each finding says which runs its percentage was +counted out of; compare two only where the markers match. +https://docs.xping.io/cli/reading-the-report.html#the-population-marker + +Detail of row 1: xping report --id f_2b84a621 --assembly MyTestProject +```` + +[Run without an account](local-first.md#how-to-read-it) explains each part of a finding. +`xping report --format json` gives the same findings as JSON, for a script or a coding agent. The +command reference lists every option. + +--- + +## Upload to Xping Cloud + +> [!NOTE] +> Xping Cloud only. The Xping CLI 2.x does not use Xping Cloud. + +Xping Cloud adds confidence scores, flaky-test detection and pull request comments, across CI and +every machine. Access is by invitation. + +1. In Xping Cloud, open **Settings → API keys** and create a key with only the Upload scope. See API keys. +2. Set the key as an environment variable: + + ```bash + export XPING_APIKEY="your-api-key" # Linux and macOS + $env:XPING_APIKEY="your-api-key" # PowerShell + set XPING_APIKEY=your-api-key # Command Prompt + ``` + +3. Run `dotnet test`. On xUnit v3, run `dotnet run` instead, to see the SDK's lines. The start line + does not say local-only: + + ``` + [Xping 09:14:02 INF] Initialized. SessionId: "0f3c9a1e-5b7d-4c2a-9e61-2d8b4f7a3c10", Environment: Default + ``` + + The SDK prints one line for each upload that Xping Cloud accepts. The upload at the end of the + run prints: + + ``` + [Xping 09:14:05 INF] Finalization receipt 7c1e04b2 (312ms, 4.6 KB) + ``` + + An upload during the run prints `Published 100 tests in 287ms (38.2 KB) · receipt 3a9d51f0`. + When an upload fails, the SDK prints an error that says why. The test run does not fail, unless + you turn on [strict mode](../configuration/configuration-reference.md#strictmode). + +Keep the key out of your repository. Do not put it in `appsettings.json`: that file is committed +and copied into the build output. In CI, store it as a secret. See [Set up CI](ci-cd-setup.md). + +The SDK keeps writing the [local store](../configuration/local-store.md) in Xping Cloud mode, so `xping report` still works. + +You do not name a project. Xping Cloud creates one project for each test assembly, on the first +upload. To send several assemblies to one project, set +[ProjectId](../configuration/configuration-reference.md#projectid). + +### Configure in code + +The Xping test framework calls `XpingContext.Initialize()` itself. To pass a configuration object +instead, call `Initialize` first, from a module initializer: + +```csharp +using System.Runtime.CompilerServices; +using Xping.Sdk.Core.Configuration; +using Xping.Sdk.XUnit; // Xping.Sdk.XUnit.V3 on xUnit v3 + +internal static class XpingModuleInitializer +{ + [ModuleInitializer] + internal static void Initialize() => XpingContext.Initialize(new XpingConfiguration + { + BatchSize = 200, + }); +} +``` + +`[ModuleInitializer]` needs .NET 5 or later. With a configuration object, the SDK reads no +`appsettings.json` file. `XPING_*` environment variables still win over the values you pass. See +[Configuration methods](../configuration/configuration-reference.md#configuration-methods). + +--- + +## What the adapter records + +- **Theories**: each data row is a separate test, with its arguments. +- **Traits**: `[Trait]` values are stored with each execution. +- **Collections**: each execution records the name of its test collection. +- **Skipped tests**: a test with `Skip` is recorded as skipped. +- **xRetry.v3 retries**: xRetry.v3 reports only the attempt that a retried test ended on, so the SDK + records only that attempt. See + [Known limitations](../troubleshooting/known-limitations.md#xunit-v3-records-only-the-last-retry-attempt). + +### Keep a test's history when you rename it + +Xping identifies a test by a hash of its fully qualified name. When you rename the method, the +class or the namespace, Xping sees a new test, and the history of the old name stops. + +To keep the history, pin a fingerprint. Use only letters, digits, `_` and `-`, at most 100 +characters: + +```csharp +using Xping.Sdk.Core.Attributes; + +[XpingFingerprint("checkout-happy-path-v1")] +[Fact] +public void PlaceOrder_WithValidCart_Succeeds() { } +``` + +For a theory, the SDK adds the arguments to the fingerprint, so each data row stays a separate +test. Do not change the value after the first run: a new value starts a new history. + +--- + +## See also + +- [Set up CI](ci-cd-setup.md) +- [Configuration reference](../configuration/configuration-reference.md) +- [Known limitations](../troubleshooting/known-limitations.md) +- [Common issues](../troubleshooting/common-issues.md) +- Sample projects: [samples/SampleApp.XUnit](https://github.com/xping-dev/sdk-dotnet/tree/main/samples/SampleApp.XUnit) (v2), + [samples/SampleApp.XUnitV3](https://github.com/xping-dev/sdk-dotnet/tree/main/samples/SampleApp.XUnitV3) (v3) diff --git a/sdk/getting-started/toc.yml b/sdk/getting-started/toc.yml new file mode 100644 index 0000000..6f5cc1b --- /dev/null +++ b/sdk/getting-started/toc.yml @@ -0,0 +1,10 @@ +- name: Run without an account + href: local-first.md +- name: "Quick start: NUnit" + href: quickstart-nunit.md +- name: "Quick start: xUnit (v2 and v3)" + href: quickstart-xunit.md +- name: "Quick start: MSTest" + href: quickstart-mstest.md +- name: Set up CI + href: ci-cd-setup.md diff --git a/sdk/index.md b/sdk/index.md index 9ba9c03..c469b34 100644 --- a/sdk/index.md +++ b/sdk/index.md @@ -1,4 +1,535 @@ -# Xping SDK for .NET +--- +uid: index +title: Xping for .NET +--- -> Moved from xping-dev/sdk-dotnet `docs/` (TODO: see "docs.xping.io switch" in the xping-dev/xping migration plan). -> The SDK is an optional, richer input: retries, environment, assertion counts and local runs. +# Xping for .NET + +> [!NOTE] +> This page describes the **Xping SDK for .NET, 1.0.0-rc series**. The SDK can upload to Xping Cloud, and these pages refer to the 1.0.0-rc `xping report` CLI. The Xping CLI 2.x is a different tool: it does not use Xping Cloud and has no `report` command. See the [Xping overview](../index.md). + +This page is for .NET developers who want to know which of their tests they can trust. It explains +what Xping records, how to start without an account, and what Xping Cloud adds. + +Xping records every `dotnet test` run, including the runs on your own machine. With that history, +you can tell a flaky test from a broken one. + +> Recording and local reports are **free**. They need **no account** and make **no network calls**. + +--- + +## Why history matters + +A single test run cannot tell a flaky test from a real failure. Both look the same: one red result. + +When you, or a coding agent, fix a test from one red run, the usual fixes hide the problem: + +| The fix | The result | +| ------- | ---------- | +| Loosen the assertion | The test runs, but it does not check the thing that broke. | +| Add a retry | A real failure that you can reproduce passes on the third attempt. | +| Increase the timeout | The race condition is still there. It happens less often, so it is harder to find in CI. | +| Move the test into its own `[Collection]` | The tests run one after another. The shared-state bug is still there, and every build is slower. | +| Mock the dependency that failed | The test always passes, because it does not run the code that broke. | + +Each of these fixes makes sense when you have only one run. Xping keeps the history of every run, +so you can decide from many runs instead. Your test code does not change. + +--- + +## What is Xping? + +**Xping SDK**: a library that connects to your test framework (NUnit, xUnit v2 and v3, MSTest) +and records each test execution: the outcome, the duration and the environment. The packages target +`netstandard2.0`. They run on .NET Framework 4.6.2 or later and on .NET 8 or later. + +**Xping CLI**: the `xping` .NET tool. It reads the recorded history and reports which tests +behaved consistently and which did not. It writes text for you and JSON for scripts and agents. +It needs the .NET 10 runtime. + +**Xping Cloud**: the hosted service at [app.xping.io](https://app.xping.io). It combines the +history from every machine, branch and CI job. It gives each test a confidence score, says how +much evidence stands behind the score, detects flaky tests and their likely cause, shows trends, +and comments on pull requests in GitHub, GitLab and Azure DevOps. Access is by invitation. + +The SDK writes the history and the CLI reads it, so a local report needs both. Xping Cloud is +optional. + +--- + +## Local and Xping Cloud + +> [!NOTE] +> Xping Cloud only. The Xping CLI 2.x does not use Xping Cloud. + +| | **Local** | **Xping Cloud** | +| -------------- | --------- | --------------- | +| **Setup** | SDK package and CLI tool | Also an API key with the Upload scope | +| **Account** | Not needed | Needed (by invitation) | +| **Your data** | Stays in `.xping/` in your repository | Uploaded to Xping Cloud | +| **History** | Your machine, your runs | Every machine and branch, CI included | +| **You get** | Observations and evidence from local runs | Confidence scores, evidence levels, flaky detection, trends, PR comments | + +The local CLI reports **what it observed**. It does not give a test a score, and it does not name +a cause. A few runs on one machine are not enough evidence for that. Xping Cloud scores tests, +because it has the history of many machines, branches and CI jobs. + +| | Local | Xping Cloud | +| -------------------------------------- | :---: | :---: | +| Pass and fail history, run by run | ✓ | ✓ | +| Tests that pass and fail inconsistently | ✓ | ✓ | +| Tests that fail in every run | ✓ | ✓ | +| Duration and environment of each run | ✓ | ✓ | +| JSON output for agents and scripts | ✓ | ✓ | +| Confidence score per test | — | ✓ | +| Effective sample size (ESS) and evidence level | — | ✓ | +| Flaky verdict and cause category | — | ✓ | +| Reliability trends | — | ✓ | +| Comparison across environments | — | ✓ | +| History from CI, branches and teammates | — | ✓ | +| Pull request comments | — | ✓ | + +**Start locally.** Nothing leaves your machine. You can add an API key later without changing +your test code. + +--- + +## Quick start + +### 1. Install the SDK and the CLI + +> [!NOTE] +> This describes the 1.0.0-rc `xping` CLI. The Xping CLI 2.x is a different tool and has no `report`, `where`, `clear` or `login` commands. + +```bash +dotnet add package Xping.Sdk.XUnit --prerelease # xUnit v2. Or Xping.Sdk.XUnit.V3, Xping.Sdk.NUnit, Xping.Sdk.MSTest +dotnet tool install -g Xping.Cli --prerelease # adds the xping command to your PATH +``` + +> All Xping packages are prereleases, so each install command needs `--prerelease`. +> The CLI needs the .NET 10 SDK or runtime. Your test projects can target .NET Framework 4.6.2 or +> later, or .NET 8 or later. The MSTest adapter needs MSTest 3.8 or later. + +### 2. Turn on tracking + +# [xUnit](#tab/xunit) + +Add one line to `AssemblyInfo.cs`. The line depends on the xUnit package that your project +references: + +```csharp +[assembly: TestFramework("Xping.Sdk.XUnit.XpingTestFramework", "Xping.Sdk.XUnit")] // xunit (v2): Xping.Sdk.XUnit +// [assembly: TestFramework(typeof(Xping.Sdk.XUnit.V3.XpingTestFramework))] // xunit.v3: Xping.Sdk.XUnit.V3 +``` + +[Quick start: xUnit →](getting-started/quickstart-xunit.md) + +# [NUnit](#tab/nunit) + +Add one file. It tracks every test in the assembly, and its setup fixture starts and ends the Xping +run: + +```csharp +using System.Threading.Tasks; +using NUnit.Framework; +using Xping.Sdk.NUnit; + +[assembly: XpingTrack] + +[SetUpFixture] +public class XpingSetup +{ + [OneTimeSetUp] + public void BeforeAllTests() => XpingContext.Initialize(); + + [OneTimeTearDown] + public async Task AfterAllTests() => await XpingContext.FinalizeAndShutdownAsync(); +} +``` + +Keep the `[OneTimeTearDown]` method. The SDK writes the run to the local store when it ends, +and without this method the run never ends. + +[Quick start: NUnit →](getting-started/quickstart-nunit.md) + +# [MSTest](#tab/mstest) + +Add one class that starts and ends the run, and make your test classes inherit from +`XpingTestBase`: + +```csharp +using System.Threading.Tasks; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Xping.Sdk.MSTest; + +[TestClass] +public static class XpingSetup +{ + [AssemblyInitialize] + public static void AssemblyInit(TestContext context) => XpingContext.Initialize(); + + [AssemblyCleanup] + public static async Task AssemblyCleanup() => await XpingContext.FinalizeAndShutdownAsync(); +} + +[TestClass] +public class MyTests : XpingTestBase { } +``` + +The `[AssemblyCleanup]` method lets the upload to Xping Cloud finish before the test process +exits. + +[Quick start: MSTest →](getting-started/quickstart-mstest.md) + +*** + +### 3. Run your tests several times + +```bash +dotnet test +``` + +Each run adds to the history. One run says nothing about reliability, so `xping report` shows no +findings until it has at least **5 runs**, and each test needs at least 5 runs of its own. Run your +tests as you normally do. The runs on your own machine count too. + +### 4. Read the report + +> [!NOTE] +> This describes the 1.0.0-rc `xping` CLI. The Xping CLI 2.x is a different tool and has no `report`, `where`, `clear` or `login` commands. + +```bash +xping report +``` + + +```` +Xping · SampleApp.MSTest · 9 runs · 2026-08-20 07:52 → 09:02 · main@bdbafba +17 tests · 14 healthy · 3 flagged + +``` +NEEDS ATTENTION (4 high) most severe first +──────────────────────────────────────────────────────────────────────── + +1. HIGH flaky + SampleTests.FlakyTest_PassesOnRetry + failed 9 of 18 executions (50%) in 9 of 9 runs, 1 failure mode + evidence adequate | -env-cluster | f_2b84a621 | ...SampleTests.cs:96 + +2. HIGH masked by retry same test as #1 + SampleTests.FlakyTest_PassesOnRetry + passed on retry 9 times in 9 of 9 runs, up to attempt 2 + evidence adequate | -env | f_e98db1e6 | .../SampleTests.cs:96 + +3. HIGH always failing + SampleTests.ThrowingTestIsTracked + failed 9 of 9 executions (100%), one failure mode: + System.InvalidOperationException + evidence sparse | -env-cluster | f_c1774d82 | .../SampleTests.cs:65 + +4. HIGH flaky + SampleTests.FlakyTest_RaceCondition_FailsIntermittently + failed 4 of 9 executions (44.4%) in 4 of 9 runs, 1 failure mode + evidence sparse | -env-cluster | f_d24c5aa9 | .../SampleTests.cs:118 +``` + +rates: the marker on each finding says which runs its percentage was +counted out of; compare two only where the markers match. +https://docs.xping.io/cli/reading-the-report.html#the-population-marker + +Detail of row 1: xping report --id f_2b84a621 --assembly SampleApp.MSTest +```` + +No API key, no account and no network calls. The history stays in `.xping/` on your machine. + +[Run without an account →](getting-started/local-first.md) + +--- + +## CLI commands + +> [!NOTE] +> This describes the 1.0.0-rc `xping` CLI. The Xping CLI 2.x is a different tool and has no `report`, `where`, `clear` or `login` commands. + +```bash +xping report # findings from recent runs +xping report --format json # versioned JSON, for a script or an agent +xping report --summary # one line per assembly, for a chat message or a CI step title +xping report --fail-on high # exit with code 1 when any assembly has a high finding +xping report --runs 50 # a larger window (or --since ) +xping report --assembly Shop.Tests --kind flaky # one assembly, one or more finding kinds +xping where # where the local runs are stored +xping clear # delete recorded runs +xping login # sign in to Xping Cloud from your browser +xping logout # sign out and remove the stored sign-in +xping auth status # which Xping Cloud credential the CLI uses +``` + +With several test projects, `xping report` prints one row per assembly. Add `--assembly` to see +the findings of one assembly. When the store holds several assemblies, `--kind`, `--top` and `--all` need `--assembly`. See +Scoping. + +For every flag, finding kind and the JSON schema, see the +Command reference. + +--- + +## Use with a coding agent + +> [!NOTE] +> This describes the 1.0.0-rc `xping` CLI. The Xping CLI 2.x is a different tool and has no `report`, `where`, `clear` or `login` commands. + +`xping report --format json` returns versioned JSON: the findings, their evidence levels, the run +counts and the failure modes. An agent can use it like this: + +1. **The agent finds a failing test.** Before it changes the assertion, it asks Xping for the + history of that test. +2. **Xping returns the evidence.** For example: failed in 34 of 34 runs, one failure mode, + evidence robust. Or: failed in 4 of 40 runs, three failure modes. +3. **The agent decides.** A test that fails the same way in every run probably found a real bug, + so the agent fixes the code and keeps the test. One local failure after a long series of passes + may be noise, so the agent runs the test again before it changes anything. + +The report gives evidence, not a verdict. The agent still makes the decision. + +--- + +## Connect to Xping Cloud + +> [!NOTE] +> Xping Cloud only. The Xping CLI 2.x does not use Xping Cloud. + +Set one environment variable. Your packages and test code stay the same. + +```bash +export XPING_APIKEY="your-api-key" +``` + +Create the key in Xping Cloud under **Settings → API keys**. Create it with only the Upload scope. See API keys. +Set it as an environment variable on each machine and in CI. Never commit it. + +Each test assembly becomes its own Xping Cloud project. Xping Cloud creates the project the first +time the tests upload. To send several assemblies to one project, set `XPING_PROJECTID` (or +`ProjectId` in `appsettings.json`). See [ProjectId](configuration/configuration-reference.md#projectid). + +The SDK uploads the results while the tests run and at the end of each run. It also keeps writing +the local store. Xping Cloud combines the runs from every machine, branch and CI job, so a test +that fails only on a teammate's laptop is part of the history. + +> **Xping Cloud access is by invitation.** [Request access](https://xping.io/contact?pilot=True). +> The local report stays free and needs no account. + +To see Xping Cloud data in your terminal, sign in once on each machine: + +```bash +xping login +xping report +``` + +`xping report` then adds the Xping Cloud confidence score to the rows it prints. A key with only +the Upload scope cannot read Xping Cloud data, so the CLI uses your sign-in instead. See +`xping login` and +Cloud data. + +To set up CI, see [Set up CI](getting-started/ci-cd-setup.md). + +--- + +## How it works + +``` + Your test project (xUnit · NUnit · MSTest) + │ + ▼ + Xping.Sdk. adapter + │ + ▼ + Xping.Sdk.Core + recording · environment detection + │ + ┌─────────────┴──────────────┐ + │ always │ with XPING_APIKEY + ▼ ▼ + .xping/ (local store) Xping Cloud + │ │ scores · flaky detection · trends + │ ├────────────▶ app.xping.io + ▼ ▼ + └───────▶ xping report ◀─────┘ (after xping login) + │ + ┌─────────────┴─────────────┐ + ▼ ▼ + you, in a terminal your agent, with --format json +``` + +Each adapter connects to the execution pipeline of its framework and passes the results to +`Xping.Sdk.Core`. Core records the results, detects the environment, writes the local store and +uploads to Xping Cloud. + +- **Only the CLI reads the local store.** Use `xping report` to read it, not the files in + `.xping/`. See [Local store](configuration/local-store.md). +- **Not everyone uses a terminal.** People who do not run the tests, such as QA, team leads and + product managers, can open [app.xping.io](https://app.xping.io) and see the same history. + +--- + +## Configuration + +You can configure the SDK with **environment variables**, **appsettings.json** or **code**. +`XPING_*` environment variables win over the other sources. Keep the API key in an environment +variable, so it never reaches source control. + +```bash +# Xping Cloud +export XPING_APIKEY="your-api-key" +export XPING_PROJECTID="your-project-id" # optional: one project for every test assembly +export XPING_BATCHSIZE="100" # optional: results per upload batch +export XPING_UPLOADSTACKTRACES="true" # optional: also upload the stack trace text (off by default) + +# Local and Xping Cloud +export XPING_ENABLED="true" +export XPING_LOGLEVEL="Information" +``` + +Without an API key from any source, and without StrictMode, the SDK writes to `.xping/` and makes +no network calls. For every option, +see the [Configuration reference](configuration/configuration-reference.md). + +--- + +## Your data + +For each test execution, Xping records the test's name, outcome, duration and times, the error +message and stack trace of a failure, its categories and traits, and its source file and line. For +each run, it records the machine, the operating system, the .NET runtime, the time zone, and the CI +build, branch, commit and the person behind the run. Outside CI, it records the branch and commit of +your local git repository. + +**Error text**: Xping stores the error message word for word, and uploads it word for word to +Xping Cloud. It contains whatever your test or your code put in it. Xping does not read your source +code. + +[Data Xping collects](configuration/collected-data.md) lists every field, the personal data among them, and the switch for +each one. The CI email and the local git author are off by default. + +**Locally**, the history stays in `.xping/`. The folder contains its own `.gitignore`, so git +ignores it. To delete the history, run `xping clear`. + +**In Xping Cloud**, the SDK uploads over HTTPS. It does not upload the stack trace text unless you +set [UploadStackTraces](configuration/configuration-reference.md#uploadstacktraces). Xping Cloud +always receives a hash of the methods in the trace, without file paths or line numbers. The local +store keeps the full trace. How long Xping Cloud keeps your data depends on your plan; see +[xping.io/pricing](https://xping.io/pricing). + +--- + +## What Xping helps you find + +Patterns that show up in the run history: + +- **Intermittent failures**: the test passes and fails with no code change between runs. +- **Parallel runs**: the test fails only when it runs at the same time as other tests. +- **Shared state**: tests that fail together because they share a fixture or a resource. +- **Time-based failures**: failures at one local time of day, at weekends, or around a + daylight-saving change. +- **Random data**: random inputs that sometimes hit an edge case. + +The local report shows the behaviour. Xping Cloud also gives a cause category. For worked +examples, see Flaky patterns and fixes. + +> Xping Cloud gives each test a confidence score from 0 to 1, based on its run history. +> See Confidence scores. + +--- + +## Documentation structure + +#### [Get started](getting-started/local-first.md) + +- [Run without an account](getting-started/local-first.md): the local-only path, from start to finish +- [Quick start: NUnit](getting-started/quickstart-nunit.md) +- [Quick start: xUnit (v2 and v3)](getting-started/quickstart-xunit.md) +- [Quick start: MSTest](getting-started/quickstart-mstest.md) +- [Set up CI](getting-started/ci-cd-setup.md) + +#### [Configure](configuration/configuration-reference.md) + +- [Configuration reference](configuration/configuration-reference.md): every option, from all three sources +- [Local store](configuration/local-store.md): what `.xping/` holds and how it is managed + +#### CLI + +- Command reference: `report`, `where`, `clear`, `login`, the flags and the JSON output + +#### Xping Cloud + +- Connect to Xping Cloud: API keys, roles and repository connections +- Confidence scores +- Session reliability score +- Reading the PR comment +- Plans and retention +- Read API + +#### Flaky tests + +- Finding flaky tests +- Flaky patterns and fixes + +#### [Performance](performance/performance.md) + +- [Performance](performance/performance.md) + +#### [Troubleshooting](troubleshooting/common-issues.md) + +- [Common issues](troubleshooting/common-issues.md) +- [Debugging](troubleshooting/debugging.md) +- [Known limitations](troubleshooting/known-limitations.md): what Xping does not do + + + +--- + +## Sample projects + +A runnable example for each framework: + +- [NUnit sample](https://github.com/xping-dev/sdk-dotnet/tree/main/samples/SampleApp.NUnit) +- [xUnit v2 sample](https://github.com/xping-dev/sdk-dotnet/tree/main/samples/SampleApp.XUnit) +- [xUnit v3 sample](https://github.com/xping-dev/sdk-dotnet/tree/main/samples/SampleApp.XUnitV3) +- [MSTest sample](https://github.com/xping-dev/sdk-dotnet/tree/main/samples/SampleApp.MSTest) + +--- + +## Roadmap + +Planned work is tracked in [Milestones](https://github.com/xping-dev/sdk-dotnet/milestones). It +includes: + +- Agent integration: a Claude skill and an MCP server over `xping report` +- Quarantine: mark known flaky tests so that CI does not fail on them +- `xping watch`: show new runs as they finish, next to `dotnet watch test` + +--- + +## Support and community + +- [GitHub Discussions](https://github.com/xping-dev/sdk-dotnet/discussions): questions and ideas +- [Issue tracker](https://github.com/xping-dev/sdk-dotnet/issues): bugs and feature requests +- [support@xping.io](mailto:support@xping.io): direct support +- [Xping Cloud](https://app.xping.io): your scored test history + +--- + +## Contributing + +The Xping SDK is open source under the MIT license. Contributions are welcome. + +- [Contributing guide](https://github.com/xping-dev/sdk-dotnet/blob/main/CONTRIBUTING.md) +- [Code of conduct](https://github.com/xping-dev/sdk-dotnet/blob/main/CODE_OF_CONDUCT.md) +- [Open issues](https://github.com/xping-dev/sdk-dotnet/issues) +- [MIT license](https://github.com/xping-dev/sdk-dotnet/blob/main/LICENSE) + +--- + +**Find out which of your tests you can trust.** +[Start locally, with no account →](getting-started/local-first.md) diff --git a/sdk/performance/performance.md b/sdk/performance/performance.md new file mode 100644 index 0000000..3ed0773 --- /dev/null +++ b/sdk/performance/performance.md @@ -0,0 +1,164 @@ +--- +uid: performance +title: Performance +--- + +# Performance + +> [!NOTE] +> This page describes the **Xping SDK for .NET, 1.0.0-rc series**. The SDK can upload to Xping Cloud, and these pages refer to the 1.0.0-rc `xping report` CLI. The Xping CLI 2.x is a different tool: it does not use Xping Cloud and has no `report` command. See the [Xping overview](../../index.md). + +This page describes the work the SDK does during a test run, and when it does it. It also lists the +settings that change that work, and how to find out whether the SDK slows a run down. + +The page gives no timings. They depend on the machine, the framework and the suite. To measure the +SDK yourself, see [Measure the SDK](#measure-the-sdk). + +--- + +## The work for each test + +When a test ends, the adapter builds one record of it: the test's identity, its outcome and +duration, its error text and stack trace when it failed, its retry attempt, and how many tests ran +at the same time. The SDK adds the record to an in-memory queue. + +This step does no file or network I/O, and it does not wait for other work. + +The SDK does not sample. It records every test that runs. + +--- + +## The work at other times + +| When | `LocalOnly` mode | `Cloud` mode | +|---|---|---| +| The run starts | The SDK reads the configuration and detects the CI, the branch and the environment, once. | The same. | +| During the run | Nothing. | The SDK uploads a batch when [`BatchSize`](../configuration/configuration-reference.md#batchsize) records are waiting, and when the [`FlushInterval`](../configuration/configuration-reference.md#flushinterval) timer fires. | +| The run ends | The SDK writes the run to the [local store](../configuration/local-store.md), and removes old runs. | The SDK writes the run to the local store first. Then it uploads the records that are left, and a final upload that closes the run. | + +`Auto`, the default mode, is `Cloud` with an API key or with `StrictMode` on, and `LocalOnly` +otherwise. See +[Mode](../configuration/configuration-reference.md#mode). + +### Uploads during the run + +> [!NOTE] +> Xping Cloud only. The Xping CLI 2.x does not use Xping Cloud. + +In `Cloud` mode, a batch upload starts on the thread of the test that filled the batch. That thread +takes the batch from the queue, serializes it to JSON and compresses it, before the request goes over +the network. The test thread does not wait for the network. The timer upload runs on a thread-pool +thread. + +Only one upload runs at a time. An upload that is due while another one runs waits for it. + +### The end of the run + +The run ends after the last test. The SDK writes the local store before any upload, so the run +is on disk even when the upload fails or the process is stopped. + +Each upload, with its retries and the delays between them, stops after twice +[`UploadTimeout`](../configuration/configuration-reference.md#uploadtimeout): 60 seconds by default. +At the end of the run, the SDK first waits for an upload that is still running. Then it uploads +the records that are left, in batches. When one of these batches fails, it sends no more of them, +and it still sends the final upload. With a failing endpoint, the end of the run can therefore wait +for up to three uploads. A failing upload does not fail the run, unless +[`StrictMode`](../configuration/configuration-reference.md#strictmode) is on. + +During the run, a failed upload does not stop the next one. Each batch tries again, until the +circuit breaker pauses uploads. See [`MaxRetries`](../configuration/configuration-reference.md#maxretries). + +--- + +## Memory + +The SDK keeps every record of the run in memory until the run ends, in every mode except +`Disabled`. It needs them all to write the run to the local store at the end. An upload during the +run does not free them. + +Memory therefore grows with the size of the run: the number of test [executions](../configuration/collected-data.md#each-execution), retries included, +and the length of their error messages and stack traces. A run with many failures and deep stacks +uses more. `BatchSize` does not limit it. + +--- + +## Settings that change the work + +| Setting | Effect | +|---|---| +| [`Mode`](../configuration/configuration-reference.md#mode) | `LocalOnly` makes no uploads. `Disabled` records nothing. | +| [`Enabled`](../configuration/configuration-reference.md#enabled) | `false` records nothing, the same as `Disabled`. | +| [`BatchSize`](../configuration/configuration-reference.md#batchsize) | `Cloud` only. A larger batch makes fewer uploads, and each one serializes more records on one test thread. | +| [`FlushInterval`](../configuration/configuration-reference.md#flushinterval) | `Cloud` only. The time between timer uploads. | +| [`EnableCompression`](../configuration/configuration-reference.md#enablecompression) | Compresses uploads larger than 1 KB. It costs CPU and saves bandwidth. | +| [`UploadStackTraces`](../configuration/configuration-reference.md#uploadstacktraces) | Off by default. On, it adds stack trace text to the uploads. The local store keeps the traces either way. | +| [`UploadTimeout`](../configuration/configuration-reference.md#uploadtimeout) | Sets the longest wait for one upload: twice this value. | +| [`MaxRetries`](../configuration/configuration-reference.md#maxretries), [`RetryDelay`](../configuration/configuration-reference.md#retrydelay) | How often, and after how long, a failed upload is retried, within the limit above. | + +--- + +## Find out whether the SDK slows a run + +1. **Measure the run without the SDK.** `XPING_ENABLED=false` turns the SDK off for one run: + + ```bash + XPING_ENABLED=false dotnet test -c Release + dotnet test -c Release + ``` + + In PowerShell: + + ```powershell + $env:XPING_ENABLED = "false"; dotnet test -c Release + Remove-Item Env:XPING_ENABLED; dotnet test -c Release + ``` + + Compare the two durations over several runs, because test durations vary from run to run. + +2. **Check the end of the run.** A long pause after the last test is usually an upload. The SDK logs + each upload and its result. Set + [`LogLevel`](../configuration/configuration-reference.md#loglevel) to `Debug` for more detail. For + upload errors, see [Common issues](../troubleshooting/common-issues.md). + +3. **Profile the test process.** `dotnet-counters` shows memory and GC activity while the tests run. + `dotnet-trace` records where the time goes. Start the tool while the tests run, and name the + process that runs them: + + - On vstest (`dotnet test` without Microsoft.Testing.Platform), the process is `testhost`. + - On Microsoft.Testing.Platform, the tests run in the test project's own executable, such as + `MyApp.Tests`. + + ```bash + dotnet tool install -g dotnet-counters + dotnet tool install -g dotnet-trace + + dotnet-counters monitor --name testhost + dotnet-trace collect --name testhost + ``` + + For a short run that ends before you can attach, start the test executable under the tool + instead: `dotnet-trace collect -- ./bin/Release/net10.0/MyApp.Tests`. + + Open the `.nettrace` file in Visual Studio or PerfView, or convert it with + `dotnet-trace convert --format speedscope`. Look for `Xping` frames. + +When you find SDK work that slows a run, open an issue at +[github.com/xping-dev/sdk-dotnet](https://github.com/xping-dev/sdk-dotnet/issues) with the trace and +the run's size. + +--- + +## Measure the SDK + +The repository has a BenchmarkDotNet project for the SDK's own code paths: recording, batching, +serialization, configuration, environment detection and the local store. It measures on your +machine. See +[the benchmarks README](https://github.com/xping-dev/sdk-dotnet/blob/main/tests/Xping.Sdk.Benchmarks/README.md). + +--- + +## See also + +- [Configuration reference](../configuration/configuration-reference.md) +- [Local store](../configuration/local-store.md) +- [Common issues](../troubleshooting/common-issues.md) diff --git a/sdk/performance/toc.yml b/sdk/performance/toc.yml new file mode 100644 index 0000000..8c7e4bb --- /dev/null +++ b/sdk/performance/toc.yml @@ -0,0 +1,2 @@ +- name: Performance + href: performance.md diff --git a/sdk/toc.yml b/sdk/toc.yml index 1ba183c..ea8cc7a 100644 --- a/sdk/toc.yml +++ b/sdk/toc.yml @@ -1,2 +1,10 @@ - name: Overview href: index.md +- name: Get started + href: getting-started/ +- name: Configure + href: configuration/ +- name: Performance + href: performance/ +- name: Troubleshooting + href: troubleshooting/ diff --git a/sdk/troubleshooting/common-issues.md b/sdk/troubleshooting/common-issues.md new file mode 100644 index 0000000..2fa82fc --- /dev/null +++ b/sdk/troubleshooting/common-issues.md @@ -0,0 +1,560 @@ +--- +uid: troubleshooting-common-issues +title: Common issues +--- + +# Common issues + +> [!NOTE] +> This page describes the **Xping SDK for .NET, 1.0.0-rc series**. The SDK can upload to Xping Cloud, and these pages refer to the 1.0.0-rc `xping report` CLI. The Xping CLI 2.x is a different tool: it does not use Xping Cloud and has no `report` command. See the [Xping overview](../../index.md). + +This page lists the problems developers run into most often with the SDK and the CLI, and how to +fix them. Most fixes start with +the SDK's own output. To see it, and to read each line, see [Debugging](debugging.md). + +--- + +## Tests don't appear in Xping Cloud + +> [!NOTE] +> Xping Cloud only. The Xping CLI 2.x does not use Xping Cloud. + +Read the SDK's start line first. See [The start line](debugging.md#the-start-line). + +### The SDK runs in local-only mode + +``` +[Xping 13:14:41 INF] Initialized in local-only mode. SessionId: "…", Environment: Default. No API key configured - results stay on this machine. +``` + +The SDK found no API key, so it keeps the results on this machine and uploads nothing. This is not an +error: `xping report` reads these runs. To upload, set the key in the environment that runs the +tests: + +```bash +export XPING_APIKEY="" +``` + +When the line says `Mode is set to LocalOnly` instead, the +[`Mode`](../configuration/configuration-reference.md#mode) setting keeps the SDK local. Remove it, or +set it to `Cloud`. + +In Xping Cloud, an Owner or an Admin creates the key in **Settings → API keys**. Create it with only +the Upload scope. See API keys. + +### The SDK is off + +``` +[Xping 13:14:41 WRN] SDK is disabled via configuration (Enabled=false). Tests will run without observability tracking. +``` + +[`Enabled`](../configuration/configuration-reference.md#enabled) is `false`, or `Mode` is `Disabled` +(the line then says `Mode=Disabled`). Remove the setting, for example `XPING_ENABLED`. + +### A setting is invalid + +``` +[Xping 10:43:01 ERR] Configuration validation failed: ApiKey is required in Cloud mode. SDK disabled - tests will run without observability tracking. +``` + +The SDK records nothing. The line names each setting that breaks a rule. See +[Validation rules](../configuration/configuration-reference.md#validation-rules). + +### The run never ends + +The SDK sends the last results when the run ends. On NUnit and MSTest, your own code ends it: + +- **NUnit:** the `[OneTimeTearDown]` method of a `[SetUpFixture]` must call + `XpingContext.FinalizeAndShutdownAsync()`. See the + [NUnit quickstart](../getting-started/quickstart-nunit.md). +- **MSTest:** an `[AssemblyCleanup]` method in the test assembly must call + `XpingContext.FinalizeAndShutdownAsync()`. See the + [MSTest quickstart](../getting-started/quickstart-mstest.md). Without it, the SDK ends the run + as the process exits, and on vstest the upload is usually lost. See + [Known limitations](known-limitations.md#mstest-a-run-finalized-by-the-process-exit-safety-net-loses-its-upload-on-vstest). + +xUnit v2 and v3 end the run themselves, through the `[assembly: TestFramework(...)]` attribute. +See the [xUnit quickstart](../getting-started/quickstart-xunit.md). + +### The upload failed + +The SDK logs an upload error, and the tests pass or fail as usual. Look for `ERR` lines. See +[Upload errors](#upload-errors) and [Network errors](#network-errors). + +--- + +## Upload errors + +> [!NOTE] +> Xping Cloud only. The Xping CLI 2.x does not use Xping Cloud. + +When Xping Cloud rejects an upload, the SDK logs one line in this form: + +``` + (HTTP ) for []: Action: +``` + +For example: + +``` +[Xping 13:16:24 ERR] Authentication failed (HTTP 401) for https://upload.xping.io/v1 [Error.ApiKey.InvalidApiKey]: The provided API key is not recognized. Action: Verify the ApiKey value matches a key issued for this workspace at https://upload.xping.io/v1 +``` + +- The `` in brackets is Xping Cloud's error code. It says what went wrong more exactly than the + status code. +- The `` is Xping Cloud's explanation, here `The provided API key is not recognized.` For a + plan limit, it says which limit the run reached. +- The `Action:` is what the SDK suggests for that code. + +When the same error repeats in the run, the SDK prints a short line, such as +`Same HTTP 401 error (2nd occurrence, batch size: 0)`. + +The SDK retries a 5xx response and a 429. It does not retry any other 4xx response. + +### The API key + +> [!NOTE] +> Xping Cloud only. The Xping CLI 2.x does not use Xping Cloud. + +| Code | Action the SDK prints | +|---|---| +| `Error.ApiKey.MissingApiKey` | Set the ApiKey in your Xping configuration; it is sent as the X-API-Key header | +| `Error.ApiKey.InvalidApiKey` | Verify the ApiKey value matches a key issued for this workspace at `` | +| `Error.ApiKey.ExpiredApiKey` | The key has passed its expiry date - issue a new API key and update your configuration | +| `Error.ApiKey.RevokedApiKey` | This key was revoked - issue a new API key and update your configuration | + +These come with HTTP 401 (`Authentication failed`). Check that `XPING_APIKEY` holds the whole key, +with no space or line break. To issue a new key, see API keys. + +### What the key may do + +| Code | Action the SDK prints | +|---|---| +| `Error.ApiKey.InsufficientScope` | Grant the API key the UPLOAD scope, or use a key that already has it | +| `Error.ApiKey.IpNotAllowed` | The key restricts client IP addresses - add this runner's public IP to the key's allow list | +| `Authorization.InsufficientAccess` | This endpoint requires an API key principal with upload access | + +These come with HTTP 403 (`Authorization failed`). A key works only from its **allowed addresses**, +when the key has any. A CI agent's public address can change between runs. + +### Plan and usage limits + +> [!NOTE] +> Xping Cloud only. The Xping CLI 2.x does not use Xping Cloud. + +| Code | Action the SDK prints | +|---|---| +| `Error.Subscription.ProjectLimitReached` | This run names a project the workspace does not have yet and the project limit is reached - upgrade the plan, or set ProjectId to report into an existing project. A solution-wide run reports one project per test assembly, so it can request several at once | +| `Error.Subscription.TestRunLimitReached`, `Error.Subscription.UsageLimitExceeded` | Upgrade the plan to continue ingesting test results this billing period | +| `Error.Billing.PaymentFailed`, `Error.Billing.CardDeclined`, `Error.Billing.InsufficientFunds` | Update the workspace payment method to restore uploads | +| `Error.ApiKey.UsageLimitReached` | This key reached its configured usage cap - raise the cap or use a different key | +| `Error.ApiKey.RateLimitExceeded` | Back off and retry later, or reduce upload frequency by batching more executions per upload | + +`ProjectLimitReached` often comes from a solution-wide `dotnet test`. Each test assembly reports into +its own project, so one run can ask for several new projects. To send them all to one project, set +[`ProjectId`](../configuration/configuration-reference.md#projectid). See +[My tests created several projects](#my-tests-created-several-projects). + +For a rate limit, a larger [`BatchSize`](../configuration/configuration-reference.md#batchsize) makes +fewer uploads. For what each plan includes, see +Plans and retention. + +### The project + +> [!NOTE] +> Xping Cloud only. The Xping CLI 2.x does not use Xping Cloud. + +| Code | Action the SDK prints | +|---|---| +| `Error.Project.ProjectDisabled` | The target project is disabled and rejects uploads - re-enable it in Xping Cloud | + +### The request + +| Code | Action the SDK prints | +|---|---| +| `Error.Uploads.MissingProjectKey` | The upload named no project: no ProjectId is configured and no test assembly could be resolved for this session. Set ProjectId to pin one, or check that your tests report an assembly name | +| `Error.Uploads.BatchSizeExceeded` | Reduce the number of executions per upload - the server accepts at most 1000 per batch | +| `Error.Uploads.UnrecognizedPayload`, `Error.Uploads.UnrecognizedState` | The server could not read this payload - update Xping.Sdk to a version compatible with the API | +| `Error.Uploads.MissingSessionId` | The upload was sent without a session id - this indicates an SDK defect, please report it | + +### A response with no error code + +> [!NOTE] +> Xping Cloud only. The Xping CLI 2.x does not use Xping Cloud. + +A proxy or a load balancer can answer instead of Xping Cloud. The response then has no Xping error +code, and the SDK suggests an action from the status code: + +| Status | Category | Action the SDK prints | +|---|---|---| +| 400, 422 | Upload rejected | Check the upload configuration (ApiEndpoint) and the SDK version | +| 401 | Authentication failed | Verify the ApiKey is set and valid for `` | +| 402 | Subscription limit reached | Review the workspace subscription - a plan limit or billing issue is blocking uploads | +| 403 | Authorization failed | Verify the API key has the UPLOAD scope and that this client's IP is permitted | +| 404 | API endpoint not found | Verify the ApiEndpoint configuration matches your deployment | +| 409 | Upload conflicts with the current project state | The target project rejected the upload in its current state - check it in Xping Cloud | +| 413 | Payload too large | Reduce the number of executions per upload | +| 429 | Rate limit exceeded | Reduce test execution frequency, or retry after the interval the server indicates | +| 5xx | Server error | Retry later; if this persists, contact support with the receipt of a failing run | + +The `` is then the response body, or `No additional error details provided` when it is +empty. A 404 often means that [`ApiEndpoint`](../configuration/configuration-reference.md#apiendpoint) +is wrong. Its default is `https://upload.xping.io/v1`. + +--- + +## Network errors + +When the SDK cannot reach the endpoint, or the request takes too long, it logs one of these: + +| Message | Meaning | +|---|---| +| `Network error occurred → HttpRequestException: ` | The connection failed, for example `Connection refused` or a DNS error. | +| `Request timeout after 30s` | One attempt took longer than [`UploadTimeout`](../configuration/configuration-reference.md#uploadtimeout). | +| `Upload timed out after 60s` | The whole upload, with its retries, took longer than twice `UploadTimeout`. | +| `Circuit breaker is open: Too many consecutive failures` | Uploads are paused. See [Uploads pause for 30 seconds](#uploads-pause-for-30-seconds). | + +The SDK retries a network error and a timeout, up to +[`MaxRetries`](../configuration/configuration-reference.md#maxretries) times. + +Check that the machine reaches `https://upload.xping.io/v1` over HTTPS on port 443. See +[Check the network](debugging.md#check-the-network). + +### Behind a proxy + +The SDK has no proxy setting of its own. It uses the standard .NET proxy settings: the +`HTTPS_PROXY`, `HTTP_PROXY` and `NO_PROXY` environment variables, and the system proxy settings on +Windows and macOS. Set them in the environment that runs the tests: + +```bash +export HTTPS_PROXY="http://proxy.example.com:8080" +``` + +For a proxy that needs a sign-in, put the user name and password in the URL: +`http://user:password@proxy.example.com:8080`. + +### Slow uploads + +When uploads time out on a slow connection, raise `UploadTimeout`: + +```bash +export XPING_UPLOADTIMEOUT="60" +``` + +Leave [`UploadStackTraces`](../configuration/configuration-reference.md#uploadstacktraces) off, which +is the default, to keep stack trace text out of the uploads. + +### Uploads pause for 30 seconds + +> [!NOTE] +> Xping Cloud only. The Xping CLI 2.x does not use Xping Cloud. + +``` +[Xping 13:20:11 ERR] Circuit breaker is open: Too many consecutive failures → BrokenCircuitException: … +[Xping 13:20:11 WRN] Status: Upload attempts will resume after circuit breaker resets (30 seconds) +``` + +The SDK stops uploading for 30 seconds when, in 30 seconds: + +- there were at least 10 upload attempts, retries included, and +- at least half of them failed with a 5xx response, a network error or a timeout. + +A 4xx response, such as 401, 403 or 429, does not count. While uploads are paused, each upload fails +at once with the message above. After 30 seconds, the SDK tries again. + +The pause means that Xping Cloud or the network failed many times in a short time. Look for the +errors logged before it. + +--- + +## An upload failure fails the run + +**Symptom:** the test run fails at its end with an upload error, although the tests passed. On NUnit +with vstest, `dotnet test` reports the run as aborted: + +``` +The active test run was aborted. Reason: Test host process crashed : … +[Xping] Xping network error in strict mode: HTTP request failed: Connection refused (127.0.0.1:9) +``` + +By default, an upload failure never fails your tests. The SDK retries the upload, logs the error, +and the [local store](../configuration/local-store.md) still gets the run. With [`StrictMode`](../configuration/configuration-reference.md#strictmode) +on (`XPING_STRICTMODE=true`), the same failure fails the run, so a CI pipeline notices that it could +not record its tests. Every test that ran stays in the TRX file and the other reports. + +**Solution:** + +- Fix the cause of the upload failure. The SDK logs it. See [Upload errors](#upload-errors) and + [Network errors](#network-errors). +- For a build with no network, set `XPING_MODE=LocalOnly`. The SDK then keeps the run on the machine + and makes no uploads. Do not just leave the API key unset: with `StrictMode` on, a missing key fails + the run before any test runs. `XPING_ENABLED=false` also turns off the local history. + +--- + +## My tests created several projects + +That is the default. Each test assembly reports into its own project, so a solution-wide +`dotnet test` that covers `Billing.Tests`, `Api.Tests` and `Web.Tests` produces three projects. Xping +Cloud creates each one on its first upload. + +To report them all as one project, pin it: + +```bash +export XPING_PROJECTID="my-app" +``` + +--- + +## The configuration is not loading + +**Symptoms:** the SDK uses its defaults, or ignores an environment variable or `appsettings.json`. +The start line shows what the SDK used. See [Check the configuration](debugging.md#check-the-configuration). + +### Environment variable names + +The SDK's environment variables are `XPING_` with one underscore, then the setting name, such as +`XPING_APIKEY` or `XPING_BATCHSIZE`. They win over every other source, including a configuration +object passed in code. + +`Xping__ApiKey`, with two underscores, is the .NET configuration form. The SDK reads it only when it +starts with `XpingContext.Initialize()`, without a configuration object. Use `XPING_APIKEY`. + +### `appsettings.json` is not read + +- The SDK reads `appsettings.json` only when it starts with `XpingContext.Initialize()`, without a + configuration object. With an object, it reads only `StrictMode` from the file. +- The SDK reads the file from the current directory. Under `dotnet test`, that is the test project's + output folder, so copy the file there: + + ```xml + + + + ``` + +- The SDK also reads `appsettings.{environment}.json`. The environment comes from + `ASPNETCORE_ENVIRONMENT` or `DOTNET_ENVIRONMENT`, and is `Production` when neither is set. +- A file that does not parse stops the SDK from starting. The SDK then prints + `[Xping] SDK initialization failed: …`, and the tests run unrecorded. + +The keys in `appsettings.json` are not case-sensitive: `apikey` and `ApiKey` both work. + +### Durations + +`FlushInterval`, `RetryDelay` and `UploadTimeout` take whole seconds (`30`) or a time with colons +(`00:00:30`). The SDK ignores any other value, keeps the default, and logs a warning: + +``` +FlushInterval '1.5' is not a duration and was ignored. Use whole seconds (30) or a time with colons (00:00:30). +``` + +The warning names the setting as you wrote it, such as `XPING_FLUSHINTERVAL` or +`Xping:FlushInterval`. + +For every setting and its rules, see the +[Configuration reference](../configuration/configuration-reference.md). + +--- + +## CI is not detected + +**Symptoms:** a pipeline run is recorded as local. `IsCIEnvironment` is `false`, and the run has no +build number or branch from the CI. + +The SDK detects the CI from the platform's own environment variables. It needs no setting. It +detects: + +| Platform | Variable it reads | +|---|---| +| GitHub Actions | `GITHUB_ACTIONS=true` | +| Azure Pipelines | `TF_BUILD` | +| Jenkins | `JENKINS_URL` | +| GitLab CI/CD | `GITLAB_CI=true` | +| CircleCI | `CIRCLECI=true` | +| Travis CI | `TRAVIS=true` | +| TeamCity | `TEAMCITY_VERSION` | +| Bitbucket Pipelines | `BITBUCKET_PIPELINE_UUID` | +| AppVeyor | `APPVEYOR=True` | +| Any other CI | `CI=true` or `CI=True` | + +Detection fails only when the test process does not get these variables. This happens most often +when the tests run in a container. Pass the CI's variables into the container. On another CI, set +`CI=true` in the pipeline. + +The environment name `Default` on a CI run is not a symptom. The +[environment name](../configuration/configuration-reference.md#environment) names the deployment +that the tests run against, not the machine. Do not set `XPING_ENVIRONMENT=CI`: it splits each +test's history away from the local runs of the same suite. + +For each platform's setup, see [Set up CI](../getting-started/ci-cd-setup.md). + +--- + +## The API key in CI + +> [!NOTE] +> Xping Cloud only. The Xping CLI 2.x does not use Xping Cloud. + +Store the key as a secret in your CI platform, and pass it to the test step as `XPING_APIKEY`. Do +not put it in `appsettings.json` or in source control. + +```yaml +# GitHub Actions +- name: Run tests + env: + XPING_APIKEY: ${{ secrets.XPING_APIKEY }} + run: dotnet test +``` + +For every platform, see [Set up CI](../getting-started/ci-cd-setup.md). + +--- + +## Flaky tests are not flagged in Xping Cloud + +> [!NOTE] +> Xping Cloud only. The Xping CLI 2.x does not use Xping Cloud. + +Xping Cloud needs at least 10 runs of a test from the last 14 days, and often more, before it can +decide whether the test is flaky. A test needs the same identity in every run, so a renamed test +starts a new history. See +When Cloud can decide. + +To find flaky tests from the runs on your machine, run `xping report`. See +Finding flaky tests. + +--- + +## The run is slow, or uses a lot of memory + +To find out whether the SDK slows the run, run once with `XPING_ENABLED=false` and compare. A pause +after the last test is usually the uploads at the end of the run. Each upload stops after twice +`UploadTimeout`, but a failing endpoint can hold up the end of the run for several of these waits. + +The SDK keeps every test [execution](../configuration/collected-data.md#each-execution) of the run in memory until the run ends, so memory grows with +the size of the run. `BatchSize` does not limit it. + +See [Performance](../performance/performance.md). + +--- + +## CLI sign-in (`xping login`) + +> [!NOTE] +> This describes the 1.0.0-rc `xping` CLI. The Xping CLI 2.x is a different tool and has no `report`, `where`, `clear` or `login` commands. + +Start with `xping auth status`. It makes no network call and says which credential the CLI would +use. Add `--verbose` to any command for the details. See the +CLI reference. + +### "Cloud data unavailable: your sign-in is no longer valid" + +> [!NOTE] +> Xping Cloud only. The Xping CLI 2.x does not use Xping Cloud. + +The session was revoked, on Settings → Security → CLI sessions or when a workspace key was +withdrawn, or it expired. The CLI has already removed it. Run `xping login` again. + +### `xping login` says it needs an interactive terminal + +> [!NOTE] +> This describes the 1.0.0-rc `xping` CLI. The Xping CLI 2.x is a different tool and has no `report`, `where`, `clear` or `login` commands. + +`login` runs only in your own shell. It refuses when stdin or stderr is not a terminal, which is the +case for every pipeline agent and coding agent, and when `CI` is `true`, `1` or `yes`. CI uses an API +key that can read Cloud data (`XPING_APIKEY`). An agent should ask you to run `xping login` yourself. + +### The browser never returns to the CLI + +The sign-in page sends the browser back to `127.0.0.1` on the machine that runs the CLI. Over SSH, in +a container, or in WSL with localhost forwarding off, that address is not the CLI's. Press Ctrl+C and +run `xping login --device`, which works with a browser on any device. + +### "Refusing to read ~/.xping/credentials.json because other users can read it" + +The CLI uses the sign-in file only when no OS credential store is available. Restore its +permissions: + +```bash +chmod 700 ~/.xping +chmod 600 ~/.xping/credentials.json +``` + +### "This API key cannot read Cloud data" + +> [!NOTE] +> Xping Cloud only. The Xping CLI 2.x does not use Xping Cloud. + +The key is upload-only, or the workspace's plan does not include API access. Sign in with +`xping login` on your machine, or give CI a key with the Read scope. The report itself is not +affected. + +### "Could not write to Windows Credential Manager (error 8…)" + +Windows refused to store any credential for your account: `cmdkey /generic:test /user:x /pass:y` +fails with the same message. `xping login` keeps the sign-in in `~/.xping/credentials.json` instead, +so the CLI works. The cause is usually a damaged Windows user profile. Other apps that save passwords +on this account are affected too. + +### macOS asks for keychain access after every upgrade + +The `xping` tool is not signed by Apple, so macOS asks once for each installed version. Choose +**Always Allow**. + +--- + +## Installation issues + +### Wrong xUnit adapter (XPING001, XPING002) + +**Symptoms:** the build of your test project stops with one of: + +``` +error XPING001: Xping.Sdk.XUnit supports xUnit v2, but this project references xUnit v3 (xunit.v3). Replace it with Xping.Sdk.XUnit.V3. +error XPING002: Xping.Sdk.XUnit.V3 supports xUnit v3, but this project references xUnit v2 (xunit). Replace it with Xping.Sdk.XUnit. +``` + +**Cause:** Xping has one adapter for each xUnit version, and the one installed does not match the +xUnit package that the project references. + +**Solution:** swap the package that the error names, and use the matching attribute: + +```bash +# XPING001: the project is on xUnit v3 +dotnet remove package Xping.Sdk.XUnit +dotnet add package Xping.Sdk.XUnit.V3 --prerelease + +# XPING002: the project is on xUnit v2 +dotnet remove package Xping.Sdk.XUnit.V3 +dotnet add package Xping.Sdk.XUnit --prerelease +``` + +See [Step 2: Turn on the Xping test framework](../getting-started/quickstart-xunit.md#step-2-turn-on-the-xping-test-framework) +for the attribute each one needs. + +**`CS0433: The type 'FactAttribute' exists in both 'xunit.core' and 'xunit.v3.core'`** is the same +mistake in a build that skips the check above, for example one that does not import NuGet's +`buildTransitive` files. The fix is the same. + +--- + +## Get help + +If a problem remains: + +1. Collect the details that support needs. See + [Collect information for support](debugging.md#collect-information-for-support). +2. Email support@xping.io, or open an issue at + [github.com/xping-dev/sdk-dotnet](https://github.com/xping-dev/sdk-dotnet/issues). Remove the API + key from anything you send. + +--- + +## See also + +- [Debugging](debugging.md) +- [Known limitations](known-limitations.md) +- [Configuration reference](../configuration/configuration-reference.md) +- [Set up CI](../getting-started/ci-cd-setup.md) +- [Performance](../performance/performance.md) diff --git a/sdk/troubleshooting/debugging.md b/sdk/troubleshooting/debugging.md new file mode 100644 index 0000000..d83fa3a --- /dev/null +++ b/sdk/troubleshooting/debugging.md @@ -0,0 +1,305 @@ +--- +uid: troubleshooting-debugging +title: Debugging +--- + +# Debugging + +> [!NOTE] +> This page describes the **Xping SDK for .NET, 1.0.0-rc series**. The SDK can upload to Xping Cloud, and these pages refer to the 1.0.0-rc `xping report` CLI. The Xping CLI 2.x is a different tool: it does not use Xping Cloud and has no `report` command. See the [Xping overview](../../index.md). + +This page shows how to see what the SDK does during a test run: where its output appears, what each +line means, and how to get more detail. For fixes to specific errors, see +[Common issues](common-issues.md). + +--- + +## See the SDK's output + +The SDK writes its messages to the test process's standard output and standard error. Messages at +`Warning` and above go to standard error, and the rest to standard output. + +Where you see them depends on the runner: + +| Runner | Where the SDK's lines appear | +|---|---| +| vstest (`dotnet test`), NUnit, MSTest and xUnit v2 | Only at `normal` verbosity or higher: `dotnet test --logger "console;verbosity=normal"`. The default verbosity hides them. | +| vstest, xUnit v3 | Not in the `dotnet test` output. Run the test project with `dotnet run`, or run its executable directly, such as `./bin/Release/net10.0/MyApp.Tests`. | +| Microsoft.Testing.Platform | In the test executable's output, at the default verbosity. | + +```bash +dotnet test --logger "console;verbosity=normal" +``` + +A line from the SDK's log starts with `[Xping`, the time and the level: + +``` +[Xping 13:16:21 INF] Initialized. SessionId: "12048a9a-1213-4aa9-8558-a3b850b2a631", Environment: Local +``` + +The levels print as `DBG`, `INF`, `WRN`, `ERR` and `FTL` (`Critical`). A few messages start with +`[Xping]` and no time. The SDK writes them directly, without its log: + +- `[Xping] SDK initialization failed: …`, when the SDK cannot start; +- `[Xping] Strict mode configuration error: …` and `[Xping] Xping network error in strict mode: …`, + when [`StrictMode`](../configuration/configuration-reference.md#strictmode) fails the run; +- `[Xping] 1 test flaked on retry this run - …`, the retry hint. + +### Filter the output + +Every SDK line contains `[Xping`: + +```bash +dotnet test --logger "console;verbosity=normal" 2>&1 | grep '\[Xping' + +# Warnings and errors only +dotnet test --logger "console;verbosity=normal" 2>&1 | grep -E '\[Xping [0-9:]+ (WRN|ERR)\]' +``` + +In PowerShell: + +```powershell +dotnet test --logger "console;verbosity=normal" 2>&1 | Select-String '\[Xping' + +# Warnings and errors only +dotnet test --logger "console;verbosity=normal" 2>&1 | Select-String '\[Xping [0-9:]+ (WRN|ERR)\]' +``` + +--- + +## Read the SDK's output + +A run in `Cloud` mode that uploads without errors prints these lines: + +``` +[Xping 13:16:21 INF] Initialized. SessionId: "12048a9a-1213-4aa9-8558-a3b850b2a631", Environment: Local +[Xping 13:16:22 INF] Published 15 tests in 23ms (21.4 KB) · receipt 3f9a1c2e +[Xping 13:16:22 INF] Finalization receipt 3f9a1c2e (1ms, 1.7 KB) +[Xping 13:16:22 INF] Total tests recorded: 15 · 10 passed, 4 failed, 1 timed out · exec: 581ms · wall: 651ms (+70ms overhead) +``` + +### The start line + +The first line says how the SDK started. Check it first when the SDK does not do what you expect. + +| Line | Meaning | +|---|---| +| `Initialized. SessionId: …, Environment: …` | `Cloud` mode. Each test assembly reports into its own project. | +| `Initialized. SessionId: …, Project: (pinned), Environment: …` | `Cloud` mode, with every result going to the [`ProjectId`](../configuration/configuration-reference.md#projectid) you set. | +| `Initialized in local-only mode. … No API key configured - results stay on this machine.` | `LocalOnly` mode, because the SDK found no API key. | +| `Initialized in local-only mode. … Mode is set to LocalOnly - results stay on this machine.` | `LocalOnly` mode, because you set it. | +| `SDK is disabled via configuration (Enabled=false). …` or `(Mode=Disabled)` | The SDK records nothing. | +| `Configuration validation failed: … SDK disabled - …` | A setting is invalid, and the SDK records nothing. See [Validation rules](../configuration/configuration-reference.md#validation-rules). | + +`Environment` is the [environment name](../configuration/configuration-reference.md#environment): +the deployment that the tests run against. It is `Default` when you set none. The examples on this +page come from a shell with `XPING_ENVIRONMENT=Local`. + +### Upload lines + +> [!NOTE] +> Xping Cloud only. The Xping CLI 2.x does not use Xping Cloud. + +In `Cloud` mode, the SDK prints a line for each upload it makes: + +- `Published 15 tests in 23ms (21.4 KB) · receipt 3f9a1c2e`: a batch of test results. The size is the + size of the JSON before compression. +- `Finalization receipt 3f9a1c2e (1ms, 1.7 KB)`: the final upload, which closes the run. + +The receipt is the first 8 characters of the receipt ID that Xping Cloud returns. Keep it when you +contact support about a run. + +`LocalOnly` mode makes no uploads, so it prints no upload lines. + +### The summary line + +At the end of the run, the SDK prints a summary of what it recorded: + +``` +[Xping 13:15:19 INF] Total tests recorded: 25 (24 tests, 1 retry) · 17 passed, 5 failed, 2 timed out · exec: 2.6s · wall: 2.7s (+161ms overhead) +``` + +- `25 (24 tests, 1 retry)`: 25 [executions](../configuration/collected-data.md#each-execution) of 24 tests. The part in brackets appears only when a test + was retried. The outcomes then count each test by its last attempt. +- `exec`: the total of each test's own duration. +- `wall`: the time from the SDK's start to the end of the run. +- `(+161ms overhead)`: `wall` minus `exec`. It includes the framework's setup and teardown and the + time between tests, not only the SDK's work. When tests run in parallel, `exec` can be larger than + `wall`, and the overhead is left out. + +`exec` is often much smaller than the duration the test framework reports. The framework's duration +also includes loading the assemblies and discovering the tests. + +When the final upload fails, the SDK prints `Session finalized.` instead of the summary. + +### The retry hint + +When a test passes on a retry in a local run, the SDK prints a hint after the summary: + +``` +[Xping] 1 test flaked on retry this run - run `xping report` for local history +``` + +It does not print the hint in CI. To hide it everywhere, set `XPING_NO_BANNER` to any value. + +### Repeated errors + +The SDK prints an upload error in full the first time. When the same error repeats in the same +run, it prints a short line instead: + +``` +[Xping 13:16:24 ERR] Same HTTP 401 error (2nd occurrence, batch size: 0) +``` + +`batch size` is the number of test results in that upload. The final upload carries none, so it shows +`0`. A successful upload resets the count. + +--- + +## Get more detail + +Set [`LogLevel`](../configuration/configuration-reference.md#loglevel) to `Debug`: + +```bash +XPING_LOGLEVEL=Debug dotnet test --logger "console;verbosity=normal" +``` + +`Debug` adds the steps that the SDK skips or absorbs so that it never breaks the test run. For +example: + +``` +[Xping 13:21:01 DBG] GitHub PR detection skipped: GITHUB_EVENT_NAME='null' (expected 'pull_request' or 'pull_request_target'). +[Xping 13:21:01 DBG] Finalizing session +``` + +Other Debug messages include `Local session store write skipped: …` and `Local session not stored: +…`, when the SDK could not write the [local store](../configuration/local-store.md). + +`LogLevel` takes `Trace`, `Debug`, `Information` (the default), `Warning`, `Error`, `Critical` and +`None`. Each level includes the levels above it. `None` silences the SDK's log. It does not hide the +lines that start with `[Xping]` and no time. + +--- + +## Warnings and errors + +These are the warnings and errors that the SDK logs, apart from the upload errors. For the upload +errors, see [Upload errors](common-issues.md#upload-errors). + +| Message starts with | Meaning | +|---|---| +| `FlushInterval '…' is not a duration and was ignored.` | The value is neither whole seconds (`30`) nor a time with colons (`00:00:30`). The setting keeps its default. The message names the setting as you wrote it, such as `XPING_FLUSHINTERVAL` or `Xping:FlushInterval`. The same applies to `RetryDelay` and `UploadTimeout`. | +| `Duplicate test fingerprint detected: …` | Two different tests have the same `[XpingFingerprint]` value. Their results can overwrite each other in Xping Cloud. Give one of them another value. | +| `N executions carry no test assembly and cannot be attributed to a project.` | The SDK could not tell which test assembly these results came from. With no `ProjectId`, Xping Cloud cannot place them. | +| `No test assembly could be resolved for this session, …` | No result named a test assembly. Set `ProjectId` for Cloud. Report it as an SDK bug. | +| `GITHUB_EVENT_NAME is not set, …` | On GitHub Actions, the test process did not get `GITHUB_EVENT_NAME`, often because the tests run in a container. Pass the `GITHUB_*` variables into the container. | +| `GitHub PR detection skipped: …` | The SDK could not read the pull request from GitHub's variables or event file. The message names what is missing. | +| `Sending the configured default branch '…' …` | You set [`DefaultBranch`](../configuration/configuration-reference.md#defaultbranch), and it differs from the branch the CI reports. | +| `[Xping] Process exiting with session … still active: …` | MSTest only. No `[AssemblyCleanup]` finalized the session. See [Known limitations](known-limitations.md#mstest-a-run-finalized-by-the-process-exit-safety-net-loses-its-upload-on-vstest). | +| `Failed to initialize Xping SDK: … SDK disabled - …` | The SDK could not start, and records nothing. The message gives the reason. | +| `Error finalizing Xping session` | The end of the run failed. The exception follows the message. | + +--- + +## Check the configuration + +1. **Read the start line.** It shows the mode, the project pin and the environment name. See + [The start line](#the-start-line). +2. **List the `XPING_*` variables that the shell sets**, without their values: + + ```bash + env | grep '^XPING_' | cut -d= -f1 + ``` + + ```powershell + Get-ChildItem Env:XPING_* | Select-Object Name + ``` + + The names use one underscore, such as `XPING_APIKEY`. They win over `appsettings.json` and over a + configuration object passed in code. +3. **Find the local store** with `xping where`. It shows the folder and the runs in it. See + [Local store](../configuration/local-store.md). +4. **Rule out the upload.** Run once with `XPING_MODE=LocalOnly`. If the problem stays, it is not the + upload. + +For the configuration sources and their order, see +[Configuration methods](../configuration/configuration-reference.md#configuration-methods). + +--- + +## Check the network + +The SDK uploads to `https://upload.xping.io/v1` over HTTPS (port 443), unless you set +[`ApiEndpoint`](../configuration/configuration-reference.md#apiendpoint). + +Check that the machine reaches it: + +```bash +curl -sS -o /dev/null -w '%{http_code}\n' https://upload.xping.io/v1 +``` + +```powershell +Test-NetConnection -ComputerName upload.xping.io -Port 443 +``` + +Any HTTP status code from `curl` means the machine reaches the endpoint. A connection error or a +timeout means a firewall, a proxy or DNS blocks it. + +The SDK uses the standard .NET proxy settings. It honours the `HTTPS_PROXY`, `HTTP_PROXY` and +`NO_PROXY` environment variables, and the system proxy settings on Windows and macOS. + +### Inspect the requests + +To see the requests, route them through a debugging proxy such as Fiddler or mitmproxy: set +`HTTPS_PROXY` to the proxy's address, and trust the proxy's root certificate on the machine. Each +upload is a `POST` to `?sessionId=`, with these headers: + +| Header | Value | +|---|---| +| `X-API-Key` | The API key | +| `X-Project-Id` | The `ProjectId`, only when you set one | +| `User-Agent` | `Xping-SDK-DotNet/` | +| `Content-Encoding` | `gzip`, when the body is larger than 1 KB and [`EnableCompression`](../configuration/configuration-reference.md#enablecompression) is on | + +Remove the API key before you share a capture. + +--- + +## Collect information for support + +When you report a problem, include: + +1. **The SDK version:** + + ```bash + dotnet list package | grep Xping + ``` + +2. **The .NET SDK, the runtime and the OS:** `dotnet --info`. +3. **The test framework, its version and the runner** (vstest or Microsoft.Testing.Platform): + + ```bash + dotnet list package | grep -E -i 'nunit|xunit|mstest' + ``` + +4. **The SDK's output, with Debug detail:** + + ```bash + XPING_LOGLEVEL=Debug dotnet test --logger "console;verbosity=normal" > test-output.log 2>&1 + ``` + +5. **The `SessionId` and the receipts** from the output, for a run that reached Xping Cloud. +6. **Your configuration, without the API key.** +7. **A small project that reproduces the problem**, if you can make one. + +Email support@xping.io, or open an issue at +[github.com/xping-dev/sdk-dotnet](https://github.com/xping-dev/sdk-dotnet/issues). + +--- + +## See also + +- [Common issues](common-issues.md) +- [Configuration reference](../configuration/configuration-reference.md) +- [Performance](../performance/performance.md) +- [Known limitations](known-limitations.md) diff --git a/sdk/troubleshooting/known-limitations.md b/sdk/troubleshooting/known-limitations.md new file mode 100644 index 0000000..f49402f --- /dev/null +++ b/sdk/troubleshooting/known-limitations.md @@ -0,0 +1,480 @@ +--- +uid: troubleshooting-known-limitations +title: Known limitations +--- + +# Known limitations + +> [!NOTE] +> This page describes the **Xping SDK for .NET, 1.0.0-rc series**. The SDK can upload to Xping Cloud, and these pages refer to the 1.0.0-rc `xping report` CLI. The Xping CLI 2.x is a different tool: it does not use Xping Cloud and has no `report` command. See the [Xping overview](../../index.md). + +This page lists what the SDK does not record, or records differently from what you might expect, +for each test framework. It is for developers who set up the SDK or read its results. + +## Requirements + +The MSTest adapter needs MSTest 3.8 or later. For the other minimum versions, see the +[quickstarts](../getting-started/quickstart-nunit.md). + +## Framework-specific limitations + +### NUnit + +#### Ignored tests are not tracked + +A test marked `[Ignore]` does not appear in Xping. + +`XpingTrackAttribute` is an NUnit `ITestAction`, which runs only for tests that execute. NUnit leaves +out `[Ignore]` tests before execution starts, so `BeforeTest` and `AfterTest` never run for them. +There is no workaround. Xping tracks only the tests that run. + +--- + +### MSTest + +#### Ignored tests are not tracked + +A test marked `[Ignore]` does not appear in Xping. + +`XpingTestBase` records a test from its `[TestInitialize]` and `[TestCleanup]` hooks, which run only +for tests that execute. MSTest skips `[Ignore]` tests before these hooks run. There is no +workaround. + +#### Retry attempts are numbered by counting + +Two executions of the same test identity in one run are recorded as attempt 1 and attempt 2 of a +retry, whether or not a retry produced them. + +MSTest runs the whole per-test lifecycle again for each retried attempt. A retry attribute derived +from `TestMethodAttribute` invokes the test method again, which builds a new test class instance and +runs `[TestInitialize]`, the method and `[TestCleanup]` once more. Xping therefore records **every +attempt** as its own `TestExecution`, with its own outcome, duration and failure text. A test that +fails and then passes has `AttemptNumber = 2` and `PassedOnRetry = true` on its last execution, so +the hidden failure is visible even though the build is green. + +```csharp +// Both attempts recorded: attempt 1 Failed with its error, attempt 2 Passed +[Retry(3)] +public void FlakyTest() +{ + // ... +} +``` + +Nothing in `TestContext` says which attempt is running, so the adapter counts the executions it has +already recorded for the same test fingerprint. A test identity that passed starts a new count, +because a retry only follows an attempt that did not pass. But two `[DataRow]` rows with *identical* +values share a fingerprint, so a failing row followed by a repeat of itself looks like a retry. + +A retry helper that runs only the method body again, without going through `ITestMethod.Invoke`, +skips `[TestInitialize]` and `[TestCleanup]`. Xping then sees one execution for the whole retry loop. + +`AttemptNumber` comes from a `RetryAttempt` or `RetryCount` test property, or from an attempt marker +in the test name (`(Retry 2)`, `[Attempt 2]`), when a retry helper publishes one. The counted value +is the lowest number used. + +--- + +### xUnit + +This section covers xUnit v2. For xUnit v3, see [xUnit v3](#xunit-v3). + +Tests with a `Skip` parameter are tracked, with `Outcome = Skipped`: + +```csharp +[Fact(Skip = "Temporarily disabled - ticket #123")] +public void MyTest() +{ + // Tracked with Outcome = Skipped +} +``` + +#### Retry attempts are tracked only for retry libraries with a single-attempt hook + +With some retry libraries, a test that fails and then passes on a retry is recorded as one passing +execution. `AttemptNumber` stays `1`, `PassedOnRetry` stays `false`, the hidden failure is not +recorded, and the duration is the total of all attempts. + +xUnit has no retry support of its own. A retry library runs each attempt on a message bus of its +own, drops the messages of each attempt it retries, and then sends one result. Xping reads test +results from a message sink outside that bus, so it never sees the dropped attempts. + +[xRetry](https://github.com/JoshKeegan/xRetry) makes `RetryTestCaseRunner.RunAsync` public, so other +xUnit extensions can supply the code that runs one attempt. Xping uses it, so it runs *inside* the +retry loop. Every attempt is recorded as its own `TestExecution`, with the right `AttemptNumber`, its +own duration and, for the attempts the retry hid, the failure message, stack trace and exception +type. xRetry still controls the retry count, the delays, the skip-on-exception handling and what the +runner sees, so the tests behave the same. + +Libraries that run the retry loop inside their own test case's `RunAsync`, behind a private bus, have +no such hook. The retry sample in xUnit's documentation is one of them. Xping leaves those test cases +alone and records only the attempt the library reports. + +```csharp +// Fully tracked: two executions, attempt 1 Failed and attempt 2 Passed +[RetryFact(3)] +public void FlakyTest() +{ + // ... +} +``` + +`AttemptNumber` is also read from a `RetryAttempt` trait, or from an attempt number in the display +name (`(attempt 2)`, `[Retry 2]`), when a library publishes one. + +--- + +### xUnit v3 + +Skipped tests are tracked, including a test that skips itself while it runs (`Assert.Skip`, +`Assert.SkipWhen`). An explicit test (`[Fact(Explicit = true)]`) that the run leaves out is not +recorded, because it did not run. + +#### xUnit v3 records only the last retry attempt + +This applies to xRetry.v3 1.0. A test that xRetry.v3 retries is recorded once, as the attempt it +ended on. `AttemptNumber` and `PassedOnRetry` are right, so a test that passed on its second attempt +shows as a pass on retry. The attempts before it are not recorded: their failure messages and stack +traces are lost, and the recorded duration is the total of all attempts. + +xRetry.v3 runs each attempt on a message bus of its own and drops every attempt but the last, as its +v2 version does. Unlike the v2 version, it has no hook to run an attempt through, so Xping cannot sit +inside the loop. It does announce each attempt (`Running test "…" attempt (2/3)`) on the run's own +bus, and the attempt number comes from there. + +#### vstest needs `xunit.v3.mtp-off` on the .NET 10 SDK + +On the .NET 10 SDK, `dotnet test` without a Microsoft.Testing.Platform `global.json` fails to build an +`xunit.v3` project, with "Testing with VSTest target is no longer supported by +Microsoft.Testing.Platform". + +`xunit.v3` makes the test project a Microsoft.Testing.Platform app, and the .NET 10 SDK's vstest +refuses one. This is how xUnit and the .NET SDK behave, with or without Xping. Reference +`xunit.v3.mtp-off` instead of `xunit.v3` to stay on vstest, or move `dotnet test` to +Microsoft.Testing.Platform. + +#### A timed-out test can crash the TRX report on Microsoft.Testing.Platform + +This applies to xunit.v3 4.0.2 with Microsoft.Testing.Extensions.TrxReport 2.5.1. Sometimes a run with +`--report-trx` exits with code 7 ("test host crashed") after a `[Fact(Timeout = …)]` test times out. +The output shows an extra `[Test Cleanup Failure (…)]` result for that test and an +`InvalidOperationException` from `TrxReportEngine.GetClassAndMethodName`, and the TRX file is empty. +Xping still records the test as timed out. It happens more often on a busy machine, such as a CI +agent. + +The test passed `TestContext.Current.CancellationToken` to the call that hung. xUnit cancels that +token at the timeout, so the abandoned task fails afterwards. xUnit v3 sometimes reports that failure +as a separate cleanup failure, which has no class or method name, and the TRX extension crashes on +it. This happens without Xping too: see [xunit/xunit#3669](https://github.com/xunit/xunit/issues/3669). +To avoid it, don't pass the token to a call that the timeout is meant to abandon (and suppress +`xUnit1069` there), or run without `--report-trx`. + +#### A theory row is identified by the arguments in its display name + +Two rows of one theory whose arguments display the same way, such as two different objects with the +same `ToString()`, share one identity and one history. A row's identity also changes when its display +text changes. + +xUnit v3 passes a theory row that it did not pre-enumerate to Xping without its arguments. Only the +display name carries them. vstest and Microsoft.Testing.Platform pre-enumerate. xUnit's own console +runner, and a runner set to `preEnumerateTheories: false`, do not. Xping always reads the arguments +from the display name, so a row keeps the same identity however it runs. + +The exception is a value that xUnit shortens in the display name, which then ends with `···`: a +string over 50 characters, a collection over 5 items, or a deeply nested object. A pre-enumerated row +with such a value is identified by its real arguments, so rows that differ after the cut stay apart. +A row that xUnit did not pre-enumerate still uses the shortened text. So such a row has a different +identity under xUnit's console runner than under vstest or Microsoft.Testing.Platform. + +#### The runner is unknown under xUnit's own console runner + +A run recorded by `xunit.v3.runner.console`, or by running the test executable directly without +Microsoft.Testing.Platform, has no `Xping.Runner` property. `xping report` then prints no command to +run a test again. + +An xUnit v3 test assembly is its own executable on every runner, so the entry assembly does not name +the runner. Xping reads the runner from the runner's code on the call stack and from vstest's +environment, and leaves it out rather than guess. + +--- + +### Timeouts + +Xping records a test that the framework stopped for running past its timeout as `Outcome = Timeout`, +not `Failed`, with the time limit the test declared. The cases below are recorded differently, or not +at all. + +#### A hang that stops the test host is not recorded + +Each adapter records a test from a callback the framework raises after the test ends: MSTest's +`[TestCleanup]`, NUnit's `AfterTest`, xUnit's result message. If a hang stops the whole test host, no +callback runs and the test is not recorded. Each framework's own `[Timeout]` handles the usual case, +and Xping records that. + +#### NUnit's blocking `[Timeout]` is not tracked + +NUnit's `[Timeout]` on a synchronous test abandons the test thread without calling +`ITestAction.AfterTest`, so Xping never sees the result and records nothing for that test. Use +`[CancelAfter]` instead. It cancels the test cooperatively, and Xping tracks it: + +```csharp +[Test, CancelAfter(500)] +public async Task MyTest(CancellationToken cancellationToken) +{ + // Tracked with Outcome = Timeout when it runs too long + await Task.Delay(5000, cancellationToken); +} +``` + +#### MSTest's cooperative `[Timeout]` is recorded as failed or passed + +With `[Timeout(..., CooperativeCancellation = true)]`, or with cooperative cancellation on for every +test (`CooperativeCancellationTimeout` in `.runsettings` or `testconfig.json`), MSTest cancels the +test's token instead of abandoning the test. When `[TestCleanup]` runs, nothing MSTest reports marks +the test as timed out: + +- A test that observes the token ends with an `OperationCanceledException`. Xping records it as + `Failed`. +- A test that ignores the token runs to the end. MSTest passes it, and Xping records `Passed`. + +A non-cooperative timeout, which is MSTest's default, is recorded as `Timeout`, for synchronous and +async tests. + +#### MSTest's run-wide timeout is recorded without a time limit + +A test stopped by a timeout for the whole run (`TestTimeout` in `.runsettings` or `testconfig.json`) +is recorded as `Timeout`. Xping reads the time limit only from the test's own `[Timeout]`, so that +execution has none. + +#### xUnit v2 applies a timeout only to async tests + +xUnit v2 rejects `[Fact(Timeout = ...)]` on a synchronous test. It fails the test with "Tests marked +with Timeout are only supported for async tests". Xping records that as `Failed`, not `Timeout`, +because the test is set up wrongly rather than hanging. + +## Fixture failures + +Xping records **where** a failing test failed in `TestExecution.Site`: the test body, the per-test +setup or teardown, or a one-time fixture. It names the member in `FailureSiteMember`. When every +failure in a group agrees on one member, `xping report` reports a **broken fixture** that names it, +instead of N separate failing tests. + +What Xping can see differs by framework. No framework reports a failure site of its own. The table +below records what running each framework showed, not what its documentation says. + +### What is recorded + +| Lifecycle member | NUnit | MSTest | xUnit v2 | xUnit v3 | +|---|---|---|---|---| +| Test body | `TestBody` | `TestBody` | `TestBody` | `TestBody` | +| Per-test setup | `TestSetup` (`[SetUp]`) | `TestSetup` (`[TestInitialize]`) | `TestSetup` (constructor, `InitializeAsync`) | `TestSetup` (constructor, `InitializeAsync`) | +| Per-test teardown | `TestTeardown` (`[TearDown]`) | **not recorded** | `TestTeardown` (`Dispose`, `DisposeAsync`) | `TestTeardown` (`Dispose`, `DisposeAsync`) | +| One-time fixture setup | **not recorded** | **not recorded** | `FixtureSetup` (`IClassFixture`, `ICollectionFixture`) | `FixtureSetup` (class, collection and assembly fixtures) | +| One-time fixture teardown | **not recorded** | **not recorded** | **not recorded** | **not recorded** | +| Assembly setup and teardown | **not recorded** | **not recorded** | **not recorded** | Setup: `FixtureSetup` (assembly fixtures). Teardown: **not recorded** | + +A failure that Xping cannot place is recorded as `Unknown`. It is not assumed to be in the test body. +A group that contains one is reported as a plain shared failure. The report never names a member it +did not observe. + +### NUnit: `[OneTimeSetUp]` and `[OneTimeTearDown]` are not observable + +A broken `[OneTimeSetUp]` produces **no Xping records at all**, not failing ones. + +`XpingTrackAttribute` is an `ITestAction`, and its hooks run only for tests that execute. When +`[OneTimeSetUp]` throws, NUnit marks the fixture's tests failed without running them, so neither +`BeforeTest` nor `AfterTest` runs, for the tests or for the fixture. The runner reports N failing +tests, and Xping sees none of them. + +`[OneTimeTearDown]` runs after the last test is reported. So when it throws, Xping records that test +as **passed**, while the runner fails it. + +To work around this, move the work into `[SetUp]`. It runs for each test instead of once, which +costs time, but Xping records it. A `[SetUp]` that breaks for every test in a fixture gives the same +broken fixture finding that a `[OneTimeSetUp]` would. + +### NUnit: the framework reports no failure site + +`ResultState.Site` is `Test` for every test-level result, including one whose `[SetUp]` threw. The +states that carry a site (`SetUpFailure`, `SetUpError`, `TearDownError`) are recorded on the +enclosing *suite*, which the adapter never sees. So Xping matches the stack trace against the +fixture's own lifecycle methods. A failure with no stack trace cannot be placed and stays `Unknown`. +`UploadStackTraces` does not change the site: Xping reads the site from the trace before the upload +leaves the trace out. + +### MSTest: a throwing `[TestCleanup]` discards the whole record + +The test produces **no `TestExecution` at all**. + +MSTest runs `[TestCleanup]` methods from the derived class first and stops at the first one that +throws. `XpingTestBase.XpingTestCleanup` is declared on the base class. So when your own +`[TestCleanup]` throws, Xping's cleanup does not run, and the record is never built. The runner +reports the test as failed, and Xping reports nothing. + +To work around this, wrap the body of your `[TestCleanup]` in a `try`/`catch`, and assert the failure +inside the test instead. + +### MSTest: `[ClassInitialize]` and `[ClassCleanup]` are not observable + +A broken `[ClassInitialize]` produces **no Xping records**. A broken `[ClassCleanup]` leaves its +tests recorded as **passed**. + +When `[ClassInitialize]` fails, MSTest stops the class before any `[TestInitialize]` runs. +`[ClassCleanup]` runs after every test is recorded. The adapter has no hook at either point. +`[AssemblyInitialize]` and `[AssemblyCleanup]` are not observable for the same reason. + +To work around this, move the work into `[TestInitialize]`, which Xping records. + +### MSTest: a run finalized by the process-exit safety net loses its upload on vstest + +When no `[AssemblyCleanup]` finalizes the run, the SDK finalizes it from a safety net that runs +as the process exits. It writes the local history, so `xping report` sees the run. But on vstest the +**Xping Cloud upload is usually lost**. On Microsoft.Testing.Platform the upload completes. + +The safety net runs in `AppDomain.ProcessExit`, and vstest stops the test host 100 ms after the run +ends. Microsoft.Testing.Platform runs in the test process and lets the handler finish. A local file +write fits in that time, and a network round trip does not. The safety net runs when the test +assembly declares no `[AssemblyCleanup]`, because MSTest runs only the assembly hooks declared in the +test assembly itself. It also runs when your `[AssemblyCleanup]` throws before it finalizes Xping. + +The SDK logs a warning when this happens. It starts with `[Xping] Process exiting with session … +still active`. + +To fix this, declare an `[AssemblyCleanup]` in the test assembly that calls +`XpingContext.FinalizeAndShutdownAsync()`. If the safety net still runs on vstest, set +`VSTEST_TESTHOST_SHUTDOWN_TIMEOUT=5000` in the environment that runs `dotnet test`, so the upload has +time to finish. + +### xUnit: fixture disposal is not attributed to a test + +A class or collection fixture whose `Dispose` throws leaves its tests recorded as **passed**. + +xUnit reports it as `ITestClassCleanupFailure`, `ITestCollectionCleanupFailure` or +`ITestAssemblyCleanupFailure`. These messages name no test, and they arrive after every test in the +class is reported. `XpingMessageSink` passes them to the runner without recording them, because there +is no test execution to attach them to. + +Fixture *construction* is recorded. xUnit v2 wraps a failing `IClassFixture` constructor in +`Xunit.Sdk.TestClassException` and names the fixture type in the message. This is the only failure +site that a framework reports directly. xUnit v2 does **not** wrap a failing `ICollectionFixture` +constructor: the exception arrives as it is, and Xping recognizes it from its constructor frame. +xUnit v3 wraps a failing fixture of every scope, assembly, collection and class, in +`Xunit.Sdk.TestPipelineException`, and names its type. + +--- + +## Local analysis + +The limits of the CLI's local analysis are on +Reading the report. + +--- + +## General limitations + +### Printed commands are quoted for one shell, chosen by `XPING_SHELL` or the OS + +> [!NOTE] +> This describes the 1.0.0-rc `xping` CLI. The Xping CLI 2.x is a different tool and has no `report`, `where`, `clear` or `login` commands. + +This applies to the drill-down, `History:` and repro commands that `xping report` prints, and to their +`--format json` fields. + +The CLI can't see which shell started it. It quotes for the shell that `XPING_SHELL` names (`posix` or +`powershell`). Without it, it quotes by OS: PowerShell 7.3+ on Windows, POSIX everywhere else. The two +styles differ for a value that holds an apostrophe or a curly single quote (`‘ ’ ‚ ‛`), which +PowerShell doubles, and for a `\`, which PowerShell leaves bare and POSIX quotes. + +- **Git Bash on Windows**, where coding agents usually run commands, gets PowerShell quoting unless + you set `XPING_SHELL=posix`. +- **cmd.exe** isn't supported. It has no single quotes, so a quoted value is split at `|`, `&` or a + space, and keeps its quotes. +- **Windows PowerShell 5.1** isn't supported. It passes a `"` inside an argument to `dotnet` without + escaping it. So a repro filter that names an NUnit test with a string argument, like `Echo("x")`, + breaks. Use PowerShell 7.3 or later. + +### The repro command needs the project path from the build + +To print a command that runs a test again, the CLI needs the test project's path. The SDK's build +targets write it into the test assembly as `[assembly: AssemblyMetadata("Xping.ProjectPath", ...)]`, +relative to the repository root. + +The path is not written when the project is built outside a git repository, or with +`GenerateAssemblyInfo=false`. The printed command then has no project path, and you run it from the +project folder. See The command. + +### Runs recorded in CI have no commit + +The SDK records the commit only outside CI. So `xping report` shows no commit for a run recorded in +CI, and `xping report --since ` matches only the runs recorded on a developer machine. To scope +CI runs, use `--since ` or `--runs`. See +Command reference. + +### Source location comes from the PDB, and points at the start of the body + +A finding's last line ends with the file and line where the test is declared: + + +``` +1. HIGH flaky + SampleTests.FlakyTest_PassesOnRetry + failed 5 of 10 executions (50%) in 5 of 5 runs, 1 failure mode + evidence sparse | -env-cluster | f_8f042eab | .../SampleTests.cs:135 +``` + +No framework reports this, so the SDK reads it from the assembly's Portable PDB, by the test method's +metadata token. Test Explorer finds it the same way. This has four limits. + +**The line is where the body starts, not the attribute.** A PDB records where *code* is, and an +attribute is not code. For + +```csharp +[Test] // line 40 +public void Checkout() // line 41 +{ // line 42 <- Debug build + Assert.That(...); // line 43 <- Release build +} +``` + +which line you get depends on the build configuration. A Debug build gives the opening brace its own +sequence point, so line 42 is reported. A Release build keeps no point for a brace that generates no +code, so the first *executable* statement, line 43, is the first line the PDB can name. The gap is not +always one line: when a body starts with a comment or a blank line, Debug reports the brace and Release +reports the first statement below them. + +Both lines are inside the method, which is what the location is for. Neither points at the attribute +or the signature. + +**No PDB, no location.** A build with `DebugType=none` has no symbols, and the location is left out. +Everything else about the test is still recorded. The default portable PDB (a `.pdb` file beside the +assembly) and `DebugType=embedded` both work. A test assembly copied to another machine without its +`.pdb` has no location either. + +**Paths are made relative to the repository when possible.** A PDB stores the absolute path on the +machine that compiled the assembly. The SDK cuts it at the nearest enclosing `.git` or solution file, +and removes the `/_/` root that a deterministic CI build (`ContinuousIntegrationBuild=true`) writes. +When neither applies, such as an assembly built somewhere other than where it runs without a +deterministic build, the absolute path is recorded as it is. + +**MSTest cannot tell overloads apart.** The MSTest adapter finds a test's `MethodInfo` from +`TestContext.FullyQualifiedTestClassName` and `TestContext.TestName`, which name a method but not its +parameters. When a test class has two overloads of the same test method name, the adapter takes the +one the runtime lists first, so the reported line may belong to the other one. The same limit applies +to the pinned fingerprint and the timeout. NUnit and xUnit pass the method itself and are not +affected. + +--- + +## Reporting issues + +If you find a limitation that is not on this page: + +1. **Search the existing issues**: [GitHub Issues](https://github.com/xping-dev/sdk-dotnet/issues) +2. **Report a new one**: [Create an issue](https://github.com/xping-dev/sdk-dotnet/issues/new) + +Include: + +- the test framework and its version; +- the Xping SDK version; +- a minimal example that reproduces it; +- what you expected, and what happened. diff --git a/sdk/troubleshooting/toc.yml b/sdk/troubleshooting/toc.yml new file mode 100644 index 0000000..4865b2b --- /dev/null +++ b/sdk/troubleshooting/toc.yml @@ -0,0 +1,6 @@ +- name: Common issues + href: common-issues.md +- name: Debugging + href: debugging.md +- name: Known limitations + href: known-limitations.md diff --git a/troubleshooting/common-issues.md b/troubleshooting/common-issues.md new file mode 100644 index 0000000..f21c91f --- /dev/null +++ b/troubleshooting/common-issues.md @@ -0,0 +1,3 @@ +--- +redirect_url: ../sdk/troubleshooting/common-issues.html +--- diff --git a/troubleshooting/debugging.md b/troubleshooting/debugging.md new file mode 100644 index 0000000..2dcf4de --- /dev/null +++ b/troubleshooting/debugging.md @@ -0,0 +1,3 @@ +--- +redirect_url: ../sdk/troubleshooting/debugging.html +--- diff --git a/troubleshooting/known-limitations.md b/troubleshooting/known-limitations.md new file mode 100644 index 0000000..d4f4e58 --- /dev/null +++ b/troubleshooting/known-limitations.md @@ -0,0 +1,3 @@ +--- +redirect_url: ../sdk/troubleshooting/known-limitations.html +---