Compare commits
No files matched your search
@@ -22,6 +22,20 @@
|
||||
"dotnet-CycloneDX"
|
||||
],
|
||||
"rollForward": false
|
||||
},
|
||||
"dotnet-sonarscanner": {
|
||||
"version": "12.0.0",
|
||||
"commands": [
|
||||
"dotnet-sonarscanner"
|
||||
],
|
||||
"rollForward": false
|
||||
},
|
||||
"dotnet-coverage": {
|
||||
"version": "18.12.0",
|
||||
"commands": [
|
||||
"dotnet-coverage"
|
||||
],
|
||||
"rollForward": false
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,8 @@
|
||||
version: 2
|
||||
|
||||
updates:
|
||||
# Projects, Directory.Packages.props and the tools in .config/dotnet-tools.json (Dependabot only looks for the tool
|
||||
# manifest there, not in the repository root).
|
||||
- package-ecosystem: nuget
|
||||
directory: /
|
||||
schedule:
|
||||
@@ -19,7 +21,10 @@ updates:
|
||||
microsoft:
|
||||
patterns: ["Microsoft.Extensions.*", "System.*"]
|
||||
tests:
|
||||
patterns: ["xunit*", "Microsoft.Testing.*", "BenchmarkDotNet*"]
|
||||
patterns: ["xunit*", "Microsoft.Testing.*", "BenchmarkDotNet*", "dotnet-coverage"]
|
||||
# vpk packs the releases that the Velopack library in the app installs: keep both on the same version.
|
||||
velopack:
|
||||
patterns: ["Velopack", "vpk"]
|
||||
ignore:
|
||||
# xunit.v3 4.x breaks Avalonia.Headless.XUnit (AvaloniaUI/Avalonia#22072).
|
||||
- dependency-name: "xunit.v3*"
|
||||
|
||||
@@ -2,7 +2,7 @@ name: Notify CI Failures
|
||||
|
||||
on:
|
||||
workflow_run:
|
||||
workflows: [CI, Security, Scorecard]
|
||||
workflows: [CI, Security, Scorecard, SonarCloud]
|
||||
types: [completed]
|
||||
|
||||
permissions: {}
|
||||
|
||||
@@ -17,6 +17,8 @@ on:
|
||||
pull_request:
|
||||
paths:
|
||||
- .github/workflows/release.yml
|
||||
# vpk and CycloneDX versions.
|
||||
- .config/dotnet-tools.json
|
||||
- build/**
|
||||
- eng/assert-release.py
|
||||
- eng/release-notes.py
|
||||
|
||||
@@ -112,8 +112,8 @@ jobs:
|
||||
run: go run github.com/rhysd/actionlint/cmd/actionlint@v1.7.12 -color
|
||||
|
||||
- name: zizmor
|
||||
uses: zizmorcore/zizmor-action@cc914d7f3750a2d13d75c7f184a1060aa0e9d482 # v0.6.4
|
||||
uses: zizmorcore/zizmor-action@85b2b9fb8e3325e7a23d7d0a9d7ba5ae0f999e3e # v0.7.1
|
||||
with:
|
||||
version: 1.30.1
|
||||
version: 1.31.1
|
||||
config: .github/zizmor.yml
|
||||
advanced-security: false
|
||||
@@ -0,0 +1,114 @@
|
||||
name: SonarCloud
|
||||
|
||||
# CI-based analysis (Automatic Analysis is turned off in SonarCloud): the C# is analysed during a real build, with
|
||||
# coverage from the unit tests and the smoke test; scripts and workflows are analysed too. SonarCloud reports the
|
||||
# quality gate on pull requests itself.
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
pull_request:
|
||||
branches: [main]
|
||||
workflow_dispatch:
|
||||
|
||||
permissions: {}
|
||||
|
||||
concurrency:
|
||||
group: sonarcloud-${{ github.event.pull_request.number || github.ref }}
|
||||
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
|
||||
|
||||
env:
|
||||
DOTNET_NOLOGO: true
|
||||
DOTNET_CLI_TELEMETRY_OPTOUT: true
|
||||
DOTNET_SKIP_FIRST_TIME_EXPERIENCE: true
|
||||
AVALONIA_TELEMETRY_OPTOUT: 1
|
||||
|
||||
jobs:
|
||||
# Pull requests from forks and from Dependabot get no repository secrets: skip the analysis instead of failing it.
|
||||
token:
|
||||
name: token
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 5
|
||||
permissions: {}
|
||||
outputs:
|
||||
available: ${{ steps.check.outputs.available }}
|
||||
steps:
|
||||
- name: Check for SONAR_TOKEN
|
||||
id: check
|
||||
env:
|
||||
SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
|
||||
run: |
|
||||
if [ -n "$SONAR_TOKEN" ]; then
|
||||
echo "available=true" >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
echo "available=false" >> "$GITHUB_OUTPUT"
|
||||
echo "::notice::SONAR_TOKEN is not available to this run (fork or Dependabot pull request); analysis skipped."
|
||||
fi
|
||||
|
||||
sonarcloud:
|
||||
name: sonarcloud
|
||||
needs: token
|
||||
# Manual runs analyse main only: other branches would create separate SonarCloud branch analyses.
|
||||
if: needs.token.outputs.available == 'true' && (github.event_name != 'workflow_dispatch' || github.ref == 'refs/heads/main')
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 30
|
||||
permissions:
|
||||
contents: read
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
# Full history: SonarCloud uses blame to tell new code from old.
|
||||
fetch-depth: 0
|
||||
persist-credentials: false
|
||||
|
||||
- uses: actions/setup-dotnet@a98b56852c35b8e3190ac28c8c2271da59106c68 # v6.0.0
|
||||
with:
|
||||
dotnet-version: 10.0.4xx
|
||||
|
||||
- uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
|
||||
with:
|
||||
path: ~/.nuget/packages
|
||||
key: nuget-${{ runner.os }}-${{ hashFiles('**/*.csproj', 'Directory.Packages.props', 'Directory.Build.props', 'global.json') }}
|
||||
restore-keys: nuget-${{ runner.os }}-
|
||||
|
||||
- name: Install tools
|
||||
run: dotnet tool restore
|
||||
|
||||
# Coverage: the Cobertura reports of the unit tests and of the smoke test. eng/ holds the CI and release scripts
|
||||
# (Python), for which no coverage is collected, so they stay out of the coverage figure.
|
||||
# Third-party Roslyn analyzers (Meziantou, ReferenceTrimmer) already fail the CI build when they warn; their
|
||||
# suggestions are not imported as SonarCloud issues.
|
||||
- name: Begin analysis
|
||||
env:
|
||||
SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
|
||||
run: |
|
||||
version=$(sed -n 's:.*<Version>\(.*\)</Version>.*:\1:p' Directory.Build.props)
|
||||
dotnet sonarscanner begin /k:poli0981_HashTool /o:poli0981 /v:"$version" \
|
||||
/d:sonar.host.url=https://sonarcloud.io /d:sonar.token="$SONAR_TOKEN" \
|
||||
/d:sonar.cs.cobertura.reportsPaths="TestResults/**/*.cobertura.xml" \
|
||||
/d:sonar.coverage.exclusions="eng/**" \
|
||||
/d:sonar.cs.roslyn.ignoreIssues=true \
|
||||
/d:sonar.qualitygate.wait=true
|
||||
|
||||
# No -warnaserror: CI enforces it, and here it would turn SonarCloud findings into build errors.
|
||||
- name: Build
|
||||
run: dotnet build HashTool.slnx -c Release
|
||||
|
||||
- name: Test
|
||||
run: >
|
||||
dotnet test --solution HashTool.slnx -c Release --no-build
|
||||
--results-directory TestResults
|
||||
--coverage --coverage-output-format cobertura
|
||||
|
||||
# The real app, headless: every page and language, hashing and verifying a file (see ci.yml).
|
||||
- name: Smoke test with coverage
|
||||
env:
|
||||
HASHTOOL_DATA_DIR: ${{ runner.temp }}/smoke-data
|
||||
run: >
|
||||
dotnet coverage collect -f cobertura -o TestResults/smoke.cobertura.xml
|
||||
"dotnet src/HashTool.App/bin/Release/net10.0/CheckHash.dll --smoke-test"
|
||||
|
||||
# Fails when the quality gate fails.
|
||||
- name: End analysis
|
||||
env:
|
||||
SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
|
||||
run: dotnet sonarscanner end /d:sonar.token="$SONAR_TOKEN"
|
||||
@@ -2,6 +2,19 @@
|
||||
|
||||
All notable changes to this project will be documented in this file.
|
||||
|
||||
## [1.2.1] - 2026-10-25
|
||||
|
||||
A small maintenance release: two fixes found while adding several hundred tests, and code analysis on every change.
|
||||
|
||||
### Fixed
|
||||
- Verify: a hash file dropped onto a row's hash box fills in that row's expected hash again, instead of being added to the list as one more file.
|
||||
- ZIP export: files from folders whose names share a beginning (such as `photos` and `photos-2024`) keep their relative paths instead of being stored with absolute ones.
|
||||
|
||||
### Security
|
||||
- Every pull request and `main` are analysed by SonarCloud, including test coverage, and Dependabot now also keeps the build tools (vpk, licence and SBOM tools) up to date.
|
||||
|
||||
---
|
||||
|
||||
## [1.2.0] - 2026-10-15
|
||||
|
||||
A big rework under the hood: faster hashing, standard checksum files, a command-line tool, a Linux build and a long list of fixes.
|
||||
|
||||
@@ -43,6 +43,8 @@ Run the app or smoke test with `HASHTOOL_DATA_DIR` pointing at a scratch folder
|
||||
workflow; `ci-ok` is the single required check.
|
||||
- Don't embed C# or regex text containing backslashes in Python/bash heredocs — the escapes get mangled. Edit such
|
||||
files with the editor tools.
|
||||
- .NET tools (vpk, nuget-license, CycloneDX, dotnet-sonarscanner, dotnet-coverage) live in `.config/dotnet-tools.json`;
|
||||
Dependabot doesn't read a root `dotnet-tools.json`. vpk and the Velopack package move together.
|
||||
|
||||
## Workflows
|
||||
|
||||
@@ -50,3 +52,6 @@ Run the app or smoke test with `HASHTOOL_DATA_DIR` pointing at a scratch folder
|
||||
- `security.yml` — vulnerable packages, licences (eng/allowed-licenses.json), gitleaks, actionlint, zizmor.
|
||||
- `release.yml` — manual (`workflow_dispatch`, version + publish) with an upgrade gate from 1.1.3; dry run on PRs that
|
||||
touch release files. Discord notifications use the maintainer's `poli0981/.github` reusable workflows, pinned by SHA.
|
||||
- `sonarcloud.yml` — SonarCloud CI analysis (Automatic Analysis is off; project `poli0981_HashTool`): scanner build,
|
||||
Cobertura coverage from the tests and the smoke test (`dotnet-coverage`), "Sonar way" gate on new code. Skipped when
|
||||
`SONAR_TOKEN` isn't available (forks, Dependabot). Issues and hotspots can't be resolved from here; fix them in code.
|
||||
+1
-1
@@ -34,7 +34,7 @@ How the code is organised: [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md).
|
||||
2. Keep the change focused; follow the existing style (the analyzers and `.editorconfig` help).
|
||||
3. Add or update tests — hashing and checksum logic belongs in `HashTool.Core` with tests in `tests/HashTool.Core.Tests`.
|
||||
4. Add a line under `## [Unreleased]` in [CHANGELOG.md](CHANGELOG.md) for anything users will notice.
|
||||
5. Open the pull request and link the issue. CI builds and tests on Windows, macOS and Linux, and scans dependencies, licences, secrets and workflows; everything must be green before merging.
|
||||
5. Open the pull request and link the issue. CI builds and tests on Windows, macOS and Linux, and scans dependencies, licences, secrets and workflows; everything must be green before merging. SonarCloud also analyses the pull request: new code should pass its quality gate (A ratings, at least 80% coverage, little duplication).
|
||||
|
||||
Commit messages follow [Conventional Commits](https://www.conventionalcommits.org/) (`fix(core): …`, `feat(app): …`, `docs: …`).
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
<ImplicitUsings>disable</ImplicitUsings>
|
||||
|
||||
<!-- Single source of truth for the product version (the release workflow also passes -p:Version=<tag>). -->
|
||||
<Version>1.2.0</Version>
|
||||
<Version>1.2.1</Version>
|
||||
<Authors>poli0981</Authors>
|
||||
<Company>poli0981</Company>
|
||||
<Product>Hash Tool</Product>
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
|
||||
[](https://github.com/poli0981/HashTool/releases/latest)
|
||||
[](https://github.com/poli0981/HashTool/actions/workflows/ci.yml)
|
||||
[](https://sonarcloud.io/summary/new_code?id=poli0981_HashTool)
|
||||
[](https://sonarcloud.io/component_measures?id=poli0981_HashTool&metric=coverage)
|
||||
[](https://scorecard.dev/viewer/?uri=github.com/poli0981/HashTool)
|
||||
[](LICENSE)
|
||||
[](https://github.com/poli0981/HashTool/releases)
|
||||
|
||||
+1
-1
@@ -14,7 +14,7 @@ Security fixes are released for the latest minor version only. Installed and por
|
||||
|
||||
### How releases are protected
|
||||
- Releases are built, tested and published by GitHub Actions from the `main` branch; every release includes `SHA256SUMS`, CycloneDX SBOMs and [build provenance attestations](https://docs.github.com/actions/security-for-github-actions/using-artifact-attestations) (`gh attestation verify <file> --repo poli0981/HashTool`).
|
||||
- Every pull request is checked for vulnerable NuGet packages, licences, leaked secrets and unsafe workflow patterns, in addition to CodeQL and OpenSSF Scorecard.
|
||||
- Every pull request is checked for vulnerable NuGet packages, licences, leaked secrets and unsafe workflow patterns, in addition to CodeQL, SonarCloud and OpenSSF Scorecard.
|
||||
- The apps are not code-signed yet, so Windows SmartScreen and macOS Gatekeeper may warn when they are first opened.
|
||||
|
||||
### Reporting a Vulnerability
|
||||
|
||||
@@ -4,6 +4,8 @@
|
||||
<IsPackable>false</IsPackable>
|
||||
<!-- Run manually, see docs/ARCHITECTURE.md (Benchmarks). -->
|
||||
<Optimize>true</Optimize>
|
||||
<!-- SonarCloud analyses benchmarks as test code: they are not product code and have no coverage. -->
|
||||
<SonarQubeTestProject>true</SonarQubeTestProject>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
||||
@@ -14,7 +14,8 @@ build/ packaging inputs (macOS Info.plist, Linux icon)
|
||||
|
||||
Shared build settings: `Directory.Build.props` (version, nullable, analyzers, NuGet audit), `Directory.Packages.props`
|
||||
(central package versions with transitive pinning), `global.json` (SDK and the Microsoft.Testing.Platform runner),
|
||||
`dotnet-tools.json` (vpk, nuget-license, CycloneDX).
|
||||
`.config/dotnet-tools.json` (vpk, nuget-license, CycloneDX, SonarScanner for .NET, dotnet-coverage; Dependabot keeps
|
||||
them up to date).
|
||||
|
||||
## HashTool.Core
|
||||
|
||||
@@ -60,6 +61,11 @@ mismatched file, 2 usage error or unreadable checksum file. Published per platfo
|
||||
- `tests/Compat/LegacyClient` — not in the solution: the release workflow uses it to update a real 1.1.3 install with
|
||||
its own Velopack 0.0.1298 library and updater (see [RELEASING.md](RELEASING.md)).
|
||||
|
||||
[SonarCloud](https://sonarcloud.io/project/overview?id=poli0981_HashTool) analyses every pull request and `main` from
|
||||
the SonarCloud workflow: the C# during a real build, with coverage from the tests above and from the smoke test
|
||||
(`dotnet-coverage`), plus the scripts and workflows. Its quality gate ("Sonar way") applies to new code; `bench/` is
|
||||
analysed as test code and `eng/` is left out of coverage.
|
||||
|
||||
## Benchmarks
|
||||
|
||||
```text
|
||||
|
||||
+12
-1
@@ -10,6 +10,7 @@ pack id HashTool, the channel, the main executable and, on macOS, the original b
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import plistlib
|
||||
import re
|
||||
import sys
|
||||
@@ -17,6 +18,16 @@ import zipfile
|
||||
from pathlib import Path
|
||||
|
||||
PACK_ID = "HashTool"
|
||||
ROOT = os.path.realpath(Path(__file__).resolve().parent.parent)
|
||||
|
||||
|
||||
def releases_folder(name: str) -> Path:
|
||||
"""The folder named on the command line; it must be inside the repository (CI passes "Releases")."""
|
||||
path = os.path.realpath(name)
|
||||
if not path.startswith(ROOT + os.sep):
|
||||
print(f"::error::{name} is outside the repository")
|
||||
raise SystemExit(1)
|
||||
return Path(path)
|
||||
|
||||
|
||||
def fail(message: str) -> None:
|
||||
@@ -103,4 +114,4 @@ if __name__ == "__main__":
|
||||
if len(sys.argv) not in (5, 6):
|
||||
print(__doc__)
|
||||
sys.exit(2)
|
||||
main(Path(sys.argv[1]), sys.argv[2], sys.argv[3], sys.argv[4], sys.argv[5] if len(sys.argv) == 6 else None)
|
||||
main(releases_folder(sys.argv[1]), sys.argv[2], sys.argv[3], sys.argv[4], sys.argv[5] if len(sys.argv) == 6 else None)
|
||||
+14
-2
@@ -9,7 +9,8 @@ Run with `python -I eng/loc.py <command>` from the repository root:
|
||||
normalize Rewrite every resx in canonical form (neutral key order, one line per header, trimmed
|
||||
multi-line values). Values never get re-wrapped.
|
||||
set FILE.json [...] Set values from JSON files shaped {"<culture>": {"Key": "value"}}. Use "neutral" for the
|
||||
English source; new keys are appended to the neutral file in the order given.
|
||||
English source; new keys are appended to the neutral file in the order given. The files
|
||||
must be inside the repository or the temporary folder.
|
||||
remove KEY [...] Delete keys from every resx.
|
||||
untranslated CULTURE List keys whose value is still identical to the English text.
|
||||
export CULTURE Print a culture's strings as JSON ("neutral" for English).
|
||||
@@ -21,8 +22,10 @@ from __future__ import annotations
|
||||
|
||||
import html
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
@@ -178,11 +181,20 @@ def cmd_normalize() -> int:
|
||||
return 0
|
||||
|
||||
|
||||
def input_file(name: str) -> Path:
|
||||
"""A file named on the command line; only files in the repository or the temporary folder are read."""
|
||||
path = os.path.realpath(name)
|
||||
for root in (os.path.realpath(ROOT), os.path.realpath(tempfile.gettempdir())):
|
||||
if path.startswith(root + os.sep):
|
||||
return Path(path)
|
||||
raise SystemExit(f"{name}: only files inside the repository or the temporary folder are accepted")
|
||||
|
||||
|
||||
def cmd_set(files: list[str]) -> int:
|
||||
neutral, cultures = load_all()
|
||||
changed: set[Path] = set()
|
||||
for file in files:
|
||||
data = json.loads(Path(file).read_text(encoding="utf-8"))
|
||||
data = json.loads(input_file(file).read_text(encoding="utf-8"))
|
||||
# Neutral first, so new keys get their position before cultures are written.
|
||||
for code in sorted(data, key=lambda c: c.lower() != "neutral"):
|
||||
resx = find_culture(cultures, neutral, code)
|
||||
|
||||
+11
-1
@@ -8,11 +8,21 @@ Prints the body of the "## [<version>]" section and fails when it is missing or
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
MAX_LENGTH = 20_000
|
||||
ROOT = os.path.realpath(Path(__file__).resolve().parent.parent)
|
||||
|
||||
|
||||
def repository_file(name: str) -> Path:
|
||||
"""A file named on the command line; only files of this repository are read."""
|
||||
path = os.path.realpath(name)
|
||||
if not path.startswith(ROOT + os.sep):
|
||||
raise SystemExit(f"::error::{name} is outside the repository")
|
||||
return Path(path)
|
||||
|
||||
|
||||
def find_section(changelog: str, version: str) -> tuple[str, str] | None:
|
||||
@@ -36,7 +46,7 @@ def main() -> int:
|
||||
parser.add_argument("--require-date", action="store_true")
|
||||
args = parser.parse_args()
|
||||
|
||||
section = find_section(Path(args.changelog).read_text(encoding="utf-8"), args.version)
|
||||
section = find_section(repository_file(args.changelog).read_text(encoding="utf-8"), args.version)
|
||||
if section is None or not section[1]:
|
||||
print(f"::error::CHANGELOG has no notes for {args.version}", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
@@ -121,13 +121,14 @@ public sealed partial class SingleInstance : IDisposable
|
||||
// One bad or broken connection must never stop the listener: keep serving later launches.
|
||||
current?.Dispose();
|
||||
current = null;
|
||||
await Task.Delay(200).ConfigureAwait(false);
|
||||
// Not the stop token: a cancelled delay would throw out of this handler and skip the cleanup below.
|
||||
await Task.Delay(200, CancellationToken.None).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
current?.Dispose();
|
||||
next?.Dispose();
|
||||
});
|
||||
}, _stop.Token);
|
||||
}
|
||||
|
||||
private NamedPipeServerStream CreateServer() =>
|
||||
|
||||
@@ -65,8 +65,17 @@ public interface ILauncherService
|
||||
/// <summary>Gives services access to the main window once it exists.</summary>
|
||||
public sealed class MainWindowAccessor
|
||||
{
|
||||
public Window? Window =>
|
||||
Application.Current?.ApplicationLifetime is IClassicDesktopStyleApplicationLifetime { MainWindow: { } window } ? window : null;
|
||||
private readonly Func<Window?> _window;
|
||||
|
||||
public MainWindowAccessor() : this(static () =>
|
||||
Application.Current?.ApplicationLifetime is IClassicDesktopStyleApplicationLifetime { MainWindow: { } window } ? window : null)
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>Tests hand in a window of their own: the headless test application has no desktop lifetime.</summary>
|
||||
internal MainWindowAccessor(Func<Window?> window) => _window = window;
|
||||
|
||||
public Window? Window => _window();
|
||||
|
||||
public TopLevel? TopLevel => Window;
|
||||
}
|
||||
|
||||
@@ -31,21 +31,34 @@ public sealed class UpdateService
|
||||
{
|
||||
public const string RepositoryUrl = "https://github.com/poli0981/HashTool";
|
||||
|
||||
private static readonly HttpClient Http = CreateHttpClient();
|
||||
private static readonly HttpClient SharedHttp = CreateHttpClient();
|
||||
|
||||
private readonly ILogger<UpdateService> _logger;
|
||||
private readonly UpdateManager? _manager;
|
||||
private readonly HttpClient _http;
|
||||
|
||||
public UpdateService(ILogger<UpdateService> logger)
|
||||
public UpdateService(ILogger<UpdateService> logger) : this(logger, CreateManager(logger), SharedHttp)
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>Tests pass a manager over a local feed and an HTTP client that never reaches GitHub.</summary>
|
||||
internal UpdateService(ILogger<UpdateService> logger, UpdateManager? manager, HttpClient http)
|
||||
{
|
||||
_logger = logger;
|
||||
_manager = manager;
|
||||
_http = http;
|
||||
}
|
||||
|
||||
private static UpdateManager? CreateManager(ILogger logger)
|
||||
{
|
||||
try
|
||||
{
|
||||
_manager = new UpdateManager(new GithubSource(RepositoryUrl, null, false));
|
||||
return new UpdateManager(new GithubSource(RepositoryUrl, null, false));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogWarning(ex, "Velopack update manager is unavailable");
|
||||
logger.LogWarning(ex, "Velopack update manager is unavailable");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -133,7 +146,7 @@ public sealed class UpdateService
|
||||
{
|
||||
try
|
||||
{
|
||||
using var response = await Http.GetAsync($"https://api.github.com/repos/poli0981/HashTool/releases/tags/{Uri.EscapeDataString(tag)}",
|
||||
using var response = await _http.GetAsync($"https://api.github.com/repos/poli0981/HashTool/releases/tags/{Uri.EscapeDataString(tag)}",
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
if (!response.IsSuccessStatusCode) continue;
|
||||
await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
|
||||
|
||||
@@ -233,13 +233,18 @@ public sealed partial class CreateHashViewModel : FileListViewModelBase
|
||||
continue;
|
||||
}
|
||||
|
||||
while (!directory.StartsWith(common, StringComparison.OrdinalIgnoreCase) && Path.GetDirectoryName(common) is { } parent)
|
||||
while (!IsSameOrInside(directory, common) && Path.GetDirectoryName(common) is { } parent)
|
||||
common = parent;
|
||||
}
|
||||
|
||||
return common ?? string.Empty;
|
||||
}
|
||||
|
||||
// "C:\data\photos-2024" shares a prefix with "C:\data\photos" but is not inside it.
|
||||
private static bool IsSameOrInside(string directory, string folder) =>
|
||||
directory.StartsWith(folder, StringComparison.OrdinalIgnoreCase)
|
||||
&& (directory.Length == folder.Length || Path.EndsInDirectorySeparator(folder) || directory[folder.Length] is '/' or '\\');
|
||||
|
||||
/// <summary>Zip entry names must be relative and use '/' (files on another drive keep their path without the colon).</summary>
|
||||
private static string ZipEntryName(string path) => path.Replace('\\', '/').Replace(":", "").TrimStart('/');
|
||||
|
||||
|
||||
@@ -224,6 +224,7 @@ public abstract partial class FileListViewModelBase : ObservableObject, IHashJob
|
||||
var options = new FileEnumerationOptions { IncludeHidden = Settings.IncludeHiddenFiles };
|
||||
var known = new HashSet<string>(_byPath.Keys, _byPath.Comparer);
|
||||
|
||||
// Importing cannot be cancelled (the batch token belongs to hashing).
|
||||
await Task.Run(async () =>
|
||||
{
|
||||
var batch = new List<FileEntry>(UiBatchSize);
|
||||
@@ -231,7 +232,7 @@ public abstract partial class FileListViewModelBase : ObservableObject, IHashJob
|
||||
foreach (var entry in FileEnumerator.Expand(paths, options, (path, ex) =>
|
||||
{
|
||||
lock (report) report.Errors.Add($"{Path.GetFileName(path)}: {ex.Message}");
|
||||
}))
|
||||
}, CancellationToken.None))
|
||||
{
|
||||
if (!known.Add(entry.FullPath))
|
||||
{
|
||||
@@ -261,7 +262,7 @@ public abstract partial class FileListViewModelBase : ObservableObject, IHashJob
|
||||
}
|
||||
|
||||
if (batch.Count > 0) await AddBatchAsync(batch, report).ConfigureAwait(false);
|
||||
});
|
||||
}, CancellationToken.None);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
@@ -434,7 +435,7 @@ public abstract partial class FileListViewModelBase : ObservableObject, IHashJob
|
||||
if (item is null) return;
|
||||
if (item.IsProcessing)
|
||||
{
|
||||
item.Cancellation?.Cancel();
|
||||
if (item.Cancellation is { } cancellation) await cancellation.CancelAsync();
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -487,7 +488,8 @@ public abstract partial class FileListViewModelBase : ObservableObject, IHashJob
|
||||
SequentialDisk = Settings.OptimizeForHdd,
|
||||
PerFileTimeout = Settings.IsFileTimeoutEnabled ? TimeSpan.FromSeconds(Settings.FileTimeoutSeconds) : null
|
||||
});
|
||||
await Task.Run(() => processor.RunAsync(toHash, CreateJob, this, _batchCts.Token));
|
||||
// The processor observes the batch token itself and reports cancelled files; Task.Run must still start.
|
||||
await Task.Run(() => processor.RunAsync(toHash, CreateJob, this, _batchCts.Token), CancellationToken.None);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
|
||||
@@ -131,7 +131,8 @@ public sealed partial class UpdateViewModel : ObservableObject
|
||||
UpdateCheckResult result;
|
||||
try
|
||||
{
|
||||
result = await _updates.CheckAsync();
|
||||
// A check is short and not cancellable from the page.
|
||||
result = await _updates.CheckAsync(CancellationToken.None);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
|
||||
@@ -14,18 +14,20 @@ public partial class CheckHashView : UserControl
|
||||
public CheckHashView()
|
||||
{
|
||||
AvaloniaXamlLoader.Load(this);
|
||||
FileDrop.Attach(this.FindControl<Panel>("DropArea")!, this.FindControl<Border>("DropHighlight"), paths =>
|
||||
DataContext is CheckHashViewModel vm ? vm.AddPathsAsync(paths) : Task.CompletedTask);
|
||||
var dropArea = this.FindControl<Panel>("DropArea")!;
|
||||
|
||||
// A checksum file dropped onto a row's hash box fills in that row's expected hash.
|
||||
AddHandler(DragDrop.DropEvent, async (sender, e) =>
|
||||
// A checksum file dropped onto a row's hash box fills in that row's expected hash. Drop events only bubble, so
|
||||
// this handler sits on the list ahead of the one that adds dropped files as new rows.
|
||||
dropArea.AddHandler(DragDrop.DropEvent, async (_, e) =>
|
||||
{
|
||||
if (e.Source is not Control { DataContext: FileItem item } source || !IsHashInput(source)) return;
|
||||
var paths = FileDrop.Paths(e);
|
||||
if (paths.Count == 0 || DataContext is not CheckHashViewModel vm) return;
|
||||
e.Handled = true;
|
||||
await vm.LoadHashFileAsync(item, paths[0]);
|
||||
}, Avalonia.Interactivity.RoutingStrategies.Tunnel);
|
||||
});
|
||||
FileDrop.Attach(dropArea, this.FindControl<Border>("DropHighlight"), paths =>
|
||||
DataContext is CheckHashViewModel vm ? vm.AddPathsAsync(paths) : Task.CompletedTask);
|
||||
}
|
||||
|
||||
private static bool IsHashInput(Control control)
|
||||
|
||||
@@ -64,13 +64,14 @@ internal static class HashCommand
|
||||
var format = request.Format ?? (request.Algorithms.Count == 1 ? ExportFormat.Gnu : ExportFormat.Bsd);
|
||||
if (format == ExportFormat.Gnu && request.Algorithms.Count > 1)
|
||||
{
|
||||
error.WriteLine("hashtool: the gnu format holds a single algorithm; use --format bsd, json or csv for several.");
|
||||
await error.WriteLineAsync("hashtool: the gnu format holds a single algorithm; use --format bsd, json or csv for several.")
|
||||
.ConfigureAwait(false);
|
||||
return HashToolCommand.UsageError;
|
||||
}
|
||||
|
||||
if (format == ExportFormat.Sfv && request.Algorithms.Any(a => a != HashType.CRC32))
|
||||
{
|
||||
error.WriteLine("hashtool: sfv files contain CRC32 only; add -a crc32.");
|
||||
await error.WriteLineAsync("hashtool: sfv files contain CRC32 only; add -a crc32.").ConfigureAwait(false);
|
||||
return HashToolCommand.UsageError;
|
||||
}
|
||||
|
||||
|
||||
@@ -88,7 +88,7 @@ internal static class VerifyCommand
|
||||
malformed += document.InvalidLines.Count;
|
||||
if (document.IsEmpty)
|
||||
{
|
||||
error.WriteLine($"hashtool: {checksumFile}: no properly formatted checksum lines found");
|
||||
await error.WriteLineAsync($"hashtool: {checksumFile}: no properly formatted checksum lines found").ConfigureAwait(false);
|
||||
exitCode = HashToolCommand.UsageError;
|
||||
continue;
|
||||
}
|
||||
@@ -101,7 +101,8 @@ internal static class VerifyCommand
|
||||
var shown = entry.FileName ?? (target is null ? checksumFile : Path.GetFileName(target));
|
||||
if (target is null)
|
||||
{
|
||||
error.WriteLine($"hashtool: {checksumFile}:{entry.LineNumber}: refusing to open network or device path '{shown}'");
|
||||
await error.WriteLineAsync($"hashtool: {checksumFile}:{entry.LineNumber}: refusing to open network or device path '{shown}'")
|
||||
.ConfigureAwait(false);
|
||||
unreadable++;
|
||||
continue;
|
||||
}
|
||||
@@ -114,14 +115,17 @@ internal static class VerifyCommand
|
||||
var outcome = await CheckAsync(engine, target, entry.Hash, candidates, cancellationToken).ConfigureAwait(false);
|
||||
if (outcome.Error is not null) unreadable++;
|
||||
else if (!outcome.IsOk) mismatched++;
|
||||
if (!quiet || !outcome.IsOk) output.WriteLine($"{shown}: {outcome.Describe()}");
|
||||
if (!quiet || !outcome.IsOk) await output.WriteLineAsync($"{shown}: {outcome.Describe()}").ConfigureAwait(false);
|
||||
if (outcome.Error is { } ex) HashToolCommand.ReportError(error, shown, ex);
|
||||
}
|
||||
}
|
||||
|
||||
if (malformed > 0) error.WriteLine($"hashtool: WARNING: {Count(malformed, "line is", "lines are")} improperly formatted");
|
||||
if (unreadable > 0) error.WriteLine($"hashtool: WARNING: {Count(unreadable, "listed file", "listed files")} could not be read");
|
||||
if (mismatched > 0) error.WriteLine($"hashtool: WARNING: {Count(mismatched, "computed checksum", "computed checksums")} did NOT match");
|
||||
if (malformed > 0)
|
||||
await error.WriteLineAsync($"hashtool: WARNING: {Count(malformed, "line is", "lines are")} improperly formatted").ConfigureAwait(false);
|
||||
if (unreadable > 0)
|
||||
await error.WriteLineAsync($"hashtool: WARNING: {Count(unreadable, "listed file", "listed files")} could not be read").ConfigureAwait(false);
|
||||
if (mismatched > 0)
|
||||
await error.WriteLineAsync($"hashtool: WARNING: {Count(mismatched, "computed checksum", "computed checksums")} did NOT match").ConfigureAwait(false);
|
||||
if (exitCode == HashToolCommand.Success && (mismatched > 0 || unreadable > 0)) exitCode = HashToolCommand.Failure;
|
||||
return exitCode;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,265 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using Avalonia.Headless.XUnit;
|
||||
using HashTool.App.Models;
|
||||
using HashTool.App.Services;
|
||||
using HashTool.App.ViewModels;
|
||||
using HashTool.Core.Hashing;
|
||||
using HashTool.Core.Tests;
|
||||
using Xunit;
|
||||
|
||||
namespace HashTool.App.Tests;
|
||||
|
||||
public sealed class CheckHashViewModelTests
|
||||
{
|
||||
private const string HelloSha256 = "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824";
|
||||
private const string HelloMd5 = "5d41402abc4b2a76b9719d911017c592";
|
||||
private const string HelloBlake3 = "ea8f163db38682925e4491c5e58d4bb3506ef8c14eb78a86e908c5624a67200f";
|
||||
|
||||
private sealed class Page : IDisposable
|
||||
{
|
||||
public Page()
|
||||
{
|
||||
Settings = TestServices.Settings(Path.Combine(Temp.Path, ".settings"));
|
||||
Vm = new CheckHashViewModel(TestServices.Create(Dialogs, Storage, null, Settings));
|
||||
}
|
||||
|
||||
public TempDirectory Temp { get; } = new();
|
||||
|
||||
public SettingsService Settings { get; }
|
||||
|
||||
public RecordingDialogs Dialogs { get; } = new();
|
||||
|
||||
public ScriptedStorage Storage { get; } = new();
|
||||
|
||||
public CheckHashViewModel Vm { get; }
|
||||
|
||||
public FileItem Row(string name) => Vm.Items.Single(i => i.FileName == name);
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
Settings.Dispose();
|
||||
Temp.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
private static string F(string key, params object?[] args) => TestServices.Localization.Format(key, args);
|
||||
|
||||
private static void Sparse(string path, long length)
|
||||
{
|
||||
using var stream = File.Create(path);
|
||||
stream.SetLength(length);
|
||||
}
|
||||
|
||||
[AvaloniaFact]
|
||||
public async Task AChecksumFile_ListsEveryEntry_AndReportsWhatItCannotUse()
|
||||
{
|
||||
using var page = new Page();
|
||||
page.Temp.File("present.txt", "hello");
|
||||
var sums = page.Temp.File("SHA256SUMS",
|
||||
$"{HelloSha256} present.txt\n{HelloSha256} missing.txt\n{HelloSha256} //server/share/x.txt\nnot a checksum line\n");
|
||||
|
||||
await page.Vm.AddPathsAsync([sums]);
|
||||
|
||||
Assert.Equal(ItemStatus.FromChecksumFile, page.Row("present.txt").Status);
|
||||
Assert.Equal(ItemStatus.NotFound, page.Row("missing.txt").Status);
|
||||
Assert.Equal(FileStatus.Failure, page.Row("missing.txt").State);
|
||||
Assert.Equal(2, page.Vm.Items.Count);
|
||||
var (message, icon) = page.Dialogs.Shown.Single();
|
||||
Assert.Contains(F("Msg_ChecksumFileInvalid", 1, "SHA256SUMS"), message, StringComparison.Ordinal);
|
||||
Assert.Contains(F("Msg_UnsafePath", "//server/share/x.txt"), message, StringComparison.Ordinal);
|
||||
Assert.Equal(DialogIcon.Warning, icon);
|
||||
}
|
||||
|
||||
[AvaloniaFact]
|
||||
public async Task UnusableChecksumFiles_AreReported()
|
||||
{
|
||||
using var page = new Page();
|
||||
var empty = page.Temp.File("empty.sha256", "nothing useful here\n");
|
||||
var huge = Path.Combine(page.Temp.Path, "huge.md5");
|
||||
Sparse(huge, 17L * 1024 * 1024);
|
||||
|
||||
await page.Vm.AddPathsAsync([empty, huge]);
|
||||
|
||||
Assert.Empty(page.Vm.Items);
|
||||
var message = page.Dialogs.Shown.Single().Message;
|
||||
Assert.Contains(F("Msg_ChecksumFileEmpty", "empty.sha256"), message, StringComparison.Ordinal);
|
||||
Assert.Contains("huge.md5", message, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[AvaloniaFact]
|
||||
public async Task Verify_FindsSidecars_AndReportsRowsItCannotCheck()
|
||||
{
|
||||
using var page = new Page();
|
||||
var withSidecar = page.Temp.File("image.iso", "hello");
|
||||
page.Temp.File("image.iso.sha256", HelloSha256);
|
||||
var unreadableSidecar = page.Temp.File("other.iso", "hello");
|
||||
Sparse(unreadableSidecar + ".sha256", 17L * 1024 * 1024);
|
||||
var noHash = page.Temp.File("plain.bin", "hello");
|
||||
var gone = page.Temp.File("gone.bin", "hello");
|
||||
await page.Vm.AddPathsAsync([withSidecar, unreadableSidecar, noHash, gone]);
|
||||
File.Delete(gone);
|
||||
|
||||
await page.Vm.RunAllCommand.ExecuteAsync(null);
|
||||
|
||||
Assert.Equal(ItemStatus.Valid, page.Row("image.iso").Status);
|
||||
Assert.Equal(withSidecar + ".sha256", page.Row("image.iso").SourceChecksumFile);
|
||||
Assert.Equal(ItemStatus.MissingHash, page.Row("other.iso").Status);
|
||||
Assert.Equal(ItemStatus.MissingHash, page.Row("plain.bin").Status);
|
||||
Assert.Equal(ItemStatus.NotFound, page.Row("gone.bin").Status);
|
||||
var (message, icon) = page.Dialogs.Shown.Last();
|
||||
Assert.StartsWith(F("Msg_CheckResult", 4, 1, 3, 0), message, StringComparison.Ordinal);
|
||||
Assert.Equal(DialogIcon.Warning, icon);
|
||||
}
|
||||
|
||||
[AvaloniaFact]
|
||||
public async Task Verify_TriesTheAlgorithmsAHashCouldBelongTo()
|
||||
{
|
||||
using var page = new Page();
|
||||
foreach (var name in new[] { "mismatch.txt", "blake3.txt", "crc.txt", "short.txt", "odd.txt", "md5row.txt" })
|
||||
page.Temp.File(name, name == "crc.txt" ? "123456789" : "hello");
|
||||
await page.Vm.AddPathsAsync([page.Temp.Path]);
|
||||
page.Row("mismatch.txt").ExpectedHash = new string('0', 64);
|
||||
page.Row("blake3.txt").ExpectedHash = HelloBlake3;
|
||||
page.Row("crc.txt").Algorithm = HashType.CRC32;
|
||||
page.Row("crc.txt").IsAlgorithmKnown = true;
|
||||
page.Row("crc.txt").ExpectedHash = "2639F4CB";
|
||||
page.Row("short.txt").IsAlgorithmKnown = true;
|
||||
page.Row("short.txt").ExpectedHash = "abc";
|
||||
page.Row("odd.txt").ExpectedHash = "0123456789";
|
||||
page.Row("md5row.txt").Algorithm = HashType.MD5;
|
||||
page.Row("md5row.txt").ExpectedHash = HelloSha256;
|
||||
|
||||
await page.Vm.RunAllCommand.ExecuteAsync(null);
|
||||
|
||||
Assert.Equal(ItemStatus.Mismatch, page.Row("mismatch.txt").Status);
|
||||
Assert.False(page.Row("mismatch.txt").IsMatch);
|
||||
Assert.Equal(ItemStatus.Valid, page.Row("blake3.txt").Status);
|
||||
Assert.Equal(HashType.BLAKE3, page.Row("blake3.txt").Algorithm);
|
||||
Assert.Equal(ItemStatus.ValidLegacyCrc, page.Row("crc.txt").Status);
|
||||
Assert.Equal(ItemStatus.LengthMismatch, page.Row("short.txt").Status);
|
||||
Assert.Equal(ItemStatus.LengthMismatch, page.Row("odd.txt").Status);
|
||||
Assert.Equal(ItemStatus.Valid, page.Row("md5row.txt").Status);
|
||||
Assert.Equal(HashType.SHA256, page.Row("md5row.txt").Algorithm);
|
||||
}
|
||||
|
||||
[AvaloniaFact]
|
||||
public async Task LoadHashFile_FillsTheRowFromAnyFile()
|
||||
{
|
||||
using var page = new Page();
|
||||
var data = page.Temp.File("data.bin", "hello");
|
||||
await page.Vm.AddPathsAsync([data]);
|
||||
var row = page.Row("data.bin");
|
||||
|
||||
await page.Vm.LoadHashFileAsync(row, page.Temp.File("tagged.txt", $"MD5 (data.bin) = {HelloMd5}\n"));
|
||||
Assert.Equal(ItemStatus.HashLoaded, row.Status);
|
||||
Assert.Equal(HashType.MD5, row.Algorithm);
|
||||
Assert.True(row.IsAlgorithmKnown);
|
||||
Assert.Equal(HelloMd5, row.ExpectedHash, ignoreCase: true);
|
||||
|
||||
await page.Vm.LoadHashFileAsync(row, page.Temp.File("others.txt", $"{HelloSha256} a.bin\n{HelloSha256} b.bin\n"));
|
||||
Assert.Equal(ItemStatus.NoHashInFile, row.Status);
|
||||
|
||||
await page.Vm.LoadHashFileAsync(row, Path.Combine(page.Temp.Path, "nowhere.sha256"));
|
||||
Assert.Equal(ItemStatus.UnreadableHashFile, row.Status);
|
||||
|
||||
row.IsProcessing = true;
|
||||
await page.Vm.LoadHashFileAsync(row, page.Temp.File("ignored.sha256", HelloSha256));
|
||||
Assert.Equal(ItemStatus.UnreadableHashFile, row.Status);
|
||||
}
|
||||
|
||||
[AvaloniaFact]
|
||||
public async Task BrowseAndOpen_UseThePickers()
|
||||
{
|
||||
using var page = new Page();
|
||||
var data = page.Temp.File("data.bin", "hello");
|
||||
await page.Vm.AddPathsAsync([data]);
|
||||
var row = page.Row("data.bin");
|
||||
|
||||
page.Storage.Files = [page.Temp.File("expected.txt", HelloSha256)];
|
||||
await page.Vm.BrowseHashFileCommand.ExecuteAsync(row);
|
||||
Assert.Equal(HelloSha256, row.ExpectedHash);
|
||||
|
||||
page.Storage.Files = [page.Temp.File("a.txt", "1"), page.Temp.File("b.txt", "2")];
|
||||
await page.Vm.BrowseHashFileCommand.ExecuteAsync(row);
|
||||
await page.Vm.BrowseHashFileCommand.ExecuteAsync(null);
|
||||
Assert.Equal(HelloSha256, row.ExpectedHash);
|
||||
|
||||
page.Temp.File("second.bin", "hello");
|
||||
page.Storage.Files = [page.Temp.File("list.sha256", $"{HelloSha256} second.bin\n")];
|
||||
await page.Vm.OpenChecksumFileCommand.ExecuteAsync(null);
|
||||
Assert.Equal(HelloSha256, page.Row("second.bin").ExpectedHash);
|
||||
|
||||
page.Storage.Files = [];
|
||||
await page.Vm.OpenChecksumFileCommand.ExecuteAsync(null);
|
||||
Assert.Equal(2, page.Vm.Items.Count);
|
||||
}
|
||||
|
||||
[AvaloniaFact]
|
||||
public async Task ChangingTheDefaultAlgorithm_UpdatesRowsWithAGuessedAlgorithm()
|
||||
{
|
||||
using var page = new Page();
|
||||
page.Temp.File("guessed.bin", "hello");
|
||||
page.Temp.File("known.bin", "hello");
|
||||
await page.Vm.AddPathsAsync([page.Temp.Path]);
|
||||
page.Row("known.bin").IsAlgorithmKnown = true;
|
||||
|
||||
page.Vm.DefaultAlgorithm = HashType.SHA512;
|
||||
|
||||
Assert.Equal(HashType.SHA512, page.Row("guessed.bin").Algorithm);
|
||||
Assert.Equal(HashType.SHA256, page.Row("known.bin").Algorithm);
|
||||
Assert.Equal(HashType.SHA512, page.Settings.Current.VerifyAlgorithm);
|
||||
}
|
||||
|
||||
[AvaloniaFact]
|
||||
public async Task ClearingResults_AndFailedRows_FollowTheExpectedHash()
|
||||
{
|
||||
using var page = new Page();
|
||||
page.Temp.File("good.bin", "hello");
|
||||
page.Temp.File("bad.bin", "hello");
|
||||
page.Temp.File("none.bin", "hello");
|
||||
await page.Vm.AddPathsAsync([page.Temp.Path]);
|
||||
page.Row("good.bin").ExpectedHash = HelloSha256;
|
||||
page.Row("bad.bin").ExpectedHash = new string('1', 64);
|
||||
await page.Vm.RunAllCommand.ExecuteAsync(null);
|
||||
|
||||
page.Vm.ClearResultsCommand.Execute(null);
|
||||
Assert.Equal(ItemStatus.Waiting, page.Row("good.bin").Status);
|
||||
Assert.Equal(ItemStatus.Ready, page.Row("none.bin").Status);
|
||||
|
||||
await page.Vm.RunAllCommand.ExecuteAsync(null);
|
||||
page.Vm.ClearFailedCommand.Execute(null);
|
||||
Assert.Equal("good.bin", Assert.Single(page.Vm.Items).FileName);
|
||||
}
|
||||
|
||||
[AvaloniaFact]
|
||||
public async Task ARowBeingHashed_IsNotMergedWithANewChecksumFile()
|
||||
{
|
||||
using var page = new Page();
|
||||
var data = page.Temp.File("data.bin", "hello");
|
||||
await page.Vm.AddPathsAsync([data]);
|
||||
page.Row("data.bin").IsProcessing = true;
|
||||
|
||||
await page.Vm.AddPathsAsync([page.Temp.File("data.bin.sha256", $"{HelloSha256} data.bin\n")]);
|
||||
|
||||
Assert.Empty(page.Row("data.bin").ExpectedHash);
|
||||
}
|
||||
|
||||
[AvaloniaFact]
|
||||
public async Task CancellingAVerification_CountsCancelledRows()
|
||||
{
|
||||
using var page = new Page();
|
||||
for (var i = 0; i < 200; i++) page.Temp.File($"f{i:D3}.bin", "hello");
|
||||
await page.Vm.AddPathsAsync([page.Temp.Path]);
|
||||
foreach (var item in page.Vm.Items) item.ExpectedHash = HelloSha256;
|
||||
|
||||
var run = page.Vm.RunAllCommand.ExecuteAsync(null);
|
||||
page.Vm.CancelCommand.Execute(null);
|
||||
await run;
|
||||
|
||||
Assert.Contains(page.Vm.Items, i => i.State == FileStatus.Cancelled);
|
||||
Assert.Equal(DialogIcon.Warning, page.Dialogs.Shown.Last().Icon);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
using System;
|
||||
using System.Linq;
|
||||
using Avalonia;
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Controls.Documents;
|
||||
using Avalonia.Headless.XUnit;
|
||||
using Avalonia.Media;
|
||||
using HashTool.App.Services.Theme;
|
||||
using HashTool.App.Views.Controls;
|
||||
using HashTool.Core.Configuration;
|
||||
using Xunit;
|
||||
|
||||
namespace HashTool.App.Tests;
|
||||
|
||||
public sealed class HighlightTextBlockControlTests
|
||||
{
|
||||
private static Run[] Runs(HighlightTextBlock control) =>
|
||||
control.FindControl<TextBlock>("PART_TextBlock")!.Inlines!.OfType<Run>().ToArray();
|
||||
|
||||
[AvaloniaFact]
|
||||
public void ShowsMatchesInBoldWithTheHighlightBrush()
|
||||
{
|
||||
var control = new HighlightTextBlock { HighlightBrush = Brushes.Orange, TextTrimming = TextTrimming.CharacterEllipsis };
|
||||
|
||||
control.Text = "report.pdf";
|
||||
Assert.Equal(["report.pdf"], Runs(control).Select(r => r.Text));
|
||||
|
||||
control.HighlightText = " REP ";
|
||||
var runs = Runs(control);
|
||||
Assert.Equal(["rep", "ort.pdf"], runs.Select(r => r.Text));
|
||||
Assert.Equal(FontWeight.Bold, runs[0].FontWeight);
|
||||
Assert.Same(Brushes.Orange, runs[0].Foreground);
|
||||
Assert.Equal(TextTrimming.CharacterEllipsis, control.TextTrimming);
|
||||
Assert.Equal(" REP ", control.HighlightText);
|
||||
}
|
||||
|
||||
[AvaloniaFact]
|
||||
public void EmptyText_ShowsNothing()
|
||||
{
|
||||
var control = new HighlightTextBlock { HighlightText = "x", Text = "" };
|
||||
|
||||
Assert.Empty(Runs(control));
|
||||
Assert.Equal("", control.Text);
|
||||
}
|
||||
|
||||
[AvaloniaFact]
|
||||
public void ChangingTheBrush_RebuildsTheRuns()
|
||||
{
|
||||
var control = new HighlightTextBlock { Text = "aXa", HighlightText = "x" };
|
||||
|
||||
control.HighlightBrush = Brushes.Red;
|
||||
|
||||
Assert.Same(Brushes.Red, Runs(control).Single(r => r.Text == "X").Foreground);
|
||||
Assert.Same(Brushes.Red, control.HighlightBrush);
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class ThemeTests
|
||||
{
|
||||
[Theory]
|
||||
[InlineData(false)]
|
||||
[InlineData(true)]
|
||||
public void EveryStyleDefinesEveryBrush(bool isDark)
|
||||
{
|
||||
foreach (var style in Enum.GetValues<AppThemeStyle>())
|
||||
{
|
||||
var palette = ThemePalettes.Get(style, isDark);
|
||||
Assert.All(ThemePalettes.Keys, key => Assert.IsAssignableFrom<IBrush>(palette[key]));
|
||||
Assert.Equal(ThemePalettes.Keys.Length, palette.Count);
|
||||
}
|
||||
}
|
||||
|
||||
[AvaloniaFact]
|
||||
public void Apply_SetsTheVariantAndTheBrushesOfTheStyle()
|
||||
{
|
||||
var app = Application.Current!;
|
||||
var theme = new ThemeService();
|
||||
|
||||
theme.CurrentThemeVariant = AppThemeVariant.Dark;
|
||||
foreach (var style in ThemeService.Styles)
|
||||
{
|
||||
theme.CurrentThemeStyle = style;
|
||||
Assert.True(theme.IsDark);
|
||||
Assert.Equal(Avalonia.Styling.ThemeVariant.Dark, app.RequestedThemeVariant);
|
||||
Assert.Equal(ThemePalettes.Get(style, isDark: true)["AppBackgroundBrush"].ToString(), app.Resources["AppBackgroundBrush"]!.ToString());
|
||||
}
|
||||
|
||||
theme.CurrentThemeVariant = AppThemeVariant.Light;
|
||||
Assert.False(theme.IsDark);
|
||||
Assert.Equal(Avalonia.Styling.ThemeVariant.Light, app.RequestedThemeVariant);
|
||||
|
||||
theme.CurrentThemeVariant = AppThemeVariant.System;
|
||||
Assert.Equal(Avalonia.Styling.ThemeVariant.Default, app.RequestedThemeVariant);
|
||||
}
|
||||
|
||||
[AvaloniaFact]
|
||||
public void Attach_FollowsThePlatformSetting()
|
||||
{
|
||||
var theme = new ThemeService { CurrentThemeStyle = AppThemeStyle.Retro, IsThemeLocked = true };
|
||||
|
||||
theme.Attach(Application.Current!);
|
||||
|
||||
Assert.Equal(Application.Current!.PlatformSettings?.GetColorValues().ThemeVariant == Avalonia.Platform.PlatformThemeVariant.Dark,
|
||||
theme.IsDark);
|
||||
Assert.True(theme.IsThemeLocked);
|
||||
}
|
||||
|
||||
[AvaloniaFact]
|
||||
public void WindowEffect_TogglesTransparencyOnAWindow()
|
||||
{
|
||||
var window = new Window();
|
||||
window.Show();
|
||||
try
|
||||
{
|
||||
// The headless platform has no transparency, so Avalonia reports the fallback background: check the hints only.
|
||||
WindowEffect.Apply(window);
|
||||
if (OperatingSystem.IsWindows() || OperatingSystem.IsMacOS())
|
||||
Assert.Contains(WindowTransparencyLevel.AcrylicBlur, window.TransparencyLevelHint);
|
||||
else
|
||||
Assert.Equal([WindowTransparencyLevel.None], window.TransparencyLevelHint);
|
||||
|
||||
WindowEffect.Disable(window);
|
||||
Assert.Equal([WindowTransparencyLevel.None], window.TransparencyLevelHint);
|
||||
|
||||
// Tests have no main window: these must simply do nothing.
|
||||
WindowEffect.ApplyToMainWindow();
|
||||
WindowEffect.DisableForMainWindow();
|
||||
}
|
||||
finally
|
||||
{
|
||||
window.Close();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
using System;
|
||||
using System.Globalization;
|
||||
using System.Linq;
|
||||
using Avalonia.Headless.XUnit;
|
||||
using Avalonia.Media;
|
||||
using HashTool.App.Converters;
|
||||
using HashTool.App.Models;
|
||||
using HashTool.App.Services;
|
||||
using HashTool.App.ViewModels;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Xunit;
|
||||
|
||||
namespace HashTool.App.Tests;
|
||||
|
||||
public sealed class ConverterTests
|
||||
{
|
||||
private static LocalizationProxy Proxy => new(TestServices.Localization);
|
||||
|
||||
private static string L(string key) => TestServices.Localization[key];
|
||||
|
||||
[AvaloniaFact]
|
||||
public void EnumLabels_TranslateEveryKindOfValue()
|
||||
{
|
||||
var converter = new EnumLabelConverter();
|
||||
object? Label(object? value) => converter.Convert([value, Proxy], typeof(string), null, CultureInfo.InvariantCulture);
|
||||
|
||||
Assert.Equal(L("Filter_All"), Label(null));
|
||||
Assert.Equal(L("Lbl_Status_Ready"), Label(FileStatus.Ready));
|
||||
Assert.Equal(L("Status_Processing_Filter"), Label(FileStatus.Processing));
|
||||
Assert.Equal(L("Status_Done"), Label(FileStatus.Success));
|
||||
Assert.Equal(L("Status_Failure"), Label(FileStatus.Failure));
|
||||
Assert.Equal(L("Status_Cancelled"), Label(FileStatus.Cancelled));
|
||||
Assert.Equal(L("Size_All"), Label(FileSizeFilter.All));
|
||||
Assert.Equal(L("Size_Small"), Label(FileSizeFilter.Small));
|
||||
Assert.Equal(L("Size_Medium"), Label(FileSizeFilter.Medium));
|
||||
Assert.Equal(L("Size_Large"), Label(FileSizeFilter.Large));
|
||||
Assert.Equal(L("Size_ExtraLarge"), Label(FileSizeFilter.ExtraLarge));
|
||||
foreach (var style in Enum.GetValues<Core.Configuration.AppThemeStyle>()) Assert.Equal(L($"Theme_{style}"), Label(style));
|
||||
Assert.Equal(L("Btn_Yes"), Label(new Option<int>(1, "Btn_Yes")));
|
||||
Assert.Equal("42", Label(42));
|
||||
}
|
||||
|
||||
[AvaloniaFact]
|
||||
public void EnumLabels_WithoutLocalization_FallBackToTheValue()
|
||||
{
|
||||
var converter = new EnumLabelConverter();
|
||||
|
||||
Assert.Equal("Success", converter.Convert([FileStatus.Success], typeof(string), null, CultureInfo.InvariantCulture));
|
||||
Assert.Equal("Success", converter.Convert([FileStatus.Success, "not a proxy"], typeof(string), null, CultureInfo.InvariantCulture));
|
||||
Assert.Null(converter.Convert([], typeof(string), null, CultureInfo.InvariantCulture));
|
||||
Assert.Null(converter.Convert([null], typeof(string), null, CultureInfo.InvariantCulture));
|
||||
}
|
||||
|
||||
[AvaloniaFact]
|
||||
public void StatusText_HasATranslationForEveryStatus()
|
||||
{
|
||||
var converter = new StatusTextConverter();
|
||||
foreach (var status in Enum.GetValues<ItemStatus>())
|
||||
{
|
||||
foreach (var detail in new[] { "SHA256", null })
|
||||
{
|
||||
var text = converter.Convert([status, detail, Proxy], typeof(string), null, CultureInfo.InvariantCulture) as string;
|
||||
Assert.False(string.IsNullOrEmpty(text), status.ToString());
|
||||
Assert.False(text.StartsWith('['), $"{status}: {text}");
|
||||
}
|
||||
}
|
||||
|
||||
Assert.Contains("SHA256", (string)converter.Convert([ItemStatus.Hashing, "SHA256", Proxy], typeof(string), null, CultureInfo.InvariantCulture)!);
|
||||
Assert.Equal("999", converter.Convert([(ItemStatus)999, null, Proxy], typeof(string), null, CultureInfo.InvariantCulture));
|
||||
}
|
||||
|
||||
[AvaloniaFact]
|
||||
public void StatusText_NeedsStatusAndLocalization()
|
||||
{
|
||||
var converter = new StatusTextConverter();
|
||||
|
||||
Assert.Null(converter.Convert([ItemStatus.Done, null], typeof(string), null, CultureInfo.InvariantCulture));
|
||||
Assert.Null(converter.Convert(["Done", null, Proxy], typeof(string), null, CultureInfo.InvariantCulture));
|
||||
Assert.Null(converter.Convert([ItemStatus.Done, null, "proxy"], typeof(string), null, CultureInfo.InvariantCulture));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void StatusSeverity_PutsEveryStatusInAtMostOneClass()
|
||||
{
|
||||
ItemStatus[] success = [ItemStatus.Done, ItemStatus.Saved, ItemStatus.Valid, ItemStatus.ValidLegacyCrc];
|
||||
ItemStatus[] error =
|
||||
[
|
||||
ItemStatus.Failed, ItemStatus.NotFound, ItemStatus.AccessDenied, ItemStatus.InUse, ItemStatus.Mismatch, ItemStatus.LengthMismatch,
|
||||
ItemStatus.UnreadableHashFile
|
||||
];
|
||||
ItemStatus[] warning = [ItemStatus.Cancelled, ItemStatus.TimedOut, ItemStatus.MissingHash, ItemStatus.NoHashInFile];
|
||||
|
||||
foreach (var status in Enum.GetValues<ItemStatus>())
|
||||
{
|
||||
Assert.Equal(success.Contains(status), Is(StatusSeverity.IsSuccess, status));
|
||||
Assert.Equal(error.Contains(status), Is(StatusSeverity.IsError, status));
|
||||
Assert.Equal(warning.Contains(status), Is(StatusSeverity.IsWarning, status));
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void LogLevelSeverity_MarksWarningsAndErrors()
|
||||
{
|
||||
Assert.True(Is(LogLevelSeverity.IsWarning, LogLevel.Warning));
|
||||
Assert.False(Is(LogLevelSeverity.IsWarning, LogLevel.Error));
|
||||
Assert.True(Is(LogLevelSeverity.IsError, LogLevel.Error));
|
||||
Assert.True(Is(LogLevelSeverity.IsError, LogLevel.Critical));
|
||||
Assert.False(Is(LogLevelSeverity.IsError, LogLevel.Information));
|
||||
}
|
||||
|
||||
private static bool Is(Avalonia.Data.Converters.IValueConverter converter, object value) =>
|
||||
(bool)converter.Convert(value, typeof(bool), null, CultureInfo.InvariantCulture)!;
|
||||
|
||||
[Theory]
|
||||
[InlineData("0123456789abcdef", true, false, null, "0123********cdef")]
|
||||
[InlineData("0123456789abcdef", true, true, null, "0123456789abcdef")]
|
||||
[InlineData("0123456789abcdef", false, false, null, "0123456789abcdef")]
|
||||
[InlineData("0123456789abcdef", false, true, "MaskOnly", "0123********cdef")]
|
||||
[InlineData("abcd1234", true, false, null, "********")]
|
||||
[InlineData("", true, false, null, "")]
|
||||
[InlineData("", false, false, "MaskOnly", "")]
|
||||
public void HashMask_HidesTheMiddleOfAHash(string hash, bool masking, bool revealed, string? parameter, string expected)
|
||||
{
|
||||
Assert.Equal(expected, new HashMaskConverter().Convert([hash, masking, revealed], typeof(string), parameter, CultureInfo.InvariantCulture));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void HashMask_ToleratesMissingValues()
|
||||
{
|
||||
var converter = new HashMaskConverter();
|
||||
|
||||
Assert.Equal("", converter.Convert([null, null], typeof(string), null, CultureInfo.InvariantCulture));
|
||||
Assert.Equal("abc", converter.Convert(["abc", null, null], typeof(string), null, CultureInfo.InvariantCulture));
|
||||
}
|
||||
|
||||
[AvaloniaFact]
|
||||
public void FontName_ShowsTheDefaultFontAsTranslatedLabel()
|
||||
{
|
||||
var converter = new FontNameConverter();
|
||||
|
||||
Assert.Equal(L("Font_Default"), converter.Convert(FontFamily.Default, typeof(string), null, CultureInfo.InvariantCulture));
|
||||
Assert.Equal(L("Font_Default"), converter.Convert(new FontFamily("$Default"), typeof(string), null, CultureInfo.InvariantCulture));
|
||||
Assert.Equal("Inter", converter.Convert(new FontFamily("Inter"), typeof(string), null, CultureInfo.InvariantCulture));
|
||||
Assert.Equal(5, converter.Convert(5, typeof(string), null, CultureInfo.InvariantCulture));
|
||||
Assert.Throws<NotSupportedException>(() => converter.ConvertBack("Inter", typeof(FontFamily), null, CultureInfo.InvariantCulture));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,301 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.IO.Compression;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using Avalonia.Headless.XUnit;
|
||||
using HashTool.App.Models;
|
||||
using HashTool.App.Services;
|
||||
using HashTool.App.ViewModels;
|
||||
using HashTool.Core.Checksums;
|
||||
using HashTool.Core.Hashing;
|
||||
using HashTool.Core.Tests;
|
||||
using Xunit;
|
||||
|
||||
namespace HashTool.App.Tests;
|
||||
|
||||
/// <summary>A Generate page of its own: settings, dialogs, pickers and clipboard belong to the test.</summary>
|
||||
internal sealed class CreatePage : IDisposable
|
||||
{
|
||||
public CreatePage()
|
||||
{
|
||||
Settings = TestServices.Settings(System.IO.Path.Combine(Temp.Path, ".settings"));
|
||||
Vm = new CreateHashViewModel(TestServices.Create(Dialogs, Storage, Clipboard, Settings));
|
||||
}
|
||||
|
||||
public TempDirectory Temp { get; } = new();
|
||||
|
||||
public SettingsService Settings { get; }
|
||||
|
||||
public RecordingDialogs Dialogs { get; } = new();
|
||||
|
||||
public ScriptedStorage Storage { get; } = new();
|
||||
|
||||
public RecordingClipboard Clipboard { get; } = new();
|
||||
|
||||
public CreateHashViewModel Vm { get; }
|
||||
|
||||
public string Path(string name) => System.IO.Path.Combine(Temp.Path, name);
|
||||
|
||||
public async Task<string[]> HashAsync(params (string Name, string Content)[] files)
|
||||
{
|
||||
var paths = files.Select(f => Temp.File(f.Name, f.Content)).ToArray();
|
||||
await Vm.AddPathsAsync(paths);
|
||||
await Vm.RunAllCommand.ExecuteAsync(null);
|
||||
return paths;
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
Settings.Dispose();
|
||||
Temp.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class CreateHashViewModelTests
|
||||
{
|
||||
private const string HelloSha256 = "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824";
|
||||
private const string HelloMd5 = "5d41402abc4b2a76b9719d911017c592";
|
||||
|
||||
[AvaloniaFact]
|
||||
public async Task ExportsOneChecksumFile_WithPathsRelativeToIt()
|
||||
{
|
||||
using var page = new CreatePage();
|
||||
await page.HashAsync(("sub/a.txt", "hello"), ("b.txt", "hello"));
|
||||
page.Storage.SavePath = page.Path("SHA256SUMS");
|
||||
|
||||
await page.Vm.ExportChecksumFileCommand.ExecuteAsync(null);
|
||||
|
||||
Assert.Equal("SHA256SUMS.sha256", page.Storage.SuggestedName);
|
||||
Assert.Equal(ExportFormat.Gnu, page.Storage.OfferedTypes[0].Tag);
|
||||
Assert.DoesNotContain(page.Storage.OfferedTypes, t => (ExportFormat)t.Tag! == ExportFormat.Sfv);
|
||||
Assert.Equal([$"{HelloSha256} sub/a.txt", $"{HelloSha256} b.txt"], (await File.ReadAllLinesAsync(page.Storage.SavePath, TestContext.Current.CancellationToken)).Order(StringComparer.Ordinal).Reverse());
|
||||
Assert.Equal(DialogIcon.Success, page.Dialogs.Shown[^1].Icon);
|
||||
}
|
||||
|
||||
[AvaloniaTheory]
|
||||
[InlineData(ExportFormat.Json, "{0}.json", "\"hash\": \"" + HelloSha256 + "\"")]
|
||||
[InlineData(ExportFormat.Csv, "{0}.csv", "b.txt,5,SHA256," + HelloSha256)]
|
||||
[InlineData(ExportFormat.Bsd, "{0}.txt", "SHA256 (b.txt) = " + HelloSha256)]
|
||||
public async Task ExportsTheFormatPickedInTheDialog(ExportFormat format, string name, string expected)
|
||||
{
|
||||
using var page = new CreatePage();
|
||||
await page.HashAsync(("b.txt", "hello"));
|
||||
page.Storage.SavePath = page.Path(string.Format(System.Globalization.CultureInfo.InvariantCulture, name, "out"));
|
||||
page.Storage.PickType = types => types.Single(t => (ExportFormat)t.Tag! == format);
|
||||
|
||||
await page.Vm.ExportChecksumFileCommand.ExecuteAsync(null);
|
||||
|
||||
Assert.Contains(expected, (await File.ReadAllTextAsync(page.Storage.SavePath, TestContext.Current.CancellationToken)), StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[AvaloniaTheory]
|
||||
[InlineData("out.json", "\"path\": \"b.txt\"")]
|
||||
[InlineData("out.csv", "path,size,algorithm,hash")]
|
||||
[InlineData("out.txt", HelloSha256 + " b.txt")]
|
||||
[InlineData("out.sha256", HelloSha256 + " b.txt")]
|
||||
public async Task WithoutAPickedType_TheExtensionDecides(string fileName, string expected)
|
||||
{
|
||||
using var page = new CreatePage();
|
||||
await page.HashAsync(("b.txt", "hello"));
|
||||
page.Storage.SavePath = page.Path(fileName);
|
||||
|
||||
await page.Vm.ExportChecksumFileCommand.ExecuteAsync(null);
|
||||
|
||||
Assert.Contains(expected, (await File.ReadAllTextAsync(page.Storage.SavePath, TestContext.Current.CancellationToken)), StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[AvaloniaFact]
|
||||
public async Task TheDefaultFormatFromSettings_IsOfferedFirst()
|
||||
{
|
||||
using var page = new CreatePage();
|
||||
page.Settings.Update(s => s.DefaultExportFormat = ExportFormat.Csv);
|
||||
await page.HashAsync(("b.txt", "hello"));
|
||||
page.Storage.SavePath = page.Path("export");
|
||||
|
||||
await page.Vm.ExportChecksumFileCommand.ExecuteAsync(null);
|
||||
|
||||
Assert.Equal(ExportFormat.Csv, page.Storage.OfferedTypes[0].Tag);
|
||||
Assert.Equal("checksums.csv", page.Storage.SuggestedName);
|
||||
Assert.StartsWith("path,size,algorithm,hash", (await File.ReadAllTextAsync(page.Storage.SavePath, TestContext.Current.CancellationToken)), StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[AvaloniaFact]
|
||||
public async Task Sfv_IsOfferedForCrc32_AndWritesUpperCase()
|
||||
{
|
||||
using var page = new CreatePage();
|
||||
page.Vm.SelectedAlgorithm = HashType.CRC32;
|
||||
await page.HashAsync(("check.txt", "123456789"));
|
||||
page.Storage.SavePath = page.Path("files.sfv");
|
||||
|
||||
await page.Vm.ExportChecksumFileCommand.ExecuteAsync(null);
|
||||
|
||||
Assert.Contains(page.Storage.OfferedTypes, t => (ExportFormat)t.Tag! == ExportFormat.Sfv);
|
||||
Assert.Equal(["; Generated by Hash Tool", "check.txt CBF43926"], (await File.ReadAllLinesAsync(page.Storage.SavePath, TestContext.Current.CancellationToken)));
|
||||
Assert.Equal(HashType.CRC32, page.Settings.Current.CreateAlgorithm);
|
||||
}
|
||||
|
||||
[AvaloniaFact]
|
||||
public async Task SeveralAlgorithms_AreWrittenAsBsd()
|
||||
{
|
||||
using var page = new CreatePage();
|
||||
await page.HashAsync(("a.txt", "hello"));
|
||||
page.Vm.SelectedAlgorithm = HashType.MD5;
|
||||
await page.HashAsync(("b.txt", "hello"));
|
||||
page.Storage.SavePath = page.Path("mixed.sha256");
|
||||
page.Storage.PickType = types => types.First(t => (ExportFormat)t.Tag! == ExportFormat.Gnu);
|
||||
|
||||
await page.Vm.ExportChecksumFileCommand.ExecuteAsync(null);
|
||||
|
||||
Assert.Equal("checksums.txt", page.Storage.SuggestedName);
|
||||
var text = (await File.ReadAllTextAsync(page.Storage.SavePath, TestContext.Current.CancellationToken));
|
||||
Assert.Contains($"SHA256 (a.txt) = {HelloSha256}", text, StringComparison.Ordinal);
|
||||
Assert.Contains($"MD5 (b.txt) = {HelloMd5}", text, StringComparison.Ordinal);
|
||||
|
||||
await page.Vm.CopyAllCommand.ExecuteAsync(null);
|
||||
Assert.Contains($"MD5 (b.txt) = {HelloMd5.ToUpperInvariant()}", Assert.Single(page.Clipboard.Texts), StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[AvaloniaFact]
|
||||
public async Task ASfvTypeForAnotherAlgorithm_FallsBackToBsd()
|
||||
{
|
||||
using var page = new CreatePage();
|
||||
await page.HashAsync(("b.txt", "hello"));
|
||||
page.Storage.SavePath = page.Path("out.sfv");
|
||||
page.Storage.SaveType = new FileTypeChoice("SFV", "*.sfv", ExportFormat.Sfv);
|
||||
|
||||
await page.Vm.ExportChecksumFileCommand.ExecuteAsync(null);
|
||||
|
||||
Assert.Equal($"SHA256 (b.txt) = {HelloSha256}", (await File.ReadAllTextAsync(page.Storage.SavePath, TestContext.Current.CancellationToken)).Trim());
|
||||
}
|
||||
|
||||
[AvaloniaFact]
|
||||
public async Task NothingHashed_NothingToExport()
|
||||
{
|
||||
using var page = new CreatePage();
|
||||
page.Storage.SavePath = page.Path("never.txt");
|
||||
|
||||
await page.Vm.ExportChecksumFileCommand.ExecuteAsync(null);
|
||||
await page.Vm.CompressCommand.ExecuteAsync(null);
|
||||
await page.Vm.CopyAllCommand.ExecuteAsync(null);
|
||||
|
||||
Assert.Equal(2, page.Dialogs.Shown.Count(d => d.Message == TestServices.Localization["Msg_NothingToExport"]));
|
||||
Assert.False(File.Exists(page.Storage.SavePath));
|
||||
Assert.Empty(page.Clipboard.Texts);
|
||||
}
|
||||
|
||||
[AvaloniaFact]
|
||||
public async Task CancellingTheSaveDialog_WritesNothing()
|
||||
{
|
||||
using var page = new CreatePage();
|
||||
await page.HashAsync(("b.txt", "hello"));
|
||||
|
||||
await page.Vm.ExportChecksumFileCommand.ExecuteAsync(null);
|
||||
await page.Vm.CompressCommand.ExecuteAsync(null);
|
||||
await page.Vm.SaveHashFileCommand.ExecuteAsync(page.Vm.Items[0]);
|
||||
|
||||
Assert.Empty(page.Dialogs.Shown);
|
||||
Assert.Single(Directory.GetFiles(page.Temp.Path));
|
||||
}
|
||||
|
||||
[AvaloniaFact]
|
||||
public async Task WriteErrors_AreShownWithTheirDetails()
|
||||
{
|
||||
using var page = new CreatePage();
|
||||
await page.HashAsync(("b.txt", "hello"));
|
||||
page.Storage.SavePath = Path.Combine(page.Temp.Path, "missing", "folder", "out.txt");
|
||||
|
||||
await page.Vm.ExportChecksumFileCommand.ExecuteAsync(null);
|
||||
await page.Vm.CompressCommand.ExecuteAsync(null);
|
||||
await page.Vm.SaveHashFileCommand.ExecuteAsync(page.Vm.Items[0]);
|
||||
|
||||
Assert.Equal(3, page.Dialogs.Shown.Count(d => d.Icon == DialogIcon.Error));
|
||||
Assert.All(page.Dialogs.ErrorDetails, d => Assert.Contains("DirectoryNotFoundException", d, StringComparison.Ordinal));
|
||||
Assert.NotEqual(ItemStatus.Saved, page.Vm.Items[0].Status);
|
||||
}
|
||||
|
||||
[AvaloniaFact]
|
||||
public async Task SaveHashFile_WritesASidecarForOneRow()
|
||||
{
|
||||
using var page = new CreatePage();
|
||||
var file = (await page.HashAsync(("photo.jpg", "hello")))[0];
|
||||
page.Storage.SavePath = file + ".sha256";
|
||||
|
||||
await page.Vm.SaveHashFileCommand.ExecuteAsync(page.Vm.Items[0]);
|
||||
await page.Vm.SaveHashFileCommand.ExecuteAsync(null);
|
||||
|
||||
Assert.Equal("photo.jpg.sha256", page.Storage.SuggestedName);
|
||||
Assert.Equal($"{HelloSha256.ToUpperInvariant()} photo.jpg", (await File.ReadAllTextAsync(page.Storage.SavePath, TestContext.Current.CancellationToken)).Trim());
|
||||
Assert.Equal(ItemStatus.Saved, page.Vm.Items[0].Status);
|
||||
}
|
||||
|
||||
[AvaloniaFact]
|
||||
public async Task Compress_ZipsOneHashFilePerFileAndAManifest()
|
||||
{
|
||||
using var page = new CreatePage();
|
||||
await page.HashAsync(("one/a.txt", "hello"), ("two/a.txt", "hello"));
|
||||
page.Storage.SavePath = page.Path("hashes.zip");
|
||||
|
||||
await page.Vm.CompressCommand.ExecuteAsync(null);
|
||||
|
||||
await using var zip = await ZipFile.OpenReadAsync(page.Storage.SavePath, TestContext.Current.CancellationToken);
|
||||
Assert.Equal(["CHECKSUMS.txt", "one/a.txt.sha256", "two/a.txt.sha256"], zip.Entries.Select(e => e.FullName).Order(StringComparer.Ordinal));
|
||||
using var manifest = new StreamReader(await zip.GetEntry("CHECKSUMS.txt")!.OpenAsync(TestContext.Current.CancellationToken));
|
||||
Assert.Contains($"SHA256 (one/a.txt) = {HelloSha256}", await manifest.ReadToEndAsync(TestContext.Current.CancellationToken), StringComparison.Ordinal);
|
||||
Assert.Equal(DialogIcon.Success, page.Dialogs.Shown[^1].Icon);
|
||||
}
|
||||
|
||||
[AvaloniaFact]
|
||||
public async Task Compress_NamesThatDifferOnlyInCase_GetUniqueEntries()
|
||||
{
|
||||
using var page = new CreatePage();
|
||||
page.Temp.File("dup.txt", "hello");
|
||||
if (File.Exists(page.Path("DUP.txt"))) return; // case-insensitive file system: two such files cannot exist
|
||||
|
||||
await page.HashAsync(("dup.txt", "hello"), ("DUP.txt", "hello"));
|
||||
page.Storage.SavePath = page.Path("hashes.zip");
|
||||
|
||||
await page.Vm.CompressCommand.ExecuteAsync(null);
|
||||
|
||||
await using var zip = await ZipFile.OpenReadAsync(page.Storage.SavePath, TestContext.Current.CancellationToken);
|
||||
Assert.Equal(3, zip.Entries.Select(e => e.FullName.ToUpperInvariant()).Distinct().Count());
|
||||
}
|
||||
|
||||
[AvaloniaFact]
|
||||
public async Task AFileThatDisappeared_FailsAsNotFound()
|
||||
{
|
||||
using var page = new CreatePage();
|
||||
var file = page.Temp.File("gone.bin", "x");
|
||||
await page.Vm.AddPathsAsync([file]);
|
||||
File.Delete(file);
|
||||
|
||||
await page.Vm.RunAllCommand.ExecuteAsync(null);
|
||||
|
||||
Assert.Equal(ItemStatus.NotFound, page.Vm.Items[0].Status);
|
||||
Assert.Equal(FileStatus.Failure, page.Vm.Items[0].State);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CommonDirectory_IsTheDeepestSharedFolder()
|
||||
{
|
||||
var root = Path.GetPathRoot(Path.GetTempPath())!;
|
||||
string P(params string[] parts) => Path.Combine([root, .. parts]);
|
||||
|
||||
Assert.Equal("", CreateHashViewModel.CommonDirectory([]));
|
||||
Assert.Equal(P("data", "a"), CreateHashViewModel.CommonDirectory([P("data", "a")]));
|
||||
Assert.Equal(P("data"), CreateHashViewModel.CommonDirectory([P("data", "a"), P("data", "b", "c")]));
|
||||
Assert.Equal(P("data", "a"), CreateHashViewModel.CommonDirectory([P("data", "a"), P("data", "a", "deeper")]));
|
||||
// A shared prefix is not a shared folder.
|
||||
Assert.Equal(P("data"), CreateHashViewModel.CommonDirectory([P("data", "photos"), P("data", "photos-2024")]));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RelativePath_KeepsFilesOutsideTheFolderAbsolute()
|
||||
{
|
||||
var root = Path.GetPathRoot(Path.GetTempPath())!;
|
||||
var folder = Path.Combine(root, "data");
|
||||
|
||||
Assert.Equal("a/b.txt", CreateHashViewModel.RelativePath(folder, Path.Combine(folder, "a", "b.txt")));
|
||||
Assert.Equal(Path.Combine(root, "other", "c.txt"), CreateHashViewModel.RelativePath(folder, Path.Combine(root, "other", "c.txt")));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,236 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using Avalonia;
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Headless;
|
||||
using Avalonia.Headless.XUnit;
|
||||
using Avalonia.Input;
|
||||
using Avalonia.Input.Platform;
|
||||
using Avalonia.Interactivity;
|
||||
using Avalonia.Threading;
|
||||
using Avalonia.VisualTree;
|
||||
using HashTool.App.Infrastructure;
|
||||
using HashTool.App.Services;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Xunit;
|
||||
|
||||
namespace HashTool.App.Tests;
|
||||
|
||||
public sealed class DialogTests
|
||||
{
|
||||
private static LocalizationService L => TestServices.Localization;
|
||||
|
||||
private static Window ShowOwner()
|
||||
{
|
||||
var owner = new Window { Width = 800, Height = 600, FontSize = 17 };
|
||||
owner.Show();
|
||||
return owner;
|
||||
}
|
||||
|
||||
/// <summary>The dialog the owner opened, once it is on screen.</summary>
|
||||
private static Window Dialog(Window owner)
|
||||
{
|
||||
Dispatcher.UIThread.RunJobs();
|
||||
var dialog = Assert.Single(owner.OwnedWindows);
|
||||
dialog.UpdateLayout();
|
||||
return dialog;
|
||||
}
|
||||
|
||||
private static Button ButtonOf(Window dialog, string text) =>
|
||||
dialog.GetVisualDescendants().OfType<Button>().Single(b => Equals(b.Content, text));
|
||||
|
||||
private static void Click(Button button) => button.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
|
||||
|
||||
[AvaloniaFact]
|
||||
public async Task Message_ClosesWithOk_AndCopiesItsDetails()
|
||||
{
|
||||
var owner = ShowOwner();
|
||||
try
|
||||
{
|
||||
var shown = DialogWindow.ShowAsync(owner, L, "Title", "Something failed", DialogIcon.Error, "stack trace");
|
||||
var dialog = Dialog(owner);
|
||||
Assert.Equal("Title", dialog.Title);
|
||||
Assert.Equal(17, dialog.FontSize);
|
||||
Assert.Equal(560, dialog.Width);
|
||||
|
||||
Click(ButtonOf(dialog, L["Btn_CopyDetails"]));
|
||||
Dispatcher.UIThread.RunJobs();
|
||||
Assert.Equal("Something failed\n\nstack trace", await dialog.Clipboard!.TryGetTextAsync());
|
||||
|
||||
Click(ButtonOf(dialog, L["Btn_OK"]));
|
||||
await shown.WaitAsync(TimeSpan.FromSeconds(10), TestContext.Current.CancellationToken);
|
||||
Assert.Empty(owner.OwnedWindows);
|
||||
}
|
||||
finally
|
||||
{
|
||||
owner.Close();
|
||||
}
|
||||
}
|
||||
|
||||
[AvaloniaTheory]
|
||||
[InlineData(true)]
|
||||
[InlineData(false)]
|
||||
public async Task Confirm_ReturnsTheAnswer(bool yes)
|
||||
{
|
||||
var owner = ShowOwner();
|
||||
try
|
||||
{
|
||||
var answer = DialogWindow.ConfirmAsync(owner, L, "Delete?", "Really?", DialogIcon.Question, "Yes!", "No!");
|
||||
Click(ButtonOf(Dialog(owner), yes ? "Yes!" : "No!"));
|
||||
|
||||
Assert.Equal(yes, await answer.WaitAsync(TimeSpan.FromSeconds(10), TestContext.Current.CancellationToken));
|
||||
}
|
||||
finally
|
||||
{
|
||||
owner.Close();
|
||||
}
|
||||
}
|
||||
|
||||
[AvaloniaFact]
|
||||
public async Task Escape_CancelsAConfirmation()
|
||||
{
|
||||
var owner = ShowOwner();
|
||||
try
|
||||
{
|
||||
var answer = DialogWindow.ConfirmAsync(owner, L, "Leave?", "Changes are lost.", DialogIcon.Warning, "Yes", "No");
|
||||
var dialog = Dialog(owner);
|
||||
dialog.RaiseEvent(new KeyEventArgs { RoutedEvent = InputElement.KeyDownEvent, Key = Key.Escape, Source = dialog });
|
||||
|
||||
Assert.False(await answer.WaitAsync(TimeSpan.FromSeconds(10), TestContext.Current.CancellationToken));
|
||||
}
|
||||
finally
|
||||
{
|
||||
owner.Close();
|
||||
}
|
||||
}
|
||||
|
||||
[AvaloniaFact]
|
||||
public async Task TheTitleBar_StartsMovingTheWindow()
|
||||
{
|
||||
var owner = ShowOwner();
|
||||
try
|
||||
{
|
||||
var shown = DialogWindow.ShowAsync(owner, L, "Drag me", "Message", DialogIcon.Success);
|
||||
var dialog = Dialog(owner);
|
||||
var title = dialog.GetVisualDescendants().OfType<TextBlock>().First(t => t.Text == "Drag me");
|
||||
var point = title.TranslatePoint(new Point(2, 2), dialog)!.Value;
|
||||
dialog.MouseDown(point, MouseButton.Left);
|
||||
dialog.MouseUp(point, MouseButton.Left);
|
||||
dialog.MouseDown(point, MouseButton.Right);
|
||||
|
||||
Click(ButtonOf(dialog, L["Btn_OK"]));
|
||||
await shown.WaitAsync(TimeSpan.FromSeconds(10), TestContext.Current.CancellationToken);
|
||||
}
|
||||
finally
|
||||
{
|
||||
owner.Close();
|
||||
}
|
||||
}
|
||||
|
||||
[AvaloniaFact]
|
||||
public async Task WithoutAVisibleOwner_NothingIsShown()
|
||||
{
|
||||
foreach (var icon in Enum.GetValues<DialogIcon>())
|
||||
await DialogWindow.ShowAsync(null, L, "Title", "Message", icon);
|
||||
|
||||
Assert.False(await DialogWindow.ConfirmAsync(new Window(), L, "Title", "Message", DialogIcon.None, "Yes", "No"));
|
||||
}
|
||||
|
||||
[AvaloniaFact]
|
||||
public async Task DialogService_ShowsDialogsOverTheMainWindow()
|
||||
{
|
||||
var owner = ShowOwner();
|
||||
try
|
||||
{
|
||||
var service = new DialogService(new MainWindowAccessor(() => owner), L);
|
||||
|
||||
var info = service.ShowAsync("Info", "Message");
|
||||
Click(ButtonOf(Dialog(owner), L["Btn_OK"]));
|
||||
await info.WaitAsync(TimeSpan.FromSeconds(10), TestContext.Current.CancellationToken);
|
||||
|
||||
var error = service.ShowErrorAsync("Error", "Message", "details");
|
||||
Click(ButtonOf(Dialog(owner), L["Btn_OK"]));
|
||||
await error.WaitAsync(TimeSpan.FromSeconds(10), TestContext.Current.CancellationToken);
|
||||
|
||||
var confirm = service.ConfirmAsync("Confirm", "Message");
|
||||
Click(ButtonOf(Dialog(owner), L["Btn_Yes"]));
|
||||
Assert.True(await confirm.WaitAsync(TimeSpan.FromSeconds(10), TestContext.Current.CancellationToken));
|
||||
}
|
||||
finally
|
||||
{
|
||||
owner.Close();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class PlatformServiceTests
|
||||
{
|
||||
private static ILogger<LauncherService> Logger => TestServices.Loggers.CreateLogger<LauncherService>();
|
||||
|
||||
[AvaloniaFact]
|
||||
public async Task WithoutAMainWindow_ServicesDoNothing()
|
||||
{
|
||||
var none = new MainWindowAccessor(() => null);
|
||||
|
||||
Assert.Empty(await new StorageService(none).PickFilesAsync("t"));
|
||||
Assert.Empty(await new StorageService(none).PickFoldersAsync("t"));
|
||||
Assert.Null(await new StorageService(none).SaveFileAsync("t", "a.txt", [new FileTypeChoice("Text", "*.txt")]));
|
||||
await new ClipboardService(none).SetTextAsync("ignored");
|
||||
await new LauncherService(none, Logger).OpenUrlAsync("https://example.com");
|
||||
Assert.Null(new MainWindowAccessor().Window);
|
||||
}
|
||||
|
||||
[AvaloniaFact]
|
||||
public async Task WithAWindow_ServicesUseThePlatform()
|
||||
{
|
||||
var window = new Window();
|
||||
window.Show();
|
||||
try
|
||||
{
|
||||
var main = new MainWindowAccessor(() => window);
|
||||
var storage = new StorageService(main);
|
||||
|
||||
// The headless platform has no pickers: they come back empty, like a cancelled dialog.
|
||||
Assert.Empty(await storage.PickFilesAsync("t", allowMultiple: false, [new FileTypeChoice("Checksum", "*.sha256")]));
|
||||
Assert.Empty(await storage.PickFoldersAsync("t"));
|
||||
Assert.Null(await storage.SaveFileAsync("t", "SHA256SUMS.sha256", [new FileTypeChoice("GNU", "*.sha256")]));
|
||||
|
||||
await new ClipboardService(main).SetTextAsync("copied");
|
||||
Assert.Equal("copied", await window.Clipboard!.TryGetTextAsync());
|
||||
}
|
||||
finally
|
||||
{
|
||||
window.Close();
|
||||
}
|
||||
}
|
||||
|
||||
[AvaloniaFact]
|
||||
public async Task Launcher_OpensOnlyWebLinksAndDataFolders()
|
||||
{
|
||||
var window = new Window();
|
||||
window.Show();
|
||||
try
|
||||
{
|
||||
var launcher = new LauncherService(new MainWindowAccessor(() => window), Logger);
|
||||
var log = Directory.CreateDirectory(AppPaths.LogDirectory).FullName;
|
||||
|
||||
await launcher.OpenUrlAsync("file:///etc/passwd");
|
||||
await launcher.OpenUrlAsync("not a url");
|
||||
await launcher.OpenUrlAsync("https://github.com/poli0981/HashTool");
|
||||
await launcher.OpenFolderAsync(Path.GetTempPath());
|
||||
await launcher.OpenFolderAsync(Path.Combine(log, "missing"));
|
||||
await launcher.OpenFolderAsync(log);
|
||||
|
||||
var messages = AppHost.Get<Infrastructure.Logging.LogSink>().Snapshot().Select(e => e.Message).ToList();
|
||||
Assert.Contains(messages, m => m.StartsWith("Refused to open file:///etc/passwd", StringComparison.Ordinal));
|
||||
Assert.Contains(messages, m => m.StartsWith("Refused to open folder", StringComparison.Ordinal));
|
||||
Assert.Contains(messages, m => m.StartsWith("Could not open https://github.com/poli0981/HashTool", StringComparison.Ordinal));
|
||||
}
|
||||
finally
|
||||
{
|
||||
window.Close();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using Avalonia;
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Headless;
|
||||
using Avalonia.Headless.XUnit;
|
||||
using Avalonia.Input;
|
||||
using Avalonia.Input.Raw;
|
||||
using Avalonia.Threading;
|
||||
using Avalonia.VisualTree;
|
||||
using HashTool.App.ViewModels;
|
||||
using HashTool.App.Views;
|
||||
using HashTool.Core.Tests;
|
||||
using Xunit;
|
||||
|
||||
namespace HashTool.App.Tests;
|
||||
|
||||
/// <summary>Files dropped from the file manager onto the pages, through Avalonia's real drag and drop routing.</summary>
|
||||
public sealed class DropTests
|
||||
{
|
||||
private const string HelloSha256 = "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824";
|
||||
|
||||
private static void Drop(TopLevel window, Point point, IDataTransfer data)
|
||||
{
|
||||
window.DragDrop(point, RawDragEventType.DragEnter, data, DragDropEffects.Copy, RawInputModifiers.None);
|
||||
window.DragDrop(point, RawDragEventType.DragOver, data, DragDropEffects.Copy, RawInputModifiers.None);
|
||||
window.DragDrop(point, RawDragEventType.Drop, data, DragDropEffects.Copy, RawInputModifiers.None);
|
||||
}
|
||||
|
||||
private static Window Show(Control view)
|
||||
{
|
||||
var window = new Window { Content = view, Width = 1200, Height = 800 };
|
||||
window.Show();
|
||||
Dispatcher.UIThread.RunJobs();
|
||||
window.UpdateLayout();
|
||||
return window;
|
||||
}
|
||||
|
||||
[AvaloniaFact]
|
||||
public async Task HashFileDroppedOnARow_FillsThatRowInsteadOfBeingAdded()
|
||||
{
|
||||
using var temp = new TempDirectory();
|
||||
var file = temp.File("data.bin", "hello");
|
||||
var hashFile = temp.File("expected.txt", HelloSha256);
|
||||
var vm = new CheckHashViewModel(TestServices.Create());
|
||||
await vm.AddPathsAsync([file]);
|
||||
var view = new CheckHashView { DataContext = vm };
|
||||
var window = Show(view);
|
||||
try
|
||||
{
|
||||
var box = view.GetVisualDescendants().OfType<TextBox>().Single(t => t.Classes.Contains("hashInput"));
|
||||
Drop(window, box.TranslatePoint(new Point(4, 4), window)!.Value, await Drops.FilesAsync(window, hashFile));
|
||||
|
||||
var row = Assert.Single(vm.Items);
|
||||
await Wait.UntilAsync(() => !string.IsNullOrEmpty(row.ExpectedHash));
|
||||
Assert.Equal(HelloSha256, row.ExpectedHash, ignoreCase: true);
|
||||
Assert.Equal(ItemStatus.HashLoaded, row.Status);
|
||||
Assert.Single(vm.Items);
|
||||
}
|
||||
finally
|
||||
{
|
||||
window.Close();
|
||||
}
|
||||
}
|
||||
|
||||
[AvaloniaFact]
|
||||
public async Task FilesDroppedOnTheList_AreAdded()
|
||||
{
|
||||
using var temp = new TempDirectory();
|
||||
var file = temp.File("data.bin", "hello");
|
||||
var vm = new CreateHashViewModel(TestServices.Create());
|
||||
var view = new CreateHashView { DataContext = vm };
|
||||
var window = Show(view);
|
||||
try
|
||||
{
|
||||
Drop(window, new Point(600, 500), await Drops.FilesAsync(window, file));
|
||||
|
||||
await Wait.UntilAsync(() => vm.Items.Count == 1);
|
||||
Assert.Equal(file, vm.Items[0].FilePath);
|
||||
}
|
||||
finally
|
||||
{
|
||||
window.Close();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Threading.Tasks;
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Input;
|
||||
using Avalonia.Threading;
|
||||
using HashTool.App.Services;
|
||||
using HashTool.App.ViewModels;
|
||||
using HashTool.Core.Configuration;
|
||||
using HashTool.Core.Hashing;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace HashTool.App.Tests;
|
||||
|
||||
/// <summary>Records dialogs instead of showing them. Confirmations get <see cref="Answer"/> (no by default).</summary>
|
||||
internal sealed class RecordingDialogs : IDialogService
|
||||
{
|
||||
public List<(string Message, DialogIcon Icon)> Shown { get; } = [];
|
||||
|
||||
public List<string> Confirmations { get; } = [];
|
||||
|
||||
public List<string?> ErrorDetails { get; } = [];
|
||||
|
||||
public Func<string, bool> Answer { get; init; } = _ => false;
|
||||
|
||||
public Task ShowAsync(string title, string message, DialogIcon icon = DialogIcon.Information)
|
||||
{
|
||||
Shown.Add((message, icon));
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
public Task<bool> ConfirmAsync(string title, string message, DialogIcon icon = DialogIcon.Question, string? yesText = null,
|
||||
string? noText = null)
|
||||
{
|
||||
Confirmations.Add(message);
|
||||
// Never accept the restart as administrator: it would start the test host again, elevated.
|
||||
return Task.FromResult(title != AppHost.Get<LocalizationService>()["Btn_RestartAdmin"] && Answer(message));
|
||||
}
|
||||
|
||||
public Task ShowErrorAsync(string title, string message, string? details = null)
|
||||
{
|
||||
Shown.Add((message, DialogIcon.Error));
|
||||
ErrorDetails.Add(details);
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>File pickers that return what the test prepared; the save dialog is cancelled unless a path is set.</summary>
|
||||
internal sealed class ScriptedStorage : IStorageService
|
||||
{
|
||||
public IReadOnlyList<string> Files { get; set; } = [];
|
||||
|
||||
public IReadOnlyList<string> Folders { get; set; } = [];
|
||||
|
||||
public string? SavePath { get; set; }
|
||||
|
||||
public FileTypeChoice? SaveType { get; set; }
|
||||
|
||||
/// <summary>Picks the file type in the save dialog from the offered ones (instead of <see cref="SaveType"/>).</summary>
|
||||
public Func<IReadOnlyList<FileTypeChoice>, FileTypeChoice?>? PickType { get; set; }
|
||||
|
||||
public string? SuggestedName { get; private set; }
|
||||
|
||||
public IReadOnlyList<FileTypeChoice> OfferedTypes { get; private set; } = [];
|
||||
|
||||
public Task<IReadOnlyList<string>> PickFilesAsync(string title, bool allowMultiple = true, IReadOnlyList<FileTypeChoice>? types = null) =>
|
||||
Task.FromResult(Files);
|
||||
|
||||
public Task<IReadOnlyList<string>> PickFoldersAsync(string title) => Task.FromResult(Folders);
|
||||
|
||||
public Task<(string Path, FileTypeChoice? Type)?> SaveFileAsync(string title, string suggestedName, IReadOnlyList<FileTypeChoice> types)
|
||||
{
|
||||
SuggestedName = suggestedName;
|
||||
OfferedTypes = types;
|
||||
var type = PickType is null ? SaveType : PickType(types);
|
||||
return Task.FromResult<(string Path, FileTypeChoice? Type)?>(SavePath is null ? null : (SavePath, type));
|
||||
}
|
||||
}
|
||||
|
||||
internal sealed class RecordingClipboard : IClipboardService
|
||||
{
|
||||
public List<string> Texts { get; } = [];
|
||||
|
||||
public Task SetTextAsync(string text)
|
||||
{
|
||||
Texts.Add(text);
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
}
|
||||
|
||||
internal sealed class RecordingLauncher : ILauncherService
|
||||
{
|
||||
public List<string> Urls { get; } = [];
|
||||
|
||||
public List<string> Folders { get; } = [];
|
||||
|
||||
public Task OpenUrlAsync(string url)
|
||||
{
|
||||
Urls.Add(url);
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
public Task OpenFolderAsync(string path)
|
||||
{
|
||||
Folders.Add(path);
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Services for a fresh page view model; settings are the shared ones unless a test brings its own.</summary>
|
||||
internal static class TestServices
|
||||
{
|
||||
public static ILoggerFactory Loggers => AppHost.Get<ILoggerFactory>();
|
||||
|
||||
public static LocalizationService Localization => AppHost.Get<LocalizationService>();
|
||||
|
||||
/// <summary>Settings of their own in <paramref name="directory"/>, for tests that change limits or preferences.</summary>
|
||||
public static SettingsService Settings(string directory) =>
|
||||
new(new SettingsStore(directory, Loggers.CreateLogger<SettingsStore>()), Loggers.CreateLogger<SettingsService>());
|
||||
|
||||
public static FileListServices Create(RecordingDialogs? dialogs = null, ScriptedStorage? storage = null, RecordingClipboard? clipboard = null,
|
||||
SettingsService? settings = null) =>
|
||||
new(Localization, settings ?? AppHost.Get<SettingsService>(), dialogs ?? new RecordingDialogs(), storage ?? new ScriptedStorage(),
|
||||
clipboard ?? new RecordingClipboard(), new HashEngine(), Loggers);
|
||||
}
|
||||
|
||||
internal static class Drops
|
||||
{
|
||||
/// <summary>The data a file manager drop carries for these files.</summary>
|
||||
public static async Task<DataTransfer> FilesAsync(TopLevel topLevel, params string[] paths)
|
||||
{
|
||||
var data = new DataTransfer();
|
||||
foreach (var path in paths)
|
||||
{
|
||||
var file = await topLevel.StorageProvider.TryGetFileFromPathAsync(new Uri(Path.GetFullPath(path)))
|
||||
?? throw new FileNotFoundException("Not found.", path);
|
||||
var item = new DataTransferItem();
|
||||
item.SetFile(file);
|
||||
data.Add(item);
|
||||
}
|
||||
|
||||
return data;
|
||||
}
|
||||
}
|
||||
|
||||
internal static class Wait
|
||||
{
|
||||
/// <summary>Runs the UI loop until <paramref name="condition"/> holds; fails instead of hanging the test run.</summary>
|
||||
public static async Task UntilAsync(Func<bool> condition, int timeoutMilliseconds = 10_000)
|
||||
{
|
||||
var deadline = DateTime.UtcNow.AddMilliseconds(timeoutMilliseconds);
|
||||
while (!condition())
|
||||
{
|
||||
if (DateTime.UtcNow > deadline) throw new TimeoutException("The expected state was not reached in time.");
|
||||
Dispatcher.UIThread.RunJobs();
|
||||
await Task.Delay(20);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,429 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using Avalonia.Headless.XUnit;
|
||||
using HashTool.App.Infrastructure;
|
||||
using HashTool.App.Models;
|
||||
using HashTool.App.Services;
|
||||
using HashTool.App.ViewModels;
|
||||
using HashTool.Core;
|
||||
using HashTool.Core.Configuration;
|
||||
using HashTool.Core.Files;
|
||||
using HashTool.Core.Hashing;
|
||||
using HashTool.Core.Processing;
|
||||
using HashTool.Core.Tests;
|
||||
using Xunit;
|
||||
|
||||
namespace HashTool.App.Tests;
|
||||
|
||||
/// <summary>The shared list behaviour on its own: row sizes can be faked, and a failing preparation can be requested.</summary>
|
||||
internal sealed class TestListViewModel(FileListServices services) : FileListViewModelBase(services)
|
||||
{
|
||||
public Dictionary<string, long> FakeSizes { get; } = new(StringComparer.Ordinal);
|
||||
|
||||
public bool FailPreparation { get; set; }
|
||||
|
||||
protected override ActivationVerb ElevationVerb => ActivationVerb.Create;
|
||||
|
||||
protected override Task<IReadOnlyList<FileItem>> CreateItemsAsync(IReadOnlyList<FileEntry> files, ImportReport report) =>
|
||||
Task.FromResult<IReadOnlyList<FileItem>>(files
|
||||
.Select(f => new FileItem(f.FullPath, FakeSizes.GetValueOrDefault(Path.GetFileName(f.FullPath), f.Length), HashType.CRC32)).ToList());
|
||||
|
||||
protected override Task<IReadOnlyList<FileItem>> PrepareAsync(IReadOnlyList<FileItem> items) =>
|
||||
FailPreparation ? Task.FromException<IReadOnlyList<FileItem>>(new InvalidOperationException("preparation failed")) : base.PrepareAsync(items);
|
||||
|
||||
protected override HashJob? CreateJob(FileItem item) => new(item.FilePath, item.Size, [item.Algorithm], item.Cancellation?.Token ?? default);
|
||||
|
||||
protected override void ApplyResult(FileItem item, HashJobResult result)
|
||||
{
|
||||
if (result.Status == HashJobStatus.Succeeded)
|
||||
{
|
||||
item.State = FileStatus.Success;
|
||||
item.SetStatus(ItemStatus.Done);
|
||||
return;
|
||||
}
|
||||
|
||||
ApplyFailure(item, result);
|
||||
}
|
||||
|
||||
public static void Fail(FileItem item, HashJobResult result) => ApplyFailure(item, result);
|
||||
|
||||
public static string Clock(TimeSpan time) => FormatClock(time);
|
||||
|
||||
public FileItem? Find(string path) => FindItem(path);
|
||||
}
|
||||
|
||||
public sealed class FileListTests
|
||||
{
|
||||
private sealed class Page : IDisposable
|
||||
{
|
||||
public Page(Func<string, bool>? answer = null)
|
||||
{
|
||||
Settings = TestServices.Settings(Path.Combine(Temp.Path, ".settings"));
|
||||
Dialogs = new RecordingDialogs { Answer = answer ?? (_ => false) };
|
||||
Vm = new TestListViewModel(TestServices.Create(Dialogs, Storage, Clipboard, Settings));
|
||||
}
|
||||
|
||||
public TempDirectory Temp { get; } = new();
|
||||
|
||||
public SettingsService Settings { get; }
|
||||
|
||||
public RecordingDialogs Dialogs { get; }
|
||||
|
||||
public ScriptedStorage Storage { get; } = new();
|
||||
|
||||
public RecordingClipboard Clipboard { get; } = new();
|
||||
|
||||
public TestListViewModel Vm { get; }
|
||||
|
||||
public string[] Files(int count, string prefix = "f", string content = "x") =>
|
||||
Enumerable.Range(0, count).Select(i => Temp.File($"{prefix}{i:D3}.bin", content)).ToArray();
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
Settings.Dispose();
|
||||
Temp.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
private static string L(string key) => TestServices.Localization[key];
|
||||
|
||||
private static string F(string key, params object?[] args) => TestServices.Localization.Format(key, args);
|
||||
|
||||
[AvaloniaFact]
|
||||
public async Task Import_ReportsDuplicatesSilently_AndEmptyFolders()
|
||||
{
|
||||
using var page = new Page();
|
||||
var file = page.Temp.File("a.bin", "x");
|
||||
var empty = Directory.CreateDirectory(Path.Combine(page.Temp.Path, "empty")).FullName;
|
||||
|
||||
await page.Vm.AddPathsAsync([file]);
|
||||
await page.Vm.AddPathsAsync([file]);
|
||||
Assert.Empty(page.Dialogs.Shown);
|
||||
Assert.Single(page.Vm.Items);
|
||||
|
||||
await page.Vm.AddPathsAsync([empty]);
|
||||
Assert.Equal(L("Msg_EmptyFolder"), Assert.Single(page.Dialogs.Shown).Message);
|
||||
Assert.Equal(page.Vm.Items[0], page.Vm.Find(file));
|
||||
Assert.True(page.Vm.HasItems);
|
||||
}
|
||||
|
||||
[AvaloniaFact]
|
||||
public async Task Import_StopsAtTheFileLimit_ForFolders()
|
||||
{
|
||||
using var page = new Page();
|
||||
page.Settings.Update(s => s.MaxFileCount = 2);
|
||||
page.Files(5);
|
||||
|
||||
await page.Vm.AddPathsAsync([page.Temp.Path]);
|
||||
|
||||
Assert.Equal(2, page.Vm.Items.Count);
|
||||
Assert.Equal(F("Msg_FileLimit", 2, 3), page.Dialogs.Shown.Single().Message);
|
||||
}
|
||||
|
||||
[AvaloniaFact]
|
||||
public async Task Import_SkipsFilesOverTheSizeLimit()
|
||||
{
|
||||
using var page = new Page();
|
||||
page.Settings.Update(s =>
|
||||
{
|
||||
s.IsFileSizeLimitEnabled = true;
|
||||
s.FileSizeLimitValue = 1;
|
||||
s.FileSizeLimitUnit = FileSizeUnit.KB;
|
||||
});
|
||||
var large = page.Files(12, "large", new string('x', 4096));
|
||||
var small = page.Temp.File("small.bin", "x");
|
||||
|
||||
await page.Vm.AddPathsAsync([.. large, small]);
|
||||
|
||||
Assert.Equal(small, Assert.Single(page.Vm.Items).FilePath);
|
||||
var (message, icon) = page.Dialogs.Shown.Single();
|
||||
Assert.Contains("large000.bin", message, StringComparison.Ordinal);
|
||||
Assert.EndsWith("…", message, StringComparison.Ordinal);
|
||||
Assert.Equal(DialogIcon.Information, icon);
|
||||
}
|
||||
|
||||
[AvaloniaFact]
|
||||
public async Task Import_ReportsUnreadablePathsAsWarning()
|
||||
{
|
||||
using var page = new Page();
|
||||
|
||||
await page.Vm.AddPathsAsync([Path.Combine(page.Temp.Path, "missing.bin")]);
|
||||
|
||||
var (message, icon) = page.Dialogs.Shown.Single();
|
||||
Assert.Contains("missing.bin", message, StringComparison.Ordinal);
|
||||
Assert.Equal(DialogIcon.Warning, icon);
|
||||
Assert.Empty(page.Vm.Items);
|
||||
}
|
||||
|
||||
[AvaloniaFact]
|
||||
public async Task Import_WhileBusy_AsksToTryLater()
|
||||
{
|
||||
using var page = new Page();
|
||||
page.Vm.IsBusy = true;
|
||||
|
||||
await page.Vm.AddPathsAsync(page.Files(1));
|
||||
await page.Vm.AddPathsAsync([]);
|
||||
|
||||
Assert.Equal(L("Msg_BusyTryLater"), page.Dialogs.Shown.Single().Message);
|
||||
Assert.False(page.Vm.CanModify);
|
||||
Assert.Empty(page.Vm.Items);
|
||||
}
|
||||
|
||||
[AvaloniaFact]
|
||||
public async Task Pickers_AddWhatWasPicked_WithinTheFolderLimit()
|
||||
{
|
||||
using var page = new Page();
|
||||
page.Storage.Files = page.Files(2);
|
||||
|
||||
await page.Vm.AddFilesCommand.ExecuteAsync(null);
|
||||
Assert.Equal(2, page.Vm.Items.Count);
|
||||
|
||||
page.Storage.Folders = Enumerable.Range(0, 4).Select(i => Directory.CreateDirectory(Path.Combine(page.Temp.Path, $"d{i}")).FullName).ToList();
|
||||
await page.Vm.AddFolderCommand.ExecuteAsync(null);
|
||||
Assert.Equal(F("Msg_FolderLimit", 3), page.Dialogs.Shown.Single().Message);
|
||||
|
||||
page.Storage.Folders = [Directory.CreateDirectory(Path.Combine(page.Temp.Path, "one")).FullName];
|
||||
page.Temp.File("one/inside.bin", "y");
|
||||
await page.Vm.AddFolderCommand.ExecuteAsync(null);
|
||||
Assert.Equal(3, page.Vm.Items.Count);
|
||||
|
||||
page.Storage.Files = [];
|
||||
page.Storage.Folders = [];
|
||||
await page.Vm.AddFilesCommand.ExecuteAsync(null);
|
||||
await page.Vm.AddFolderCommand.ExecuteAsync(null);
|
||||
Assert.Equal(3, page.Vm.Items.Count);
|
||||
}
|
||||
|
||||
[AvaloniaFact]
|
||||
public async Task Filters_ByNameStatusAndSize()
|
||||
{
|
||||
using var page = new Page();
|
||||
page.Vm.FakeSizes["small.bin"] = 10;
|
||||
page.Vm.FakeSizes["medium.bin"] = 5L * ByteSize.OneMB;
|
||||
page.Vm.FakeSizes["large.bin"] = 200L * ByteSize.OneMB;
|
||||
page.Vm.FakeSizes["huge.bin"] = 2L * ByteSize.OneGB;
|
||||
foreach (var name in page.Vm.FakeSizes.Keys) page.Temp.File(name, "x");
|
||||
await page.Vm.AddPathsAsync([page.Temp.Path]);
|
||||
Assert.Equal(4, page.Vm.Items.Count);
|
||||
|
||||
foreach (var (filter, expected) in new[]
|
||||
{
|
||||
(FileSizeFilter.Small, "small.bin"), (FileSizeFilter.Medium, "medium.bin"), (FileSizeFilter.Large, "large.bin"),
|
||||
(FileSizeFilter.ExtraLarge, "huge.bin")
|
||||
})
|
||||
{
|
||||
page.Vm.SelectedSizeFilter = filter;
|
||||
Assert.Equal(expected, Assert.Single(page.Vm.Items).FileName);
|
||||
}
|
||||
|
||||
page.Vm.SelectedSizeFilter = FileSizeFilter.All;
|
||||
page.Vm.SelectedStatusFilter = FileStatus.Success;
|
||||
Assert.Empty(page.Vm.Items);
|
||||
Assert.Equal($"{F("Lbl_TotalFiles", 0)} / 4", page.Vm.TotalFilesText);
|
||||
page.Vm.SelectedStatusFilter = null;
|
||||
|
||||
page.Vm.SearchText = " MEDIUM ";
|
||||
await Wait.UntilAsync(() => page.Vm.Items.Count == 1);
|
||||
Assert.Equal("medium.bin", page.Vm.Items[0].FileName);
|
||||
page.Vm.SearchText = "";
|
||||
await Wait.UntilAsync(() => page.Vm.Items.Count == 4);
|
||||
Assert.Equal(F("Lbl_TotalFiles", 4), page.Vm.TotalFilesText);
|
||||
}
|
||||
|
||||
[AvaloniaFact]
|
||||
public async Task ClearList_AsksFirstForLongLists()
|
||||
{
|
||||
var answer = false;
|
||||
using var page = new Page(_ => answer);
|
||||
await page.Vm.AddPathsAsync(page.Files(21));
|
||||
|
||||
await page.Vm.ClearListCommand.ExecuteAsync(null);
|
||||
Assert.Equal(21, page.Vm.Items.Count);
|
||||
Assert.Equal(F("Msg_ConfirmClear", 21), page.Dialogs.Confirmations.Single());
|
||||
|
||||
answer = true;
|
||||
await page.Vm.ClearListCommand.ExecuteAsync(null);
|
||||
Assert.Empty(page.Vm.Items);
|
||||
Assert.False(page.Vm.HasItems);
|
||||
|
||||
await page.Vm.ClearListCommand.ExecuteAsync(null);
|
||||
Assert.Single(page.Dialogs.Confirmations.Skip(1));
|
||||
}
|
||||
|
||||
[AvaloniaFact]
|
||||
public async Task RowCommands_RemoveAndResetRows()
|
||||
{
|
||||
using var page = new Page();
|
||||
await page.Vm.AddPathsAsync(page.Files(4));
|
||||
await page.Vm.RunAllCommand.ExecuteAsync(null);
|
||||
Assert.All(page.Vm.Items, i => Assert.Equal(ItemStatus.Done, i.Status));
|
||||
|
||||
page.Vm.ClearItemResultCommand.Execute(page.Vm.Items[0]);
|
||||
page.Vm.ClearItemResultCommand.Execute(null);
|
||||
Assert.Equal(ItemStatus.Ready, page.Vm.Items[0].Status);
|
||||
|
||||
page.Vm.ClearResultsCommand.Execute(null);
|
||||
Assert.All(page.Vm.Items, i => Assert.Equal(FileStatus.Ready, i.State));
|
||||
|
||||
var removed = page.Vm.Items[0];
|
||||
page.Vm.RemoveItemCommand.Execute(removed);
|
||||
page.Vm.RemoveItemCommand.Execute(null);
|
||||
Assert.True(removed.IsRemoved);
|
||||
Assert.Equal(3, page.Vm.Items.Count);
|
||||
|
||||
page.Vm.SelectedItem = page.Vm.Items[0];
|
||||
page.Vm.RemoveSelectedCommand.Execute(null);
|
||||
Assert.Equal(2, page.Vm.Items.Count);
|
||||
|
||||
page.Vm.Items[0].IsProcessing = true;
|
||||
page.Vm.RemoveItemCommand.Execute(page.Vm.Items[0]);
|
||||
page.Vm.ClearItemResultCommand.Execute(page.Vm.Items[0]);
|
||||
Assert.Equal(2, page.Vm.Items.Count);
|
||||
}
|
||||
|
||||
[AvaloniaFact]
|
||||
public async Task ClearFailed_RemovesFailedAndCancelledRows()
|
||||
{
|
||||
using var page = new Page();
|
||||
var files = page.Files(3);
|
||||
await page.Vm.AddPathsAsync(files);
|
||||
File.Delete(files[0]);
|
||||
|
||||
await page.Vm.RunAllCommand.ExecuteAsync(null);
|
||||
Assert.Equal(ItemStatus.NotFound, page.Vm.Find(files[0])!.Status);
|
||||
Assert.Equal(1, page.Vm.FailedCount);
|
||||
Assert.Equal(DialogIcon.Warning, page.Dialogs.Shown.Last().Icon);
|
||||
|
||||
page.Vm.ClearFailedCommand.Execute(null);
|
||||
Assert.Equal(2, page.Vm.Items.Count);
|
||||
Assert.Null(page.Vm.Find(files[0]));
|
||||
}
|
||||
|
||||
[AvaloniaFact]
|
||||
public async Task CancellingABatch_CancelsEveryRow()
|
||||
{
|
||||
using var page = new Page();
|
||||
await page.Vm.AddPathsAsync(page.Files(300));
|
||||
|
||||
var run = page.Vm.RunAllCommand.ExecuteAsync(null);
|
||||
page.Vm.CancelCommand.Execute(null);
|
||||
await run;
|
||||
|
||||
Assert.True(page.Vm.CancelledCount > 0);
|
||||
Assert.Equal(300, page.Vm.ProcessedCount);
|
||||
Assert.Equal(DialogIcon.Warning, page.Dialogs.Shown.Last().Icon);
|
||||
Assert.False(page.Vm.IsBusy);
|
||||
}
|
||||
|
||||
[AvaloniaFact]
|
||||
public async Task RunItem_HashesOneRow_OrStopsItWhileRunning()
|
||||
{
|
||||
using var page = new Page();
|
||||
await page.Vm.AddPathsAsync(page.Files(2));
|
||||
var row = page.Vm.Items[0];
|
||||
|
||||
await page.Vm.RunItemCommand.ExecuteAsync(row);
|
||||
await page.Vm.RunItemCommand.ExecuteAsync(null);
|
||||
Assert.Equal(ItemStatus.Done, row.Status);
|
||||
Assert.Equal(ItemStatus.Ready, page.Vm.Items[1].Status);
|
||||
Assert.Empty(page.Dialogs.Shown); // one row: no summary
|
||||
|
||||
using var cancellation = new System.Threading.CancellationTokenSource();
|
||||
row.Cancellation = cancellation;
|
||||
row.IsProcessing = true;
|
||||
await page.Vm.RunItemCommand.ExecuteAsync(row);
|
||||
Assert.True(cancellation.IsCancellationRequested);
|
||||
}
|
||||
|
||||
[AvaloniaFact]
|
||||
public async Task ALargeFile_ShowsProgressAndSpeed()
|
||||
{
|
||||
using var page = new Page();
|
||||
page.Settings.Update(s => s.ShowReadWriteSpeed = true);
|
||||
var big = Path.Combine(page.Temp.Path, "big.bin");
|
||||
await using (var stream = File.Create(big))
|
||||
{
|
||||
var block = new byte[1024 * 1024];
|
||||
Random.Shared.NextBytes(block);
|
||||
for (var i = 0; i < 80; i++) await stream.WriteAsync(block);
|
||||
}
|
||||
|
||||
await page.Vm.AddPathsAsync([big, page.Temp.File("small.bin", "x")]);
|
||||
await page.Vm.RunAllCommand.ExecuteAsync(null);
|
||||
|
||||
Assert.All(page.Vm.Items, i => Assert.Equal(FileStatus.Success, i.State));
|
||||
Assert.Equal(1, page.Vm.ProgressValue);
|
||||
Assert.False(string.IsNullOrEmpty(page.Vm.ProgressText));
|
||||
Assert.False(string.IsNullOrEmpty(page.Vm.DetailText));
|
||||
}
|
||||
|
||||
[AvaloniaFact]
|
||||
public async Task AFailingPreparation_IsShownAsUnexpectedError()
|
||||
{
|
||||
using var page = new Page();
|
||||
await page.Vm.AddPathsAsync(page.Files(2));
|
||||
page.Vm.FailPreparation = true;
|
||||
|
||||
await page.Vm.RunAllCommand.ExecuteAsync(null);
|
||||
|
||||
Assert.Contains(page.Dialogs.Shown, d => d.Icon == DialogIcon.Error && d.Message.Contains("preparation failed", StringComparison.Ordinal));
|
||||
Assert.False(page.Vm.IsBusy);
|
||||
}
|
||||
|
||||
[AvaloniaFact]
|
||||
public async Task CopyText_PutsTheTextOnTheClipboard()
|
||||
{
|
||||
using var page = new Page();
|
||||
|
||||
await page.Vm.CopyTextCommand.ExecuteAsync("ABC");
|
||||
await page.Vm.CopyTextCommand.ExecuteAsync("");
|
||||
await page.Vm.CopyTextCommand.ExecuteAsync(null);
|
||||
|
||||
Assert.Equal(["ABC"], page.Clipboard.Texts);
|
||||
}
|
||||
|
||||
[AvaloniaFact]
|
||||
public void SearchFocus_IsForwardedToTheView()
|
||||
{
|
||||
using var page = new Page();
|
||||
var raised = 0;
|
||||
page.Vm.FocusSearchRequested += (_, _) => raised++;
|
||||
|
||||
page.Vm.RequestSearchFocus();
|
||||
|
||||
Assert.Equal(1, raised);
|
||||
Assert.Contains(HashType.SHA256, page.Vm.Algorithms);
|
||||
Assert.Contains(null, page.Vm.StatusFilterOptions);
|
||||
Assert.Contains(FileSizeFilter.ExtraLarge, page.Vm.SizeFilterOptions);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(HashJobStatus.Cancelled, null, ItemStatus.Cancelled, FileStatus.Cancelled)]
|
||||
[InlineData(HashJobStatus.TimedOut, null, ItemStatus.TimedOut, FileStatus.Cancelled)]
|
||||
[InlineData(HashJobStatus.Failed, typeof(FileNotFoundException), ItemStatus.NotFound, FileStatus.Failure)]
|
||||
[InlineData(HashJobStatus.Failed, typeof(UnauthorizedAccessException), ItemStatus.AccessDenied, FileStatus.Failure)]
|
||||
[InlineData(HashJobStatus.Failed, typeof(InvalidOperationException), ItemStatus.Failed, FileStatus.Failure)]
|
||||
[InlineData(HashJobStatus.Failed, null, ItemStatus.Failed, FileStatus.Failure)]
|
||||
public void Failures_MapToRowStatuses(HashJobStatus status, Type? error, ItemStatus expected, FileStatus state)
|
||||
{
|
||||
var item = new FileItem(Path.Combine(Path.GetTempPath(), "x.bin"), 1, HashType.SHA256) { IsMatch = true };
|
||||
var exception = error is null ? null : (Exception)Activator.CreateInstance(error, "message")!;
|
||||
|
||||
TestListViewModel.Fail(item, new HashJobResult(status, null, exception, TimeSpan.Zero));
|
||||
|
||||
Assert.Equal(expected, item.Status);
|
||||
Assert.Equal(state, item.State);
|
||||
Assert.Equal(state == FileStatus.Cancelled ? null : false, item.IsMatch);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Clock_ShowsHoursMinutesAndSeconds()
|
||||
{
|
||||
Assert.Equal("0:00:05", TestListViewModel.Clock(TimeSpan.FromSeconds(5)));
|
||||
Assert.Equal("26:03:04", TestListViewModel.Clock(new TimeSpan(1, 2, 3, 4)));
|
||||
Assert.Equal("15 ms", FileItem.FormatDuration(TimeSpan.FromMilliseconds(15)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,267 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using Avalonia.Headless.XUnit;
|
||||
using Avalonia.Logging;
|
||||
using Avalonia.Threading;
|
||||
using HashTool.App.Infrastructure;
|
||||
using HashTool.App.Infrastructure.Logging;
|
||||
using HashTool.Core.Tests;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Xunit;
|
||||
|
||||
namespace HashTool.App.Tests;
|
||||
|
||||
/// <summary>Captures what is logged through it.</summary>
|
||||
internal sealed class RecordingLogger : ILogger
|
||||
{
|
||||
public List<(LogLevel Level, string Message)> Entries { get; } = [];
|
||||
|
||||
public IDisposable? BeginScope<TState>(TState state) where TState : notnull => null;
|
||||
|
||||
public bool IsEnabled(LogLevel logLevel) => true;
|
||||
|
||||
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter) =>
|
||||
Entries.Add((logLevel, formatter(state, exception)));
|
||||
}
|
||||
|
||||
public sealed class FileLoggerTests
|
||||
{
|
||||
private static string Today => DateTime.Now.ToString("yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture);
|
||||
|
||||
private static string ReadAll(string directory) =>
|
||||
string.Join("\n", Directory.GetFiles(directory, "*.log").Order(StringComparer.Ordinal).Select(f =>
|
||||
{
|
||||
using var stream = new FileStream(f, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete);
|
||||
return new StreamReader(stream).ReadToEnd();
|
||||
}));
|
||||
|
||||
[Fact]
|
||||
public void WritesEveryLevelWithItsTag()
|
||||
{
|
||||
using var temp = new TempDirectory();
|
||||
var provider = new FileLoggerProvider(temp.Path, () => LogLevel.Trace, PathSanitizer.Shared);
|
||||
var logger = provider.CreateLogger("HashTool.App.Sample");
|
||||
|
||||
logger.LogTrace("t");
|
||||
logger.LogDebug("d");
|
||||
logger.LogInformation("i");
|
||||
logger.LogWarning("w");
|
||||
logger.LogError(new InvalidOperationException("boom"), "e");
|
||||
logger.LogCritical("c");
|
||||
logger.Log((LogLevel)42, "odd");
|
||||
logger.Log(LogLevel.None, "never");
|
||||
Assert.Null(logger.BeginScope("scope"));
|
||||
provider.Flush();
|
||||
provider.Dispose();
|
||||
provider.Dispose();
|
||||
logger.LogError("after dispose");
|
||||
|
||||
var text = ReadAll(temp.Path);
|
||||
foreach (var tag in new[] { "[TRC] Sample: t", "[DBG] Sample: d", "[INF] Sample: i", "[WRN] Sample: w", "[ERR] Sample: e", "[CRT] Sample: c", "[???] Sample: odd" })
|
||||
Assert.Contains(tag, text, StringComparison.Ordinal);
|
||||
Assert.Contains("InvalidOperationException: boom", text, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("never", text, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("after dispose", text, StringComparison.Ordinal);
|
||||
Assert.Equal(temp.Path, provider.Directory);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void BelowTheMinimumLevel_NothingIsWritten()
|
||||
{
|
||||
using var temp = new TempDirectory();
|
||||
using var provider = new FileLoggerProvider(temp.Path, () => LogLevel.Warning, PathSanitizer.Shared);
|
||||
var logger = provider.CreateLogger("Quiet");
|
||||
|
||||
logger.LogInformation("hidden");
|
||||
logger.LogWarning("shown");
|
||||
provider.Flush();
|
||||
|
||||
Assert.False(logger.IsEnabled(LogLevel.Information));
|
||||
var text = ReadAll(temp.Path);
|
||||
Assert.DoesNotContain("hidden", text, StringComparison.Ordinal);
|
||||
Assert.Contains("[WRN] Quiet: shown", text, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AFullFile_RollsOverToTheNextNumber()
|
||||
{
|
||||
using var temp = new TempDirectory();
|
||||
foreach (var name in new[] { $"hashtool-{Today}.log", $"hashtool-{Today}.1.log" })
|
||||
{
|
||||
using var full = File.Create(Path.Combine(temp.Path, name));
|
||||
full.SetLength(10L * 1024 * 1024);
|
||||
}
|
||||
|
||||
using (var provider = new FileLoggerProvider(temp.Path, () => LogLevel.Information, PathSanitizer.Shared))
|
||||
provider.CreateLogger("Roll").LogWarning("next file");
|
||||
|
||||
Assert.Contains("next file", File.ReadAllText(Path.Combine(temp.Path, $"hashtool-{Today}.2.log")), StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void FilesOlderThanTwoWeeks_AreDeleted()
|
||||
{
|
||||
using var temp = new TempDirectory();
|
||||
var oldLog = temp.File("hashtool-20000101.log", "old");
|
||||
var oldCrash = temp.File("crash-20000101-000000.txt", "old");
|
||||
var recent = temp.File("hashtool-recent.log", "recent");
|
||||
File.SetLastWriteTimeUtc(oldLog, DateTime.UtcNow.AddDays(-30));
|
||||
File.SetLastWriteTimeUtc(oldCrash, DateTime.UtcNow.AddDays(-30));
|
||||
|
||||
new FileLoggerProvider(temp.Path, () => LogLevel.Information, PathSanitizer.Shared).Dispose();
|
||||
|
||||
Assert.False(File.Exists(oldLog));
|
||||
Assert.False(File.Exists(oldCrash));
|
||||
Assert.True(File.Exists(recent));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AnUnwritableFolder_NeverThrows()
|
||||
{
|
||||
using var temp = new TempDirectory();
|
||||
var blocker = temp.File("not-a-folder", "x");
|
||||
using var provider = new FileLoggerProvider(Path.Combine(blocker, "log"), () => LogLevel.Information, PathSanitizer.Shared);
|
||||
|
||||
provider.CreateLogger("X").LogError("lost");
|
||||
provider.Flush();
|
||||
|
||||
Assert.False(Directory.Exists(Path.Combine(blocker, "log")));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("HashTool.App.Services.UpdateService", "UpdateService")]
|
||||
[InlineData("Plain", "Plain")]
|
||||
[InlineData("Trailing.", "Trailing.")]
|
||||
public void Categories_AreShortenedToTheTypeName(string category, string expected)
|
||||
{
|
||||
Assert.Equal(expected, FileLoggerProvider.ShortCategory(category));
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class LogSinkTests
|
||||
{
|
||||
[Fact]
|
||||
public void KeepsTheLatestEntries_AndReportsThem()
|
||||
{
|
||||
using var sink = new LogSink(PathSanitizer.Shared);
|
||||
var logger = sink.CreateLogger("HashTool.Test");
|
||||
var added = 0;
|
||||
sink.EntryAdded += (_, _) => added++;
|
||||
|
||||
logger.LogTrace("too low");
|
||||
for (var i = 0; i <= LogSink.Capacity; i++) logger.LogInformation("entry {Number}", i);
|
||||
logger.LogError(new IOException("disk"), "failed");
|
||||
|
||||
var entries = sink.Snapshot();
|
||||
Assert.Equal(LogSink.Capacity, entries.Count);
|
||||
Assert.Equal("entry 2", entries[0].Message);
|
||||
Assert.Equal("failed — IOException: disk", entries[^1].Message);
|
||||
Assert.Equal(LogSink.Capacity + 2, added);
|
||||
Assert.Null(logger.BeginScope("scope"));
|
||||
|
||||
sink.Clear();
|
||||
Assert.Empty(sink.Snapshot());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Paused_RecordsNothing()
|
||||
{
|
||||
using var sink = new LogSink(PathSanitizer.Shared) { IsRecording = false };
|
||||
var logger = sink.CreateLogger("Paused");
|
||||
|
||||
logger.LogWarning("ignored");
|
||||
|
||||
Assert.False(logger.IsEnabled(LogLevel.Warning));
|
||||
Assert.Empty(sink.Snapshot());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(LogLevel.Trace, "TRACE")]
|
||||
[InlineData(LogLevel.Debug, "DEBUG")]
|
||||
[InlineData(LogLevel.Information, "INFO")]
|
||||
[InlineData(LogLevel.Warning, "WARN")]
|
||||
[InlineData(LogLevel.Error, "ERROR")]
|
||||
[InlineData(LogLevel.Critical, "FATAL")]
|
||||
[InlineData(LogLevel.None, "")]
|
||||
public void LevelTags(LogLevel level, string expected)
|
||||
{
|
||||
Assert.Equal(expected, new LogEntry(DateTimeOffset.UnixEpoch, level, "C", "m").LevelTag);
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class AvaloniaLogForwarderTests
|
||||
{
|
||||
[Fact]
|
||||
public void ForwardsWarningsAndErrorsToTheAppLog()
|
||||
{
|
||||
var logger = new RecordingLogger();
|
||||
var forwarder = new AvaloniaLogForwarder(logger);
|
||||
|
||||
Assert.True(forwarder.IsEnabled(LogEventLevel.Warning, "Binding"));
|
||||
Assert.False(forwarder.IsEnabled(LogEventLevel.Information, "Binding"));
|
||||
|
||||
forwarder.Log(LogEventLevel.Warning, "Binding", this, "Path not found");
|
||||
forwarder.Log(LogEventLevel.Error, "Layout", null, "Measure failed", 1, null);
|
||||
forwarder.Log(LogEventLevel.Fatal, "Render", null, "Lost device", []);
|
||||
|
||||
Assert.Equal([LogLevel.Warning, LogLevel.Error, LogLevel.Critical], logger.Entries.Select(e => e.Level));
|
||||
Assert.Contains("Avalonia Binding (AvaloniaLogForwarderTests): Path not found", logger.Entries[0].Message, StringComparison.Ordinal);
|
||||
Assert.Contains("Measure failed [1, ]", logger.Entries[1].Message, StringComparison.Ordinal);
|
||||
Assert.EndsWith("Lost device", logger.Entries[2].Message, StringComparison.Ordinal);
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class CrashReporterTests
|
||||
{
|
||||
[AvaloniaFact]
|
||||
public void Report_WritesACrashFileIntoTheLogFolder()
|
||||
{
|
||||
var path = CrashReporter.Report(new InvalidOperationException("crash test"), isTerminating: false);
|
||||
|
||||
Assert.NotNull(path);
|
||||
Assert.StartsWith(Path.GetFullPath(AppPaths.LogDirectory), path, StringComparison.Ordinal);
|
||||
var text = File.ReadAllText(path);
|
||||
Assert.Contains($"Hash Tool {CrashReporter.Version}", text, StringComparison.Ordinal);
|
||||
Assert.Contains("crash test", text, StringComparison.Ordinal);
|
||||
Assert.Contains("(no exception object)", File.ReadAllText(CrashReporter.Report(null, isTerminating: false)!), StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TestsNeverUseTheRealDataFolder()
|
||||
{
|
||||
Assert.StartsWith(Path.GetFullPath(Path.GetTempPath()), Path.GetFullPath(AppPaths.DataDirectory), StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
[AvaloniaFact]
|
||||
public async Task UnobservedTaskExceptions_AreLoggedNotFatal()
|
||||
{
|
||||
var sink = AppHost.Get<LogSink>();
|
||||
var before = sink.Snapshot().Count(e => e.Message.Contains("Unobserved task exception", StringComparison.Ordinal));
|
||||
|
||||
Abandon();
|
||||
for (var i = 0; i < 20 && sink.Snapshot().Count(e => e.Message.Contains("Unobserved task exception", StringComparison.Ordinal)) == before; i++)
|
||||
{
|
||||
GC.Collect();
|
||||
GC.WaitForPendingFinalizers();
|
||||
await Task.Delay(50);
|
||||
}
|
||||
|
||||
Assert.True(sink.Snapshot().Count(e => e.Message.Contains("Unobserved task exception", StringComparison.Ordinal)) > before);
|
||||
|
||||
static void Abandon() => _ = Task.Run(() => throw new InvalidOperationException("nobody waits for me"));
|
||||
}
|
||||
|
||||
[AvaloniaFact]
|
||||
public void UnhandledUiExceptions_AreLoggedAndShown()
|
||||
{
|
||||
var sink = AppHost.Get<LogSink>();
|
||||
|
||||
Dispatcher.UIThread.Post(() => throw new InvalidOperationException("ui failure"));
|
||||
Dispatcher.UIThread.RunJobs();
|
||||
|
||||
Assert.Contains(sink.Snapshot(), e => e.Message.Contains("Unhandled UI exception", StringComparison.Ordinal) && e.Message.Contains("ui failure", StringComparison.Ordinal));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,352 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using Avalonia.Headless.XUnit;
|
||||
using HashTool.App.Infrastructure;
|
||||
using HashTool.App.Infrastructure.Logging;
|
||||
using HashTool.App.Services;
|
||||
using HashTool.App.Services.Theme;
|
||||
using HashTool.App.ViewModels;
|
||||
using HashTool.Core.Configuration;
|
||||
using HashTool.Core.Tests;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Xunit;
|
||||
|
||||
namespace HashTool.App.Tests;
|
||||
|
||||
/// <summary>A main window view model over pages of its own, so nothing leaks into the shared singletons.</summary>
|
||||
internal sealed class MainPage : IDisposable
|
||||
{
|
||||
public MainPage(bool corruptSettings = false)
|
||||
{
|
||||
var settingsFolder = Path.Combine(Temp.Path, ".settings");
|
||||
if (corruptSettings) Temp.File(".settings/config.json", "{ this is not json");
|
||||
Settings = TestServices.Settings(settingsFolder);
|
||||
var services = TestServices.Create(Dialogs, Storage, Clipboard, Settings);
|
||||
Create = new CreateHashViewModel(services);
|
||||
Check = new CheckHashViewModel(services);
|
||||
Theme = new ThemeService();
|
||||
var fonts = new FontService(TestServices.Loggers.CreateLogger<FontService>());
|
||||
var notInstalled = new UpdateService(TestServices.Loggers.CreateLogger<UpdateService>(), null, new System.Net.Http.HttpClient());
|
||||
SettingsPage = new SettingsViewModel(Settings, TestServices.Localization, fonts, Theme, Dialogs, Clipboard, Launcher, notInstalled,
|
||||
new LogLevelSwitch(), TestServices.Loggers.CreateLogger<SettingsViewModel>());
|
||||
Update = new UpdateViewModel(notInstalled, Settings, TestServices.Localization, Launcher, TestServices.Loggers.CreateLogger<UpdateViewModel>());
|
||||
Developer = new DeveloperViewModel(new LogSink(PathSanitizer.Shared), TestServices.Localization, Clipboard, Storage, Launcher);
|
||||
Activation = new ActivationService(TestServices.Loggers.CreateLogger<ActivationService>());
|
||||
Vm = new MainWindowViewModel(Create, Check, SettingsPage, Update, new AboutViewModel(notInstalled, TestServices.Localization, Launcher),
|
||||
Developer, Settings, TestServices.Localization, fonts, Theme, Activation);
|
||||
}
|
||||
|
||||
public TempDirectory Temp { get; } = new();
|
||||
|
||||
public SettingsService Settings { get; }
|
||||
|
||||
public RecordingDialogs Dialogs { get; } = new();
|
||||
|
||||
public ScriptedStorage Storage { get; } = new();
|
||||
|
||||
public RecordingClipboard Clipboard { get; } = new();
|
||||
|
||||
public RecordingLauncher Launcher { get; } = new();
|
||||
|
||||
public CreateHashViewModel Create { get; }
|
||||
|
||||
public CheckHashViewModel Check { get; }
|
||||
|
||||
public ThemeService Theme { get; }
|
||||
|
||||
public SettingsViewModel SettingsPage { get; }
|
||||
|
||||
public UpdateViewModel Update { get; }
|
||||
|
||||
public DeveloperViewModel Developer { get; }
|
||||
|
||||
public ActivationService Activation { get; }
|
||||
|
||||
public MainWindowViewModel Vm { get; }
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
Settings.Dispose();
|
||||
Temp.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class MainWindowViewModelTests
|
||||
{
|
||||
[AvaloniaFact]
|
||||
public void Navigation_SwitchesPages_ButNotAwayFromABusyList()
|
||||
{
|
||||
using var page = new MainPage();
|
||||
|
||||
foreach (var (name, expected) in new (string, object)[]
|
||||
{
|
||||
("Check", page.Check), ("Settings", page.SettingsPage), ("Update", page.Update), ("About", page.Vm.About),
|
||||
("Developer", page.Developer), ("Create", page.Create), ("Unknown", page.Create)
|
||||
})
|
||||
{
|
||||
page.Vm.NavigateCommand.Execute(name);
|
||||
Assert.Same(expected, page.Vm.CurrentPage);
|
||||
Assert.Equal(name == "Unknown" ? "Create" : name, page.Vm.CurrentPageName);
|
||||
}
|
||||
|
||||
var changed = new List<string?>();
|
||||
page.Vm.PropertyChanged += (_, e) => changed.Add(e.PropertyName);
|
||||
page.Create.IsBusy = true;
|
||||
Assert.True(page.Vm.IsBusy);
|
||||
Assert.False(page.Vm.IsIdle);
|
||||
Assert.Contains(nameof(MainWindowViewModel.IsIdle), changed);
|
||||
|
||||
page.Vm.NavigateCommand.Execute("Settings");
|
||||
page.Vm.ShowUpdateCommand.Execute(null);
|
||||
Assert.Same(page.Create, page.Vm.CurrentPage);
|
||||
page.Vm.NavigateCommand.Execute("Check");
|
||||
Assert.Same(page.Check, page.Vm.CurrentPage);
|
||||
|
||||
page.Create.IsBusy = false;
|
||||
page.Vm.ShowUpdateCommand.Execute(null);
|
||||
Assert.Same(page.Update, page.Vm.CurrentPage);
|
||||
}
|
||||
|
||||
[AvaloniaFact]
|
||||
public void UpdateBanner_ShowsAnAvailableUpdate_ExceptOnTheUpdatePage()
|
||||
{
|
||||
using var page = new MainPage();
|
||||
var changed = 0;
|
||||
page.Vm.PropertyChanged += (_, e) => changed += e.PropertyName == nameof(MainWindowViewModel.UpdateBannerText) ? 1 : 0;
|
||||
|
||||
Assert.Null(page.Vm.UpdateBannerText);
|
||||
page.Update.AvailableVersion = "9.9.9";
|
||||
page.Update.State = UpdateState.Available;
|
||||
Assert.Equal(TestServices.Localization.Format("Msg_UpdateAvailableBanner", "9.9.9"), page.Vm.UpdateBannerText);
|
||||
|
||||
page.Vm.NavigateCommand.Execute("Update");
|
||||
Assert.Null(page.Vm.UpdateBannerText);
|
||||
Assert.True(changed >= 2);
|
||||
}
|
||||
|
||||
[AvaloniaFact]
|
||||
public void ARecoveredSettingsFile_IsAnnounced_UntilDismissed()
|
||||
{
|
||||
using var page = new MainPage(corruptSettings: true);
|
||||
|
||||
Assert.Equal(TestServices.Localization["Msg_SettingsRecovered"], page.Vm.NoticeText);
|
||||
page.Vm.DismissNoticeCommand.Execute(null);
|
||||
Assert.Null(page.Vm.NoticeText);
|
||||
}
|
||||
|
||||
[AvaloniaFact]
|
||||
public void ToggleTheme_SwitchesLightAndDark_UnlessLocked()
|
||||
{
|
||||
using var page = new MainPage();
|
||||
page.Theme.CurrentThemeVariant = AppThemeVariant.Light;
|
||||
|
||||
page.Vm.ToggleThemeCommand.Execute(null);
|
||||
Assert.Equal(AppThemeVariant.Dark, page.Theme.CurrentThemeVariant);
|
||||
page.Vm.ToggleThemeCommand.Execute(null);
|
||||
Assert.Equal(AppThemeVariant.Light, page.Theme.CurrentThemeVariant);
|
||||
|
||||
page.Theme.IsThemeLocked = true;
|
||||
page.Vm.ToggleThemeCommand.Execute(null);
|
||||
Assert.Equal(AppThemeVariant.Light, page.Theme.CurrentThemeVariant);
|
||||
}
|
||||
|
||||
[AvaloniaFact]
|
||||
public async Task Activation_OpensThePageThatFitsTheFiles()
|
||||
{
|
||||
using var page = new MainPage();
|
||||
var activated = 0;
|
||||
page.Vm.ActivateWindowRequested += (_, _) => activated++;
|
||||
var data = page.Temp.File("data.bin", "hello");
|
||||
var sums = page.Temp.File("data.bin.sha256", "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824 data.bin\n");
|
||||
|
||||
await page.Vm.HandleActivationAsync(new ActivationRequest(ActivationVerb.Auto, [sums]));
|
||||
Assert.Same(page.Check, page.Vm.CurrentPage);
|
||||
await page.Vm.HandleActivationAsync(new ActivationRequest(ActivationVerb.Auto, [data]));
|
||||
Assert.Same(page.Create, page.Vm.CurrentPage);
|
||||
await page.Vm.HandleActivationAsync(new ActivationRequest(ActivationVerb.Verify, [data]));
|
||||
Assert.Same(page.Check, page.Vm.CurrentPage);
|
||||
|
||||
page.Create.IsBusy = true;
|
||||
var waiting = page.Vm.HandleActivationAsync(new ActivationRequest(ActivationVerb.Create, [page.Temp.File("later.bin", "x")]));
|
||||
await Task.Delay(300, TestContext.Current.CancellationToken);
|
||||
Assert.False(waiting.IsCompleted);
|
||||
page.Create.IsBusy = false;
|
||||
await waiting.WaitAsync(TimeSpan.FromSeconds(10), TestContext.Current.CancellationToken);
|
||||
|
||||
Assert.Equal(["data.bin", "later.bin"], page.Create.Items.Select(i => i.FileName).Order(StringComparer.Ordinal));
|
||||
Assert.Equal(4, activated);
|
||||
}
|
||||
|
||||
[AvaloniaFact]
|
||||
public async Task Opening_DeliversQueuedActivations()
|
||||
{
|
||||
using var page = new MainPage();
|
||||
page.Activation.Enqueue(new ActivationRequest(ActivationVerb.Create, [page.Temp.File("queued.bin", "x")]));
|
||||
|
||||
await page.Vm.OnOpenedAsync();
|
||||
|
||||
await Wait.UntilAsync(() => page.Create.Items.Count == 1);
|
||||
Assert.Equal("queued.bin", page.Create.Items[0].FileName);
|
||||
}
|
||||
|
||||
[AvaloniaFact]
|
||||
public async Task Shortcuts_ActOnTheCurrentList()
|
||||
{
|
||||
using var page = new MainPage();
|
||||
page.Storage.Files = [page.Temp.File("a.bin", "hello")];
|
||||
page.Storage.Folders = [Directory.CreateDirectory(Path.Combine(page.Temp.Path, "folder")).FullName];
|
||||
page.Temp.File("folder/b.bin", "hello");
|
||||
var focus = 0;
|
||||
page.Create.FocusSearchRequested += (_, _) => focus++;
|
||||
|
||||
await page.Vm.AddFilesCommand.ExecuteAsync(null);
|
||||
await page.Vm.AddFolderCommand.ExecuteAsync(null);
|
||||
await page.Vm.RunAllCommand.ExecuteAsync(null);
|
||||
page.Vm.CancelAllCommand.Execute(null);
|
||||
page.Vm.FocusSearchCommand.Execute(null);
|
||||
|
||||
Assert.Equal(2, page.Create.Items.Count);
|
||||
Assert.All(page.Create.Items, i => Assert.False(string.IsNullOrEmpty(i.ResultHash)));
|
||||
Assert.Equal(1, focus);
|
||||
|
||||
page.Vm.NavigateCommand.Execute("About");
|
||||
await page.Vm.AddFilesCommand.ExecuteAsync(null);
|
||||
await page.Vm.AddFolderCommand.ExecuteAsync(null);
|
||||
await page.Vm.RunAllCommand.ExecuteAsync(null);
|
||||
page.Vm.CancelAllCommand.Execute(null);
|
||||
page.Vm.FocusSearchCommand.Execute(null);
|
||||
Assert.Equal(2, page.Create.Items.Count);
|
||||
}
|
||||
|
||||
[AvaloniaFact]
|
||||
public void SettingsChanges_UpdateTheWindowFlags()
|
||||
{
|
||||
using var page = new MainPage();
|
||||
var changed = new List<string?>();
|
||||
page.Vm.PropertyChanged += (_, e) => changed.Add(e.PropertyName);
|
||||
|
||||
page.Settings.Update(s =>
|
||||
{
|
||||
s.IsDeveloperModeEnabled = true;
|
||||
s.IsHashMaskingEnabled = true;
|
||||
});
|
||||
|
||||
Assert.True(page.Vm.IsDeveloperModeEnabled);
|
||||
Assert.True(page.Vm.IsHashMaskingEnabled);
|
||||
Assert.Same(page.Settings.Current, page.Vm.Settings);
|
||||
Assert.Contains(nameof(MainWindowViewModel.IsHashMaskingEnabled), changed);
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class DeveloperViewModelTests
|
||||
{
|
||||
private sealed class Console : IDisposable
|
||||
{
|
||||
public Console()
|
||||
{
|
||||
Logger = Sink.CreateLogger("HashTool.Test");
|
||||
Logger.LogInformation("before the console opened");
|
||||
Vm = new DeveloperViewModel(Sink, TestServices.Localization, Clipboard, Storage, Launcher);
|
||||
}
|
||||
|
||||
public TempDirectory Temp { get; } = new();
|
||||
|
||||
public LogSink Sink { get; } = new(PathSanitizer.Shared);
|
||||
|
||||
public ILogger Logger { get; }
|
||||
|
||||
public RecordingClipboard Clipboard { get; } = new();
|
||||
|
||||
public ScriptedStorage Storage { get; } = new();
|
||||
|
||||
public RecordingLauncher Launcher { get; } = new();
|
||||
|
||||
public DeveloperViewModel Vm { get; }
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
Sink.Dispose();
|
||||
Temp.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
[AvaloniaFact]
|
||||
public async Task NewEntries_AppearAndScroll_FilteredByLevel()
|
||||
{
|
||||
using var console = new Console();
|
||||
var appended = 0;
|
||||
console.Vm.EntriesAppended += (_, _) => appended++;
|
||||
Assert.Single(console.Vm.Entries);
|
||||
|
||||
console.Logger.LogDebug("debug line");
|
||||
console.Logger.LogWarning("warning line");
|
||||
await Wait.UntilAsync(() => console.Vm.Entries.Count == 3);
|
||||
Assert.True(appended > 0);
|
||||
|
||||
console.Vm.MinimumLevel = LogLevel.Warning;
|
||||
Assert.Equal("warning line", Assert.Single(console.Vm.Entries).Message);
|
||||
console.Logger.LogInformation("filtered out");
|
||||
console.Logger.LogError("error line");
|
||||
await Wait.UntilAsync(() => console.Vm.Entries.Count == 2);
|
||||
Assert.Contains(LogLevel.Error, console.Vm.Levels);
|
||||
}
|
||||
|
||||
[AvaloniaFact]
|
||||
public async Task TheConsole_KeepsAtMostTheSinkCapacity()
|
||||
{
|
||||
using var console = new Console();
|
||||
console.Vm.AutoScroll = false;
|
||||
|
||||
for (var i = 0; i <= LogSink.Capacity; i++) console.Logger.LogInformation("entry {Index}", i);
|
||||
|
||||
await Wait.UntilAsync(() => console.Vm.Entries.Count == LogSink.Capacity && console.Vm.Entries[^1].Message == $"entry {LogSink.Capacity}");
|
||||
Assert.Equal("entry 1", console.Vm.Entries[0].Message);
|
||||
}
|
||||
|
||||
[AvaloniaFact]
|
||||
public async Task Commands_PauseClearCopyExportAndOpenTheFolder()
|
||||
{
|
||||
using var console = new Console();
|
||||
|
||||
console.Vm.IsRecording = false;
|
||||
console.Logger.LogWarning("not recorded");
|
||||
Assert.False(console.Sink.IsRecording);
|
||||
console.Vm.IsRecording = true;
|
||||
|
||||
await console.Vm.CopyCommand.ExecuteAsync(null);
|
||||
Assert.Contains("before the console opened", Assert.Single(console.Clipboard.Texts), StringComparison.Ordinal);
|
||||
|
||||
await console.Vm.ExportCommand.ExecuteAsync(null);
|
||||
console.Storage.SavePath = Path.Combine(console.Temp.Path, "log.txt");
|
||||
await console.Vm.ExportCommand.ExecuteAsync(null);
|
||||
Assert.Contains("before the console opened", (await File.ReadAllTextAsync(console.Storage.SavePath, TestContext.Current.CancellationToken)), StringComparison.Ordinal);
|
||||
Assert.StartsWith("hashtool-log-", console.Storage.SuggestedName, StringComparison.Ordinal);
|
||||
|
||||
await console.Vm.OpenLogFolderCommand.ExecuteAsync(null);
|
||||
Assert.Equal([AppPaths.LogDirectory], console.Launcher.Folders);
|
||||
|
||||
console.Vm.ClearCommand.Execute(null);
|
||||
Assert.Empty(console.Vm.Entries);
|
||||
Assert.Empty(console.Sink.Snapshot());
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class AboutViewModelTests
|
||||
{
|
||||
[AvaloniaFact]
|
||||
public async Task Links_OpenInTheBrowser()
|
||||
{
|
||||
var launcher = new RecordingLauncher();
|
||||
var about = new AboutViewModel(AppHost.Get<UpdateService>(), TestServices.Localization, launcher);
|
||||
|
||||
await about.OpenUrlCommand.ExecuteAsync("https://github.com/poli0981/HashTool");
|
||||
await about.OpenUrlCommand.ExecuteAsync("");
|
||||
await about.OpenUrlCommand.ExecuteAsync(null);
|
||||
|
||||
Assert.Equal(["https://github.com/poli0981/HashTool"], launcher.Urls);
|
||||
Assert.All(about.Libraries, l => Assert.False(string.IsNullOrEmpty(l.Version)));
|
||||
}
|
||||
}
|
||||
@@ -16,48 +16,11 @@ using Xunit;
|
||||
|
||||
namespace HashTool.App.Tests;
|
||||
|
||||
/// <summary>Records dialogs instead of showing them, so batch summaries can be checked.</summary>
|
||||
internal sealed class RecordingDialogs : IDialogService
|
||||
{
|
||||
public List<(string Message, DialogIcon Icon)> Shown { get; } = [];
|
||||
|
||||
public Task ShowAsync(string title, string message, DialogIcon icon = DialogIcon.Information)
|
||||
{
|
||||
Shown.Add((message, icon));
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
public Task<bool> ConfirmAsync(string title, string message, DialogIcon icon = DialogIcon.Question, string? yesText = null,
|
||||
string? noText = null) => Task.FromResult(false);
|
||||
|
||||
public Task ShowErrorAsync(string title, string message, string? details = null)
|
||||
{
|
||||
Shown.Add((message, DialogIcon.Error));
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
}
|
||||
|
||||
internal sealed class NoStorage : IStorageService
|
||||
{
|
||||
public Task<IReadOnlyList<string>> PickFilesAsync(string title, bool allowMultiple = true, IReadOnlyList<FileTypeChoice>? types = null) =>
|
||||
Task.FromResult<IReadOnlyList<string>>([]);
|
||||
|
||||
public Task<IReadOnlyList<string>> PickFoldersAsync(string title) => Task.FromResult<IReadOnlyList<string>>([]);
|
||||
|
||||
public Task<(string Path, FileTypeChoice? Type)?> SaveFileAsync(string title, string suggestedName, IReadOnlyList<FileTypeChoice> types) =>
|
||||
Task.FromResult<(string Path, FileTypeChoice? Type)?>(null);
|
||||
}
|
||||
|
||||
internal sealed class NoClipboard : IClipboardService
|
||||
{
|
||||
public Task SetTextAsync(string text) => Task.CompletedTask;
|
||||
}
|
||||
|
||||
public sealed class BatchRegressionTests
|
||||
{
|
||||
private static FileListServices Services(RecordingDialogs dialogs) => new(
|
||||
AppHost.Get<LocalizationService>(), AppHost.Get<SettingsService>(), dialogs, new NoStorage(), new NoClipboard(), new HashEngine(),
|
||||
AppHost.Get<ILoggerFactory>());
|
||||
AppHost.Get<LocalizationService>(), AppHost.Get<SettingsService>(), dialogs, new ScriptedStorage(), new RecordingClipboard(),
|
||||
new HashEngine(), AppHost.Get<ILoggerFactory>());
|
||||
|
||||
[AvaloniaFact]
|
||||
public async Task LargeBatch_FinishesEveryRow()
|
||||
|
||||
@@ -0,0 +1,379 @@
|
||||
using System;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using Avalonia.Headless.XUnit;
|
||||
using Avalonia.Media;
|
||||
using HashTool.App.Infrastructure;
|
||||
using HashTool.App.Services;
|
||||
using HashTool.App.Services.Theme;
|
||||
using HashTool.App.ViewModels;
|
||||
using HashTool.Core.Checksums;
|
||||
using HashTool.Core.Configuration;
|
||||
using HashTool.Core.Hashing;
|
||||
using HashTool.Core.Tests;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Xunit;
|
||||
|
||||
namespace HashTool.App.Tests;
|
||||
|
||||
/// <summary>Tests that change process-wide state (the UI language and culture) never run alongside other tests.</summary>
|
||||
[CollectionDefinition(Name, DisableParallelization = true)]
|
||||
public sealed class SharedStateCollection
|
||||
{
|
||||
public const string Name = "Shared state";
|
||||
}
|
||||
|
||||
[Collection(SharedStateCollection.Name)]
|
||||
public sealed class SettingsViewModelTests
|
||||
{
|
||||
private sealed class Page : IDisposable
|
||||
{
|
||||
public Page(Func<string, bool>? answer = null)
|
||||
{
|
||||
Settings = TestServices.Settings(Path.Combine(Temp.Path, ".settings"));
|
||||
Dialogs = new RecordingDialogs { Answer = answer ?? (_ => false) };
|
||||
Font = new FontService(TestServices.Loggers.CreateLogger<FontService>());
|
||||
Vm = new SettingsViewModel(Settings, TestServices.Localization, Font, Theme, Dialogs, Clipboard, Launcher,
|
||||
AppHost.Get<UpdateService>(), LogLevel, TestServices.Loggers.CreateLogger<SettingsViewModel>());
|
||||
}
|
||||
|
||||
public TempDirectory Temp { get; } = new();
|
||||
|
||||
public SettingsService Settings { get; }
|
||||
|
||||
public RecordingDialogs Dialogs { get; }
|
||||
|
||||
public FontService Font { get; }
|
||||
|
||||
public ThemeService Theme { get; } = new();
|
||||
|
||||
public RecordingClipboard Clipboard { get; } = new();
|
||||
|
||||
public RecordingLauncher Launcher { get; } = new();
|
||||
|
||||
public LogLevelSwitch LogLevel { get; } = new();
|
||||
|
||||
public SettingsViewModel Vm { get; }
|
||||
|
||||
public AppSettings Current => Settings.Current;
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
Settings.Dispose();
|
||||
Temp.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
[AvaloniaFact]
|
||||
public void EveryOption_IsStoredInTheSettings()
|
||||
{
|
||||
using var page = new Page();
|
||||
var changed = new System.Collections.Generic.List<string?>();
|
||||
page.Vm.PropertyChanged += (_, e) => changed.Add(e.PropertyName);
|
||||
|
||||
page.Vm.IsFileSizeLimitEnabled = true;
|
||||
page.Vm.FileSizeLimitValue = 5;
|
||||
page.Vm.FileSizeLimitUnit = FileSizeUnit.MB;
|
||||
page.Vm.IsFileTimeoutEnabled = true;
|
||||
page.Vm.FileTimeoutSeconds = 30;
|
||||
page.Vm.IsMaxFileCountEnabled = false;
|
||||
page.Vm.MaxFileCount = 50;
|
||||
page.Vm.IsMaxFolderCountEnabled = false;
|
||||
page.Vm.MaxFolderCount = 7;
|
||||
page.Vm.MaxParallelFiles = 2;
|
||||
page.Vm.OptimizeForHdd = true;
|
||||
page.Vm.IncludeHiddenFiles = true;
|
||||
page.Vm.HashLetterCase = page.Vm.HexCaseOptions.Single(o => o.Value == HexCase.Lower);
|
||||
page.Vm.DefaultExportFormat = page.Vm.ExportFormatOptions.Single(o => o.Value == ExportFormat.Json);
|
||||
page.Vm.IsHashMaskingEnabled = true;
|
||||
page.Vm.ShowReadWriteSpeed = true;
|
||||
page.Vm.CheckForUpdatesOnStartup = false;
|
||||
|
||||
var s = page.Current;
|
||||
Assert.True(s.IsFileSizeLimitEnabled);
|
||||
Assert.Equal(5, s.FileSizeLimitValue);
|
||||
Assert.Equal(FileSizeUnit.MB, page.Vm.FileSizeLimitUnit);
|
||||
Assert.True(page.Vm.IsFileTimeoutEnabled);
|
||||
Assert.Equal(30, page.Vm.FileTimeoutSeconds);
|
||||
Assert.False(page.Vm.IsMaxFileCountEnabled);
|
||||
Assert.Equal(50, page.Vm.MaxFileCount);
|
||||
Assert.False(page.Vm.IsMaxFolderCountEnabled);
|
||||
Assert.Equal(7, page.Vm.MaxFolderCount);
|
||||
Assert.Equal(2, page.Vm.MaxParallelFiles);
|
||||
Assert.True(page.Vm.OptimizeForHdd);
|
||||
Assert.True(page.Vm.IncludeHiddenFiles);
|
||||
Assert.Equal(HexCase.Lower, page.Vm.HashLetterCase.Value);
|
||||
Assert.Equal(ExportFormat.Json, page.Vm.DefaultExportFormat.Value);
|
||||
Assert.True(page.Vm.IsHashMaskingEnabled);
|
||||
Assert.True(page.Vm.ShowReadWriteSpeed);
|
||||
Assert.False(page.Vm.CheckForUpdatesOnStartup);
|
||||
Assert.Contains(nameof(SettingsViewModel.MaxFolderCount), changed);
|
||||
Assert.Contains(nameof(SettingsViewModel.CheckForUpdatesOnStartup), changed);
|
||||
}
|
||||
|
||||
[AvaloniaFact]
|
||||
public void DeveloperMode_LowersTheLogLevel()
|
||||
{
|
||||
using var page = new Page();
|
||||
|
||||
page.Vm.IsDeveloperModeEnabled = true;
|
||||
Assert.Equal(LogLevel.Debug, page.LogLevel.Minimum);
|
||||
Assert.True(page.Vm.IsDeveloperModeEnabled);
|
||||
|
||||
page.Vm.IsDeveloperModeEnabled = false;
|
||||
Assert.Equal(LogLevel.Information, page.LogLevel.Minimum);
|
||||
}
|
||||
|
||||
[AvaloniaFact]
|
||||
public async Task LockingTheSettings_DisablesEditing_AndReset()
|
||||
{
|
||||
using var page = new Page(_ => true);
|
||||
|
||||
page.Vm.IsSettingsLocked = true;
|
||||
|
||||
Assert.True(page.Vm.IsSettingsLocked);
|
||||
Assert.False(page.Vm.CanEdit);
|
||||
Assert.False(page.Vm.CanChangeTheme);
|
||||
Assert.False(page.Vm.CanChangeFont);
|
||||
page.Vm.SetVariantCommand.Execute(AppThemeVariant.Dark);
|
||||
Assert.Equal(AppThemeVariant.System, page.Theme.CurrentThemeVariant);
|
||||
await page.Vm.ResetSettingsCommand.ExecuteAsync(null);
|
||||
Assert.Empty(page.Dialogs.Confirmations);
|
||||
}
|
||||
|
||||
[AvaloniaFact]
|
||||
public async Task Reset_RestoresDefaults_OnlyWhenConfirmed()
|
||||
{
|
||||
var answer = false;
|
||||
using var page = new Page(_ => answer);
|
||||
page.Vm.MaxFileCount = 5;
|
||||
page.Vm.IsDeveloperModeEnabled = true;
|
||||
|
||||
await page.Vm.ResetSettingsCommand.ExecuteAsync(null);
|
||||
Assert.Equal(5, page.Current.MaxFileCount);
|
||||
|
||||
answer = true;
|
||||
await page.Vm.ResetSettingsCommand.ExecuteAsync(null);
|
||||
Assert.Equal(new AppSettings().MaxFileCount, page.Current.MaxFileCount);
|
||||
Assert.False(page.Current.IsDeveloperModeEnabled);
|
||||
Assert.Equal(LogLevel.Information, page.LogLevel.Minimum);
|
||||
Assert.Equal(2, page.Dialogs.Confirmations.Count);
|
||||
}
|
||||
|
||||
[AvaloniaFact]
|
||||
public void ThemeAndFontChanges_AreSaved()
|
||||
{
|
||||
using var page = new Page();
|
||||
|
||||
page.Vm.SetVariantCommand.Execute(AppThemeVariant.Dark);
|
||||
page.Theme.CurrentThemeStyle = AppThemeStyle.Pastel;
|
||||
page.Theme.IsThemeLocked = true;
|
||||
page.Vm.SetVariantCommand.Execute(AppThemeVariant.Light);
|
||||
|
||||
Assert.Equal(AppThemeVariant.Dark, page.Current.ThemeVariant);
|
||||
Assert.Equal(AppThemeStyle.Pastel, page.Current.ThemeStyle);
|
||||
Assert.True(page.Current.IsThemeLocked);
|
||||
Assert.False(page.Vm.CanChangeTheme);
|
||||
|
||||
page.Font.BaseFontSize = 16;
|
||||
page.Font.UiScale = 1.25;
|
||||
page.Font.IsLockedFont = true;
|
||||
Assert.False(page.Font.IsAutoFont);
|
||||
page.Font.SelectedFont = new FontFamily("Inter");
|
||||
page.Font.IsAutoFont = true;
|
||||
|
||||
Assert.Equal(16, page.Current.BaseFontSize);
|
||||
Assert.Equal(1.25, page.Current.UiScale);
|
||||
Assert.True(page.Current.IsAutoFont);
|
||||
Assert.False(page.Current.IsFontLocked);
|
||||
Assert.True(page.Vm.CanChangeFont);
|
||||
}
|
||||
|
||||
[AvaloniaFact]
|
||||
public void Apply_PushesTheStoredSettingsIntoTheServices()
|
||||
{
|
||||
using var page = new Page();
|
||||
var language = TestServices.Localization.SelectedLanguage;
|
||||
try
|
||||
{
|
||||
page.Settings.Update(s =>
|
||||
{
|
||||
s.LanguageCode = "de-DE";
|
||||
s.ThemeStyle = AppThemeStyle.Retro;
|
||||
s.ThemeVariant = AppThemeVariant.Light;
|
||||
s.IsAutoFont = false;
|
||||
s.FontFamily = "Some Font";
|
||||
s.BaseFontSize = 13;
|
||||
s.IsDeveloperModeEnabled = true;
|
||||
});
|
||||
|
||||
page.Vm.Apply();
|
||||
|
||||
Assert.Equal("de-DE", TestServices.Localization.SelectedLanguage.Code);
|
||||
Assert.Equal(AppThemeStyle.Retro, page.Theme.CurrentThemeStyle);
|
||||
Assert.Equal(AppThemeVariant.Light, page.Theme.CurrentThemeVariant);
|
||||
Assert.Equal(13, page.Font.BaseFontSize);
|
||||
Assert.Equal(LogLevel.Debug, page.LogLevel.Minimum);
|
||||
// The settings are not written back while they are being applied.
|
||||
Assert.Equal("de-DE", page.Current.LanguageCode);
|
||||
}
|
||||
finally
|
||||
{
|
||||
TestServices.Localization.SelectedLanguage = language;
|
||||
}
|
||||
}
|
||||
|
||||
[AvaloniaFact]
|
||||
public void SelectedLanguage_ChangesTheUiAndIsSaved()
|
||||
{
|
||||
using var page = new Page();
|
||||
var language = TestServices.Localization.SelectedLanguage;
|
||||
var proxy = page.Vm.Localization;
|
||||
try
|
||||
{
|
||||
var japanese = TestServices.Localization.Find("ja-JP");
|
||||
page.Vm.SelectedLanguage = japanese;
|
||||
page.Vm.SelectedLanguage = japanese;
|
||||
page.Vm.SelectedLanguage = null!;
|
||||
|
||||
Assert.Equal("ja-JP", page.Current.LanguageCode);
|
||||
Assert.Equal("ja-JP", page.Vm.SelectedLanguage.Code);
|
||||
Assert.NotSame(proxy, page.Vm.Localization);
|
||||
Assert.Contains(page.Vm.AutomaticParallelism.ToString(CultureInfo.InvariantCulture), page.Vm.ParallelFilesHint, StringComparison.Ordinal);
|
||||
}
|
||||
finally
|
||||
{
|
||||
TestServices.Localization.SelectedLanguage = language;
|
||||
}
|
||||
}
|
||||
|
||||
[AvaloniaFact]
|
||||
public async Task ConfigurationCommands_CopyThePathAndOpenTheDataFolder()
|
||||
{
|
||||
using var page = new Page();
|
||||
|
||||
await page.Vm.CopyConfigPathCommand.ExecuteAsync(null);
|
||||
await page.Vm.OpenDataFolderCommand.ExecuteAsync(null);
|
||||
|
||||
Assert.Equal([page.Settings.FilePath], page.Clipboard.Texts);
|
||||
Assert.Equal(page.Settings.FilePath, page.Vm.ConfigFilePath);
|
||||
Assert.Equal(DialogIcon.Success, page.Dialogs.Shown.Single().Icon);
|
||||
Assert.Equal([AppPaths.DataDirectory], page.Launcher.Folders);
|
||||
}
|
||||
|
||||
[AvaloniaFact]
|
||||
public void SystemIntegration_ReflectsThePlatform()
|
||||
{
|
||||
using var page = new Page();
|
||||
|
||||
Assert.Equal(OperatingSystem.IsWindows(), page.Vm.IsWindows);
|
||||
Assert.Equal(Elevation.IsElevated, page.Vm.IsElevated);
|
||||
Assert.Equal(Elevation.CanRestartElevated, page.Vm.CanRestartElevated);
|
||||
if (!OperatingSystem.IsWindows()) Assert.False(page.Vm.CanUseShellIntegration);
|
||||
Assert.NotEmpty(page.Vm.ThemeStyles);
|
||||
Assert.NotEmpty(page.Vm.FileSizeUnits);
|
||||
|
||||
// Setting the current value again does nothing (and never touches the registry).
|
||||
var current = page.Vm.IsShellIntegrationEnabled;
|
||||
page.Vm.IsShellIntegrationEnabled = current;
|
||||
page.Vm.RefreshShellIntegration();
|
||||
// Elsewhere than Windows the Explorer integration is a no-op, so the switch itself can be exercised.
|
||||
if (OperatingSystem.IsWindows()) return;
|
||||
page.Vm.IsShellIntegrationEnabled = true;
|
||||
Assert.True(page.Current.IsShellIntegrationEnabled);
|
||||
page.Vm.RefreshShellIntegration();
|
||||
page.Vm.IsShellIntegrationEnabled = false;
|
||||
Assert.False(page.Current.IsShellIntegrationEnabled);
|
||||
}
|
||||
|
||||
[AvaloniaFact]
|
||||
public void RestartElevated_DoesNothingWhereElevationIsUnavailable()
|
||||
{
|
||||
// On a non-administrator Windows account this would show a UAC prompt: only run it where nothing can start.
|
||||
if (Elevation.CanRestartElevated) return;
|
||||
using var page = new Page();
|
||||
var shutdown = false;
|
||||
page.Vm.RequestShutdown += (_, _) => shutdown = true;
|
||||
|
||||
page.Vm.RestartElevatedCommand.Execute(null);
|
||||
|
||||
Assert.False(shutdown);
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class FontServiceTests
|
||||
{
|
||||
private static FontService Create() => new(TestServices.Loggers.CreateLogger<FontService>());
|
||||
|
||||
[AvaloniaFact]
|
||||
public async Task SelectFont_WaitsForTheFontListToLoad()
|
||||
{
|
||||
var fonts = Create();
|
||||
fonts.SelectFont("Inter");
|
||||
Assert.Equal(FontFamily.Default, fonts.SelectedFont);
|
||||
|
||||
await fonts.LoadAsync();
|
||||
|
||||
Assert.Contains(fonts.InstalledFonts, f => f == FontFamily.Default);
|
||||
if (fonts.InstalledFonts.Any(f => f.Name == "Inter")) Assert.Equal("Inter", fonts.SelectedFontName);
|
||||
fonts.SelectFont("$Default");
|
||||
Assert.Null(fonts.SelectedFontName);
|
||||
fonts.SelectFont(null);
|
||||
Assert.Equal(FontFamily.Default, fonts.SelectedFont);
|
||||
}
|
||||
|
||||
[AvaloniaFact]
|
||||
public void AutomaticAndLockedFont_ExcludeEachOther()
|
||||
{
|
||||
var fonts = Create();
|
||||
|
||||
fonts.IsLockedFont = true;
|
||||
Assert.False(fonts.IsAutoFont);
|
||||
fonts.ApplyAutomaticFont(CultureInfo.GetCultureInfo("ja-JP"));
|
||||
Assert.Equal(FontFamily.Default, fonts.SelectedFont);
|
||||
|
||||
fonts.IsAutoFont = true;
|
||||
Assert.False(fonts.IsLockedFont);
|
||||
fonts.ApplyAutomaticFont(CultureInfo.GetCultureInfo("en-US"));
|
||||
Assert.Equal(FontFamily.Default, fonts.SelectedFont);
|
||||
|
||||
fonts.UiScale = 2;
|
||||
fonts.BaseFontSize = 20;
|
||||
fonts.Reset();
|
||||
Assert.Equal(1.0, fonts.UiScale);
|
||||
Assert.Equal(14.0, fonts.BaseFontSize);
|
||||
Assert.True(fonts.IsAutoFont);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("ja-JP", "Yu Gothic UI")]
|
||||
[InlineData("ko-KR", "Malgun Gothic")]
|
||||
[InlineData("zh-Hant", "Microsoft JhengHei UI")]
|
||||
[InlineData("zh-Hans-CN", "Microsoft YaHei UI")]
|
||||
[InlineData("th-TH", "Leelawadee UI")]
|
||||
[InlineData("lo-LA", "Lao Sangam MN")]
|
||||
[InlineData("km-KH", "Khmer Sangam MN")]
|
||||
[InlineData("my-MM", "Myanmar Text")]
|
||||
[InlineData("ar", "Geeza Pro")]
|
||||
[InlineData("fa-IR", "Noto Sans Arabic")]
|
||||
[InlineData("ps-AF", "Tahoma")]
|
||||
[InlineData("he-IL", "Arial Hebrew")]
|
||||
[InlineData("hi-IN", "Nirmala UI")]
|
||||
[InlineData("ne-NP", "Kohinoor Devanagari")]
|
||||
[InlineData("bn-BD", "Kohinoor Bangla")]
|
||||
[InlineData("si-LK", "Sinhala Sangam MN")]
|
||||
[InlineData("dz-BT", "Microsoft Himalaya")]
|
||||
[InlineData("dv-MV", "MV Boli")]
|
||||
public void EachScript_HasPreferredFonts(string culture, string expected)
|
||||
{
|
||||
Assert.Contains(expected, FontService.CandidatesFor(CultureInfo.GetCultureInfo(culture)));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void LatinScripts_UseTheDefaultFont()
|
||||
{
|
||||
Assert.Empty(FontService.CandidatesFor(CultureInfo.GetCultureInfo("vi-VN")));
|
||||
}
|
||||
}
|
||||
@@ -1,20 +1,18 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using Avalonia;
|
||||
using Avalonia.Headless;
|
||||
using HashTool.App.Infrastructure;
|
||||
using HashTool.App.Tests;
|
||||
|
||||
[assembly: AvaloniaTestApplication(typeof(TestApp))]
|
||||
|
||||
// One application for the whole run, like the app itself. With a new one per test, the asynchronous part of the app's
|
||||
// startup (font loading, then applying the settings) of one test lands on the dispatcher of a later one.
|
||||
[assembly: AvaloniaTestIsolation(AvaloniaTestIsolationLevel.PerAssembly)]
|
||||
|
||||
namespace HashTool.App.Tests;
|
||||
|
||||
/// <summary>Runs the real <see cref="App"/> on Avalonia's headless platform, with settings and logs in a temporary folder.</summary>
|
||||
/// <summary>Runs the real <see cref="App"/> on Avalonia's headless platform (data folder: see <see cref="TestEnvironment"/>).</summary>
|
||||
public static class TestApp
|
||||
{
|
||||
public static AppBuilder BuildAvaloniaApp()
|
||||
{
|
||||
Environment.SetEnvironmentVariable(AppPaths.DataDirectoryVariable, Directory.CreateTempSubdirectory("hashtool-app-tests-").FullName);
|
||||
return AppBuilder.Configure<App>().UseHeadless(new AvaloniaHeadlessPlatformOptions()).WithInterFont();
|
||||
}
|
||||
public static AppBuilder BuildAvaloniaApp() =>
|
||||
AppBuilder.Configure<App>().UseHeadless(new AvaloniaHeadlessPlatformOptions()).WithInterFont();
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Runtime.CompilerServices;
|
||||
using HashTool.App.Infrastructure;
|
||||
|
||||
namespace HashTool.App.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// Runs before the first test touches <see cref="AppPaths"/>, which resolves its folder only once: settings, logs and crash
|
||||
/// reports of every test go to a temporary folder, never the user's own.
|
||||
/// </summary>
|
||||
internal static class TestEnvironment
|
||||
{
|
||||
[ModuleInitializer]
|
||||
internal static void Initialize() =>
|
||||
Environment.SetEnvironmentVariable(AppPaths.DataDirectoryVariable, Directory.CreateTempSubdirectory("hashtool-app-tests-").FullName);
|
||||
}
|
||||
@@ -0,0 +1,438 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.IO.Compression;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Avalonia.Headless.XUnit;
|
||||
using HashTool.App.Services;
|
||||
using HashTool.App.ViewModels;
|
||||
using HashTool.Core.Tests;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using Velopack;
|
||||
using Velopack.Locators;
|
||||
using Velopack.Logging;
|
||||
using Velopack.Sources;
|
||||
using Xunit;
|
||||
|
||||
namespace HashTool.App.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// A Velopack feed in a temporary folder, as vpk publishes it, and an installed Hash Tool 1.2.0 that updates from it.
|
||||
/// Nothing reaches the network, and nothing ever applies an update.
|
||||
/// </summary>
|
||||
internal sealed class LocalFeed : IDisposable
|
||||
{
|
||||
public const string Channel = "test";
|
||||
|
||||
public LocalFeed(string? newVersion = "1.3.0", string? notes = "## Changes\n- **Faster** hashing", bool withPackage = true)
|
||||
{
|
||||
Directory.CreateDirectory(FeedDirectory);
|
||||
Directory.CreateDirectory(PackagesDirectory);
|
||||
var assets = new List<object>();
|
||||
if (newVersion is not null)
|
||||
{
|
||||
var fileName = $"HashTool-{newVersion}-full.nupkg";
|
||||
var package = Path.Combine(FeedDirectory, fileName);
|
||||
using (var zip = ZipFile.Open(package, ZipArchiveMode.Create))
|
||||
{
|
||||
using var nuspec = new StreamWriter(zip.CreateEntry("HashTool.nuspec").Open(), Encoding.UTF8);
|
||||
nuspec.Write($"<?xml version=\"1.0\"?><package><metadata><id>HashTool</id><version>{newVersion}</version>" +
|
||||
"<authors>tests</authors><description>tests</description></metadata></package>");
|
||||
}
|
||||
|
||||
var bytes = File.ReadAllBytes(package);
|
||||
if (!withPackage) File.Delete(package);
|
||||
assets.Add(new Dictionary<string, object?>
|
||||
{
|
||||
["PackageId"] = "HashTool",
|
||||
["Version"] = newVersion,
|
||||
["Type"] = "Full",
|
||||
["FileName"] = fileName,
|
||||
["SHA1"] = Convert.ToHexString(SHA1.HashData(bytes)),
|
||||
["SHA256"] = Convert.ToHexString(SHA256.HashData(bytes)),
|
||||
["Size"] = bytes.LongLength,
|
||||
["NotesMarkdown"] = notes
|
||||
});
|
||||
}
|
||||
|
||||
File.WriteAllText(Path.Combine(FeedDirectory, $"releases.{Channel}.json"), JsonSerializer.Serialize(new Dictionary<string, object> { ["Assets"] = assets }));
|
||||
}
|
||||
|
||||
public TempDirectory Temp { get; } = new();
|
||||
|
||||
public string FeedDirectory => Path.Combine(Temp.Path, "feed");
|
||||
|
||||
public string PackagesDirectory => Path.Combine(Temp.Path, "packages");
|
||||
|
||||
public UpdateManager Manager(IUpdateSource? source = null) =>
|
||||
new(source ?? new SimpleFileSource(new DirectoryInfo(FeedDirectory)), new UpdateOptions { ExplicitChannel = Channel },
|
||||
new TestVelopackLocator("HashTool", "1.2.0", PackagesDirectory, null));
|
||||
|
||||
public UpdateService Service(IUpdateSource? source = null, HttpMessageHandler? http = null) =>
|
||||
new(NullLogger<UpdateService>.Instance, Manager(source), new HttpClient(http ?? new StubHttp(_ => new HttpResponseMessage(HttpStatusCode.NotFound))));
|
||||
|
||||
public void Dispose() => Temp.Dispose();
|
||||
}
|
||||
|
||||
/// <summary>Answers HTTP requests from the test instead of the network.</summary>
|
||||
internal sealed class StubHttp(Func<HttpRequestMessage, HttpResponseMessage> respond) : HttpMessageHandler
|
||||
{
|
||||
public List<string> Requests { get; } = [];
|
||||
|
||||
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
|
||||
{
|
||||
Requests.Add(request.RequestUri!.AbsolutePath);
|
||||
return Task.FromResult(respond(request));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A release source that fails with <c>feedError</c>, never answers (no error), or with <see cref="Feed"/> lists that feed but
|
||||
/// never finishes downloading.
|
||||
/// </summary>
|
||||
internal sealed class TroubledSource(Exception? feedError = null) : IUpdateSource
|
||||
{
|
||||
public IUpdateSource? Feed { get; init; }
|
||||
|
||||
public Task<VelopackAssetFeed> GetReleaseFeed(IVelopackLogger logger, string? appId, string channel, Guid? stagingId = null,
|
||||
VelopackAsset? latestLocalRelease = null) =>
|
||||
Feed?.GetReleaseFeed(logger, appId, channel, stagingId, latestLocalRelease)
|
||||
?? (feedError is null ? new TaskCompletionSource<VelopackAssetFeed>().Task : Task.FromException<VelopackAssetFeed>(feedError));
|
||||
|
||||
public Task DownloadReleaseEntry(IVelopackLogger logger, VelopackAsset releaseEntry, string localFile, Action<int> progress,
|
||||
CancellationToken cancelToken = default) =>
|
||||
Task.Delay(Timeout.Infinite, cancelToken);
|
||||
}
|
||||
|
||||
public sealed class UpdateServiceTests
|
||||
{
|
||||
[Fact]
|
||||
public async Task WithoutAnInstallation_UpdatesAreUnavailable()
|
||||
{
|
||||
var service = new UpdateService(NullLogger<UpdateService>.Instance, null, new HttpClient(new StubHttp(_ => throw new InvalidOperationException())));
|
||||
|
||||
Assert.False(service.IsInstalled);
|
||||
Assert.False(service.IsPortable);
|
||||
Assert.False(service.IsUpdatePendingRestart);
|
||||
Assert.False(string.IsNullOrEmpty(service.CurrentVersion));
|
||||
Assert.Equal(UpdateCheckStatus.NotInstalled, (await service.CheckAsync(TestContext.Current.CancellationToken)).Status);
|
||||
|
||||
using var feed = new LocalFeed();
|
||||
var update = (await feed.Service().CheckAsync(TestContext.Current.CancellationToken)).Update!;
|
||||
await service.DownloadAsync(update, null, TestContext.Current.CancellationToken);
|
||||
// Without an update manager these only log: nothing is applied and nothing exits.
|
||||
service.ApplyAndRestart(update);
|
||||
service.ApplyOnExit(update);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AnInstalledApp_FindsTheNewerRelease_WithItsNotes()
|
||||
{
|
||||
using var feed = new LocalFeed();
|
||||
var service = feed.Service();
|
||||
|
||||
var result = await service.CheckAsync(TestContext.Current.CancellationToken);
|
||||
|
||||
Assert.True(service.IsInstalled);
|
||||
Assert.Equal("1.2.0", service.CurrentVersion);
|
||||
Assert.Equal(UpdateCheckStatus.UpdateAvailable, result.Status);
|
||||
Assert.Equal("1.3.0", result.Version);
|
||||
Assert.Contains("Faster", result.ReleaseNotes, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task WithoutNewerRelease_TheAppIsUpToDate()
|
||||
{
|
||||
using var feed = new LocalFeed(newVersion: null);
|
||||
|
||||
Assert.Equal(UpdateCheckStatus.UpToDate, (await feed.Service().CheckAsync(TestContext.Current.CancellationToken)).Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task NotesMissingFromTheFeed_AreReadFromTheGitHubRelease()
|
||||
{
|
||||
using var feed = new LocalFeed(notes: null);
|
||||
var http = new StubHttp(request => request.RequestUri!.AbsolutePath.EndsWith("/v1.3.0", StringComparison.Ordinal)
|
||||
? new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent("{\"body\":\"From GitHub\"}") }
|
||||
: new HttpResponseMessage(HttpStatusCode.NotFound));
|
||||
|
||||
var result = await feed.Service(http: http).CheckAsync(TestContext.Current.CancellationToken);
|
||||
|
||||
Assert.Equal("From GitHub", result.ReleaseNotes);
|
||||
Assert.Equal(["/repos/poli0981/HashTool/releases/tags/1.3.0", "/repos/poli0981/HashTool/releases/tags/v1.3.0"], http.Requests);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UnreachableReleaseNotes_LeaveTheNotesEmpty()
|
||||
{
|
||||
using var feed = new LocalFeed(notes: null);
|
||||
|
||||
var result = await feed.Service(http: new StubHttp(_ => throw new HttpRequestException("offline"))).CheckAsync(TestContext.Current.CancellationToken);
|
||||
|
||||
Assert.Equal(UpdateCheckStatus.UpdateAvailable, result.Status);
|
||||
Assert.Null(result.ReleaseNotes);
|
||||
}
|
||||
|
||||
public static TheoryData<Exception, UpdateCheckStatus> Failures => new()
|
||||
{
|
||||
{ new HttpRequestException("forbidden", null, HttpStatusCode.Forbidden), UpdateCheckStatus.RateLimited },
|
||||
{ new HttpRequestException("slow down", null, HttpStatusCode.TooManyRequests), UpdateCheckStatus.RateLimited },
|
||||
{ new HttpRequestException("no route"), UpdateCheckStatus.NetworkError },
|
||||
{ new TimeoutException("stalled"), UpdateCheckStatus.NetworkError },
|
||||
{ new TaskCanceledException("client time-out"), UpdateCheckStatus.NetworkError },
|
||||
{ new InvalidDataException("broken feed"), UpdateCheckStatus.Failed }
|
||||
};
|
||||
|
||||
[Theory]
|
||||
[MemberData(nameof(Failures))]
|
||||
public async Task CheckFailures_AreClassified(Exception error, UpdateCheckStatus expected)
|
||||
{
|
||||
using var feed = new LocalFeed();
|
||||
|
||||
var result = await feed.Service(new TroubledSource(error)).CheckAsync(TestContext.Current.CancellationToken);
|
||||
|
||||
Assert.Equal(expected, result.Status);
|
||||
Assert.Same(error, result.Error);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ACancelledCheck_IsCancelled()
|
||||
{
|
||||
using var feed = new LocalFeed();
|
||||
using var cancelled = new CancellationTokenSource();
|
||||
await cancelled.CancelAsync();
|
||||
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => feed.Service(new TroubledSource()).CheckAsync(cancelled.Token));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Download_FetchesThePackageAndReportsProgress()
|
||||
{
|
||||
using var feed = new LocalFeed();
|
||||
var service = feed.Service();
|
||||
var update = (await service.CheckAsync(TestContext.Current.CancellationToken)).Update!;
|
||||
var progress = new List<int>();
|
||||
|
||||
await service.DownloadAsync(update, p =>
|
||||
{
|
||||
lock (progress) progress.Add(p);
|
||||
}, TestContext.Current.CancellationToken);
|
||||
|
||||
Assert.True(File.Exists(Path.Combine(feed.PackagesDirectory, "HashTool-1.3.0-full.nupkg")));
|
||||
lock (progress) Assert.Contains(100, progress);
|
||||
}
|
||||
}
|
||||
|
||||
[Collection(SharedStateCollection.Name)]
|
||||
public sealed class UpdateViewModelTests
|
||||
{
|
||||
private sealed class Page : IDisposable
|
||||
{
|
||||
public Page(UpdateService updates)
|
||||
{
|
||||
Settings = TestServices.Settings(Path.Combine(Temp.Path, ".settings"));
|
||||
Vm = new UpdateViewModel(updates, Settings, TestServices.Localization, Launcher, TestServices.Loggers.CreateLogger<UpdateViewModel>());
|
||||
}
|
||||
|
||||
public TempDirectory Temp { get; } = new();
|
||||
|
||||
public SettingsService Settings { get; }
|
||||
|
||||
public RecordingLauncher Launcher { get; } = new();
|
||||
|
||||
public UpdateViewModel Vm { get; }
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
Settings.Dispose();
|
||||
Temp.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
private static string L(string key) => TestServices.Localization[key];
|
||||
|
||||
private static UpdateService NotInstalled() =>
|
||||
new(NullLogger<UpdateService>.Instance, null, new HttpClient(new StubHttp(_ => new HttpResponseMessage(HttpStatusCode.NotFound))));
|
||||
|
||||
[AvaloniaFact]
|
||||
public async Task AnUninstalledBuild_CannotCheck()
|
||||
{
|
||||
using var page = new Page(NotInstalled());
|
||||
|
||||
Assert.Equal(UpdateState.NotInstalled, page.Vm.State);
|
||||
Assert.False(page.Vm.CanCheck);
|
||||
Assert.Equal(L("Msg_UpdatesUnavailable"), page.Vm.StatusText);
|
||||
|
||||
await page.Vm.CheckCommand.ExecuteAsync(null);
|
||||
Assert.Equal(UpdateState.NotInstalled, page.Vm.State);
|
||||
Assert.NotNull(page.Settings.Current.LastUpdateCheck);
|
||||
}
|
||||
|
||||
[AvaloniaFact]
|
||||
public async Task Check_ShowsTheNewVersionAndItsNotes()
|
||||
{
|
||||
using var feed = new LocalFeed();
|
||||
using var page = new Page(feed.Service());
|
||||
|
||||
await page.Vm.CheckCommand.ExecuteAsync(null);
|
||||
|
||||
Assert.Equal(UpdateState.Available, page.Vm.State);
|
||||
Assert.Equal("1.3.0", page.Vm.AvailableVersion);
|
||||
Assert.Equal("Changes\n• Faster hashing", page.Vm.ReleaseNotes);
|
||||
Assert.Equal(TestServices.Localization.Format("Msg_UpdateAvailableBanner", "1.3.0"), page.Vm.StatusText);
|
||||
Assert.True(page.Vm.CanInstall);
|
||||
Assert.False(page.Vm.IsChecking);
|
||||
|
||||
await page.Vm.OpenReleasePageCommand.ExecuteAsync(null);
|
||||
Assert.Equal($"{UpdateService.RepositoryUrl}/releases/tag/1.3.0", page.Launcher.Urls.Single());
|
||||
}
|
||||
|
||||
[AvaloniaFact]
|
||||
public async Task Check_WithoutUpdate_IsUpToDate()
|
||||
{
|
||||
using var feed = new LocalFeed(newVersion: null);
|
||||
using var page = new Page(feed.Service());
|
||||
|
||||
await page.Vm.CheckCommand.ExecuteAsync(null);
|
||||
await page.Vm.OpenReleasePageCommand.ExecuteAsync(null);
|
||||
|
||||
Assert.Equal(UpdateState.UpToDate, page.Vm.State);
|
||||
Assert.Equal(L("Status_Latest"), page.Vm.StatusText);
|
||||
Assert.Equal($"{UpdateService.RepositoryUrl}/releases", page.Launcher.Urls.Single());
|
||||
}
|
||||
|
||||
public static TheoryData<Exception, string> CheckErrors => new()
|
||||
{
|
||||
{ new HttpRequestException("forbidden", null, HttpStatusCode.Forbidden), "Error_ApiLimit" },
|
||||
{ new HttpRequestException("no route"), "Error_Network" },
|
||||
{ new InvalidDataException("broken feed"), "broken feed" }
|
||||
};
|
||||
|
||||
[AvaloniaTheory]
|
||||
[MemberData(nameof(CheckErrors))]
|
||||
public async Task CheckErrors_AreExplained(Exception error, string expected)
|
||||
{
|
||||
using var feed = new LocalFeed();
|
||||
using var page = new Page(feed.Service(new TroubledSource(error)));
|
||||
|
||||
await page.Vm.CheckCommand.ExecuteAsync(null);
|
||||
|
||||
Assert.Equal(UpdateState.Error, page.Vm.State);
|
||||
Assert.Equal(expected.Contains(' ', StringComparison.Ordinal) ? expected : L(expected), page.Vm.ErrorDetail);
|
||||
Assert.Equal(TestServices.Localization.Format("Status_CheckError", page.Vm.ErrorDetail), page.Vm.StatusText);
|
||||
}
|
||||
|
||||
[AvaloniaFact]
|
||||
public async Task AFailedDownload_IsReported_AndNothingIsInstalled()
|
||||
{
|
||||
using var feed = new LocalFeed(withPackage: false);
|
||||
using var page = new Page(feed.Service());
|
||||
await page.Vm.CheckCommand.ExecuteAsync(null);
|
||||
|
||||
await page.Vm.InstallOnExitCommand.ExecuteAsync(null);
|
||||
|
||||
Assert.Equal(UpdateState.Error, page.Vm.State);
|
||||
Assert.False(string.IsNullOrEmpty(page.Vm.ErrorDetail));
|
||||
}
|
||||
|
||||
[AvaloniaFact]
|
||||
public async Task CancellingTheDownload_GoesBackToAvailable()
|
||||
{
|
||||
using var feed = new LocalFeed();
|
||||
using var page = new Page(feed.Service(new TroubledSource { Feed = new SimpleFileSource(new DirectoryInfo(feed.FeedDirectory)) }));
|
||||
await page.Vm.CheckCommand.ExecuteAsync(null);
|
||||
|
||||
var install = page.Vm.InstallCommand.ExecuteAsync(null);
|
||||
await Wait.UntilAsync(() => page.Vm.IsDownloading);
|
||||
page.Vm.CancelDownloadCommand.Execute(null);
|
||||
await install;
|
||||
|
||||
Assert.Equal(UpdateState.Available, page.Vm.State);
|
||||
page.Vm.CancelDownloadCommand.Execute(null);
|
||||
}
|
||||
|
||||
[AvaloniaFact]
|
||||
public void StatusText_FollowsTheState()
|
||||
{
|
||||
using var page = new Page(NotInstalled());
|
||||
|
||||
page.Vm.State = UpdateState.Idle;
|
||||
Assert.Equal(L("Lbl_Status_Ready"), page.Vm.StatusText);
|
||||
page.Vm.State = UpdateState.Checking;
|
||||
Assert.Equal(L("Status_Checking"), page.Vm.StatusText);
|
||||
Assert.True(page.Vm.IsChecking);
|
||||
page.Vm.State = UpdateState.Downloading;
|
||||
page.Vm.DownloadProgress = 42;
|
||||
Assert.Equal(TestServices.Localization.Format("Status_Downloading", 42), page.Vm.StatusText);
|
||||
Assert.True(page.Vm.IsDownloading);
|
||||
page.Vm.State = UpdateState.ReadyToInstall;
|
||||
Assert.Equal(L("Status_ReadyToInstall"), page.Vm.StatusText);
|
||||
Assert.True(page.Vm.CanInstall);
|
||||
Assert.False(string.IsNullOrEmpty(page.Vm.CurrentVersionText));
|
||||
}
|
||||
|
||||
[AvaloniaFact]
|
||||
public void CheckOnStartup_IsTheSharedSetting()
|
||||
{
|
||||
using var page = new Page(NotInstalled());
|
||||
var changed = 0;
|
||||
page.Vm.PropertyChanged += (_, e) => changed += e.PropertyName == nameof(UpdateViewModel.CheckOnStartup) ? 1 : 0;
|
||||
|
||||
page.Vm.CheckOnStartup = false;
|
||||
page.Settings.Update(s => s.CheckForUpdatesOnStartup = true);
|
||||
|
||||
Assert.True(page.Vm.CheckOnStartup);
|
||||
Assert.True(changed >= 2);
|
||||
}
|
||||
|
||||
[AvaloniaFact]
|
||||
public async Task BackgroundCheck_RunsAtMostOnceADay()
|
||||
{
|
||||
using var feed = new LocalFeed();
|
||||
using var page = new Page(feed.Service());
|
||||
var found = 0;
|
||||
page.Vm.UpdateFound += (_, _) => found++;
|
||||
var ci = Environment.GetEnvironmentVariable("CI");
|
||||
try
|
||||
{
|
||||
Environment.SetEnvironmentVariable("CI", null);
|
||||
page.Vm.CheckOnStartup = false;
|
||||
await page.Vm.CheckInBackgroundIfDueAsync();
|
||||
Assert.Equal(UpdateState.Idle, page.Vm.State);
|
||||
|
||||
page.Vm.CheckOnStartup = true;
|
||||
await page.Vm.CheckInBackgroundIfDueAsync();
|
||||
Assert.Equal(UpdateState.Available, page.Vm.State);
|
||||
Assert.Equal(1, found);
|
||||
|
||||
// Checked a moment ago: not due again.
|
||||
page.Vm.State = UpdateState.Idle;
|
||||
await page.Vm.CheckInBackgroundIfDueAsync();
|
||||
Assert.Equal(UpdateState.Idle, page.Vm.State);
|
||||
|
||||
Environment.SetEnvironmentVariable("CI", "true");
|
||||
page.Settings.Update(s => s.LastUpdateCheck = null);
|
||||
await page.Vm.CheckInBackgroundIfDueAsync();
|
||||
Assert.Equal(UpdateState.Idle, page.Vm.State);
|
||||
}
|
||||
finally
|
||||
{
|
||||
Environment.SetEnvironmentVariable("CI", ci);
|
||||
}
|
||||
}
|
||||
|
||||
[AvaloniaFact]
|
||||
public void ReleaseNotes_WithoutText_AreEmpty()
|
||||
{
|
||||
Assert.Null(UpdateViewModel.ToPlainText(null));
|
||||
Assert.Null(UpdateViewModel.ToPlainText(" "));
|
||||
}
|
||||
}
|
||||
@@ -16,6 +16,7 @@ using Xunit;
|
||||
namespace HashTool.App.Tests;
|
||||
|
||||
/// <summary>Renders the real window and pages on Avalonia's headless platform.</summary>
|
||||
[Collection(SharedStateCollection.Name)]
|
||||
public sealed class ViewTests
|
||||
{
|
||||
private const string Sha256Of123456789 = "15E2B0D3C33891EBB0F1EF609EC419420C20E320CE94C65FBC8C3312448EB225";
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Threading.Tasks;
|
||||
using HashTool.Core.Tests;
|
||||
using Xunit;
|
||||
|
||||
namespace HashTool.Cli.Tests;
|
||||
|
||||
/// <summary>Error paths and their exit codes (0 ok, 1 failed or mismatched file, 2 usage error).</summary>
|
||||
public sealed class CliErrorTests : IDisposable
|
||||
{
|
||||
private readonly TempDirectory _temp = new();
|
||||
|
||||
public void Dispose() => _temp.Dispose();
|
||||
|
||||
private static async Task<(int ExitCode, string Output, string Error)> RunAsync(params string[] args)
|
||||
{
|
||||
using var output = new StringWriter { NewLine = "\n" };
|
||||
using var error = new StringWriter { NewLine = "\n" };
|
||||
var exitCode = await HashToolCommand.RunAsync(args, output, error, TestContext.Current.CancellationToken);
|
||||
return (exitCode, output.ToString(), error.ToString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Sfv_NeedsCrc32()
|
||||
{
|
||||
var (exitCode, _, error) = await RunAsync("hash", _temp.File("a.txt", "x"), "-f", "sfv");
|
||||
|
||||
Assert.Equal(2, exitCode);
|
||||
Assert.Contains("sfv files contain CRC32 only", error, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task MissingInput_FailsButHashesTheRest()
|
||||
{
|
||||
var file = _temp.File("a.txt", "x");
|
||||
|
||||
var (exitCode, output, error) = await RunAsync("hash", file, Path.Combine(_temp.Path, "missing.txt"));
|
||||
|
||||
Assert.Equal(1, exitCode);
|
||||
Assert.Contains("a.txt", output, StringComparison.Ordinal);
|
||||
Assert.Contains("missing.txt: No such file or directory", error, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ALockedInput_IsReported()
|
||||
{
|
||||
var file = _temp.File("locked.bin", "x");
|
||||
await using var lockHandle = new FileStream(file, FileMode.Open, FileAccess.ReadWrite, FileShare.None);
|
||||
|
||||
var (exitCode, _, error) = await RunAsync("hash", file);
|
||||
|
||||
Assert.Equal(1, exitCode);
|
||||
Assert.Contains("locked.bin", error, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AnUnwritableOutput_IsReported()
|
||||
{
|
||||
var file = _temp.File("a.txt", "x");
|
||||
var blocker = _temp.File("not-a-folder", "x");
|
||||
|
||||
var (exitCode, _, error) = await RunAsync("hash", file, "-o", Path.Combine(blocker, "SHA256SUMS"));
|
||||
|
||||
Assert.Equal(1, exitCode);
|
||||
Assert.Contains("SHA256SUMS", error, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Verify_AFileWithoutChecksumLines_IsAUsageError()
|
||||
{
|
||||
var (exitCode, _, error) = await RunAsync("verify", _temp.File("notes.sha256", "just some notes\n"));
|
||||
|
||||
Assert.Equal(2, exitCode);
|
||||
Assert.Contains("no properly formatted checksum lines found", error, StringComparison.Ordinal);
|
||||
Assert.Contains("1 line is improperly formatted", error, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Check_AHashOfTheWrongLength_IsNotValidForTheAlgorithm()
|
||||
{
|
||||
var file = _temp.File("a.txt", "x");
|
||||
|
||||
var (exitCode, output, _) = await RunAsync("check", file, "-e", "abcd", "-a", "sha256");
|
||||
|
||||
Assert.Equal(1, exitCode);
|
||||
Assert.Contains("FAILED (not a valid hash for the algorithm)", output, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Verify_AFolderListedAsFile_CannotBeRead()
|
||||
{
|
||||
Directory.CreateDirectory(Path.Combine(_temp.Path, "folder"));
|
||||
var sums = _temp.File("SUMS", $"{new string('0', 64)} folder\n");
|
||||
|
||||
var (exitCode, output, error) = await RunAsync("verify", sums);
|
||||
|
||||
Assert.Equal(1, exitCode);
|
||||
Assert.Contains("folder: FAILED open or read", output, StringComparison.Ordinal);
|
||||
Assert.Contains("could not be read", error, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ErrorsAreDescribedLikeCoreutils()
|
||||
{
|
||||
Assert.Equal("No such file or directory", HashToolCommand.Describe(new FileNotFoundException()));
|
||||
Assert.Equal("Permission denied", HashToolCommand.Describe(new UnauthorizedAccessException()));
|
||||
Assert.Equal("disk full", HashToolCommand.Describe(new IOException("disk full")));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,218 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using HashTool.Core.Checksums;
|
||||
using HashTool.Core.Configuration;
|
||||
using HashTool.Core.Files;
|
||||
using HashTool.Core.Hashing;
|
||||
using Xunit;
|
||||
|
||||
namespace HashTool.Core.Tests;
|
||||
|
||||
public sealed class HashAlgorithmNameTests
|
||||
{
|
||||
public static TheoryData<HashType> All => new(HashAlgorithms.All);
|
||||
|
||||
[Theory]
|
||||
[MemberData(nameof(All))]
|
||||
public void EveryAlgorithm_HasAnExtensionATagAndASize(HashType type)
|
||||
{
|
||||
Assert.True(HashAlgorithms.IsDefined(type));
|
||||
Assert.True(HashAlgorithms.TryParse(HashAlgorithms.FileExtension(type), out var fromExtension));
|
||||
Assert.Equal(type, fromExtension);
|
||||
Assert.True(HashAlgorithms.TryParse(HashAlgorithms.BsdTag(type), out var fromTag));
|
||||
Assert.Equal(type, fromTag);
|
||||
Assert.Equal(HashAlgorithms.SizeInBytes(type) * 2, HashAlgorithms.HexLength(type));
|
||||
Assert.Equal(type is HashType.MD5 or HashType.SHA1, type.IsInsecure());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void UnknownAlgorithms_AreRejected()
|
||||
{
|
||||
var unknown = (HashType)99;
|
||||
|
||||
Assert.False(HashAlgorithms.IsDefined(unknown));
|
||||
Assert.Throws<ArgumentOutOfRangeException>(() => HashAlgorithms.SizeInBytes(unknown));
|
||||
Assert.Throws<ArgumentOutOfRangeException>(() => HashAlgorithms.FileExtension(unknown));
|
||||
Assert.Throws<ArgumentOutOfRangeException>(() => HashAlgorithms.BsdTag(unknown));
|
||||
Assert.Throws<ArgumentOutOfRangeException>(() => HashFunction.Create(unknown, 0));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(".sha256", HashType.SHA256)]
|
||||
[InlineData(" SHA-512 ", HashType.SHA512)]
|
||||
[InlineData("b3", HashType.BLAKE3)]
|
||||
[InlineData("XxHash3", HashType.XxHash3)]
|
||||
[InlineData("crc32", HashType.CRC32)]
|
||||
public void Names_AreParsedLeniently(string name, HashType expected)
|
||||
{
|
||||
Assert.True(HashAlgorithms.TryParse(name, out var type));
|
||||
Assert.Equal(expected, type);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(null)]
|
||||
[InlineData(" ")]
|
||||
[InlineData("sha3")]
|
||||
[InlineData("2")]
|
||||
public void UnknownNames_AreNotParsed(string? name)
|
||||
{
|
||||
Assert.False(HashAlgorithms.TryParse(name, out _));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Results_PrintInUpperCaseByDefault()
|
||||
{
|
||||
var result = (await new HashEngine().ComputeStreamAsync(new MemoryStream("123456789"u8.ToArray()), [HashType.CRC32],
|
||||
cancellationToken: TestContext.Current.CancellationToken)).Single();
|
||||
|
||||
Assert.Equal("CBF43926", result.ToString());
|
||||
Assert.Equal("cbf43926", result.ToHex(HexCase.Lower));
|
||||
Assert.Same(HashEngineOptions.Default, new HashEngine().Options);
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class FileErrorTests
|
||||
{
|
||||
[Fact]
|
||||
public void Errors_AreClassifiedIndependentlyOfTheirMessages()
|
||||
{
|
||||
Assert.Equal(FileErrorKind.None, FileErrors.Classify(null));
|
||||
Assert.Equal(FileErrorKind.NotFound, FileErrors.Classify(new FileNotFoundException()));
|
||||
Assert.Equal(FileErrorKind.NotFound, FileErrors.Classify(new DirectoryNotFoundException()));
|
||||
Assert.Equal(FileErrorKind.AccessDenied, FileErrors.Classify(new UnauthorizedAccessException()));
|
||||
Assert.Equal(FileErrorKind.Io, FileErrors.Classify(new IOException("disk")));
|
||||
Assert.Equal(FileErrorKind.Unknown, FileErrors.Classify(new InvalidOperationException()));
|
||||
// ERROR_SHARING_VIOLATION is a Windows notion; elsewhere it is an ordinary I/O error.
|
||||
var sharing = new IOException("in use", unchecked((int)0x80070020));
|
||||
Assert.Equal(OperatingSystem.IsWindows() ? FileErrorKind.InUse : FileErrorKind.Io, FileErrors.Classify(sharing));
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class SettingLimitTests
|
||||
{
|
||||
[Theory]
|
||||
[InlineData(FileSizeUnit.Byte, 1L)]
|
||||
[InlineData(FileSizeUnit.KB, ByteSize.OneKB)]
|
||||
[InlineData(FileSizeUnit.MB, ByteSize.OneMB)]
|
||||
[InlineData(FileSizeUnit.GB, ByteSize.OneGB)]
|
||||
[InlineData(FileSizeUnit.TB, ByteSize.OneTB)]
|
||||
[InlineData(FileSizeUnit.PB, ByteSize.OnePB)]
|
||||
public void SizeLimit_IsTheValueTimesTheUnit(FileSizeUnit unit, long multiplier)
|
||||
{
|
||||
var settings = new AppSettings { IsFileSizeLimitEnabled = true, FileSizeLimitValue = 3, FileSizeLimitUnit = unit };
|
||||
|
||||
Assert.Equal(3 * multiplier, settings.MaxFileSizeBytes());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SizeLimit_OffOrHuge_IsUnlimited()
|
||||
{
|
||||
Assert.Equal(long.MaxValue, new AppSettings { IsFileSizeLimitEnabled = false }.MaxFileSizeBytes());
|
||||
Assert.Equal(long.MaxValue,
|
||||
new AppSettings { IsFileSizeLimitEnabled = true, FileSizeLimitValue = 1_000_000, FileSizeLimitUnit = FileSizeUnit.PB }.MaxFileSizeBytes());
|
||||
Assert.EndsWith("settings", SettingsStore.DefaultSettingsDirectory, StringComparison.Ordinal);
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class ChecksumEdgeTests
|
||||
{
|
||||
[Theory]
|
||||
[InlineData(ExportFormat.Sfv, null, "sfv")]
|
||||
[InlineData(ExportFormat.Json, null, "json")]
|
||||
[InlineData(ExportFormat.Csv, null, "csv")]
|
||||
[InlineData(ExportFormat.Gnu, HashType.MD5, "md5")]
|
||||
[InlineData(ExportFormat.Bsd, null, "txt")]
|
||||
public void SuggestedExtensions(ExportFormat format, HashType? single, string expected)
|
||||
{
|
||||
Assert.Equal(expected, ChecksumWriter.SuggestedExtension(format, single));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Writing_RejectsWhatTheFormatCannotHold()
|
||||
{
|
||||
ChecksumLine[] lines = [new("a.txt", HashType.SHA256, "00")];
|
||||
|
||||
Assert.Throws<ArgumentException>(() => ChecksumWriter.Write(lines, ExportFormat.Sfv));
|
||||
Assert.Throws<ArgumentOutOfRangeException>(() => ChecksumWriter.Write(lines, (ExportFormat)42));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GnuNamesWithBackslashesOrLineBreaks_AreEscapedAndReadBack()
|
||||
{
|
||||
var name = "dir\\odd\nname\r.txt";
|
||||
var text = ChecksumWriter.Write([new ChecksumLine(name, HashType.MD5, "5D41402ABC4B2A76B9719D911017C592")], ExportFormat.Gnu);
|
||||
|
||||
Assert.Equal("\\5d41402abc4b2a76b9719d911017c592 dir\\\\odd\\nname\\r.txt\n", text);
|
||||
Assert.Equal(name, Assert.Single(ChecksumParser.Parse(text).Entries).FileName);
|
||||
Assert.Equal("bxname", Assert.Single(ChecksumParser.Parse("\\5d41402abc4b2a76b9719d911017c592 b\\xname").Entries).FileName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void OverlongLines_AreInvalid()
|
||||
{
|
||||
var document = ChecksumParser.Parse($"{new string('a', 64)} {new string('n', 40_000)}\n");
|
||||
|
||||
Assert.Empty(document.Entries);
|
||||
Assert.Equal([1], document.InvalidLines);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(@"\\server\share\file.iso")]
|
||||
[InlineData("//server/share/file.iso")]
|
||||
[InlineData("C:/data/file\0.iso")]
|
||||
public void UnsafePaths_AreRejected(string path)
|
||||
{
|
||||
Assert.False(ChecksumEntry.IsSafePath(path));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DevicePaths_AreRejectedOutsideWindows()
|
||||
{
|
||||
Assert.Equal(OperatingSystem.IsWindows(), ChecksumEntry.IsSafePath("/dev/sda"));
|
||||
Assert.Equal(OperatingSystem.IsWindows(), ChecksumEntry.IsSafePath("/proc/self/environ"));
|
||||
Assert.Null(new ChecksumEntry("00", "bad\0name", HashType.MD5, false, 1).ResolvePath(Path.GetTempPath()));
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class FileEnumeratorEdgeTests
|
||||
{
|
||||
[Fact]
|
||||
public void Expand_ReportsMissingAndInvalidPaths_AndSkipsBlanks()
|
||||
{
|
||||
using var temp = new TempDirectory();
|
||||
var file = temp.File("a.txt", "x");
|
||||
var errors = new List<string>();
|
||||
|
||||
var found = FileEnumerator.Expand([file, " ", Path.Combine(temp.Path, "missing.txt"), "bad\0path"], null,
|
||||
(path, _) => errors.Add(path), TestContext.Current.CancellationToken).ToList();
|
||||
|
||||
Assert.Equal(file, Assert.Single(found).FullPath);
|
||||
Assert.Equal(2, errors.Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EnumeratingAMissingFolder_ReportsIt()
|
||||
{
|
||||
var errors = new List<string>();
|
||||
var missing = Path.Combine(Path.GetTempPath(), $"hashtool-missing-{Guid.NewGuid():N}");
|
||||
|
||||
Assert.Empty(FileEnumerator.EnumerateDirectory(missing, null, (path, _) => errors.Add(path), TestContext.Current.CancellationToken));
|
||||
Assert.Equal([missing], errors);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Expand_StopsWhenCancelled()
|
||||
{
|
||||
using var temp = new TempDirectory();
|
||||
temp.File("a.txt", "x");
|
||||
using var cancelled = new CancellationTokenSource();
|
||||
cancelled.Cancel();
|
||||
|
||||
Assert.Throws<OperationCanceledException>(() => FileEnumerator.Expand([temp.Path], null, null, cancelled.Token).ToList());
|
||||
Assert.Throws<OperationCanceledException>(() => FileEnumerator.EnumerateDirectory(temp.Path, null, null, cancelled.Token).ToList());
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user