diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json new file mode 100644 index 000000000..4505872b7 --- /dev/null +++ b/.devcontainer/devcontainer.json @@ -0,0 +1,8 @@ +{ + "name": "C# (.NET Core)", + "image": "mcr.microsoft.com/vscode/devcontainers/dotnet:10.0", + "settings": { + "terminal.integrated.shell.linux": "/bin/bash" + }, + "postCreateCommand": "dotnet restore" +} \ No newline at end of file diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 000000000..64fe33bba --- /dev/null +++ b/.editorconfig @@ -0,0 +1,11 @@ +; This file is for unifying the coding style for different editors and IDEs. +; More information at http://EditorConfig.org + +root = true + +[*] +end_of_line = CRLF + +[*.cs] +indent_style = space +indent_size = 4 diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md new file mode 100644 index 000000000..3f67edd4a --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -0,0 +1,24 @@ +--- +name: Bug report +about: Create a report to help us improve +title: '' +labels: 'state: needs discussion, type: bug' +assignees: '' + +--- + +**Describe the bug** +A clear and concise description of what the bug is. + +**To Reproduce** +Steps to reproduce the behavior: +1. Go to '...' +2. Click on '....' +3. Scroll down to '....' +4. See error + +**Expected behavior** +A clear and concise description of what you expected to happen. + +**Additional context** +Add any other context about the problem here. diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md new file mode 100644 index 000000000..a5f90597a --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.md @@ -0,0 +1,20 @@ +--- +name: Feature request +about: Suggest an idea for this project +title: '' +labels: 'state: needs discussion, type: enhancement' +assignees: '' + +--- + +**Is your feature request related to a problem? Please describe.** +A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] + +**Describe the solution you'd like** +A clear and concise description of what you want to happen. + +**Describe alternatives you've considered** +A clear and concise description of any alternative solutions or features you've considered. + +**Additional context** +Add any other context or screenshots about the feature request here. diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md new file mode 100644 index 000000000..6d1647723 --- /dev/null +++ b/.github/copilot-instructions.md @@ -0,0 +1,147 @@ +# System.IO.Abstractions Development Guide + +System.IO.Abstractions is a .NET library that provides testable abstractions for System.IO operations, enabling developers to write unit tests that don't rely on the actual file system. + +**ALWAYS reference these instructions first and fallback to search or bash commands only when you encounter unexpected information that does not match the info here.** + +## Working Effectively + +### Bootstrap and Build Process +- **CRITICAL**: Install .NET SDK 9.0.304 (required version specified in global.json): + ```bash + curl -sSL https://dot.net/v1/dotnet-install.sh | bash /dev/stdin --version 9.0.304 + export PATH="$HOME/.dotnet:$PATH" + ``` +- Verify installation: `dotnet --version` should return `9.0.304` +- **Build the solution**: `dotnet build` -- takes ~70 seconds. NEVER CANCEL. Set timeout to 120+ minutes. +- **Run all tests**: `dotnet test --configuration Release` -- takes ~30 seconds. NEVER CANCEL. Set timeout to 60+ minutes. + +### Code Quality and Formatting +- **ALWAYS run code formatting before committing**: `dotnet format` +- **Verify formatting compliance**: `dotnet format --verify-no-changes` -- takes ~40 seconds. NEVER CANCEL. +- The codebase uses EditorConfig with CRLF line endings and 4-space indentation for C# files +- **CRITICAL**: All formatting issues must be resolved before CI will pass + +### Build System Details +- **Primary build method**: `dotnet build` and `dotnet test` commands work reliably +- **NUKE build script**: `./build.sh` available but may have GitVersion issues with shallow clones +- **Available NUKE targets**: UnitTests, ApiChecks, CodeCoverage, CodeAnalysis, Pack +- **Build artifacts**: Generated in `Artifacts/` and `TestResults/` directories + +## Project Structure + +### Key Projects +- **System.IO.Abstractions**: Core abstractions and interfaces +- **TestableIO.System.IO.Abstractions**: Main implementation +- **TestableIO.System.IO.Abstractions.Wrappers**: Wrapper implementations +- **TestableIO.System.IO.Abstractions.TestingHelpers**: Mock implementations for testing +- **Multiple test projects**: Comprehensive test coverage across different scenarios + +### Target Frameworks +- .NET Framework 4.7.2 (net472) +- .NET Standard 2.0, 2.1 (netstandard2.0, netstandard2.1) +- .NET 6.0, 8.0, 9.0 (net6.0, net8.0, net9.0) + +### Important Directories +- `src/`: All source code projects +- `tests/`: All test projects including unit tests, API tests, and parity tests +- `benchmarks/`: Performance benchmarking projects +- `Pipeline/`: NUKE build system configuration +- `.github/workflows/`: CI/CD pipeline definitions + +## Validation + +### Manual Validation Steps +After making changes, ALWAYS validate functionality by: + +1. **Build verification**: `dotnet build` must succeed +2. **Test execution**: `dotnet test --configuration Release` must pass +3. **Code formatting**: `dotnet format --verify-no-changes` must pass +4. **Functional validation**: Create a test scenario to verify your changes work: + +```csharp +using System.IO.Abstractions; +using System.IO.Abstractions.TestingHelpers; + +// Test MockFileSystem functionality +var mockFileSystem = new MockFileSystem(); +mockFileSystem.File.WriteAllText(@"C:\test.txt", "Test content"); +var content = mockFileSystem.File.ReadAllText(@"C:\test.txt"); + +// Test real FileSystem functionality +var realFileSystem = new FileSystem(); +var tempFile = "/tmp/test.txt"; +realFileSystem.File.WriteAllText(tempFile, "Real test"); +var realContent = realFileSystem.File.ReadAllText(tempFile); +realFileSystem.File.Delete(tempFile); +``` + +### Test Suite Information +- **Total tests**: ~2,234 tests across all projects +- **Expected passing**: ~1,993 tests (some platform-specific tests are skipped on Linux) +- **Test categories**: Unit tests, API compatibility tests, parity tests +- **Platform considerations**: Some Windows-specific functionality is skipped on Linux/macOS + +### Continuous Integration Requirements +The CI pipeline (.github/workflows/ci.yml) requires: +- All unit tests to pass on Ubuntu, Windows, and macOS +- API compatibility checks to succeed +- Code formatting compliance +- Static code analysis (SonarCloud) to pass + +## Common Development Tasks + +### Adding New Functionality +- Implement abstractions in the main System.IO.Abstractions project +- Add wrapper implementations in TestableIO.System.IO.Abstractions.Wrappers +- Create mock implementations in TestableIO.System.IO.Abstractions.TestingHelpers +- Add comprehensive tests covering all target frameworks +- Update XML documentation for all public APIs + +### Debugging Build Issues +- Check .NET SDK version compatibility first +- Verify all package references are properly restored +- For NUKE build issues, use direct `dotnet` commands instead +- Review build logs in Artifacts/ directory for detailed error information + +### Package Management +- Uses Central Package Management (Directory.Packages.props) +- NuGet source: nuget.org only (configured in nuget.config) +- Package versioning uses Nerdbank.GitVersioning + +## Pull Request Guidelines + +### Pull Request Title +To communicate intent to the consumers of your library, the title of the pull requests is prefixed with one of the following elements: +- `fix:`: patches a bug +- `feat:`: introduces a new feature +- `refactor:`: improves internal structure without changing the observable behavior +- `docs:`: updates documentation or XML comments +- `chore:`: updates to dependencies, build pipelines, ... + +## Performance Expectations + +### Command Timing (with appropriate timeouts) +- **dotnet build**: ~70 seconds (set timeout: 120+ minutes) +- **dotnet test**: ~30 seconds (set timeout: 60+ minutes) +- **dotnet format**: ~40 seconds (set timeout: 10+ minutes) +- **NUKE build restore**: ~30 seconds (set timeout: 10+ minutes) + +### **NEVER CANCEL** long-running operations +Builds and tests may occasionally take longer than expected. Always wait for completion rather than canceling operations. + +## Troubleshooting + +### Common Issues +- **GitVersion errors**: Use direct `dotnet` commands instead of NUKE build script +- **Shallow clone issues**: Expected in GitHub Actions environment, doesn't affect functionality +- **Platform-specific test failures**: Normal for Windows-specific functionality on Linux/macOS +- **Code formatting failures**: Run `dotnet format` to fix automatically + +### SDK Installation Issues +If .NET SDK 9.0.304 is not available: +- Check global.json for exact version requirement +- Use dotnet-install script with specific version +- Ensure PATH includes the installed SDK location + +**Remember**: This is a mature, well-tested library with extensive CI/CD. Focus on maintaining compatibility across all target frameworks and ensuring comprehensive test coverage for any changes. \ No newline at end of file diff --git a/.github/mergify.yml b/.github/mergify.yml new file mode 100644 index 000000000..edb6bc85d --- /dev/null +++ b/.github/mergify.yml @@ -0,0 +1,16 @@ +pull_request_rules: + - name: Automatic merge on approval + conditions: + - "#approved-reviews-by>=1" + actions: + merge: + method: squash + commit_message_template: |- + {{ title }} (#{{ number }}) + {{ body }} + - name: Automatic merge for Renovate pull requests + conditions: + - author=renovate[bot] + actions: + merge: + method: squash diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml new file mode 100644 index 000000000..7a56907ad --- /dev/null +++ b/.github/workflows/build.yml @@ -0,0 +1,213 @@ +name: Build + +on: + push: + branches: [ main ] + tags: [ 'v[0-9]+.[0-9]+.[0-9]+*' ] + +jobs: + unit-tests: + name: "Unit tests" + strategy: + matrix: + os: [ ubuntu-latest, windows-latest, macos-latest ] + runs-on: ${{ matrix.os }} + steps: + - uses: actions/checkout@v6 + with: + fetch-depth: 0 + - name: Setup .NET SDKs + uses: actions/setup-dotnet@v5 + with: + dotnet-version: | + 6.0.x + 7.0.x + 8.0.x + 9.0.x + 10.0.x + - name: Run unit tests (windows) + if: matrix.os == 'windows-latest' + run: ./build.ps1 CodeCoverage + - name: Run unit tests (ubuntu|macos) + if: matrix.os != 'windows-latest' + run: ./build.sh CodeCoverage + - name: Upload artifacts + if: always() + uses: actions/upload-artifact@v6 + with: + name: ${{ runner.os }}-artifacts + path: | + ./Artifacts/* + ./TestResults/*.trx + + api-tests: + name: "API tests" + runs-on: ubuntu-latest + env: + DOTNET_NOLOGO: true + steps: + - uses: actions/checkout@v6 + with: + fetch-depth: 0 + - name: Setup .NET SDKs + uses: actions/setup-dotnet@v5 + with: + dotnet-version: | + 6.0.x + 7.0.x + 8.0.x + 9.0.x + 10.0.x + - name: API checks + run: ./build.sh ApiChecks + - name: Upload artifacts + if: always() + uses: actions/upload-artifact@v6 + with: + name: API-tests + path: | + ./Artifacts/* + ./TestResults/*.trx + + static-code-analysis: + name: "Static code analysis" + runs-on: ubuntu-latest + env: + REPORTGENERATOR_LICENSE: ${{ secrets.REPORTGENERATOR_LICENSE }} + SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }} + DOTNET_NOLOGO: true + steps: + - uses: actions/checkout@v6 + with: + fetch-depth: 0 + - name: Setup .NET SDKs + uses: actions/setup-dotnet@v5 + with: + dotnet-version: | + 6.0.x + 7.0.x + 8.0.x + 9.0.x + 10.0.x + - name: Run sonarcloud analysis + run: ./build.sh CodeAnalysis + + publish-test-results: + name: "Publish Tests Results" + needs: [ api-tests, unit-tests ] + runs-on: ubuntu-latest + permissions: + checks: write + pull-requests: write + if: always() + steps: + - name: Download Artifacts + uses: actions/download-artifact@v7 + with: + path: artifacts + - name: Publish Test Results + uses: EnricoMi/publish-unit-test-result-action@v2 + with: + comment_mode: always + files: "artifacts/**/**/*.trx" + + pack: + name: "Pack" + runs-on: ubuntu-latest + needs: [ publish-test-results, static-code-analysis ] + env: + DOTNET_NOLOGO: true + steps: + - uses: actions/checkout@v6 + with: + fetch-depth: 0 + - name: Setup .NET SDKs + uses: actions/setup-dotnet@v5 + with: + dotnet-version: | + 6.0.x + 7.0.x + 8.0.x + 9.0.x + 10.0.x + - name: Pack nuget packages + run: ./build.sh Pack + - name: Upload packages + if: always() + uses: actions/upload-artifact@v6 + with: + path: Artifacts/Packages + name: Packages + + push: + name: "Push" + if: ${{ startsWith(github.ref, 'refs/tags/v') }} + runs-on: macos-latest + environment: production + needs: [ pack ] + permissions: + contents: write + steps: + - name: Download packages + uses: actions/download-artifact@v7 + with: + name: Packages + path: Artifacts/Packages + - name: Setup .NET SDKs + uses: actions/setup-dotnet@v5 + - name: Publish + run: | + echo "Found the following packages to push:" + search_dir=Artifacts/Packages + for entry in Artifacts/Packages/*.nupkg + do + echo "- $entry" + done + for entry in Artifacts/Packages/*.nupkg + do + dotnet nuget push $entry --source https://api.nuget.org/v3/index.json --api-key "${{secrets.NUGET_API_KEY}}" --skip-duplicate + done + - name: Check pre-release + id: check-pre-release + run: | + if [[ ${{ github.event.ref }} =~ ^refs/tags/v[0-9]+\.[0-9]+\.[0-9]+$ ]]; then + echo "release=true" >> $GITHUB_OUTPUT + fi + - name: Create GitHub release + if: steps.check-pre-release.outputs.release == 'true' + continue-on-error: true + uses: softprops/action-gh-release@v2 + with: + name: ${{ steps.tag.outputs.release_version }} + tag_name: ${{ steps.tag.outputs.release_version }} + token: ${{ secrets.GITHUB_TOKEN }} + generate_release_notes: true + + finalize-release: + name: "Finalize release" + if: startsWith(github.ref, 'refs/tags/v') + runs-on: ubuntu-latest + needs: [ push ] + permissions: + contents: read + issues: write + pull-requests: write + steps: + - name: Check pre-release + id: check-pre-release + run: | + if [[ ${{ github.event.ref }} =~ ^refs/tags/v[0-9]+\.[0-9]+\.[0-9]+$ ]]; then + echo "release=true" >> $GITHUB_OUTPUT + fi + - name: Comment relevant issues and pull requests + if: steps.check-pre-release.outputs.release == 'true' + continue-on-error: true + uses: apexskier/github-release-commenter@v1.4.1 + with: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + comment-template: | + This is addressed in release {release_link}. + label-template: | + state: released + skip-label: | + state: released diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 000000000..814ea78ab --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,113 @@ +name: CI + +on: + workflow_dispatch: + pull_request: + branches: [ main ] + +jobs: + unit-tests: + name: "Unit tests" + strategy: + matrix: + os: [ ubuntu-latest, windows-latest, macos-latest ] + runs-on: ${{ matrix.os }} + steps: + - uses: actions/checkout@v6 + with: + fetch-depth: 0 + - name: Setup .NET SDKs + uses: actions/setup-dotnet@v5 + with: + dotnet-version: | + 6.0.x + 7.0.x + 8.0.x + 9.0.x + 10.0.x + - name: Run unit tests (windows) + if: matrix.os == 'windows-latest' + run: ./build.ps1 CodeCoverage + - name: Run unit tests (ubuntu|macos) + if: matrix.os != 'windows-latest' + run: ./build.sh CodeCoverage + - name: Upload artifacts + if: always() + uses: actions/upload-artifact@v6 + with: + name: ${{ runner.os }}-artifacts + path: | + ./Artifacts/* + ./TestResults/*.trx + + api-tests: + name: "API tests" + runs-on: ubuntu-latest + env: + DOTNET_NOLOGO: true + steps: + - uses: actions/checkout@v6 + with: + fetch-depth: 0 + - name: Setup .NET SDKs + uses: actions/setup-dotnet@v5 + with: + dotnet-version: | + 6.0.x + 7.0.x + 8.0.x + 9.0.x + 10.0.x + - name: API checks + run: ./build.sh ApiChecks + - name: Upload artifacts + if: always() + uses: actions/upload-artifact@v6 + with: + name: API-tests + path: | + ./Artifacts/* + ./TestResults/*.trx + + static-code-analysis: + name: "Static code analysis" + if: ${{ github.actor != 'dependabot[bot]' && github.event.pull_request.head.repo.full_name == github.event.pull_request.base.repo.full_name }} + runs-on: ubuntu-latest + env: + REPORTGENERATOR_LICENSE: ${{ secrets.REPORTGENERATOR_LICENSE }} + SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }} + DOTNET_NOLOGO: true + steps: + - uses: actions/checkout@v6 + with: + fetch-depth: 0 + - name: Setup .NET SDKs + uses: actions/setup-dotnet@v5 + with: + dotnet-version: | + 6.0.x + 7.0.x + 8.0.x + 9.0.x + 10.0.x + - name: Run sonarcloud analysis + run: ./build.sh CodeAnalysis + + publish-test-results: + name: "Publish Tests Results" + needs: [ api-tests, unit-tests ] + runs-on: ubuntu-latest + permissions: + checks: write + pull-requests: write + if: always() + steps: + - name: Download Artifacts + uses: actions/download-artifact@v7 + with: + path: artifacts + - name: Publish Test Results + uses: EnricoMi/publish-unit-test-result-action@v2 + with: + comment_mode: always + files: "artifacts/**/**/*.trx" diff --git a/.gitignore b/.gitignore index 5715feb65..2a6761c23 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,7 @@ +# Artifact and test results directories +/Artifacts +/TestResults + ## Ignore Visual Studio temporary files, build results, and ## files generated by popular Visual Studio add-ons. @@ -6,6 +10,7 @@ *.user *.sln.docstates *.ide/ +.vs/ # Build results @@ -44,6 +49,9 @@ build/ *.log *.scc +# Benchmarks results +BenchmarkDotNet.Artifacts + # Visual C++ cache files ipch/ *.aps @@ -151,3 +159,27 @@ $RECYCLE.BIN/ #System.IO.Abstractions specific ignores Releases System.IO.Abstractions.*.nupkg + +# Common IntelliJ Platform excludes +# https://github.com/JetBrains/resharper-rider-samples/blob/master/.gitignore + +# User specific +**/.idea/**/workspace.xml +**/.idea/**/tasks.xml +**/.idea/shelf/* +**/.idea/dictionaries +**/.idea/httpRequests/ + +# Sensitive or high-churn files +**/.idea/**/dataSources/ +**/.idea/**/dataSources.ids +**/.idea/**/dataSources.xml +**/.idea/**/dataSources.local.xml +**/.idea/**/sqlDataSources.xml +**/.idea/**/dynamic.xml + +# Rider +# Rider auto-generates .iml files, and contentModel.xml +**/.idea/**/*.iml +**/.idea/**/contentModel.xml +**/.idea/**/modules.xml \ No newline at end of file diff --git a/.idea/.idea.System.IO.Abstractions/.idea/.gitignore b/.idea/.idea.System.IO.Abstractions/.idea/.gitignore new file mode 100644 index 000000000..9b9147a9b --- /dev/null +++ b/.idea/.idea.System.IO.Abstractions/.idea/.gitignore @@ -0,0 +1,13 @@ +# Default ignored files +/shelf/ +/workspace.xml +# Rider ignored files +/contentModel.xml +/projectSettingsUpdater.xml +/.idea.System.IO.Abstractions.iml +/modules.xml +# Editor-based HTTP Client requests +/httpRequests/ +# Datasource local storage ignored files +/dataSources/ +/dataSources.local.xml diff --git a/.idea/.idea.System.IO.Abstractions/.idea/encodings.xml b/.idea/.idea.System.IO.Abstractions/.idea/encodings.xml new file mode 100644 index 000000000..df87cf951 --- /dev/null +++ b/.idea/.idea.System.IO.Abstractions/.idea/encodings.xml @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/.idea/.idea.System.IO.Abstractions/.idea/indexLayout.xml b/.idea/.idea.System.IO.Abstractions/.idea/indexLayout.xml new file mode 100644 index 000000000..7b08163ce --- /dev/null +++ b/.idea/.idea.System.IO.Abstractions/.idea/indexLayout.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/.idea/.idea.System.IO.Abstractions/.idea/vcs.xml b/.idea/.idea.System.IO.Abstractions/.idea/vcs.xml new file mode 100644 index 000000000..94a25f7f4 --- /dev/null +++ b/.idea/.idea.System.IO.Abstractions/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/.nuke/build.schema.json b/.nuke/build.schema.json new file mode 100644 index 000000000..47d67fd11 --- /dev/null +++ b/.nuke/build.schema.json @@ -0,0 +1,141 @@ +{ + "$schema": "http://json-schema.org/draft-04/schema#", + "definitions": { + "Host": { + "type": "string", + "enum": [ + "AppVeyor", + "AzurePipelines", + "Bamboo", + "Bitbucket", + "Bitrise", + "GitHubActions", + "GitLab", + "Jenkins", + "Rider", + "SpaceAutomation", + "TeamCity", + "Terminal", + "TravisCI", + "VisualStudio", + "VSCode" + ] + }, + "ExecutableTarget": { + "type": "string", + "enum": [ + "ApiChecks", + "CalculateNugetVersion", + "Clean", + "CodeAnalysis", + "CodeAnalysisBegin", + "CodeAnalysisEnd", + "CodeCoverage", + "Compile", + "DotNetFrameworkUnitTests", + "DotNetUnitTests", + "Pack", + "Restore", + "UnitTests", + "UpdateReadme" + ] + }, + "Verbosity": { + "type": "string", + "description": "", + "enum": [ + "Verbose", + "Normal", + "Minimal", + "Quiet" + ] + }, + "NukeBuild": { + "properties": { + "Continue": { + "type": "boolean", + "description": "Indicates to continue a previously failed build attempt" + }, + "Help": { + "type": "boolean", + "description": "Shows the help text for this build assembly" + }, + "Host": { + "description": "Host for execution. Default is 'automatic'", + "$ref": "#/definitions/Host" + }, + "NoLogo": { + "type": "boolean", + "description": "Disables displaying the NUKE logo" + }, + "Partition": { + "type": "string", + "description": "Partition to use on CI" + }, + "Plan": { + "type": "boolean", + "description": "Shows the execution plan (HTML)" + }, + "Profile": { + "type": "array", + "description": "Defines the profiles to load", + "items": { + "type": "string" + } + }, + "Root": { + "type": "string", + "description": "Root directory during build execution" + }, + "Skip": { + "type": "array", + "description": "List of targets to be skipped. Empty list skips all dependencies", + "items": { + "$ref": "#/definitions/ExecutableTarget" + } + }, + "Target": { + "type": "array", + "description": "List of targets to be invoked. Default is '{default_target}'", + "items": { + "$ref": "#/definitions/ExecutableTarget" + } + }, + "Verbosity": { + "description": "Logging verbosity during build execution. Default is 'Normal'", + "$ref": "#/definitions/Verbosity" + } + } + } + }, + "allOf": [ + { + "properties": { + "Configuration": { + "type": "string", + "description": "Configuration to build - Default is 'Debug' (local) or 'Release' (server)", + "enum": [ + "Debug", + "Release" + ] + }, + "GithubToken": { + "type": "string", + "description": "Github Token" + }, + "Solution": { + "type": "string", + "description": "Path to a solution file that is automatically loaded" + }, + "SonarToken": { + "type": "string", + "description": "The key to push to sonarcloud", + "default": "Secrets must be entered via 'nuke :secrets [profile]'" + } + } + }, + { + "$ref": "#/definitions/NukeBuild" + } + ] +} diff --git a/.nuke/parameters.json b/.nuke/parameters.json new file mode 100644 index 000000000..80b1853fd --- /dev/null +++ b/.nuke/parameters.json @@ -0,0 +1,4 @@ +{ + "$schema": "build.schema.json", + "Solution": "System.IO.Abstractions.slnx" +} diff --git a/.remarkrc.yaml b/.remarkrc.yaml new file mode 100644 index 000000000..8b3ed1a09 --- /dev/null +++ b/.remarkrc.yaml @@ -0,0 +1,3 @@ +plugins: + - remark-preset-lint-consistent + - remark-preset-lint-markdown-style-guide \ No newline at end of file diff --git a/.vscode/extensions.json b/.vscode/extensions.json new file mode 100644 index 000000000..e958ab141 --- /dev/null +++ b/.vscode/extensions.json @@ -0,0 +1,6 @@ +{ + "recommendations": [ + "ms-vscode-remote.remote-containers", + "ms-dotnettools.csharp" + ] +} \ No newline at end of file diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 000000000..80cb5799b --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,76 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +In the interest of fostering an open and welcoming environment, we as +contributors and maintainers pledge to making participation in our project and +our community a harassment-free experience for everyone, regardless of age, body +size, disability, ethnicity, sex characteristics, gender identity and expression, +level of experience, education, socio-economic status, nationality, personal +appearance, race, religion, or sexual identity and orientation. + +## Our Standards + +Examples of behavior that contributes to creating a positive environment +include: + +* Using welcoming and inclusive language +* Being respectful of differing viewpoints and experiences +* Gracefully accepting constructive criticism +* Focusing on what is best for the community +* Showing empathy towards other community members + +Examples of unacceptable behavior by participants include: + +* The use of sexualized language or imagery and unwelcome sexual attention or + advances +* Trolling, insulting/derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or electronic + address, without explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Our Responsibilities + +Project maintainers are responsible for clarifying the standards of acceptable +behavior and are expected to take appropriate and fair corrective action in +response to any instances of unacceptable behavior. + +Project maintainers have the right and responsibility to remove, edit, or +reject comments, commits, code, wiki edits, issues, and other contributions +that are not aligned to this Code of Conduct, or to ban temporarily or +permanently any contributor for other behaviors that they deem inappropriate, +threatening, offensive, or harmful. + +## Scope + +This Code of Conduct applies both within project spaces and in public spaces +when an individual is representing the project or its community. Examples of +representing a project or community include using an official project e-mail +address, posting via an official social media account, or acting as an appointed +representative at an online or offline event. Representation of a project may be +further defined and clarified by project maintainers. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported by contacting the project team at code-of-conduct@testably.org. All +complaints will be reviewed and investigated and will result in a response that +is deemed necessary and appropriate to the circumstances. The project team is +obligated to maintain confidentiality with regard to the reporter of an incident. +Further details of specific enforcement policies may be posted separately. + +Project maintainers who do not follow or enforce the Code of Conduct in good +faith may face temporary or permanent repercussions as determined by other +members of the project's leadership. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, +available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html + +[homepage]: https://www.contributor-covenant.org + +For answers to common questions about this code of conduct, see +https://www.contributor-covenant.org/faq diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 000000000..e1a7488f6 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,31 @@ +# Contributor guide + +## Versioning + +This library uses [Nerdbank.GitVersioning](https://github.com/AArnott/Nerdbank.GitVersioning) for generating stable and reproducible version numbers. + +The base version is manually maintained in [the version config](version.json). Every build calculates its final version number based on the base version and the number of changes that occured since the last change to the version config. + +The base version represents the MAJOR and MINOR parts of [SemVer](https://semver.org). If a PR contains breaking changes or new features the base version has to be changed accordingly. If a PR solely contains minor changes (bug fixes, code improvements) nothing needs to be done as the PATCH number will automatically increment with each commit. + +## Branches / tags + +- `main` contains the latest sources. Each merge there triggers a deploy to `nuget.org`. +- All versions on `nuget.org` have a matching GitHub release/tag. + +## Commits and PR title + +- Please use [conventional commits](https://www.conventionalcommits.org/en/v1.0.0/) to name your commits and PR title. + We use [action-semantic-pull-request](https://github.com/amannn/action-semantic-pull-request?tab=readme-ov-file#configuration) to enforce this policy, feel free to have a closer look. +- Available prefixes: + - `feat:` A new feature + - `fix:` A bug fix + - `docs:` Documentation only changes + - `style:` Changes that do not affect the meaning of the code (white-space, formatting, missing semi-colons, etc) + - `refactor:` A code change that neither fixes a bug nor adds a feature + - `perf:` A code change that improves performance + - `test:` Adding missing tests or correcting existing tests + - `build:` Changes that affect the build system or external dependencies (example scopes: gulp, broccoli, npm) + - `ci:` Changes to our CI configuration files and scripts (example scopes: Travis, Circle, BrowserStack, SauceLabs) + - `chore:` Other changes that don't modify src or test files + - `revert:` Reverts a previous commit diff --git a/Directory.Build.props b/Directory.Build.props new file mode 100644 index 000000000..a2f0f6f0b --- /dev/null +++ b/Directory.Build.props @@ -0,0 +1,32 @@ + + + System.IO.Abstractions + Copyright © Tatham Oddie & friends 2010-$([System.DateTime]::Now.ToString('yyyy')) + Tatham Oddie & friends + True + 00240000048000009400000006020000002400005253413100040000010001001160c7a0f907c400c5392975b66d2f3752fb82625d5674d386b83896d4d4ae8d0ef8319ef391fbb3466de0058ad2f361b8f5cb8a32ecb4e908bece5c519387552cedd2ca0250e36b59c6d6dc3dc260ca73a7e27c3add4ae22d5abaa562225d7ba34d427e8f3f52928a46a674deb0208eca7d379aa22712355b91a55a5ce521d2 + $(MSBuildThisFileDirectory)StrongName.snk + latest + testing + CS1591 + https://github.com/TestableIO/System.IO.Abstractions + MIT + README.md + $(DefineConstants);FEATURE_FILE_SYSTEM_ACL_EXTENSIONS + $(DefineConstants);FEATURE_ASYNC_FILE;FEATURE_ENUMERATION_OPTIONS;FEATURE_ADVANCED_PATH_OPERATIONS;FEATURE_PATH_JOIN_WITH_SPAN;FEATURE_SPAN + $(DefineConstants);FEATURE_FILE_MOVE_WITH_OVERWRITE;FEATURE_SUPPORTED_OS_ATTRIBUTE;FEATURE_FILE_SYSTEM_WATCHER_FILTERS;FEATURE_ENDS_IN_DIRECTORY_SEPARATOR;FEATURE_PATH_JOIN_WITH_PARAMS;FEATURE_PATH_JOIN_WITH_FOUR_PATHS;FEATURE_FILE_SYSTEM_INFO_LINK_TARGET;FEATURE_CREATE_SYMBOLIC_LINK;FEATURE_FILESTREAM_OPTIONS + $(DefineConstants);FEATURE_PATH_EXISTS;FEATURE_FILE_SYSTEM_WATCHER_WAIT_WITH_TIMESPAN;FEATURE_FILE_ATTRIBUTES_VIA_HANDLE;FEATURE_CREATE_TEMP_SUBDIRECTORY;FEATURE_READ_LINES_ASYNC;FEATURE_UNIX_FILE_MODE + $(DefineConstants);FEATURE_PATH_SPAN;FEATURE_FILE_SPAN + $(DefineConstants);FEATURE_SERIALIZABLE + + + true + true + true + snupkg + false + + + + + diff --git a/Directory.Packages.props b/Directory.Packages.props new file mode 100644 index 000000000..c42994a1c --- /dev/null +++ b/Directory.Packages.props @@ -0,0 +1,39 @@ + + + true + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/LICENSE b/LICENSE new file mode 100644 index 000000000..64c7af08b --- /dev/null +++ b/LICENSE @@ -0,0 +1,23 @@ +The MIT License (MIT) + +Copyright (c) Tatham Oddie and Contributors + +All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/License.txt b/License.txt deleted file mode 100644 index da3dc935e..000000000 --- a/License.txt +++ /dev/null @@ -1,31 +0,0 @@ -Microsoft Public License (Ms-PL) - -This license governs use of the accompanying software. If you use the software, you accept this license. If you do not accept the license, do not use the software. - -1. Definitions - -The terms "reproduce," "reproduction," "derivative works," and "distribution" have the same meaning here as under U.S. copyright law. - -A "contribution" is the original software, or any additions or changes to the software. - -A "contributor" is any person that distributes its contribution under this license. - -"Licensed patents" are a contributor's patent claims that read directly on its contribution. - -2. Grant of Rights - -(A) Copyright Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free copyright license to reproduce its contribution, prepare derivative works of its contribution, and distribute its contribution or any derivative works that you create. - -(B) Patent Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free license under its licensed patents to make, have made, use, sell, offer for sale, import, and/or otherwise dispose of its contribution in the software or derivative works of the contribution in the software. - -3. Conditions and Limitations - -(A) No Trademark License- This license does not grant you rights to use any contributors' name, logo, or trademarks. - -(B) If you bring a patent claim against any contributor over patents that you claim are infringed by the software, your patent license from such contributor to the software ends automatically. - -(C) If you distribute any portion of the software, you must retain all copyright, patent, trademark, and attribution notices that are present in the software. - -(D) If you distribute any portion of the software in source code form, you may do so only under this license by including a complete copy of this license with your distribution. If you distribute any portion of the software in compiled or object code form, you may only do so under a license that complies with this license. - -(E) The software is licensed "as-is." You bear the risk of using it. The contributors give no express warranties, guarantees or conditions. You may have additional consumer rights under your local laws which this license cannot change. To the extent permitted under your local laws, the contributors exclude the implied warranties of merchantability, fitness for a particular purpose and non-infringement. \ No newline at end of file diff --git a/Pipeline/.editorconfig b/Pipeline/.editorconfig new file mode 100644 index 000000000..31e43dcd8 --- /dev/null +++ b/Pipeline/.editorconfig @@ -0,0 +1,11 @@ +[*.cs] +dotnet_style_qualification_for_field = false:warning +dotnet_style_qualification_for_property = false:warning +dotnet_style_qualification_for_method = false:warning +dotnet_style_qualification_for_event = false:warning +dotnet_style_require_accessibility_modifiers = never:warning + +csharp_style_expression_bodied_methods = true:silent +csharp_style_expression_bodied_properties = true:warning +csharp_style_expression_bodied_indexers = true:warning +csharp_style_expression_bodied_accessors = true:warning diff --git a/Pipeline/Build.ApiChecks.cs b/Pipeline/Build.ApiChecks.cs new file mode 100644 index 000000000..f99768d39 --- /dev/null +++ b/Pipeline/Build.ApiChecks.cs @@ -0,0 +1,28 @@ +using Nuke.Common; +using Nuke.Common.ProjectModel; +using Nuke.Common.Tooling; +using Nuke.Common.Tools.DotNet; +using static Nuke.Common.Tools.DotNet.DotNetTasks; + +// ReSharper disable AllUnderscoreLocalParameterName + +namespace Build; + +partial class Build +{ + Target ApiChecks => _ => _ + .DependsOn(Compile) + .Executes(() => + { + Project project = Solution.Tests.TestableIO_System_IO_Abstractions_Api_Tests; + + DotNetTest(s => s + .SetConfiguration(Configuration == Configuration.Debug ? "Debug" : "Release") + .SetProcessEnvironmentVariable("DOTNET_CLI_UI_LANGUAGE", "en-US") + .EnableNoBuild() + .SetResultsDirectory(TestResultsDirectory) + .CombineWith(cc => cc + .SetProjectFile(project) + .AddLoggers($"trx;LogFileName={project.Name}.trx")), completeOnFailure: true); + }); +} diff --git a/Pipeline/Build.CodeAnalysis.cs b/Pipeline/Build.CodeAnalysis.cs new file mode 100644 index 000000000..9f3e9b035 --- /dev/null +++ b/Pipeline/Build.CodeAnalysis.cs @@ -0,0 +1,42 @@ +using Nuke.Common; +using Nuke.Common.Tools.SonarScanner; + +// ReSharper disable AllUnderscoreLocalParameterName + +namespace Build; + +partial class Build +{ + [Parameter("The key to push to sonarcloud")] [Secret] readonly string SonarToken; + + Target CodeAnalysisBegin => _ => _ + .Unlisted() + .Before(Compile) + .Before(CodeCoverage) + .Executes(() => + { + SonarScannerTasks.SonarScannerBegin(s => s + .SetOrganization("testableio") + .SetProjectKey("TestableIO_System.IO.Abstractions") + .AddVSTestReports(TestResultsDirectory / "*.trx") + .AddOpenCoverPaths(TestResultsDirectory / "reports" / "OpenCover.xml") + .SetPullRequestOrBranchName(GitHubActions, GitVersion) + .SetVersion(GitVersion.SemVer) + .SetToken(SonarToken)); + }); + + Target CodeAnalysisEnd => _ => _ + .Unlisted() + .DependsOn(Compile) + .DependsOn(CodeCoverage) + .OnlyWhenDynamic(() => IsServerBuild) + .Executes(() => + { + SonarScannerTasks.SonarScannerEnd(s => s + .SetToken(SonarToken)); + }); + + Target CodeAnalysis => _ => _ + .DependsOn(CodeAnalysisBegin) + .DependsOn(CodeAnalysisEnd); +} diff --git a/Pipeline/Build.CodeCoverage.cs b/Pipeline/Build.CodeCoverage.cs new file mode 100644 index 000000000..6954e898b --- /dev/null +++ b/Pipeline/Build.CodeCoverage.cs @@ -0,0 +1,25 @@ +using Nuke.Common; +using Nuke.Common.Tooling; +using Nuke.Common.Tools.ReportGenerator; +using static Nuke.Common.Tools.ReportGenerator.ReportGeneratorTasks; + +// ReSharper disable AllUnderscoreLocalParameterName + +namespace Build; + +partial class Build +{ + Target CodeCoverage => _ => _ + .DependsOn(UnitTests) + .Executes(() => + { + ReportGenerator(s => s + .SetProcessToolPath(NuGetToolPathResolver.GetPackageExecutable("ReportGenerator", "ReportGenerator.dll", + framework: "net8.0")) + .SetTargetDirectory(TestResultsDirectory / "reports") + .AddReports(TestResultsDirectory / "**/coverage.cobertura.xml") + .AddReportTypes(ReportTypes.OpenCover) + .AddFileFilters("-*.g.cs") + .SetAssemblyFilters("+TestableIO*", "+System.IO.Abstractions*")); + }); +} diff --git a/Pipeline/Build.Compile.cs b/Pipeline/Build.Compile.cs new file mode 100644 index 000000000..a26a6ef7b --- /dev/null +++ b/Pipeline/Build.Compile.cs @@ -0,0 +1,119 @@ +using System; +using System.Linq; +using Nuke.Common; +using Nuke.Common.IO; +using Nuke.Common.Tools.DotNet; +using Nuke.Common.Tools.GitVersion; +using Nuke.Common.Utilities; +using Nuke.Common.Utilities.Collections; +using Serilog; +using static Nuke.Common.Tools.DotNet.DotNetTasks; + +// ReSharper disable AllUnderscoreLocalParameterName + +namespace Build; + +partial class Build +{ + string BranchName; + string SemVer; + AssemblyVersion MainVersion; + + Target CalculateNugetVersion => _ => _ + .Unlisted() + .Executes(() => + { + string preRelease = "-CI"; + if (GitHubActions == null) + { + preRelease = "-DEV"; + } + else if (GitHubActions.Ref.StartsWith("refs/tags/", StringComparison.OrdinalIgnoreCase)) + { + int preReleaseIndex = GitHubActions.Ref.IndexOf('-'); + preRelease = preReleaseIndex > 0 ? GitHubActions.Ref[preReleaseIndex..] : ""; + } + + SemVer = GitVersion.SemVer; + BranchName = GitVersion.BranchName; + MainVersion = AssemblyVersion.FromGitVersion(GitVersion, preRelease); + + if (GitHubActions?.IsPullRequest == true) + { + string buildNumber = GitHubActions.RunNumber.ToString(); + Console.WriteLine( + $"Branch spec is a pull request. Adding build number {buildNumber}"); + + SemVer = string.Join('.', GitVersion.SemVer.Split('.').Take(3).Union([buildNumber,])); + } + + Console.WriteLine($"SemVer = {SemVer}"); + }); + + Target Clean => _ => _ + .Unlisted() + .Before(Restore) + .Executes(() => + { + ArtifactsDirectory.CreateOrCleanDirectory(); + Log.Information("Cleaned {path}...", ArtifactsDirectory); + + TestResultsDirectory.CreateOrCleanDirectory(); + Log.Information("Cleaned {path}...", TestResultsDirectory); + }); + + Target Restore => _ => _ + .Unlisted() + .DependsOn(Clean) + .Executes(() => + { + DotNetRestore(s => s + .SetProjectFile(Solution) + .EnableNoCache() + .SetConfigFile(RootDirectory / "nuget.config")); + }); + + Target Compile => _ => _ + .DependsOn(Restore) + .DependsOn(CalculateNugetVersion) + .Executes(() => + { + string preRelease = "-CI"; + if (GitHubActions == null) + { + preRelease = "-DEV"; + } + else if (GitHubActions.Ref.StartsWith("refs/tags/", StringComparison.OrdinalIgnoreCase)) + { + int preReleaseIndex = GitHubActions.Ref.IndexOf('-'); + preRelease = preReleaseIndex > 0 ? GitHubActions.Ref[preReleaseIndex..] : ""; + } + + ReportSummary(s => s + .WhenNotNull(SemVer, (summary, semVer) => summary + .AddPair("Version", MainVersion.FileVersion + MainVersion.PreRelease))); + + DotNetBuild(s => s + .SetProjectFile(Solution) + .SetConfiguration(Configuration) + .EnableNoLogo() + .EnableNoRestore() + .SetVersion(MainVersion.FileVersion + MainVersion.PreRelease) + .SetAssemblyVersion(MainVersion.FileVersion) + .SetFileVersion(MainVersion.FileVersion) + .SetInformationalVersion(MainVersion.InformationalVersion)); + }); + + public record AssemblyVersion(string FileVersion, string InformationalVersion, string PreRelease) + { + public static AssemblyVersion FromGitVersion(GitVersion gitVersion, string preRelease) + { + if (gitVersion is null) + { + return null; + } + + return new AssemblyVersion(gitVersion.AssemblySemVer, gitVersion.InformationalVersion, preRelease); + } + } +} diff --git a/Pipeline/Build.Pack.cs b/Pipeline/Build.Pack.cs new file mode 100644 index 000000000..75fc31bde --- /dev/null +++ b/Pipeline/Build.Pack.cs @@ -0,0 +1,99 @@ +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using Nuke.Common; +using Nuke.Common.IO; +using Nuke.Common.ProjectModel; +using Nuke.Common.Utilities; +using Nuke.Common.Utilities.Collections; +using static Serilog.Log; + +// ReSharper disable AllUnderscoreLocalParameterName + +namespace Build; + +partial class Build +{ + Target UpdateReadme => _ => _ + .DependsOn(Clean) + .Before(Compile) + .Executes(() => + { + string version = string.Join('.', GitVersion.SemVer.Split('.').Take(3)); + if (version.IndexOf('-') != -1) + { + version = version.Substring(0, version.IndexOf('-')); + } + + StringBuilder sb = new(); + string[] lines = File.ReadAllLines(Solution.Directory / "README.md"); + sb.AppendLine(lines.First()); + sb.AppendLine( + $"[![Changelog](https://img.shields.io/badge/Changelog-v{version}-blue)](https://github.com/TestableIO/System.IO.Abstractions/releases/tag/v{version})"); + foreach (string line in lines.Skip(1)) + { + if (line.StartsWith("[![Build](https://github.com/TestableIO/System.IO.Abstractions/actions/workflows/build.yml") || + line.StartsWith("[![Quality Gate Status](https://sonarcloud.io/api/project_badges/measure")) + { + continue; + } + + if (line.StartsWith("[![Coverage](https://sonarcloud.io/api/project_badges/measure")) + { + sb.AppendLine(line + .Replace(")", $"&branch=release/v{version})")); + continue; + } + + if (line.StartsWith("[![Mutation testing badge](https://img.shields.io/endpoint")) + { + sb.AppendLine(line + .Replace("%2Fmain)", $"%2Frelease%2Fv{version})") + .Replace("/main)", $"/release/v{version})")); + continue; + } + + sb.AppendLine(line); + } + + File.WriteAllText(ArtifactsDirectory / "README.md", sb.ToString()); + }); + + Target Pack => _ => _ + .DependsOn(UpdateReadme) + .DependsOn(Compile) + .Executes(() => + { + AbsolutePath packagesDirectory = ArtifactsDirectory / "Packages"; + packagesDirectory.CreateOrCleanDirectory(); + + List packages = new(); + foreach (Project project in new[] + { + Solution.TestableIO_System_IO_Abstractions_Wrappers, + Solution.TestableIO_System_IO_Abstractions_TestingHelpers, + Solution.Meta.TestableIO_System_IO_Abstractions, + Solution.Meta.System_IO_Abstractions, + Solution.Meta.System_IO_Abstractions_TestingHelpers, + }) + { + foreach (string package in + Directory.EnumerateFiles(project.Directory / "bin", "*.nupkg", SearchOption.AllDirectories)) + { + File.Move(package, packagesDirectory / Path.GetFileName(package)); + Debug("Found nuget package: {PackagePath}", package); + packages.Add(Path.GetFileName(package)); + } + + foreach (string symbolPackage in + Directory.EnumerateFiles(project.Directory / "bin", "*.snupkg", SearchOption.AllDirectories)) + { + File.Move(symbolPackage, packagesDirectory / Path.GetFileName(symbolPackage)); + Debug("Found symbol package: {PackagePath}", symbolPackage); + } + } + ReportSummary(s => s + .AddPair("Packages", string.Join(", ", packages))); + }); +} diff --git a/Pipeline/Build.UnitTest.cs b/Pipeline/Build.UnitTest.cs new file mode 100644 index 000000000..c88133073 --- /dev/null +++ b/Pipeline/Build.UnitTest.cs @@ -0,0 +1,79 @@ +using System.IO; +using System.Linq; +using Nuke.Common; +using Nuke.Common.IO; +using Nuke.Common.ProjectModel; +using Nuke.Common.Tooling; +using Nuke.Common.Tools.DotNet; +using Nuke.Common.Tools.NUnit; +using static Nuke.Common.Tools.DotNet.DotNetTasks; + +// ReSharper disable AllUnderscoreLocalParameterName + +namespace Build; + +partial class Build +{ + Target UnitTests => _ => _ + .DependsOn(DotNetFrameworkUnitTests) + .DependsOn(DotNetUnitTests); + + Project[] UnitTestProjects => + [ + Solution.Tests.TestableIO_System_IO_Abstractions_Wrappers_Tests, + Solution.Tests.TestableIO_System_IO_Abstractions_TestingHelpers_Tests, + Solution.Tests.TestableIO_System_IO_Abstractions_Parity_Tests, + ]; + + Target DotNetFrameworkUnitTests => _ => _ + .Unlisted() + .DependsOn(Compile) + .OnlyWhenDynamic(() => EnvironmentInfo.IsWin) + .Executes(() => + { + var testAssemblies = UnitTestProjects + .SelectMany(project => + project.Directory.GlobFiles( + $"bin/{(Configuration == Configuration.Debug ? "Debug" : "Release")}/net472/*.Tests.dll")) + .Select(p => p.ToString()) + .ToArray(); + + Assert.NotEmpty(testAssemblies.ToList()); + + foreach (var testAssembly in testAssemblies) + { + var currentDirectory = Path.GetDirectoryName(testAssembly); + + NUnitTasks.NUnit3(s => s + .SetInputFiles(testAssembly) + .SetProcessWorkingDirectory(currentDirectory) + ); + } + }); + + Target DotNetUnitTests => _ => _ + .Unlisted() + .DependsOn(Compile) + .Executes(() => + { + string[] excludedFrameworks = ["net48",]; + DotNetTest(s => s + .SetConfiguration(Configuration) + .SetProcessEnvironmentVariable("DOTNET_CLI_UI_LANGUAGE", "en-US") + .EnableNoBuild() + .SetDataCollector("XPlat Code Coverage") + .SetResultsDirectory(TestResultsDirectory) + .CombineWith( + UnitTestProjects, + (settings, project) => settings + .SetProjectFile(project) + .CombineWith( + project.GetTargetFrameworks()?.Except(excludedFrameworks), + (frameworkSettings, framework) => frameworkSettings + .SetFramework(framework) + .AddLoggers($"trx;LogFileName={project.Name}_{framework}.trx") + ) + ), completeOnFailure: true + ); + }); +} \ No newline at end of file diff --git a/Pipeline/Build.cs b/Pipeline/Build.cs new file mode 100644 index 000000000..10372f655 --- /dev/null +++ b/Pipeline/Build.cs @@ -0,0 +1,31 @@ +using Nuke.Common; +using Nuke.Common.CI.GitHubActions; +using Nuke.Common.IO; +using Nuke.Common.ProjectModel; +using Nuke.Common.Tools.GitVersion; + +namespace Build; + +[GitHubActions( + "Build", + GitHubActionsImage.UbuntuLatest, + AutoGenerate = false, + ImportSecrets = [nameof(GithubToken),] +)] +partial class Build : NukeBuild +{ + [Parameter("Configuration to build - Default is 'Debug' (local) or 'Release' (server)")] + readonly Configuration Configuration = IsLocalBuild ? Configuration.Debug : Configuration.Release; + + [Parameter("Github Token")] readonly string GithubToken; + + [Required] [GitVersion(Framework = "net8.0", NoCache = true, NoFetch = true)] readonly GitVersion GitVersion; + + [Solution(GenerateProjects = true)] readonly Solution Solution; + + AbsolutePath ArtifactsDirectory => RootDirectory / "Artifacts"; + AbsolutePath TestResultsDirectory => RootDirectory / "TestResults"; + GitHubActions GitHubActions => GitHubActions.Instance; + + public static int Main() => Execute(x => x.UnitTests, x => x.Pack); +} diff --git a/Pipeline/Build.csproj b/Pipeline/Build.csproj new file mode 100644 index 000000000..bef4b864c --- /dev/null +++ b/Pipeline/Build.csproj @@ -0,0 +1,31 @@ + + + + Exe + net10.0 + + CS0649;CS0169;CA1050;CA1822;CA2211;IDE1006 + .. + .. + 1 + false + + + + + + + + + + + + + + + + + + + + diff --git a/Pipeline/Build.csproj.DotSettings b/Pipeline/Build.csproj.DotSettings new file mode 100644 index 000000000..88a8824cd --- /dev/null +++ b/Pipeline/Build.csproj.DotSettings @@ -0,0 +1,31 @@ + + DO_NOT_SHOW + DO_NOT_SHOW + DO_NOT_SHOW + DO_NOT_SHOW + DO_NOT_SHOW + Implicit + Implicit + ExpressionBody + 0 + NEXT_LINE + True + False + 120 + IF_OWNER_IS_SINGLE_LINE + WRAP_IF_LONG + False + <Policy Inspect="True" Prefix="" Suffix="" Style="AaBb" /> + <Policy Inspect="True" Prefix="" Suffix="" Style="AaBb" /> + <Policy><Descriptor Staticness="Instance" AccessRightKinds="Private" Description="Instance fields (private)"><ElementKinds><Kind Name="FIELD" /><Kind Name="READONLY_FIELD" /></ElementKinds></Descriptor><Policy Inspect="True" WarnAboutPrefixesAndSuffixes="False" Prefix="" Suffix="" Style="AaBb" /></Policy> + <Policy><Descriptor Staticness="Static" AccessRightKinds="Private" Description="Static fields (private)"><ElementKinds><Kind Name="FIELD" /></ElementKinds></Descriptor><Policy Inspect="True" WarnAboutPrefixesAndSuffixes="False" Prefix="" Suffix="" Style="AaBb" /></Policy> + True + True + True + True + True + True + True + True + True + True diff --git a/Pipeline/BuildExtensions.cs b/Pipeline/BuildExtensions.cs new file mode 100644 index 000000000..cd3e593a6 --- /dev/null +++ b/Pipeline/BuildExtensions.cs @@ -0,0 +1,36 @@ +using System; +using Nuke.Common.CI.GitHubActions; +using Nuke.Common.Tools.GitVersion; +using Nuke.Common.Tools.SonarScanner; +using Serilog; + +namespace Build; + +public static class BuildExtensions +{ + public static SonarScannerBeginSettings SetPullRequestOrBranchName( + this SonarScannerBeginSettings settings, + GitHubActions gitHubActions, + GitVersion gitVersion) + { + if (gitHubActions?.IsPullRequest == true) + { + Log.Information("Use pull request analysis"); + return settings + .SetPullRequestKey(gitHubActions.PullRequestNumber.ToString()) + .SetPullRequestBranch(gitHubActions.Ref) + .SetPullRequestBase(gitHubActions.BaseRef); + } + + if (gitHubActions?.Ref.StartsWith("refs/tags/", StringComparison.OrdinalIgnoreCase) == true) + { + string version = gitHubActions.Ref.Substring("refs/tags/".Length); + string branchName = "release/" + version; + Log.Information("Use release branch analysis for '{BranchName}'", branchName); + return settings.SetBranchName(branchName); + } + + Log.Information("Use branch analysis for '{BranchName}'", gitVersion.BranchName); + return settings.SetBranchName(gitVersion.BranchName); + } +} diff --git a/Pipeline/Configuration.cs b/Pipeline/Configuration.cs new file mode 100644 index 000000000..9c08b1ae9 --- /dev/null +++ b/Pipeline/Configuration.cs @@ -0,0 +1,16 @@ +using System; +using System.ComponentModel; +using System.Linq; +using Nuke.Common.Tooling; + +[TypeConverter(typeof(TypeConverter))] +public class Configuration : Enumeration +{ + public static Configuration Debug = new Configuration { Value = nameof(Debug) }; + public static Configuration Release = new Configuration { Value = nameof(Release) }; + + public static implicit operator string(Configuration configuration) + { + return configuration.Value; + } +} diff --git a/Pipeline/Directory.Build.props b/Pipeline/Directory.Build.props new file mode 100644 index 000000000..e147d6352 --- /dev/null +++ b/Pipeline/Directory.Build.props @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/Pipeline/Directory.Build.targets b/Pipeline/Directory.Build.targets new file mode 100644 index 000000000..253260956 --- /dev/null +++ b/Pipeline/Directory.Build.targets @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/README.md b/README.md index 4648956b7..64b50d973 100644 --- a/README.md +++ b/README.md @@ -1,16 +1,20 @@ -[![AppVeyor](https://ci.appveyor.com/api/projects/status/github/tathamoddie/System.IO.Abstractions?svg=true)](https://ci.appveyor.com/project/tathamoddie/system-io-abstractions) +![System.IO.Abstractions](https://socialify.git.ci/TestableIO/System.IO.Abstractions/image?description=1&font=Source%20Code%20Pro&forks=1&issues=1&pattern=Charlie%20Brown&pulls=1&stargazers=1&theme=Dark) +[![NuGet](https://img.shields.io/nuget/v/TestableIO.System.IO.Abstractions.svg)](https://www.nuget.org/packages/TestableIO.System.IO.Abstractions) +[![Build](https://github.com/TestableIO/System.IO.Abstractions/actions/workflows/build.yml/badge.svg)](https://github.com/TestableIO/System.IO.Abstractions/actions/workflows/build.yml) +[![Quality Gate Status](https://sonarcloud.io/api/project_badges/measure?project=TestableIO_System.IO.Abstractions&metric=alert_status)](https://sonarcloud.io/summary/new_code?id=TestableIO_System.IO.Abstractions) +[![Coverage](https://sonarcloud.io/api/project_badges/measure?project=TestableIO_System.IO.Abstractions&metric=coverage)](https://sonarcloud.io/summary/new_code?id=TestableIO_System.IO.Abstractions) +[![Renovate enabled](https://img.shields.io/badge/renovate-enabled-brightgreen.svg)](https://renovatebot.com/) +[![FOSSA Status](https://app.fossa.com/api/projects/git%2Bgithub.com%2FTestableIO%2FSystem.IO.Abstractions.svg?type=shield)](https://app.fossa.com/projects/git%2Bgithub.com%2FTestableIO%2FSystem.IO.Abstractions?ref=badge_shield) -Just like System.Web.Abstractions, but for System.IO. Yay for testable IO access! +At the core of the library is `IFileSystem` and `FileSystem`. Instead of calling methods like `File.ReadAllText` directly, use `IFileSystem.File.ReadAllText`. We have exactly the same API, except that ours is injectable and testable. -NuGet only: +## Usage - Install-Package System.IO.Abstractions - -and/or: - - Install-Package System.IO.Abstractions.TestingHelpers +```shell +dotnet add package TestableIO.System.IO.Abstractions.Wrappers +``` -At the core of the library is IFileSystem and FileSystem. Instead of calling methods like `File.ReadAllText` directly, use `IFileSystem.File.ReadAllText`. We have exactly the same API, except that ours is injectable and testable. +*Note: This NuGet package is also published as `System.IO.Abstractions` but we suggest to use the prefix to make clear that this is not an official .NET package.* ```csharp public class MyComponent @@ -23,9 +27,9 @@ public class MyComponent this.fileSystem = fileSystem; } /// Create MyComponent - public MyComponent() : this( + public MyComponent() : this( fileSystem: new FileSystem() //use default implementation which calls System.IO - ) + ) { } @@ -41,8 +45,16 @@ public class MyComponent } ``` +### Test helpers + The library also ships with a series of test helpers to save you from having to mock out every call, for basic scenarios. They are not a complete copy of a real-life file system, but they'll get you most of the way there. +```shell +dotnet add package TestableIO.System.IO.Abstractions.TestingHelpers +``` + +*Note: This NuGet package is also published as `System.IO.Abstractions.TestingHelpers` but we suggest to use the prefix to make clear that this is not an official .NET package.* + ```csharp [Test] public void MyComponent_Validate_ShouldThrowNotSupportedExceptionIfTestingIsNotAwesome() @@ -64,24 +76,134 @@ public void MyComponent_Validate_ShouldThrowNotSupportedExceptionIfTestingIsNotA catch (NotSupportedException ex) { // Assert - Assert.AreEqual("We can't go on together. It's not me, it's you.", ex.Message); + Assert.That(ex.Message, Is.EqualTo("We can't go on together. It's not me, it's you.")); return; } Assert.Fail("The expected exception was not thrown."); } ``` + We even support casting from the .NET Framework's untestable types to our testable wrappers: ```csharp -FileInfo SomeBadApiMethodThatReturnsFileInfo() +FileInfo SomeApiMethodThatReturnsFileInfo() { return new FileInfo("a"); } void MyFancyMethod() { - var testableFileInfo = (FileInfoBase)SomeBadApiMethodThatReturnsFileInfo(); + var testableFileInfo = (FileInfoBase)SomeApiMethodThatReturnsFileInfo(); ... } ``` + +### Mock support + +Since version 4.0 the top-level APIs expose interfaces instead of abstract base classes (these still exist, though), allowing you to completely mock the file system. Here's a small example, using [Mockolate](https://github.com/aweXpect/Mockolate): + +```csharp +[Test] +public void Test1() +{ + var watcher = Mock.Create(); + var file = Mock.Create(); + + file.SetupMock.Method.Exists(It.IsAny()).Returns(true); + file.SetupMock.Method.ReadAllText(It.IsAny()).Throws(); + + var unitUnderTest = new SomeClassUsingFileSystemWatcher(watcher, file); + + Assert.Throws(() => { + watcher.RaiseOnMock.Created(null, new System.IO.FileSystemEventArgs(System.IO.WatcherChangeTypes.Created, @"C:\Some\Directory", "Some.File")); + }); + + file.VerifyMock.Invoked.Exists(It.IsAny()).Once(); + + Assert.That(unitUnderTest.FileWasCreated, Is.True); +} + +public class SomeClassUsingFileSystemWatcher +{ + private readonly IFileSystemWatcher _watcher; + private readonly IFile _file; + + public bool FileWasCreated { get; private set; } + + public SomeClassUsingFileSystemWatcher(IFileSystemWatcher watcher, IFile file) + { + this._file = file; + this._watcher = watcher; + this._watcher.Created += Watcher_Created; + } + + private void Watcher_Created(object sender, System.IO.FileSystemEventArgs e) + { + FileWasCreated = true; + + if(_file.Exists(e.FullPath)) + { + var text = _file.ReadAllText(e.FullPath); + } + } +} +``` + +## Relationship with Testably.Abstractions + +[`Testably.Abstractions`](https://github.com/Testably/Testably.Abstractions) is a complementary project that uses the same interfaces as TestableIO. This means **no changes to your production code are necessary** when switching between the testing libraries. + +Both projects share the same maintainer, but active development and new features are primarily focused on the Testably.Abstractions project. TestableIO.System.IO.Abstractions continues to be maintained for stability and compatibility, but significant new functionality is unlikely to be added. + +### When to use Testably.Abstractions vs TestableIO +- **Use TestableIO.System.IO.Abstractions** if you need: + - Basic file system mocking capabilities + - Direct manipulation of stored file entities (MockFileData, MockDirectoryData) + - Established codebase with existing TestableIO integration + +- **Use Testably.Abstractions** if you need: + - Advanced testing scenarios (FileSystemWatcher, SafeFileHandles, multiple drives) + - Additional abstractions (ITimeSystem, IRandomSystem) + - Cross-platform file system simulation (Linux, MacOS, Windows) + - More extensive and consistent behavior validation + - Active development and new features + +### Migrating from TestableIO +Switching from TestableIO to Testably only requires changes in your test projects: + +1. Replace the NuGet package reference in your test projects: + ```xml + + + + + ``` + +2. Update your test code to use the new `MockFileSystem`: + ```csharp + // Before (TestableIO) + var fileSystem = new MockFileSystem(); + fileSystem.AddDirectory("some-directory"); + fileSystem.AddFile("some-file.txt", new MockFileData("content")); + + // After (Testably) + var fileSystem = new MockFileSystem(); + fileSystem.Directory.CreateDirectory("some-directory"); + fileSystem.File.WriteAllText("some-file.txt", "content"); + // or using fluent initialization: + fileSystem.Initialize() + .WithSubdirectory("some-directory") + .WithFile("some-file.txt").Which(f => f + .HasStringContent("content")); + ``` + +Your production code using `IFileSystem` remains unchanged. + +## Other related projects + +- [`System.IO.Abstractions.Extensions`](https://github.com/TestableIO/System.IO.Abstractions.Extensions) + provides convenience functionality on top of the core abstractions. + +- [`System.IO.Abstractions.Analyzers`](https://github.com/TestableIO/System.IO.Abstractions.Analyzers) + provides Roslyn analyzers to help use abstractions over static methods. \ No newline at end of file diff --git a/StrongName.pfx b/StrongName.pfx deleted file mode 100644 index 39bb6519c..000000000 Binary files a/StrongName.pfx and /dev/null differ diff --git a/StrongName.snk b/StrongName.snk new file mode 100644 index 000000000..31c957881 Binary files /dev/null and b/StrongName.snk differ diff --git a/System.IO.Abstractions.ncrunchsolution b/System.IO.Abstractions.ncrunchsolution deleted file mode 100644 index f2e00196f..000000000 --- a/System.IO.Abstractions.ncrunchsolution +++ /dev/null @@ -1,13 +0,0 @@ - - 1 - True - true - true - UseDynamicAnalysis - UseStaticAnalysis - UseStaticAnalysis - UseStaticAnalysis - Run all tests automatically:BFRydWU=;Run all tests manually:BUZhbHNl;Run impacted tests automatically, others manually (experimental!):CklzSW1wYWN0ZWQ=;Run pinned tests automatically, others manually:CElzUGlubmVk - - - \ No newline at end of file diff --git a/System.IO.Abstractions.sln b/System.IO.Abstractions.sln deleted file mode 100644 index c9047e5d3..000000000 --- a/System.IO.Abstractions.sln +++ /dev/null @@ -1,40 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 14 -VisualStudioVersion = 14.0.25420.1 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{5F3BDA62-8052-4C37-97A0-94354AA971B0}" - ProjectSection(SolutionItems) = preProject - appveyor.yml = appveyor.yml - StrongName.pfx = StrongName.pfx - EndProjectSection -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "System.IO.Abstractions", "System.IO.Abstractions\System.IO.Abstractions.csproj", "{4D398F3A-0784-4401-93CD-46CD2FBD6B92}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TestingHelpers", "TestingHelpers\TestingHelpers.csproj", "{251BD5E5-8133-47A4-AB19-17CF0F43D6AE}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TestHelpers.Tests", "TestHelpers.Tests\TestHelpers.Tests.csproj", "{20B02738-952A-40F5-9C10-E2F83013E9FC}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Release|Any CPU = Release|Any CPU - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {4D398F3A-0784-4401-93CD-46CD2FBD6B92}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {4D398F3A-0784-4401-93CD-46CD2FBD6B92}.Debug|Any CPU.Build.0 = Debug|Any CPU - {4D398F3A-0784-4401-93CD-46CD2FBD6B92}.Release|Any CPU.ActiveCfg = Release|Any CPU - {4D398F3A-0784-4401-93CD-46CD2FBD6B92}.Release|Any CPU.Build.0 = Release|Any CPU - {251BD5E5-8133-47A4-AB19-17CF0F43D6AE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {251BD5E5-8133-47A4-AB19-17CF0F43D6AE}.Debug|Any CPU.Build.0 = Debug|Any CPU - {251BD5E5-8133-47A4-AB19-17CF0F43D6AE}.Release|Any CPU.ActiveCfg = Release|Any CPU - {251BD5E5-8133-47A4-AB19-17CF0F43D6AE}.Release|Any CPU.Build.0 = Release|Any CPU - {20B02738-952A-40F5-9C10-E2F83013E9FC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {20B02738-952A-40F5-9C10-E2F83013E9FC}.Debug|Any CPU.Build.0 = Debug|Any CPU - {20B02738-952A-40F5-9C10-E2F83013E9FC}.Release|Any CPU.ActiveCfg = Release|Any CPU - {20B02738-952A-40F5-9C10-E2F83013E9FC}.Release|Any CPU.Build.0 = Release|Any CPU - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection -EndGlobal diff --git a/System.IO.Abstractions.sln.DotSettings b/System.IO.Abstractions.sln.DotSettings deleted file mode 100644 index f455d6b20..000000000 --- a/System.IO.Abstractions.sln.DotSettings +++ /dev/null @@ -1,2 +0,0 @@ - - <Policy Inspect="True" Prefix="" Suffix="" Style="aaBb" /> \ No newline at end of file diff --git a/System.IO.Abstractions.slnx b/System.IO.Abstractions.slnx new file mode 100644 index 000000000..4d162ad2d --- /dev/null +++ b/System.IO.Abstractions.slnx @@ -0,0 +1,41 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/System.IO.Abstractions/Converters.cs b/System.IO.Abstractions/Converters.cs deleted file mode 100644 index d4784bf6a..000000000 --- a/System.IO.Abstractions/Converters.cs +++ /dev/null @@ -1,39 +0,0 @@ -using System.Collections.Generic; -using System.Globalization; -using System.Linq; - -namespace System.IO.Abstractions -{ - internal static class Converters - { - internal static FileSystemInfoBase[] WrapFileSystemInfos(this IEnumerable input) - { - return input - .Select(item => - { - if (item is FileInfo) - return (FileInfoBase) item; - - if (item is DirectoryInfo) - return (DirectoryInfoBase) item; - - throw new NotImplementedException(string.Format( - CultureInfo.InvariantCulture, - "The type {0} is not recognized by the System.IO.Abstractions library.", - item.GetType().AssemblyQualifiedName - )); - }) - .ToArray(); - } - - internal static DirectoryInfoBase[] WrapDirectories(this IEnumerable input) - { - return input.Select(f => (DirectoryInfoBase)f).ToArray(); - } - - internal static FileInfoBase[] WrapFiles(this IEnumerable input) - { - return input.Select(f => (FileInfoBase)f).ToArray(); - } - } -} \ No newline at end of file diff --git a/System.IO.Abstractions/DirectoryBase.cs b/System.IO.Abstractions/DirectoryBase.cs deleted file mode 100644 index 84db1e6e3..000000000 --- a/System.IO.Abstractions/DirectoryBase.cs +++ /dev/null @@ -1,53 +0,0 @@ -using System.Collections.Generic; -using System.Security.AccessControl; - -namespace System.IO.Abstractions -{ - [Serializable] - public abstract class DirectoryBase - { - public abstract DirectoryInfoBase CreateDirectory(string path); - public abstract DirectoryInfoBase CreateDirectory(string path, DirectorySecurity directorySecurity); - public abstract void Delete(string path); - public abstract void Delete(string path, bool recursive); - public abstract bool Exists(string path); - public abstract DirectorySecurity GetAccessControl(string path); - public abstract DirectorySecurity GetAccessControl(string path, AccessControlSections includeSections); - public abstract DateTime GetCreationTime(string path); - public abstract DateTime GetCreationTimeUtc(string path); - public abstract string GetCurrentDirectory(); - public abstract string[] GetDirectories(string path); - public abstract string[] GetDirectories(string path, string searchPattern); - public abstract string[] GetDirectories(string path, string searchPattern, SearchOption searchOption); - public abstract string GetDirectoryRoot(string path); - public abstract string[] GetFiles(string path); - public abstract string[] GetFiles(string path, string searchPattern); - public abstract string[] GetFiles(string path, string searchPattern, SearchOption searchOption); - public abstract string[] GetFileSystemEntries(string path); - public abstract string[] GetFileSystemEntries(string path, string searchPattern); - public abstract DateTime GetLastAccessTime(string path); - public abstract DateTime GetLastAccessTimeUtc(string path); - public abstract DateTime GetLastWriteTime(string path); - public abstract DateTime GetLastWriteTimeUtc(string path); - public abstract string[] GetLogicalDrives(); - public abstract DirectoryInfoBase GetParent(string path); - public abstract void Move(string sourceDirName, string destDirName); - public abstract void SetAccessControl(string path, DirectorySecurity directorySecurity); - public abstract void SetCreationTime(string path, DateTime creationTime); - public abstract void SetCreationTimeUtc(string path, DateTime creationTimeUtc); - public abstract void SetCurrentDirectory(string path); - public abstract void SetLastAccessTime(string path, DateTime lastAccessTime); - public abstract void SetLastAccessTimeUtc(string path, DateTime lastAccessTimeUtc); - public abstract void SetLastWriteTime(string path, DateTime lastWriteTime); - public abstract void SetLastWriteTimeUtc(string path, DateTime lastWriteTimeUtc); - public abstract IEnumerable EnumerateDirectories(String path); - public abstract IEnumerable EnumerateDirectories(String path, String searchPattern); - public abstract IEnumerable EnumerateDirectories(String path, String searchPattern, SearchOption searchOption); - public abstract IEnumerable EnumerateFiles(string path); - public abstract IEnumerable EnumerateFiles(string path, string searchPattern); - public abstract IEnumerable EnumerateFiles(string path, string searchPattern, SearchOption searchOption); - public abstract IEnumerable EnumerateFileSystemEntries(string path); - public abstract IEnumerable EnumerateFileSystemEntries(string path, string searchPattern); - public abstract IEnumerable EnumerateFileSystemEntries(string path, string searchPattern, SearchOption searchOption); - } -} \ No newline at end of file diff --git a/System.IO.Abstractions/DirectoryInfoBase.cs b/System.IO.Abstractions/DirectoryInfoBase.cs deleted file mode 100644 index 19be4683c..000000000 --- a/System.IO.Abstractions/DirectoryInfoBase.cs +++ /dev/null @@ -1,46 +0,0 @@ -using System.Collections.Generic; -using System.Security.AccessControl; - -namespace System.IO.Abstractions -{ - [Serializable] - public abstract class DirectoryInfoBase : FileSystemInfoBase - { - public abstract void Create(); - public abstract void Create(DirectorySecurity directorySecurity); - public abstract DirectoryInfoBase CreateSubdirectory(string path); - public abstract DirectoryInfoBase CreateSubdirectory(string path, DirectorySecurity directorySecurity); - public abstract void Delete(bool recursive); - public abstract IEnumerable EnumerateDirectories(); - public abstract IEnumerable EnumerateDirectories(string searchPattern); - public abstract IEnumerable EnumerateDirectories(string searchPattern, SearchOption searchOption); - public abstract IEnumerable EnumerateFiles(); - public abstract IEnumerable EnumerateFiles(string searchPattern); - public abstract IEnumerable EnumerateFiles(string searchPattern, SearchOption searchOption); - public abstract IEnumerable EnumerateFileSystemInfos(); - public abstract IEnumerable EnumerateFileSystemInfos(string searchPattern); - public abstract IEnumerable EnumerateFileSystemInfos(string searchPattern, SearchOption searchOption); - public abstract DirectorySecurity GetAccessControl(); - public abstract DirectorySecurity GetAccessControl(AccessControlSections includeSections); - public abstract DirectoryInfoBase[] GetDirectories(); - public abstract DirectoryInfoBase[] GetDirectories(string searchPattern); - public abstract DirectoryInfoBase[] GetDirectories(string searchPattern, SearchOption searchOption); - public abstract FileInfoBase[] GetFiles(); - public abstract FileInfoBase[] GetFiles(string searchPattern); - public abstract FileInfoBase[] GetFiles(string searchPattern, SearchOption searchOption); - public abstract FileSystemInfoBase[] GetFileSystemInfos(); - public abstract FileSystemInfoBase[] GetFileSystemInfos(string searchPattern); - public abstract FileSystemInfoBase[] GetFileSystemInfos(string searchPattern, SearchOption searchOption); - public abstract void MoveTo(string destDirName); - public abstract void SetAccessControl(DirectorySecurity directorySecurity); - public abstract DirectoryInfoBase Parent { get; } - public abstract DirectoryInfoBase Root { get; } - - public static implicit operator DirectoryInfoBase(DirectoryInfo directoryInfo) - { - if (directoryInfo == null) - return null; - return new DirectoryInfoWrapper(directoryInfo); - } - } -} \ No newline at end of file diff --git a/System.IO.Abstractions/DirectoryInfoFactory.cs b/System.IO.Abstractions/DirectoryInfoFactory.cs deleted file mode 100644 index 61e4f34dc..000000000 --- a/System.IO.Abstractions/DirectoryInfoFactory.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace System.IO.Abstractions -{ - [Serializable] - internal class DirectoryInfoFactory : IDirectoryInfoFactory - { - public DirectoryInfoBase FromDirectoryName(string directoryName) - { - var realDirectoryInfo = new DirectoryInfo(directoryName); - return new DirectoryInfoWrapper(realDirectoryInfo); - } - } -} \ No newline at end of file diff --git a/System.IO.Abstractions/DirectoryInfoWrapper.cs b/System.IO.Abstractions/DirectoryInfoWrapper.cs deleted file mode 100644 index 06c4bf456..000000000 --- a/System.IO.Abstractions/DirectoryInfoWrapper.cs +++ /dev/null @@ -1,244 +0,0 @@ -using System.Collections.Generic; -using System.Linq; -using System.Security.AccessControl; - -namespace System.IO.Abstractions -{ - [Serializable] - public class DirectoryInfoWrapper : DirectoryInfoBase - { - private readonly DirectoryInfo instance; - - public DirectoryInfoWrapper(DirectoryInfo instance) - { - if (instance == null) - { - throw new ArgumentNullException("instance"); - } - - this.instance = instance; - } - - public override void Delete() - { - instance.Delete(); - } - - public override void Refresh() - { - instance.Refresh(); - } - - public override FileAttributes Attributes - { - get { return instance.Attributes; } - set { instance.Attributes = value; } - } - - public override DateTime CreationTime - { - get { return instance.CreationTime; } - set { instance.CreationTime = value; } - } - - public override DateTime CreationTimeUtc - { - get { return instance.CreationTimeUtc; } - set { instance.CreationTimeUtc = value; } - } - - public override bool Exists - { - get { return instance.Exists; } - } - - public override string Extension - { - get { return instance.Extension; } - } - - public override string FullName - { - get { return instance.FullName; } - } - - public override DateTime LastAccessTime - { - get { return instance.LastAccessTime; } - set { instance.LastAccessTime = value; } - } - - public override DateTime LastAccessTimeUtc - { - get { return instance.LastAccessTimeUtc; } - set { instance.LastAccessTimeUtc = value; } - } - - public override DateTime LastWriteTime - { - get { return instance.LastWriteTime; } - set { instance.LastWriteTime = value; } - } - - public override DateTime LastWriteTimeUtc - { - get { return instance.LastWriteTimeUtc; } - set { instance.LastWriteTimeUtc = value; } - } - - public override string Name - { - get { return instance.Name; } - } - - public override void Create() - { - instance.Create(); - } - - public override void Create(DirectorySecurity directorySecurity) - { - instance.Create(directorySecurity); - } - - public override DirectoryInfoBase CreateSubdirectory(string path) - { - return new DirectoryInfoWrapper(instance.CreateSubdirectory(path)); - } - - public override DirectoryInfoBase CreateSubdirectory(string path, DirectorySecurity directorySecurity) - { - return new DirectoryInfoWrapper(instance.CreateSubdirectory(path, directorySecurity)); - } - - public override void Delete(bool recursive) - { - instance.Delete(recursive); - } - - public override IEnumerable EnumerateDirectories() - { - return instance.EnumerateDirectories().Select(directoryInfo => new DirectoryInfoWrapper(directoryInfo)); - } - - public override IEnumerable EnumerateDirectories(string searchPattern) - { - return instance.EnumerateDirectories(searchPattern).Select(directoryInfo => new DirectoryInfoWrapper(directoryInfo)); - } - - public override IEnumerable EnumerateDirectories(string searchPattern, SearchOption searchOption) - { - return instance.EnumerateDirectories(searchPattern, searchOption).Select(directoryInfo => new DirectoryInfoWrapper(directoryInfo)); - } - - public override IEnumerable EnumerateFiles() - { - return instance.EnumerateFiles().Select(fileInfo => new FileInfoWrapper(fileInfo)); - } - - public override IEnumerable EnumerateFiles(string searchPattern) - { - return instance.EnumerateFiles(searchPattern).Select(fileInfo => new FileInfoWrapper(fileInfo)); - } - - public override IEnumerable EnumerateFiles(string searchPattern, SearchOption searchOption) - { - return instance.EnumerateFiles(searchPattern, searchOption).Select(fileInfo => new FileInfoWrapper(fileInfo)); - } - - public override IEnumerable EnumerateFileSystemInfos() - { - return instance.EnumerateFileSystemInfos().WrapFileSystemInfos(); - } - - public override IEnumerable EnumerateFileSystemInfos(string searchPattern) - { - return instance.EnumerateFileSystemInfos(searchPattern).WrapFileSystemInfos(); - } - - public override IEnumerable EnumerateFileSystemInfos(string searchPattern, SearchOption searchOption) - { - return instance.EnumerateFileSystemInfos(searchPattern, searchOption).WrapFileSystemInfos(); - } - - public override DirectorySecurity GetAccessControl() - { - return instance.GetAccessControl(); - } - - public override DirectorySecurity GetAccessControl(AccessControlSections includeSections) - { - return instance.GetAccessControl(includeSections); - } - - public override DirectoryInfoBase[] GetDirectories() - { - return instance.GetDirectories().WrapDirectories(); - } - - public override DirectoryInfoBase[] GetDirectories(string searchPattern) - { - return instance.GetDirectories(searchPattern).WrapDirectories(); - } - - public override DirectoryInfoBase[] GetDirectories(string searchPattern, SearchOption searchOption) - { - return instance.GetDirectories(searchPattern, searchOption).WrapDirectories(); - } - - public override FileInfoBase[] GetFiles() - { - return instance.GetFiles().WrapFiles(); - } - - public override FileInfoBase[] GetFiles(string searchPattern) - { - return instance.GetFiles(searchPattern).WrapFiles(); - } - - public override FileInfoBase[] GetFiles(string searchPattern, SearchOption searchOption) - { - return instance.GetFiles(searchPattern, searchOption).WrapFiles(); - } - - public override FileSystemInfoBase[] GetFileSystemInfos() - { - return instance.GetFileSystemInfos().WrapFileSystemInfos(); - } - - public override FileSystemInfoBase[] GetFileSystemInfos(string searchPattern) - { - return instance.GetFileSystemInfos(searchPattern).WrapFileSystemInfos(); - } - - public override FileSystemInfoBase[] GetFileSystemInfos(string searchPattern, SearchOption searchOption) - { - return instance.GetFileSystemInfos(searchPattern, searchOption).WrapFileSystemInfos(); - } - - public override void MoveTo(string destDirName) - { - instance.MoveTo(destDirName); - } - - public override void SetAccessControl(DirectorySecurity directorySecurity) - { - instance.SetAccessControl(directorySecurity); - } - - public override DirectoryInfoBase Parent - { - get { return instance.Parent; } - } - - public override DirectoryInfoBase Root - { - get { return instance.Root; } - } - - public override string ToString() - { - return instance.ToString(); - } - } -} \ No newline at end of file diff --git a/System.IO.Abstractions/DirectoryWrapper.cs b/System.IO.Abstractions/DirectoryWrapper.cs deleted file mode 100644 index 760632924..000000000 --- a/System.IO.Abstractions/DirectoryWrapper.cs +++ /dev/null @@ -1,224 +0,0 @@ -using System.Collections.Generic; -using System.Security.AccessControl; - -namespace System.IO.Abstractions -{ - [Serializable] - public class DirectoryWrapper : DirectoryBase - { - public override DirectoryInfoBase CreateDirectory(string path) - { - return Directory.CreateDirectory(path); - } - - public override DirectoryInfoBase CreateDirectory(string path, DirectorySecurity directorySecurity) - { - return Directory.CreateDirectory(path, directorySecurity); - } - - public override void Delete(string path) - { - Directory.Delete(path); - } - - public override void Delete(string path, bool recursive) - { - Directory.Delete(path, recursive); - } - - public override bool Exists(string path) - { - return Directory.Exists(path); - } - - public override DirectorySecurity GetAccessControl(string path) - { - return Directory.GetAccessControl(path); - } - - public override DirectorySecurity GetAccessControl(string path, AccessControlSections includeSections) - { - return Directory.GetAccessControl(path, includeSections); - } - - public override DateTime GetCreationTime(string path) - { - return Directory.GetCreationTime(path); - } - - public override DateTime GetCreationTimeUtc(string path) - { - return Directory.GetCreationTimeUtc(path); - } - - public override string GetCurrentDirectory() - { - return Directory.GetCurrentDirectory(); - } - - public override string[] GetDirectories(string path) - { - return Directory.GetDirectories(path); - } - - public override string[] GetDirectories(string path, string searchPattern) - { - return Directory.GetDirectories(path, searchPattern); - } - - public override string[] GetDirectories(string path, string searchPattern, SearchOption searchOption) - { - return Directory.GetDirectories(path, searchPattern, searchOption); - } - - public override string GetDirectoryRoot(string path) - { - return Directory.GetDirectoryRoot(path); - } - - public override string[] GetFiles(string path) - { - return Directory.GetFiles(path); - } - - public override string[] GetFiles(string path, string searchPattern) - { - return Directory.GetFiles(path, searchPattern); - } - - public override string[] GetFiles(string path, string searchPattern, SearchOption searchOption) - { - return Directory.GetFiles(path, searchPattern, searchOption); - } - - public override string[] GetFileSystemEntries(string path) - { - return Directory.GetFileSystemEntries(path); - } - - public override string[] GetFileSystemEntries(string path, string searchPattern) - { - return Directory.GetFileSystemEntries(path, searchPattern); - } - - public override DateTime GetLastAccessTime(string path) - { - return Directory.GetLastAccessTime(path); - } - - public override DateTime GetLastAccessTimeUtc(string path) - { - return Directory.GetLastAccessTimeUtc(path); - } - - public override DateTime GetLastWriteTime(string path) - { - return Directory.GetLastWriteTime(path); - } - - public override DateTime GetLastWriteTimeUtc(string path) - { - return Directory.GetLastWriteTimeUtc(path); - } - - public override string[] GetLogicalDrives() - { - return Directory.GetLogicalDrives(); - } - - public override DirectoryInfoBase GetParent(string path) - { - return Directory.GetParent(path); - } - - public override void Move(string sourceDirName, string destDirName) - { - Directory.Move(sourceDirName, destDirName); - } - - public override void SetAccessControl(string path, DirectorySecurity directorySecurity) - { - Directory.SetAccessControl(path, directorySecurity); - } - - public override void SetCreationTime(string path, DateTime creationTime) - { - Directory.SetCreationTime(path, creationTime); - } - - public override void SetCreationTimeUtc(string path, DateTime creationTimeUtc) - { - Directory.SetCreationTimeUtc(path, creationTimeUtc); - } - - public override void SetCurrentDirectory(string path) - { - Directory.SetCurrentDirectory(path); - } - - public override void SetLastAccessTime(string path, DateTime lastAccessTime) - { - Directory.SetLastAccessTime(path, lastAccessTime); - } - - public override void SetLastAccessTimeUtc(string path, DateTime lastAccessTimeUtc) - { - Directory.SetLastAccessTimeUtc(path, lastAccessTimeUtc); - } - - public override void SetLastWriteTime(string path, DateTime lastWriteTime) - { - Directory.SetLastAccessTime(path, lastWriteTime); - } - - public override void SetLastWriteTimeUtc(string path, DateTime lastWriteTimeUtc) - { - Directory.SetLastWriteTimeUtc(path, lastWriteTimeUtc); - } - - public override IEnumerable EnumerateDirectories(string path) - { - return Directory.EnumerateDirectories(path); - } - - public override IEnumerable EnumerateDirectories(string path, string searchPattern) - { - return Directory.EnumerateDirectories(path, searchPattern); - } - - public override IEnumerable EnumerateDirectories(string path, string searchPattern, SearchOption searchOption) - { - return Directory.EnumerateDirectories(path, searchPattern, searchOption); - } - - public override IEnumerable EnumerateFiles(string path) - { - return Directory.EnumerateFiles(path); - } - - public override IEnumerable EnumerateFiles(string path, string searchPattern) - { - return Directory.EnumerateFiles(path, searchPattern); - } - - public override IEnumerable EnumerateFiles(string path, string searchPattern, SearchOption searchOption) - { - return Directory.EnumerateFiles(path, searchPattern, searchOption); - } - - public override IEnumerable EnumerateFileSystemEntries(string path) - { - return Directory.EnumerateFileSystemEntries(path); - } - - public override IEnumerable EnumerateFileSystemEntries(string path, string searchPattern) - { - return Directory.EnumerateFileSystemEntries(path, searchPattern); - } - - public override IEnumerable EnumerateFileSystemEntries(string path, string searchPattern, SearchOption searchOption) - { - return Directory.EnumerateFileSystemEntries(path, searchPattern, searchOption); - } - } -} \ No newline at end of file diff --git a/System.IO.Abstractions/DriveInfoBase.cs b/System.IO.Abstractions/DriveInfoBase.cs deleted file mode 100644 index 7e80f3a96..000000000 --- a/System.IO.Abstractions/DriveInfoBase.cs +++ /dev/null @@ -1,124 +0,0 @@ -namespace System.IO.Abstractions -{ - [Serializable] - public abstract class DriveInfoBase - { - /// - /// Gets or sets the amount of available free space on a drive, in bytes. - /// - /// The amount of free space available on the drive, in bytes. - /// - /// This property indicates the amount of free space available on the drive. - /// Note that this number may be different from the TotalFreeSpace number because this property takes into account disk quotas. - /// - /// Thrown if the access to the drive information is denied. - /// Thrown if an I/O error occurred (for example, a disk error or a drive was not ready). - public virtual long AvailableFreeSpace { get; protected set; } - - /// - /// Gets or sets the name of the file system, such as NTFS or FAT32. - /// - /// - /// Use DriveFormat to determine what formatting a drive uses. - /// - /// The name of the file system on the specified drive. - /// Thrown if the access to the drive information is denied. - /// Thrown if the drive does not exist or is not mapped. - /// Thrown if an I/O error occurred (for example, a disk error or a drive was not ready). - public virtual string DriveFormat { get; protected set; } - - /// - /// Gets or sets the drive type, such as CD-ROM, removable, network, or fixed. - /// - /// One of the enumeration values that specifies a drive type. - /// - /// The DriveType property indicates whether a drive is one of the following: CDRom, Fixed, Network, NoRootDirectory, Ram, Removable, or Unknown. - /// These values are described in the DriveType enumeration. - /// - public virtual DriveType DriveType { get; protected set; } - - /// - /// Gets or sets a value indicating whether a drive is ready. - /// - /// - /// if the drive is ready; if the drive is not ready. - /// - /// - /// IsReady indicates whether a drive is ready. - /// For example, it indicates whether a CD is in a CD drive or whether a removable storage device is ready for read/write operations. - /// If you do not test whether a drive is ready, and it is not ready, querying the drive using will raise an IOException. - /// Do not rely on IsReady to avoid catching exceptions from other members such as TotalSize, TotalFreeSpace, and . - /// Between the time that your code checks IsReady and then accesses one of the other properties (even if the access occurs immediately after the check), - /// a drive may have been disconnected or a disk may have been removed. - /// - public virtual bool IsReady { get; protected set; } - - /// - /// Gets or sets the name of a drive, such as C:\. - /// - /// The name of the drive. - /// - /// This property is the name assigned to the drive, such as C:\ or E:\. - /// - public virtual string Name { get; protected set; } - - /// - /// Gets or sets the root directory of a drive. - /// - /// An object that contains the root directory of the drive. - public virtual DirectoryInfoBase RootDirectory { get; protected set; } - - /// - /// Gets or sets the total amount of free space available on a drive, in bytes. - /// - /// The total free space available on a drive, in bytes. - /// This property indicates the total amount of free space available on the drive, not just what is available to the current user. - /// Thrown if the access to the drive information is denied. - /// Thrown if the drive does not exist or is not mapped. - /// Thrown if an I/O error occurred (for example, a disk error or a drive was not ready). - public virtual long TotalFreeSpace { get; protected set; } - - /// - /// Gets or sets the total size of storage space on a drive, in bytes. - /// - /// The total size of the drive, in bytes. - /// - /// This property indicates the total size of the drive in bytes, not just what is available to the current user. - /// - /// Thrown if the access to the drive information is denied. - /// Thrown if the drive does not exist or is not mapped. - /// Thrown if an I/O error occurred (for example, a disk error or a drive was not ready). - public virtual long TotalSize { get; protected set; } - - /// - /// Gets or sets the volume label of a drive. - /// - /// The volume label. - /// - /// The label length is determined by the operating system. For example, NTFS allows a volume label to be up to 32 characters long. Note that is a valid VolumeLabel. - /// - /// Thrown if an I/O error occurred (for example, a disk error or a drive was not ready). - /// Thrown if the drive does not exist or is not mapped. - /// Thrown if the caller does not have the required permission. - /// - /// Thrown if the volume label is being set on a network or CD-ROM drive - /// -or- - /// Access to the drive information is denied. - /// - public virtual string VolumeLabel { get; set; } - - /// - /// Converts a into a . - /// - /// The drive info to be converted. - public static implicit operator DriveInfoBase(DriveInfo driveInfo) - { - if (driveInfo == null) - { - return null; - } - - return new DriveInfoWrapper(driveInfo); - } - } -} diff --git a/System.IO.Abstractions/DriveInfoFactory.cs b/System.IO.Abstractions/DriveInfoFactory.cs deleted file mode 100644 index 4bef25b00..000000000 --- a/System.IO.Abstractions/DriveInfoFactory.cs +++ /dev/null @@ -1,23 +0,0 @@ -namespace System.IO.Abstractions -{ - [Serializable] - internal class DriveInfoFactory : IDriveInfoFactory - { - /// - /// Retrieves the drive names of all logical drives on a computer. - /// - /// An array of type that represents the logical drives on a computer. - public DriveInfoBase[] GetDrives() - { - var driveInfos = DriveInfo.GetDrives(); - var driveInfoWrappers = new DriveInfoBase[driveInfos.Length]; - for (int index = 0; index < driveInfos.Length; index++) - { - var driveInfo = driveInfos[index]; - driveInfoWrappers[index] = new DriveInfoWrapper(driveInfo); - } - - return driveInfoWrappers; - } - } -} diff --git a/System.IO.Abstractions/DriveInfoWrapper.cs b/System.IO.Abstractions/DriveInfoWrapper.cs deleted file mode 100644 index e5b028093..000000000 --- a/System.IO.Abstractions/DriveInfoWrapper.cs +++ /dev/null @@ -1,166 +0,0 @@ -namespace System.IO.Abstractions -{ - /// - /// The wrapper for a . - /// - [Serializable] - public class DriveInfoWrapper : DriveInfoBase - { - /// - /// The instance of the real . - /// - private readonly DriveInfo instance; - - /// - /// Initializes a new instance of the class, which acts as a wrapper for a drive info. - /// - /// The drive info. - public DriveInfoWrapper(DriveInfo instance) - { - if (instance == null) - { - throw new ArgumentNullException("instance"); - } - - this.instance = instance; - } - - /// - /// Gets or sets the name of a drive, such as C:\. - /// - /// The name of the drive. - /// - /// This property is the name assigned to the drive, such as C:\ or E:\. - /// - public override string Name - { - get { return instance.Name; } - } - - /// - /// Gets or sets the drive type, such as CD-ROM, removable, network, or fixed. - /// - /// One of the enumeration values that specifies a drive type. - /// - /// The DriveType property indicates whether a drive is one of the following: CDRom, Fixed, Network, NoRootDirectory, Ram, Removable, or Unknown. - /// These values are described in the DriveType enumeration. - /// - public override DriveType DriveType - { - get { return instance.DriveType; } - } - - /// - /// Gets or sets the name of the file system, such as NTFS or FAT32. - /// - /// - /// Use DriveFormat to determine what formatting a drive uses. - /// - /// The name of the file system on the specified drive. - /// Thrown if the access to the drive information is denied. - /// Thrown if the drive does not exist or is not mapped. - /// Thrown if an I/O error occurred (for example, a disk error or a drive was not ready). - public override string DriveFormat - { - get { return instance.DriveFormat; } - } - - /// - /// Gets or sets a value indicating whether a drive is ready. - /// - /// - /// if the drive is ready; if the drive is not ready. - /// - /// - /// IsReady indicates whether a drive is ready. - /// For example, it indicates whether a CD is in a CD drive or whether a removable storage device is ready for read/write operations. - /// If you do not test whether a drive is ready, and it is not ready, querying the drive using will raise an IOException. - /// Do not rely on IsReady to avoid catching exceptions from other members such as TotalSize, TotalFreeSpace, and . - /// Between the time that your code checks IsReady and then accesses one of the other properties (even if the access occurs immediately after the check), - /// a drive may have been disconnected or a disk may have been removed. - /// - public override bool IsReady - { - get { return instance.IsReady; } - } - - /// - /// Gets or sets the amount of available free space on a drive, in bytes. - /// - /// The amount of free space available on the drive, in bytes. - /// - /// This property indicates the amount of free space available on the drive. - /// Note that this number may be different from the TotalFreeSpace number because this property takes into account disk quotas. - /// - /// Thrown if the access to the drive information is denied. - /// Thrown if an I/O error occurred (for example, a disk error or a drive was not ready). - public override long AvailableFreeSpace - { - get { return instance.AvailableFreeSpace; } - } - - /// - /// Gets or sets the total amount of free space available on a drive, in bytes. - /// - /// The total free space available on a drive, in bytes. - /// This property indicates the total amount of free space available on the drive, not just what is available to the current user. - /// Thrown if the access to the drive information is denied. - /// Thrown if the drive does not exist or is not mapped. - /// Thrown if an I/O error occurred (for example, a disk error or a drive was not ready). - public override long TotalFreeSpace - { - get { return instance.TotalFreeSpace; } - } - - /// - /// Gets or sets the total size of storage space on a drive, in bytes. - /// - /// The total size of the drive, in bytes. - /// - /// This property indicates the total size of the drive in bytes, not just what is available to the current user. - /// - /// Thrown if the access to the drive information is denied. - /// Thrown if the drive does not exist or is not mapped. - /// Thrown if an I/O error occurred (for example, a disk error or a drive was not ready). - public override long TotalSize - { - get { return instance.TotalSize; } - } - - /// - /// Gets or sets the root directory of a drive. - /// - /// An object that contains the root directory of the drive. - public override DirectoryInfoBase RootDirectory - { - get { return instance.RootDirectory; } - } - - /// - /// Gets or sets the volume label of a drive. - /// - /// The volume label. - /// - /// The label length is determined by the operating system. For example, NTFS allows a volume label to be up to 32 characters long. Note that is a valid VolumeLabel. - /// - /// Thrown if an I/O error occurred (for example, a disk error or a drive was not ready). - /// Thrown if the drive does not exist or is not mapped. - /// Thrown if the caller does not have the required permission. - /// - /// Thrown if the volume label is being set on a network or CD-ROM drive - /// -or- - /// Access to the drive information is denied. - /// - public override string VolumeLabel - { - get { return instance.VolumeLabel; } - - set { instance.VolumeLabel = value; } - } - - public override string ToString() - { - return instance.ToString(); - } - } -} diff --git a/System.IO.Abstractions/FileBase.cs b/System.IO.Abstractions/FileBase.cs deleted file mode 100644 index eb3c6bf3f..000000000 --- a/System.IO.Abstractions/FileBase.cs +++ /dev/null @@ -1,485 +0,0 @@ -using System.Collections.Generic; -using System.Security.AccessControl; -using System.Text; - -namespace System.IO.Abstractions -{ - [Serializable] - public abstract class FileBase - { - public abstract void AppendAllLines(string path, IEnumerable contents); - public abstract void AppendAllLines(string path, IEnumerable contents, Encoding encoding); - public abstract void AppendAllText(string path, string contents); - public abstract void AppendAllText(string path, string contents, Encoding encoding); - public abstract StreamWriter AppendText(string path); - public abstract void Copy(string sourceFileName, string destFileName); - public abstract void Copy(string sourceFileName, string destFileName, bool overwrite); - public abstract Stream Create(string path); - public abstract Stream Create(string path, int bufferSize); - public abstract Stream Create(string path, int bufferSize, FileOptions options); - public abstract Stream Create(string path, int bufferSize, FileOptions options, FileSecurity fileSecurity); - public abstract StreamWriter CreateText(string path); - public abstract void Decrypt(string path); - public abstract void Delete(string path); - public abstract void Encrypt(string path); - - /// - /// Determines whether the specified file exists. - /// - /// The file to check. - /// if the caller has the required permissions and path contains the name of an existing file; otherwise, . This method also returns if is , an invalid path, or a zero-length string. If the caller does not have sufficient permissions to read the specified file, no exception is thrown and the method returns regardless of the existence of . - /// - /// - /// The Exists method should not be used for path validation, this method merely checks if the file specified in exists. - /// Passing an invalid path to Exists returns . - /// - /// - /// Be aware that another process can potentially do something with the file in between the time you call the Exists method and perform another operation on the file, such as . - /// - /// - /// The parameter is permitted to specify relative or absolute path information. - /// Relative path information is interpreted as relative to the current working directory. - /// To obtain the current working directory, see . - /// - /// - /// If describes a directory, this method returns . Trailing spaces are removed from the parameter before determining if the file exists. - /// - /// - /// The Exists method returns if any error occurs while trying to determine if the specified file exists. - /// This can occur in situations that raise exceptions such as passing a file name with invalid characters or too many characters - /// a failing or missing disk, or if the caller does not have permission to read the file. - /// - /// - public abstract bool Exists(string path); - public abstract FileSecurity GetAccessControl(string path); - public abstract FileSecurity GetAccessControl(string path, AccessControlSections includeSections); - - /// - /// Gets the of the file on the path. - /// - /// The path to the file. - /// The of the file on the path. - /// is empty, contains only white spaces, or contains invalid characters. - /// The specified path, file name, or both exceed the system-defined maximum length. For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters. - /// is in an invalid format. - /// represents a file and is invalid, such as being on an unmapped drive, or the file cannot be found. - /// represents a directory and is invalid, such as being on an unmapped drive, or the directory cannot be found. - /// This file is being used by another process. - /// The caller does not have the required permission. - public abstract FileAttributes GetAttributes(string path); - - /// - /// Returns the creation date and time of the specified file or directory. - /// - /// The file or directory for which to obtain creation date and time information. - /// A structure set to the creation date and time for the specified file or directory. This value is expressed in local time. - /// The caller does not have the required permission. - /// is empty, contains only white spaces, or contains invalid characters. - /// is . - /// The specified path, file name, or both exceed the system-defined maximum length. For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters. - /// is in an invalid format. - /// - /// - /// The parameter is permitted to specify relative or absolute path information. Relative path information is interpreted as relative to the current working directory. To obtain the current working directory, see . - /// - /// - /// If the file described in the parameter does not exist, this method returns 12:00 midnight, January 1, 1601 A.D. (C.E.) Coordinated Universal Time (UTC), adjusted to local time. - /// - /// - /// NTFS-formatted drives may cache file meta-info, such as file creation time, for a short period of time, which is known as "file tunneling." As a result, it may be necessary to explicitly set the creation time of a file if you are overwriting or replacing an existing file. - /// - /// - public abstract DateTime GetCreationTime(string path); - - /// - /// Returns the creation date and time, in coordinated universal time (UTC), of the specified file or directory. - /// - /// The file or directory for which to obtain creation date and time information. - /// A structure set to the creation date and time for the specified file or directory. This value is expressed in UTC time. - /// The caller does not have the required permission. - /// is empty, contains only white spaces, or contains invalid characters. - /// is . - /// The specified path, file name, or both exceed the system-defined maximum length. For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters. - /// is in an invalid format. - /// - /// - /// The parameter is permitted to specify relative or absolute path information. Relative path information is interpreted as relative to the current working directory. To obtain the current working directory, see . - /// - /// - /// If the file described in the parameter does not exist, this method returns 12:00 midnight, January 1, 1601 A.D. (C.E.) Coordinated Universal Time (UTC). - /// - /// - /// NTFS-formatted drives may cache file meta-info, such as file creation time, for a short period of time, which is known as "file tunneling." As a result, it may be necessary to explicitly set the creation time of a file if you are overwriting or replacing an existing file. - /// - /// - public abstract DateTime GetCreationTimeUtc(string path); - - /// - /// Returns the date and time the specified file or directory was last accessed. - /// - /// The file or directory for which to obtain access date and time information. - /// A structure set to the date and time that the specified file or directory was last accessed. This value is expressed in local time. - /// The caller does not have the required permission. - /// is empty, contains only white spaces, or contains invalid characters. - /// is . - /// The specified path, file name, or both exceed the system-defined maximum length. For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters. - /// is in an invalid format. - /// - /// - /// The parameter is permitted to specify relative or absolute path information. Relative path information is interpreted as relative to the current working directory. To obtain the current working directory, see . - /// - /// - /// If the file described in the parameter does not exist, this method returns 12:00 midnight, January 1, 1601 A.D. (C.E.) Coordinated Universal Time (UTC), adjusted to local time. - /// - /// - /// NTFS-formatted drives may cache file meta-info, such as file creation time, for a short period of time, which is known as "file tunneling." As a result, it may be necessary to explicitly set the creation time of a file if you are overwriting or replacing an existing file. - /// - /// - public abstract DateTime GetLastAccessTime(string path); - - /// - /// Returns the date and time, in coordinated universal time (UTC), that the specified file or directory was last accessed. - /// - /// The file or directory for which to obtain creation date and time information. - /// A structure set to the date and time that the specified file or directory was last accessed. This value is expressed in UTC time. - /// The caller does not have the required permission. - /// is empty, contains only white spaces, or contains invalid characters. - /// is . - /// The specified path, file name, or both exceed the system-defined maximum length. For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters. - /// is in an invalid format. - /// - /// - /// The parameter is permitted to specify relative or absolute path information. Relative path information is interpreted as relative to the current working directory. To obtain the current working directory, see . - /// - /// - /// If the file described in the parameter does not exist, this method returns 12:00 midnight, January 1, 1601 A.D. (C.E.) Coordinated Universal Time (UTC). - /// - /// - /// NTFS-formatted drives may cache file meta-info, such as file creation time, for a short period of time, which is known as "file tunneling." As a result, it may be necessary to explicitly set the creation time of a file if you are overwriting or replacing an existing file. - /// - /// - public abstract DateTime GetLastAccessTimeUtc(string path); - - /// - /// Returns the date and time the specified file or directory was last written to. - /// - /// The file or directory for which to obtain creation date and time information. - /// A structure set to the date and time that the specified file or directory was last written to. This value is expressed in local time. - /// The caller does not have the required permission. - /// is empty, contains only white spaces, or contains invalid characters. - /// is . - /// The specified path, file name, or both exceed the system-defined maximum length. For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters. - /// is in an invalid format. - /// - /// - /// If the file described in the path parameter does not exist, this method returns 12:00 midnight, January 1, 1601 A.D. (C.E.) Coordinated Universal Time (UTC), adjusted to local time. - /// - /// - /// The parameter is permitted to specify relative or absolute path information. Relative path information is interpreted as relative to the current working directory. To obtain the current working directory, see . - /// - /// - /// NTFS-formatted drives may cache file meta-info, such as file creation time, for a short period of time, which is known as "file tunneling." As a result, it may be necessary to explicitly set the creation time of a file if you are overwriting or replacing an existing file. - /// - /// - public abstract DateTime GetLastWriteTime(string path); - - /// - /// Returns the date and time, in coordinated universal time (UTC), that the specified file or directory was last written to. - /// - /// The file or directory for which to obtain creation date and time information. - /// A structure set to the date and time that the specified file or directory was last written to. This value is expressed in local time. - /// The caller does not have the required permission. - /// is empty, contains only white spaces, or contains invalid characters. - /// is . - /// The specified path, file name, or both exceed the system-defined maximum length. For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters. - /// is in an invalid format. - /// - /// - /// If the file described in the path parameter does not exist, this method returns 12:00 midnight, January 1, 1601 A.D. (C.E.) Coordinated Universal Time (UTC). - /// - /// - /// The parameter is permitted to specify relative or absolute path information. Relative path information is interpreted as relative to the current working directory. To obtain the current working directory, see . - /// - /// - /// NTFS-formatted drives may cache file meta-info, such as file creation time, for a short period of time, which is known as "file tunneling." As a result, it may be necessary to explicitly set the creation time of a file if you are overwriting or replacing an existing file. - /// - /// - public abstract DateTime GetLastWriteTimeUtc(string path); - public abstract void Move(string sourceFileName, string destFileName); - public abstract Stream Open(string path, FileMode mode); - public abstract Stream Open(string path, FileMode mode, FileAccess access); - public abstract Stream Open(string path, FileMode mode, FileAccess access, FileShare share); - public abstract Stream OpenRead(string path); - public abstract StreamReader OpenText(string path); - public abstract Stream OpenWrite(string path); - public abstract byte[] ReadAllBytes(string path); - public abstract string[] ReadAllLines(string path); - public abstract string[] ReadAllLines(string path, Encoding encoding); - public abstract string ReadAllText(string path); - public abstract string ReadAllText(string path, Encoding encoding); - public abstract IEnumerable ReadLines(string path); - public abstract IEnumerable ReadLines(string path, Encoding encoding); - public abstract void Replace(string sourceFileName, string destinationFileName, string destinationBackupFileName); - public abstract void Replace(string sourceFileName, string destinationFileName, string destinationBackupFileName, bool ignoreMetadataErrors); - public abstract void SetAccessControl(string path, FileSecurity fileSecurity); - public abstract void SetAttributes(string path, FileAttributes fileAttributes); - public abstract void SetCreationTime(string path, DateTime creationTime); - public abstract void SetCreationTimeUtc(string path, DateTime creationTimeUtc); - public abstract void SetLastAccessTime(string path, DateTime lastAccessTime); - public abstract void SetLastAccessTimeUtc(string path, DateTime lastAccessTimeUtc); - public abstract void SetLastWriteTime(string path, DateTime lastWriteTime); - public abstract void SetLastWriteTimeUtc(string path, DateTime lastWriteTimeUtc); - - /// - /// Creates a new file, writes the specified byte array to the file, and then closes the file. - /// If the target file already exists, it is overwritten. - /// - /// The file to write to. - /// The bytes to write to the file. - /// is a zero-length string, contains only white space, or contains one or more invalid characters as defined by . - /// is or contents is empty. - /// - /// The specified path, file name, or both exceed the system-defined maximum length. - /// For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters. - /// - /// The specified path is invalid (for example, it is on an unmapped drive). - /// An I/O error occurred while opening the file. - /// - /// path specified a file that is read-only. - /// -or- - /// This operation is not supported on the current platform. - /// -or- - /// path specified a directory. - /// -or- - /// The caller does not have the required permission. - /// - /// The file specified in was not found. - /// is in an invalid format. - /// The caller does not have the required permission. - /// - /// Given a byte array and a file path, this method opens the specified file, writes the contents of the byte array to the file, and then closes the file. - /// - public abstract void WriteAllBytes(string path, byte[] bytes); - - /// - /// Creates a new file, writes a collection of strings to the file, and then closes the file. - /// - /// The file to write to. - /// The lines to write to the file. - /// is a zero-length string, contains only white space, or contains one or more invalid characters as defined by . - /// Either or is . - /// The specified path is invalid (for example, it is on an unmapped drive). - /// The file specified in was not found. - /// An I/O error occurred while opening the file. - /// - /// The specified path, file name, or both exceed the system-defined maximum length. - /// For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters. - /// - /// is in an invalid format. - /// The caller does not have the required permission. - /// - /// specified a file that is read-only. - /// -or- - /// This operation is not supported on the current platform. - /// -or- - /// specified a directory. - /// -or- - /// The caller does not have the required permission. - /// - /// - /// - /// If the target file already exists, it is overwritten. - /// - /// - /// You can use this method to create the contents for a collection class that takes an in its constructor, such as a , , or a class. - /// - /// - public abstract void WriteAllLines(string path, IEnumerable contents); - - /// - /// Creates a new file by using the specified encoding, writes a collection of strings to the file, and then closes the file. - /// - /// The file to write to. - /// The lines to write to the file. - /// The character encoding to use. - /// is a zero-length string, contains only white space, or contains one or more invalid characters as defined by . - /// Either , , or is . - /// The specified path is invalid (for example, it is on an unmapped drive). - /// The file specified in was not found. - /// An I/O error occurred while opening the file. - /// - /// The specified path, file name, or both exceed the system-defined maximum length. - /// For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters. - /// - /// is in an invalid format. - /// The caller does not have the required permission. - /// - /// specified a file that is read-only. - /// -or- - /// This operation is not supported on the current platform. - /// -or- - /// specified a directory. - /// -or- - /// The caller does not have the required permission. - /// - /// - /// - /// If the target file already exists, it is overwritten. - /// - /// - /// You can use this method to create a file that contains the following: - /// - /// - /// The results of a LINQ to Objects query on the lines of a file, as obtained by using the ReadLines method. - /// - /// - /// The contents of a collection that implements an of strings. - /// - /// - /// - /// - public abstract void WriteAllLines(string path, IEnumerable contents, Encoding encoding); - - /// - /// Creates a new file, writes the specified string array to the file by using the specified encoding, and then closes the file. - /// - /// The file to write to. - /// The string array to write to the file. - /// is a zero-length string, contains only white space, or contains one or more invalid characters as defined by . - /// Either or is . - /// - /// The specified path, file name, or both exceed the system-defined maximum length. - /// For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters. - /// - /// The specified path is invalid (for example, it is on an unmapped drive). - /// An I/O error occurred while opening the file. - /// - /// specified a file that is read-only. - /// -or- - /// This operation is not supported on the current platform. - /// -or- - /// specified a directory. - /// -or- - /// The caller does not have the required permission. - /// - /// The file specified in was not found. - /// is in an invalid format. - /// The caller does not have the required permission. - /// - /// - /// If the target file already exists, it is overwritten. - /// - /// - /// The default behavior of the WriteAllLines method is to write out data using UTF-8 encoding without a byte order mark (BOM). If it is necessary to include a UTF-8 identifier, such as a byte order mark, at the beginning of a file, use the method overload with encoding. - /// - /// - /// Given a string array and a file path, this method opens the specified file, writes the string array to the file using the specified encoding, - /// and then closes the file. - /// - /// - public abstract void WriteAllLines(string path, string[] contents); - - /// - /// Creates a new file, writes the specified string array to the file by using the specified encoding, and then closes the file. - /// - /// The file to write to. - /// The string array to write to the file. - /// An object that represents the character encoding applied to the string array. - /// is a zero-length string, contains only white space, or contains one or more invalid characters as defined by . - /// Either or is . - /// - /// The specified path, file name, or both exceed the system-defined maximum length. - /// For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters. - /// - /// The specified path is invalid (for example, it is on an unmapped drive). - /// An I/O error occurred while opening the file. - /// - /// specified a file that is read-only. - /// -or- - /// This operation is not supported on the current platform. - /// -or- - /// specified a directory. - /// -or- - /// The caller does not have the required permission. - /// - /// The file specified in was not found. - /// is in an invalid format. - /// The caller does not have the required permission. - /// - /// - /// If the target file already exists, it is overwritten. - /// - /// - /// Given a string array and a file path, this method opens the specified file, writes the string array to the file using the specified encoding, - /// and then closes the file. - /// - /// - public abstract void WriteAllLines(string path, string[] contents, Encoding encoding); - - /// - /// Creates a new file, writes the specified string to the file using the specified encoding, and then closes the file. If the target file already exists, it is overwritten. - /// - /// The file to write to. - /// The string to write to the file. - /// is a zero-length string, contains only white space, or contains one or more invalid characters as defined by . - /// is or contents is empty. - /// - /// The specified path, file name, or both exceed the system-defined maximum length. - /// For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters. - /// - /// The specified path is invalid (for example, it is on an unmapped drive). - /// An I/O error occurred while opening the file. - /// - /// path specified a file that is read-only. - /// -or- - /// This operation is not supported on the current platform. - /// -or- - /// path specified a directory. - /// -or- - /// The caller does not have the required permission. - /// - /// The file specified in was not found. - /// is in an invalid format. - /// The caller does not have the required permission. - /// - /// This method uses UTF-8 encoding without a Byte-Order Mark (BOM), so using the method will return an empty byte array. - /// If it is necessary to include a UTF-8 identifier, such as a byte order mark, at the beginning of a file, use the method overload with encoding. - /// - /// Given a string and a file path, this method opens the specified file, writes the string to the file, and then closes the file. - /// - /// - public abstract void WriteAllText(string path, string contents); - - /// - /// Creates a new file, writes the specified string to the file using the specified encoding, and then closes the file. If the target file already exists, it is overwritten. - /// - /// The file to write to. - /// The string to write to the file. - /// The encoding to apply to the string. - /// is a zero-length string, contains only white space, or contains one or more invalid characters as defined by . - /// is or contents is empty. - /// - /// The specified path, file name, or both exceed the system-defined maximum length. - /// For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters. - /// - /// The specified path is invalid (for example, it is on an unmapped drive). - /// An I/O error occurred while opening the file. - /// - /// path specified a file that is read-only. - /// -or- - /// This operation is not supported on the current platform. - /// -or- - /// path specified a directory. - /// -or- - /// The caller does not have the required permission. - /// - /// The file specified in was not found. - /// is in an invalid format. - /// The caller does not have the required permission. - /// - /// Given a string and a file path, this method opens the specified file, writes the string to the file using the specified encoding, and then closes the file. - /// The file handle is guaranteed to be closed by this method, even if exceptions are raised. - /// - public abstract void WriteAllText(string path, string contents, Encoding encoding); - } -} \ No newline at end of file diff --git a/System.IO.Abstractions/FileInfoBase.cs b/System.IO.Abstractions/FileInfoBase.cs deleted file mode 100644 index 31d31979c..000000000 --- a/System.IO.Abstractions/FileInfoBase.cs +++ /dev/null @@ -1,37 +0,0 @@ -using System.Security.AccessControl; - -namespace System.IO.Abstractions -{ - [Serializable] - public abstract class FileInfoBase : FileSystemInfoBase - { - public abstract StreamWriter AppendText(); - public abstract FileInfoBase CopyTo(string destFileName); - public abstract FileInfoBase CopyTo(string destFileName, bool overwrite); - public abstract Stream Create(); - public abstract StreamWriter CreateText(); - public abstract void Decrypt(); - public abstract void Encrypt(); - public abstract FileSecurity GetAccessControl(); - public abstract FileSecurity GetAccessControl(AccessControlSections includeSections); - public abstract void MoveTo(string destFileName); - public abstract Stream Open(FileMode mode); - public abstract Stream Open(FileMode mode, FileAccess access); - public abstract Stream Open(FileMode mode, FileAccess access, FileShare share); - public abstract Stream OpenRead(); - public abstract StreamReader OpenText(); - public abstract Stream OpenWrite(); - public abstract FileInfoBase Replace(string destinationFileName, string destinationBackupFileName); - public abstract FileInfoBase Replace(string destinationFileName, string destinationBackupFileName, bool ignoreMetadataErrors); - public abstract void SetAccessControl(FileSecurity fileSecurity); - public abstract DirectoryInfoBase Directory { get; } - public abstract string DirectoryName { get; } - public abstract bool IsReadOnly { get; set; } - public abstract long Length { get; } - - public static implicit operator FileInfoBase(FileInfo fileInfo) - { - return new FileInfoWrapper(fileInfo); - } - } -} \ No newline at end of file diff --git a/System.IO.Abstractions/FileInfoFactory.cs b/System.IO.Abstractions/FileInfoFactory.cs deleted file mode 100644 index e34449dd9..000000000 --- a/System.IO.Abstractions/FileInfoFactory.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace System.IO.Abstractions -{ - [Serializable] - internal class FileInfoFactory : IFileInfoFactory - { - public FileInfoBase FromFileName(string fileName) - { - var realFileInfo = new FileInfo(fileName); - return new FileInfoWrapper(realFileInfo); - } - } -} \ No newline at end of file diff --git a/System.IO.Abstractions/FileInfoWrapper.cs b/System.IO.Abstractions/FileInfoWrapper.cs deleted file mode 100644 index 2660723d1..000000000 --- a/System.IO.Abstractions/FileInfoWrapper.cs +++ /dev/null @@ -1,208 +0,0 @@ -using System.Security.AccessControl; - -namespace System.IO.Abstractions -{ - [Serializable] - public class FileInfoWrapper : FileInfoBase - { - private readonly FileInfo instance; - - public FileInfoWrapper(FileInfo instance) - { - if (instance == null) - { - throw new ArgumentNullException("instance"); - } - - this.instance = instance; - } - - public override void Delete() - { - instance.Delete(); - } - - public override void Refresh() - { - instance.Refresh(); - } - - public override FileAttributes Attributes - { - get { return instance.Attributes; } - set { instance.Attributes = value; } - } - - public override DateTime CreationTime - { - get { return instance.CreationTime; } - set { instance.CreationTime = value; } - } - - public override DateTime CreationTimeUtc - { - get { return instance.CreationTimeUtc; } - set { instance.CreationTimeUtc = value; } - } - - public override bool Exists - { - get { return instance.Exists; } - } - - public override string Extension - { - get { return instance.Extension; } - } - - public override string FullName - { - get { return instance.FullName; } - } - - public override DateTime LastAccessTime - { - get { return instance.LastAccessTime; } - set { instance.LastAccessTime = value; } - } - - public override DateTime LastAccessTimeUtc - { - get { return instance.LastAccessTimeUtc; } - set { instance.LastAccessTimeUtc = value; } - } - - public override DateTime LastWriteTime - { - get { return instance.LastWriteTime; } - set { instance.LastWriteTime = value; } - } - - public override DateTime LastWriteTimeUtc - { - get { return instance.LastWriteTimeUtc; } - set { instance.LastWriteTimeUtc = value; } - } - - public override string Name - { - get { return instance.Name; } - } - - public override StreamWriter AppendText() - { - return instance.AppendText(); - } - - public override FileInfoBase CopyTo(string destFileName) - { - return instance.CopyTo(destFileName); - } - - public override FileInfoBase CopyTo(string destFileName, bool overwrite) - { - return instance.CopyTo(destFileName, overwrite); - } - - public override Stream Create() - { - return instance.Create(); - } - - public override StreamWriter CreateText() - { - return instance.CreateText(); - } - - public override void Decrypt() - { - instance.Decrypt(); - } - - public override void Encrypt() - { - instance.Encrypt(); - } - - public override FileSecurity GetAccessControl() - { - return instance.GetAccessControl(); - } - - public override FileSecurity GetAccessControl(AccessControlSections includeSections) - { - return instance.GetAccessControl(includeSections); - } - - public override void MoveTo(string destFileName) - { - instance.MoveTo(destFileName); - } - - public override Stream Open(FileMode mode) - { - return instance.Open(mode); - } - - public override Stream Open(FileMode mode, FileAccess access) - { - return instance.Open(mode, access); - } - - public override Stream Open(FileMode mode, FileAccess access, FileShare share) - { - return instance.Open(mode, access, share); - } - - public override Stream OpenRead() - { - return instance.OpenRead(); - } - - public override StreamReader OpenText() - { - return instance.OpenText(); - } - - public override Stream OpenWrite() - { - return instance.OpenWrite(); - } - - public override FileInfoBase Replace(string destinationFileName, string destinationBackupFileName) - { - return instance.Replace(destinationFileName, destinationBackupFileName); - } - - public override FileInfoBase Replace(string destinationFileName, string destinationBackupFileName, bool ignoreMetadataErrors) - { - return instance.Replace(destinationFileName, destinationBackupFileName, ignoreMetadataErrors); - } - - public override void SetAccessControl(FileSecurity fileSecurity) - { - instance.SetAccessControl(fileSecurity); - } - - public override DirectoryInfoBase Directory - { - get { return instance.Directory; } - } - - public override string DirectoryName - { - get { return instance.DirectoryName; } - } - - public override bool IsReadOnly - { - get { return instance.IsReadOnly; } - set { instance.IsReadOnly = value; } - } - - public override long Length - { - get { return instance.Length; } - } - } -} \ No newline at end of file diff --git a/System.IO.Abstractions/FileSystem.cs b/System.IO.Abstractions/FileSystem.cs deleted file mode 100644 index 28f3a77c5..000000000 --- a/System.IO.Abstractions/FileSystem.cs +++ /dev/null @@ -1,43 +0,0 @@ -namespace System.IO.Abstractions -{ - [Serializable] - public class FileSystem : IFileSystem - { - DirectoryBase directory; - public DirectoryBase Directory - { - get { return directory ?? (directory = new DirectoryWrapper()); } - } - - FileBase file; - public FileBase File - { - get { return file ?? (file = new FileWrapper()); } - } - - FileInfoFactory fileInfoFactory; - public IFileInfoFactory FileInfo - { - get { return fileInfoFactory ?? (fileInfoFactory = new FileInfoFactory()); } - } - - PathBase path; - public PathBase Path - { - get { return path ?? (path = new PathWrapper()); } - } - - DirectoryInfoFactory directoryInfoFactory; - public IDirectoryInfoFactory DirectoryInfo - { - get { return directoryInfoFactory ?? (directoryInfoFactory = new DirectoryInfoFactory()); } - } - - private readonly Lazy driveInfoFactory = new Lazy(() => new DriveInfoFactory()); - - public IDriveInfoFactory DriveInfo - { - get { return driveInfoFactory.Value; } - } - } -} \ No newline at end of file diff --git a/System.IO.Abstractions/FileSystemInfoBase.cs b/System.IO.Abstractions/FileSystemInfoBase.cs deleted file mode 100644 index 28e81dd76..000000000 --- a/System.IO.Abstractions/FileSystemInfoBase.cs +++ /dev/null @@ -1,20 +0,0 @@ -namespace System.IO.Abstractions -{ - [Serializable] - public abstract class FileSystemInfoBase - { - public abstract void Delete(); - public abstract void Refresh(); - public abstract FileAttributes Attributes { get; set; } - public abstract DateTime CreationTime { get; set; } - public abstract DateTime CreationTimeUtc { get; set; } - public abstract bool Exists { get; } - public abstract string Extension { get; } - public abstract string FullName { get; } - public abstract DateTime LastAccessTime { get; set; } - public abstract DateTime LastAccessTimeUtc { get; set; } - public abstract DateTime LastWriteTime { get; set; } - public abstract DateTime LastWriteTimeUtc { get; set; } - public abstract string Name { get; } - } -} \ No newline at end of file diff --git a/System.IO.Abstractions/FileSystemWatcherBase.cs b/System.IO.Abstractions/FileSystemWatcherBase.cs deleted file mode 100644 index 474425566..000000000 --- a/System.IO.Abstractions/FileSystemWatcherBase.cs +++ /dev/null @@ -1,93 +0,0 @@ -using System.ComponentModel; - -namespace System.IO.Abstractions -{ - [Serializable] - public abstract class FileSystemWatcherBase : IDisposable - { - public abstract bool IncludeSubdirectories { get; set; } - public abstract bool EnableRaisingEvents { get; set; } - public abstract string Filter { get; set; } - public abstract int InternalBufferSize { get; set; } - public abstract NotifyFilters NotifyFilter { get; set; } - public abstract string Path { get; set; } - public abstract ISite Site { get; set; } - public abstract ISynchronizeInvoke SynchronizingObject { get; set; } - public virtual event FileSystemEventHandler Changed; - public virtual event FileSystemEventHandler Created; - public virtual event FileSystemEventHandler Deleted; - public virtual event ErrorEventHandler Error; - public virtual event RenamedEventHandler Renamed; - public abstract void BeginInit(); - - public void Dispose() - { - Dispose(true); - GC.SuppressFinalize(this); - } - - public abstract void EndInit(); - public abstract WaitForChangedResult WaitForChanged(WatcherChangeTypes changeType); - public abstract WaitForChangedResult WaitForChanged(WatcherChangeTypes changeType, int timeout); - - public static implicit operator FileSystemWatcherBase(FileSystemWatcher watcher) - { - if (watcher == null) - { - throw new ArgumentNullException("watcher"); - } - - return new FileSystemWatcherWrapper(watcher); - } - - public virtual void Dispose(bool disposing) - { - // do nothing - } - - protected void OnCreated(object sender, FileSystemEventArgs args) - { - var onCreated = Created; - if (onCreated != null) - { - onCreated(sender, args); - } - } - - protected void OnChanged(object sender, FileSystemEventArgs args) - { - var onChanged = Changed; - if (onChanged != null) - { - onChanged(sender, args); - } - } - - protected void OnDeleted(object sender, FileSystemEventArgs args) - { - var onDeleted = Deleted; - if (onDeleted != null) - { - onDeleted(sender, args); - } - } - - protected void OnRenamed(object sender, RenamedEventArgs args) - { - var onRenamed = Renamed; - if (onRenamed != null) - { - onRenamed(sender, args); - } - } - - protected void OnError(object sender, ErrorEventArgs args) - { - var onError = Error; - if (onError != null) - { - onError(sender, args); - } - } - } -} diff --git a/System.IO.Abstractions/FileSystemWatcherWrapper.cs b/System.IO.Abstractions/FileSystemWatcherWrapper.cs deleted file mode 100644 index a3c24dfd0..000000000 --- a/System.IO.Abstractions/FileSystemWatcherWrapper.cs +++ /dev/null @@ -1,127 +0,0 @@ -using System.ComponentModel; - -namespace System.IO.Abstractions -{ - [Serializable] - public class FileSystemWatcherWrapper : FileSystemWatcherBase - { - [NonSerialized] - private readonly FileSystemWatcher watcher; - - public FileSystemWatcherWrapper() - : this(new FileSystemWatcher()) - { - // do nothing - } - - public FileSystemWatcherWrapper(string path) - : this(new FileSystemWatcher(path)) - { - // do nothing - } - - public FileSystemWatcherWrapper(string path, string filter) - : this(new FileSystemWatcher(path, filter)) - { - // do nothing - } - - public FileSystemWatcherWrapper(FileSystemWatcher watcher) - { - if (watcher == null) - { - throw new ArgumentNullException("watcher"); - } - - this.watcher = watcher; - this.watcher.Created += OnCreated; - this.watcher.Changed += OnChanged; - this.watcher.Deleted += OnDeleted; - this.watcher.Error += OnError; - this.watcher.Renamed += OnRenamed; - } - - public override bool IncludeSubdirectories - { - get { return watcher.IncludeSubdirectories; } - set { watcher.IncludeSubdirectories = value; } - } - - public override bool EnableRaisingEvents - { - get { return watcher.EnableRaisingEvents; } - set { watcher.EnableRaisingEvents = value; } - } - - public override string Filter - { - get { return watcher.Filter; } - set { watcher.Filter = value; } - } - - public override int InternalBufferSize - { - get { return watcher.InternalBufferSize; } - set { watcher.InternalBufferSize = value; } - } - - public override NotifyFilters NotifyFilter - { - get { return watcher.NotifyFilter; } - set { watcher.NotifyFilter = value; } - } - - public override string Path - { - get { return watcher.Path; } - set { watcher.Path = value; } - } - - public override ISite Site - { - get { return watcher.Site; } - set { watcher.Site = value; } - } - - public override ISynchronizeInvoke SynchronizingObject - { - get { return watcher.SynchronizingObject; } - set { watcher.SynchronizingObject = value; } - } - - public override void BeginInit() - { - watcher.BeginInit(); - } - - public override void Dispose(bool disposing) - { - if (disposing) - { - watcher.Created -= OnCreated; - watcher.Changed -= OnChanged; - watcher.Deleted -= OnDeleted; - watcher.Error -= OnError; - watcher.Renamed -= OnRenamed; - watcher.Dispose(); - } - - base.Dispose(disposing); - } - - public override void EndInit() - { - watcher.EndInit(); - } - - public override WaitForChangedResult WaitForChanged(WatcherChangeTypes changeType) - { - return watcher.WaitForChanged(changeType); - } - - public override WaitForChangedResult WaitForChanged(WatcherChangeTypes changeType, int timeout) - { - return watcher.WaitForChanged(changeType, timeout); - } - } -} diff --git a/System.IO.Abstractions/FileWrapper.cs b/System.IO.Abstractions/FileWrapper.cs deleted file mode 100644 index 10e1eed5f..000000000 --- a/System.IO.Abstractions/FileWrapper.cs +++ /dev/null @@ -1,540 +0,0 @@ -using System.Collections.Generic; -using System.Security.AccessControl; -using System.Text; - -namespace System.IO.Abstractions -{ - [Serializable] - public class FileWrapper : FileBase - { - public override void AppendAllLines(string path, IEnumerable contents) - { - File.AppendAllLines(path, contents); - } - - public override void AppendAllLines(string path, IEnumerable contents, Encoding encoding) - { - File.AppendAllLines(path, contents, encoding); - } - - public override void AppendAllText(string path, string contents) - { - File.AppendAllText(path, contents); - } - - public override void AppendAllText(string path, string contents, Encoding encoding) - { - File.AppendAllText(path, contents, encoding); - } - - public override StreamWriter AppendText(string path) - { - return File.AppendText(path); - } - - public override void Copy(string sourceFileName, string destFileName) - { - File.Copy(sourceFileName, destFileName); - } - - public override void Copy(string sourceFileName, string destFileName, bool overwrite) - { - File.Copy(sourceFileName, destFileName, overwrite); - } - - public override Stream Create(string path) - { - return File.Create(path); - } - - public override Stream Create(string path, int bufferSize) - { - return File.Create(path, bufferSize); - } - - public override Stream Create(string path, int bufferSize, FileOptions options) - { - return File.Create(path, bufferSize, options); - } - - public override Stream Create(string path, int bufferSize, FileOptions options, FileSecurity fileSecurity) - { - return File.Create(path, bufferSize, options, fileSecurity); - } - - public override StreamWriter CreateText(string path) - { - return File.CreateText(path); - } - - public override void Decrypt(string path) - { - File.Decrypt(path); - } - - public override void Delete(string path) - { - File.Delete(path); - } - - public override void Encrypt(string path) - { - File.Encrypt(path); - } - - public override bool Exists(string path) - { - return File.Exists(path); - } - - public override FileSecurity GetAccessControl(string path) - { - return File.GetAccessControl(path); - } - - public override FileSecurity GetAccessControl(string path, AccessControlSections includeSections) - { - return File.GetAccessControl(path, includeSections); - } - - /// - /// Gets the of the file on the path. - /// - /// The path to the file. - /// The of the file on the path. - /// is empty, contains only white spaces, or contains invalid characters. - /// The specified path, file name, or both exceed the system-defined maximum length. For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters. - /// is in an invalid format. - /// represents a file and is invalid, such as being on an unmapped drive, or the file cannot be found. - /// represents a directory and is invalid, such as being on an unmapped drive, or the directory cannot be found. - /// This file is being used by another process. - /// The caller does not have the required permission. - public override FileAttributes GetAttributes(string path) - { - return File.GetAttributes(path); - } - - public override DateTime GetCreationTime(string path) - { - return File.GetCreationTime(path); - } - - public override DateTime GetCreationTimeUtc(string path) - { - return File.GetCreationTimeUtc(path); - } - - public override DateTime GetLastAccessTime(string path) - { - return File.GetLastAccessTime(path); - } - - public override DateTime GetLastAccessTimeUtc(string path) - { - return File.GetLastAccessTimeUtc(path); - } - - public override DateTime GetLastWriteTime(string path) - { - return File.GetLastWriteTime(path); - } - - public override DateTime GetLastWriteTimeUtc(string path) - { - return File.GetLastWriteTimeUtc(path); - } - - public override void Move(string sourceFileName, string destFileName) - { - File.Move(sourceFileName, destFileName); - } - - public override Stream Open(string path, FileMode mode) - { - return File.Open(path, mode); - } - - public override Stream Open(string path, FileMode mode, FileAccess access) - { - return File.Open(path, mode, access); - } - - public override Stream Open(string path, FileMode mode, FileAccess access, FileShare share) - { - return File.Open(path, mode, access, share); - } - - public override Stream OpenRead(string path) - { - return File.OpenRead(path); - } - - public override StreamReader OpenText(string path) - { - return File.OpenText(path); - } - - public override Stream OpenWrite(string path) - { - return File.OpenWrite(path); - } - - public override byte[] ReadAllBytes(string path) - { - return File.ReadAllBytes(path); - } - - public override string[] ReadAllLines(string path) - { - return File.ReadAllLines(path); - } - - public override string[] ReadAllLines(string path, Encoding encoding) - { - return File.ReadAllLines(path, encoding); - } - - public override string ReadAllText(string path) - { - return File.ReadAllText(path); - } - - public override string ReadAllText(string path, Encoding encoding) - { - return File.ReadAllText(path, encoding); - } - - public override IEnumerable ReadLines(string path) - { - return File.ReadLines(path); - } - - public override IEnumerable ReadLines(string path, Encoding encoding) - { - return File.ReadLines(path, encoding); - } - - public override void Replace(string sourceFileName, string destinationFileName, string destinationBackupFileName) - { - File.Replace(sourceFileName, destinationFileName, destinationBackupFileName); - } - - public override void Replace(string sourceFileName, string destinationFileName, string destinationBackupFileName, bool ignoreMetadataErrors) - { - File.Replace(sourceFileName, destinationFileName, destinationBackupFileName, ignoreMetadataErrors); - } - - public override void SetAccessControl(string path, FileSecurity fileSecurity) - { - File.SetAccessControl(path, fileSecurity); - } - - public override void SetAttributes(string path, FileAttributes fileAttributes) - { - File.SetAttributes(path, fileAttributes); - } - - public override void SetCreationTime(string path, DateTime creationTime) - { - File.SetCreationTime(path, creationTime); - } - - public override void SetCreationTimeUtc(string path, DateTime creationTimeUtc) - { - File.SetCreationTimeUtc(path, creationTimeUtc); - } - - public override void SetLastAccessTime(string path, DateTime lastAccessTime) - { - File.SetLastAccessTime(path, lastAccessTime); - } - - public override void SetLastAccessTimeUtc(string path, DateTime lastAccessTimeUtc) - { - File.SetLastAccessTimeUtc(path, lastAccessTimeUtc); - } - - public override void SetLastWriteTime(string path, DateTime lastWriteTime) - { - File.SetLastWriteTime(path, lastWriteTime); - } - - public override void SetLastWriteTimeUtc(string path, DateTime lastWriteTimeUtc) - { - File.SetLastWriteTimeUtc(path, lastWriteTimeUtc); - } - - /// - /// Creates a new file, writes the specified byte array to the file, and then closes the file. - /// If the target file already exists, it is overwritten. - /// - /// The file to write to. - /// The bytes to write to the file. - /// is a zero-length string, contains only white space, or contains one or more invalid characters as defined by . - /// is or contents is empty. - /// - /// The specified path, file name, or both exceed the system-defined maximum length. - /// For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters. - /// - /// The specified path is invalid (for example, it is on an unmapped drive). - /// An I/O error occurred while opening the file. - /// - /// path specified a file that is read-only. - /// -or- - /// This operation is not supported on the current platform. - /// -or- - /// path specified a directory. - /// -or- - /// The caller does not have the required permission. - /// - /// The file specified in was not found. - /// is in an invalid format. - /// The caller does not have the required permission. - /// - /// Given a byte array and a file path, this method opens the specified file, writes the contents of the byte array to the file, and then closes the file. - /// - public override void WriteAllBytes(string path, byte[] bytes) - { - File.WriteAllBytes(path, bytes); - } - - /// - /// Creates a new file, writes a collection of strings to the file, and then closes the file. - /// - /// The file to write to. - /// The lines to write to the file. - /// is a zero-length string, contains only white space, or contains one or more invalid characters as defined by . - /// Either or is . - /// The specified path is invalid (for example, it is on an unmapped drive). - /// The file specified in was not found. - /// An I/O error occurred while opening the file. - /// - /// The specified path, file name, or both exceed the system-defined maximum length. - /// For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters. - /// - /// is in an invalid format. - /// The caller does not have the required permission. - /// - /// specified a file that is read-only. - /// -or- - /// This operation is not supported on the current platform. - /// -or- - /// specified a directory. - /// -or- - /// The caller does not have the required permission. - /// - /// - /// - /// If the target file already exists, it is overwritten. - /// - /// - /// You can use this method to create the contents for a collection class that takes an in its constructor, such as a , , or a class. - /// - /// - public override void WriteAllLines(string path, IEnumerable contents) - { - File.WriteAllLines(path, contents); - } - - /// - /// Creates a new file by using the specified encoding, writes a collection of strings to the file, and then closes the file. - /// - /// The file to write to. - /// The lines to write to the file. - /// The character encoding to use. - /// is a zero-length string, contains only white space, or contains one or more invalid characters as defined by . - /// Either , , or is . - /// The specified path is invalid (for example, it is on an unmapped drive). - /// The file specified in was not found. - /// An I/O error occurred while opening the file. - /// - /// The specified path, file name, or both exceed the system-defined maximum length. - /// For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters. - /// - /// is in an invalid format. - /// The caller does not have the required permission. - /// - /// specified a file that is read-only. - /// -or- - /// This operation is not supported on the current platform. - /// -or- - /// specified a directory. - /// -or- - /// The caller does not have the required permission. - /// - /// - /// - /// If the target file already exists, it is overwritten. - /// - /// - /// You can use this method to create a file that contains the following: - /// - /// - /// The results of a LINQ to Objects query on the lines of a file, as obtained by using the ReadLines method. - /// - /// - /// The contents of a collection that implements an of strings. - /// - /// - /// - /// - public override void WriteAllLines(string path, IEnumerable contents, Encoding encoding) - { - File.WriteAllLines(path, contents, encoding); - } - - /// - /// Creates a new file, writes the specified string array to the file by using the specified encoding, and then closes the file. - /// - /// The file to write to. - /// The string array to write to the file. - /// is a zero-length string, contains only white space, or contains one or more invalid characters as defined by . - /// Either or is . - /// - /// The specified path, file name, or both exceed the system-defined maximum length. - /// For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters. - /// - /// The specified path is invalid (for example, it is on an unmapped drive). - /// An I/O error occurred while opening the file. - /// - /// specified a file that is read-only. - /// -or- - /// This operation is not supported on the current platform. - /// -or- - /// specified a directory. - /// -or- - /// The caller does not have the required permission. - /// - /// The file specified in was not found. - /// is in an invalid format. - /// The caller does not have the required permission. - /// - /// - /// If the target file already exists, it is overwritten. - /// - /// - /// The default behavior of the WriteAllLines method is to write out data using UTF-8 encoding without a byte order mark (BOM). If it is necessary to include a UTF-8 identifier, such as a byte order mark, at the beginning of a file, use the method overload with encoding. - /// - /// - /// Given a string array and a file path, this method opens the specified file, writes the string array to the file using the specified encoding, - /// and then closes the file. - /// - /// - public override void WriteAllLines(string path, string[] contents) - { - File.WriteAllLines(path, contents); - } - - /// - /// Creates a new file, writes the specified string array to the file by using the specified encoding, and then closes the file. - /// - /// The file to write to. - /// The string array to write to the file. - /// An object that represents the character encoding applied to the string array. - /// is a zero-length string, contains only white space, or contains one or more invalid characters as defined by . - /// Either or is . - /// - /// The specified path, file name, or both exceed the system-defined maximum length. - /// For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters. - /// - /// The specified path is invalid (for example, it is on an unmapped drive). - /// An I/O error occurred while opening the file. - /// - /// specified a file that is read-only. - /// -or- - /// This operation is not supported on the current platform. - /// -or- - /// specified a directory. - /// -or- - /// The caller does not have the required permission. - /// - /// The file specified in was not found. - /// is in an invalid format. - /// The caller does not have the required permission. - /// - /// - /// If the target file already exists, it is overwritten. - /// - /// - /// Given a string array and a file path, this method opens the specified file, writes the string array to the file using the specified encoding, - /// and then closes the file. - /// - /// - public override void WriteAllLines(string path, string[] contents, Encoding encoding) - { - File.WriteAllLines(path, contents, encoding); - } - - /// - /// Creates a new file, writes the specified string to the file using the specified encoding, and then closes the file. If the target file already exists, it is overwritten. - /// - /// The file to write to. - /// The string to write to the file. - /// is a zero-length string, contains only white space, or contains one or more invalid characters as defined by . - /// is or contents is empty. - /// - /// The specified path, file name, or both exceed the system-defined maximum length. - /// For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters. - /// - /// The specified path is invalid (for example, it is on an unmapped drive). - /// An I/O error occurred while opening the file. - /// - /// path specified a file that is read-only. - /// -or- - /// This operation is not supported on the current platform. - /// -or- - /// path specified a directory. - /// -or- - /// The caller does not have the required permission. - /// - /// The file specified in was not found. - /// is in an invalid format. - /// The caller does not have the required permission. - /// - /// This method uses UTF-8 encoding without a Byte-Order Mark (BOM), so using the method will return an empty byte array. - /// If it is necessary to include a UTF-8 identifier, such as a byte order mark, at the beginning of a file, use the method overload with encoding. - /// - /// Given a string and a file path, this method opens the specified file, writes the string to the file, and then closes the file. - /// - /// - public override void WriteAllText(string path, string contents) - { - File.WriteAllText(path, contents); - } - - /// - /// Creates a new file, writes the specified string to the file using the specified encoding, and then closes the file. If the target file already exists, it is overwritten. - /// - /// The file to write to. - /// The string to write to the file. - /// The encoding to apply to the string. - /// is a zero-length string, contains only white space, or contains one or more invalid characters as defined by . - /// is or contents is empty. - /// - /// The specified path, file name, or both exceed the system-defined maximum length. - /// For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters. - /// - /// The specified path is invalid (for example, it is on an unmapped drive). - /// An I/O error occurred while opening the file. - /// - /// path specified a file that is read-only. - /// -or- - /// This operation is not supported on the current platform. - /// -or- - /// path specified a directory. - /// -or- - /// The caller does not have the required permission. - /// - /// The file specified in was not found. - /// is in an invalid format. - /// The caller does not have the required permission. - /// - /// Given a string and a file path, this method opens the specified file, writes the string to the file using the specified encoding, and then closes the file. - /// The file handle is guaranteed to be closed by this method, even if exceptions are raised. - /// - public override void WriteAllText(string path, string contents, Encoding encoding) - { - File.WriteAllText(path, contents, encoding); - } - } -} \ No newline at end of file diff --git a/System.IO.Abstractions/IDirectoryInfoFactory.cs b/System.IO.Abstractions/IDirectoryInfoFactory.cs deleted file mode 100644 index 9f6e9e32e..000000000 --- a/System.IO.Abstractions/IDirectoryInfoFactory.cs +++ /dev/null @@ -1,11 +0,0 @@ -namespace System.IO.Abstractions -{ - public interface IDirectoryInfoFactory - { - /// - /// Initializes a new instance of the class, which acts as a wrapper for a directory path. - /// - /// The fully qualified name of the new directory, or the relative directory name. - DirectoryInfoBase FromDirectoryName(string directoryName); - } -} \ No newline at end of file diff --git a/System.IO.Abstractions/IDriveInfoFactory.cs b/System.IO.Abstractions/IDriveInfoFactory.cs deleted file mode 100644 index cd3856af2..000000000 --- a/System.IO.Abstractions/IDriveInfoFactory.cs +++ /dev/null @@ -1,14 +0,0 @@ -namespace System.IO.Abstractions -{ - /// - /// A factory to create all for a . - /// - public interface IDriveInfoFactory - { - /// - /// Retrieves the drive names of all logical drives on a computer. - /// - /// An array of type that represents the logical drives on a computer. - DriveInfoBase[] GetDrives(); - } -} diff --git a/System.IO.Abstractions/IFileInfoFactory.cs b/System.IO.Abstractions/IFileInfoFactory.cs deleted file mode 100644 index aeeeded04..000000000 --- a/System.IO.Abstractions/IFileInfoFactory.cs +++ /dev/null @@ -1,11 +0,0 @@ -namespace System.IO.Abstractions -{ - public interface IFileInfoFactory - { - /// - /// Initializes a new instance of the class, which acts as a wrapper for a file path. - /// - /// The fully qualified name of the new file, or the relative file name. - FileInfoBase FromFileName(string fileName); - } -} \ No newline at end of file diff --git a/System.IO.Abstractions/IFileSystem.cs b/System.IO.Abstractions/IFileSystem.cs deleted file mode 100644 index 3d875e1cc..000000000 --- a/System.IO.Abstractions/IFileSystem.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace System.IO.Abstractions -{ - public interface IFileSystem - { - FileBase File { get; } - DirectoryBase Directory { get; } - IFileInfoFactory FileInfo { get; } - PathBase Path { get; } - IDirectoryInfoFactory DirectoryInfo { get; } - IDriveInfoFactory DriveInfo { get; } - } -} \ No newline at end of file diff --git a/System.IO.Abstractions/PathBase.cs b/System.IO.Abstractions/PathBase.cs deleted file mode 100644 index 9ce7d54d7..000000000 --- a/System.IO.Abstractions/PathBase.cs +++ /dev/null @@ -1,32 +0,0 @@ -namespace System.IO.Abstractions -{ - [Serializable] - public abstract class PathBase - { - public abstract char AltDirectorySeparatorChar { get; } - public abstract char DirectorySeparatorChar { get; } - [Obsolete("Please use GetInvalidPathChars or GetInvalidFileNameChars instead.")] - public abstract char[] InvalidPathChars { get; } - public abstract char PathSeparator { get; } - public abstract char VolumeSeparatorChar { get; } - - public abstract string ChangeExtension(string path, string extension); - public abstract string Combine(params string[] paths); - public abstract string Combine(string path1, string path2); - public abstract string Combine(string path1, string path2, string path3); - public abstract string Combine(string path1, string path2, string path3, string path4); - public abstract string GetDirectoryName(string path); - public abstract string GetExtension(string path); - public abstract string GetFileName(string path); - public abstract string GetFileNameWithoutExtension(string path); - public abstract string GetFullPath(string path); - public abstract char[] GetInvalidFileNameChars(); - public abstract char[] GetInvalidPathChars(); - public abstract string GetPathRoot(string path); - public abstract string GetRandomFileName(); - public abstract string GetTempFileName(); - public abstract string GetTempPath(); - public abstract bool HasExtension(string path); - public abstract bool IsPathRooted(string path); - } -} \ No newline at end of file diff --git a/System.IO.Abstractions/PathWrapper.cs b/System.IO.Abstractions/PathWrapper.cs deleted file mode 100644 index ba36e9b27..000000000 --- a/System.IO.Abstractions/PathWrapper.cs +++ /dev/null @@ -1,122 +0,0 @@ -namespace System.IO.Abstractions -{ - [Serializable] - public class PathWrapper : PathBase - { - public override char AltDirectorySeparatorChar - { - get { return Path.AltDirectorySeparatorChar; } - } - - public override char DirectorySeparatorChar - { - get { return Path.DirectorySeparatorChar; } - } - - [Obsolete("Please use GetInvalidPathChars or GetInvalidFileNameChars instead.")] - public override char[] InvalidPathChars - { - get { return Path.InvalidPathChars; } - } - - public override char PathSeparator - { - get { return Path.PathSeparator; } - } - - public override char VolumeSeparatorChar - { - get { return Path.VolumeSeparatorChar; } - } - - public override string ChangeExtension(string path, string extension) - { - return Path.ChangeExtension(path, extension); - } - - public override string Combine(params string[] paths) - { - return Path.Combine(paths); - } - - public override string Combine(string path1, string path2) - { - return Path.Combine(path1, path2); - } - - public override string Combine(string path1, string path2, string path3) - { - return Path.Combine(path1, path2, path3); - } - - public override string Combine(string path1, string path2, string path3, string path4) - { - return Path.Combine(path1, path2, path3, path4); - } - - public override string GetDirectoryName(string path) - { - return Path.GetDirectoryName(path); - } - - public override string GetExtension(string path) - { - return Path.GetExtension(path); - } - - public override string GetFileName(string path) - { - return Path.GetFileName(path); - } - - public override string GetFileNameWithoutExtension(string path) - { - return Path.GetFileNameWithoutExtension(path); - } - - public override string GetFullPath(string path) - { - return Path.GetFullPath(path); - } - - public override char[] GetInvalidFileNameChars() - { - return Path.GetInvalidFileNameChars(); - } - - public override char[] GetInvalidPathChars() - { - return Path.GetInvalidPathChars(); - } - - public override string GetPathRoot(string path) - { - return Path.GetPathRoot(path); - } - - public override string GetRandomFileName() - { - return Path.GetRandomFileName(); - } - - public override string GetTempFileName() - { - return Path.GetTempFileName(); - } - - public override string GetTempPath() - { - return Path.GetTempPath(); - } - - public override bool HasExtension(string path) - { - return Path.HasExtension(path); - } - - public override bool IsPathRooted(string path) - { - return Path.IsPathRooted(path); - } - } -} diff --git a/System.IO.Abstractions/Properties/AssemblyInfo.cs b/System.IO.Abstractions/Properties/AssemblyInfo.cs deleted file mode 100644 index d8418bd92..000000000 --- a/System.IO.Abstractions/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,19 +0,0 @@ -using System; -using System.Reflection; -using System.Runtime.InteropServices; - -[assembly: AssemblyVersion("0.0.0.1")] -[assembly: AssemblyFileVersion("0.0.0.1")] - -[assembly: AssemblyTitle("System.IO.Abstractions")] -[assembly: AssemblyDescription("A set of abstractions to help make file system interactions testable.")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("System.IO.Abstractions")] -[assembly: AssemblyCopyright("Copyright © Tatham Oddie 2010")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -[assembly: ComVisible(false)] - -[assembly: CLSCompliant(true)] diff --git a/System.IO.Abstractions/System.IO.Abstractions.csproj b/System.IO.Abstractions/System.IO.Abstractions.csproj deleted file mode 100644 index 730e3540b..000000000 --- a/System.IO.Abstractions/System.IO.Abstractions.csproj +++ /dev/null @@ -1,126 +0,0 @@ - - - - Debug - AnyCPU - 9.0.30729 - 2.0 - {4D398F3A-0784-4401-93CD-46CD2FBD6B92} - Library - Properties - System.IO.Abstractions - System.IO.Abstractions - v4.0 - 512 - - - 3.5 - - publish\ - true - Disk - false - Foreground - 7 - Days - false - false - true - 0 - 1.0.0.%2a - false - false - true - - - - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - AllRules.ruleset - false - false - 5 - - - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - AllRules.ruleset - true - false - - - ..\StrongName.pfx - - - - - 3.5 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - False - .NET Framework 3.5 SP1 Client Profile - false - - - False - .NET Framework 3.5 SP1 - true - - - False - Windows Installer 3.1 - true - - - - - Designer - - - - - \ No newline at end of file diff --git a/System.IO.Abstractions/System.IO.Abstractions.ncrunchproject b/System.IO.Abstractions/System.IO.Abstractions.ncrunchproject deleted file mode 100644 index 59d3df4c1..000000000 --- a/System.IO.Abstractions/System.IO.Abstractions.ncrunchproject +++ /dev/null @@ -1,20 +0,0 @@ - - false - false - false - true - false - false - false - false - true - true - false - true - true - 60000 - - - - AutoDetect - \ No newline at end of file diff --git a/System.IO.Abstractions/System.IO.Abstractions.nuspec b/System.IO.Abstractions/System.IO.Abstractions.nuspec deleted file mode 100644 index 6fa1b73ad..000000000 --- a/System.IO.Abstractions/System.IO.Abstractions.nuspec +++ /dev/null @@ -1,14 +0,0 @@ - - - - System.IO.Abstractions - $version$ - Tatham Oddie - Tatham Oddie - https://github.com/tathamoddie/System.IO.Abstractions/blob/master/License.txt - https://github.com/tathamoddie/System.IO.Abstractions - false - Just like System.Web.Abstractions, but for System.IO. Yay for testable IO access! Be sure to check out the System.IO.Abstractions.TestingHelpers package too. - testing - - \ No newline at end of file diff --git a/TestHelpers.Tests/FileSystemTests.cs b/TestHelpers.Tests/FileSystemTests.cs deleted file mode 100644 index df6577ea8..000000000 --- a/TestHelpers.Tests/FileSystemTests.cs +++ /dev/null @@ -1,20 +0,0 @@ -using NUnit.Framework; - -namespace System.IO.Abstractions.TestingHelpers.Tests -{ - [TestFixture] - public class FileSystemTests - { - [Test] - public void Is_Serializable() - { - var fileSystem = new FileSystem(); - var memoryStream = new MemoryStream(); - - var serializer = new Runtime.Serialization.Formatters.Binary.BinaryFormatter(); - serializer.Serialize(memoryStream, fileSystem); - - Assert.That(memoryStream.Length > 0, "Length didn't increase after serialization task."); - } - } -} diff --git a/TestHelpers.Tests/MockDirectoryArgumentPathTests.cs b/TestHelpers.Tests/MockDirectoryArgumentPathTests.cs deleted file mode 100644 index 342338ed3..000000000 --- a/TestHelpers.Tests/MockDirectoryArgumentPathTests.cs +++ /dev/null @@ -1,40 +0,0 @@ -using System.Collections.Generic; -using System.Security.AccessControl; -using NUnit.Framework; - -namespace System.IO.Abstractions.TestingHelpers.Tests -{ - public class MockDirectoryArgumentPathTests - { - private static IEnumerable> GetFileSystemActionsForArgumentNullException() - { - yield return ds => ds.Delete(null); - yield return ds => ds.Delete(null, true); - yield return ds => ds.CreateDirectory(null); - yield return ds => ds.CreateDirectory(null, new DirectorySecurity()); - yield return ds => ds.SetCreationTime(null, DateTime.Now); - yield return ds => ds.SetCreationTimeUtc(null, DateTime.Now); - yield return ds => ds.SetLastAccessTime(null, DateTime.Now); - yield return ds => ds.SetLastAccessTimeUtc(null, DateTime.Now); - yield return ds => ds.SetLastWriteTime(null, DateTime.Now); - yield return ds => ds.SetLastWriteTimeUtc(null, DateTime.Now); - yield return ds => ds.EnumerateDirectories(null); - yield return ds => ds.EnumerateDirectories(null, "foo"); - yield return ds => ds.EnumerateDirectories(null, "foo", SearchOption.AllDirectories); - } - - [TestCaseSource("GetFileSystemActionsForArgumentNullException")] - public void Operations_ShouldThrowArgumentNullExceptionIfPathIsNull(Action action) - { - // Arrange - var fileSystem = new MockFileSystem(); - - // Act - TestDelegate wrapped = () => action(fileSystem.Directory); - - // Assert - var exception = Assert.Throws(wrapped); - Assert.AreEqual("path", exception.ParamName); - } - } -} diff --git a/TestHelpers.Tests/MockDirectoryInfoTests.cs b/TestHelpers.Tests/MockDirectoryInfoTests.cs deleted file mode 100644 index 92cbbb5d5..000000000 --- a/TestHelpers.Tests/MockDirectoryInfoTests.cs +++ /dev/null @@ -1,284 +0,0 @@ -using System.Collections.Generic; -using System.Linq; -using NUnit.Framework; - -namespace System.IO.Abstractions.TestingHelpers.Tests -{ - using XFS = MockUnixSupport; - - [TestFixture] - public class MockDirectoryInfoTests - { - public static IEnumerable MockDirectoryInfo_GetExtension_Cases - { - get - { - yield return new object[] { XFS.Path(@"c:\temp") }; - yield return new object[] { XFS.Path(@"c:\temp\") }; - } - } - - [TestCaseSource("MockDirectoryInfo_GetExtension_Cases")] - public void MockDirectoryInfo_GetExtension_ShouldReturnEmptyString(string directoryPath) - { - // Arrange - var fileSystem = new MockFileSystem(new Dictionary()); - var directoryInfo = new MockDirectoryInfo(fileSystem, directoryPath); - - // Act - var result = directoryInfo.Extension; - - // Assert - Assert.AreEqual(string.Empty, result); - } - - public static IEnumerable MockDirectoryInfo_Exists_Cases - { - get - { - yield return new object[]{ XFS.Path(@"c:\temp\folder"), true }; - yield return new object[]{ XFS.Path(@"c:\temp\folder\notExistant"), false }; - } - } - - [TestCaseSource("MockDirectoryInfo_Exists_Cases")] - public void MockDirectoryInfo_Exists(string path, bool expected) - { - var fileSystem = new MockFileSystem(new Dictionary - { - {XFS.Path(@"c:\temp\folder\file.txt"), new MockFileData("Hello World")} - }); - var directoryInfo = new MockDirectoryInfo(fileSystem, path); - - var result = directoryInfo.Exists; - - Assert.That(result, Is.EqualTo(expected)); - } - - [Test] - public void MockDirectoryInfo_FullName_ShouldReturnFullNameWithoutIncludingTrailingPathDelimiter() - { - var fileSystem = new MockFileSystem(new Dictionary - { - { - XFS.Path(@"c:\temp\folder\file.txt"), - new MockFileData("Hello World") - } - }); - var directoryInfo = new MockDirectoryInfo(fileSystem, XFS.Path(@"c:\temp\folder")); - - var result = directoryInfo.FullName; - - Assert.That(result, Is.EqualTo(XFS.Path(@"c:\temp\folder"))); - } - - [Test] - public void MockDirectoryInfo_GetFileSystemInfos_ShouldReturnBothDirectoriesAndFiles() - { - var fileSystem = new MockFileSystem(new Dictionary - { - { XFS.Path(@"c:\temp\folder\file.txt"), new MockFileData("Hello World") }, - { XFS.Path(@"c:\temp\folder\folder"), new MockDirectoryData() } - }); - - var directoryInfo = new MockDirectoryInfo(fileSystem, XFS.Path(@"c:\temp\folder")); - var result = directoryInfo.GetFileSystemInfos(); - - Assert.That(result.Length, Is.EqualTo(2)); - } - - [Test] - public void MockDirectoryInfo_EnumerateFileSystemInfos_ShouldReturnBothDirectoriesAndFiles() - { - var fileSystem = new MockFileSystem(new Dictionary - { - { XFS.Path(@"c:\temp\folder\file.txt"), new MockFileData("Hello World") }, - { XFS.Path(@"c:\temp\folder\folder"), new MockDirectoryData() } - }); - - var directoryInfo = new MockDirectoryInfo(fileSystem, XFS.Path(@"c:\temp\folder")); - var result = directoryInfo.EnumerateFileSystemInfos().ToArray(); - - Assert.That(result.Length, Is.EqualTo(2)); - } - - [Test] - public void MockDirectoryInfo_GetFileSystemInfos_ShouldReturnDirectoriesAndNamesWithSearchPattern() - { - var fileSystem = new MockFileSystem(new Dictionary - { - { XFS.Path(@"c:\temp\folder\file.txt"), new MockFileData("Hello World") }, - { XFS.Path(@"c:\temp\folder\folder"), new MockDirectoryData() }, - { XFS.Path(@"c:\temp\folder\older"), new MockDirectoryData() } - }); - - var directoryInfo = new MockDirectoryInfo(fileSystem, XFS.Path(@"c:\temp\folder")); - var result = directoryInfo.GetFileSystemInfos("f*"); - - Assert.That(result.Length, Is.EqualTo(2)); - } - - [Test] - public void MockDirectoryInfo_EnumerateFileSystemInfos_ShouldReturnDirectoriesAndNamesWithSearchPattern() - { - var fileSystem = new MockFileSystem(new Dictionary - { - { XFS.Path(@"c:\temp\folder\file.txt"), new MockFileData("Hello World") }, - { XFS.Path(@"c:\temp\folder\folder"), new MockDirectoryData() }, - { XFS.Path(@"c:\temp\folder\older"), new MockDirectoryData() } - }); - - var directoryInfo = new MockDirectoryInfo(fileSystem, XFS.Path(@"c:\temp\folder")); - var result = directoryInfo.EnumerateFileSystemInfos("f*", SearchOption.AllDirectories).ToArray(); - - Assert.That(result.Length, Is.EqualTo(2)); - } - - [Test] - public void MockDirectoryInfo_GetParent_ShouldReturnDirectoriesAndNamesWithSearchPattern() - { - // Arrange - var fileSystem = new MockFileSystem(); - fileSystem.AddDirectory(XFS.Path(@"c:\a\b\c")); - var directoryInfo = new MockDirectoryInfo(fileSystem, XFS.Path(@"c:\a\b\c")); - - // Act - var result = directoryInfo.Parent; - - // Assert - Assert.AreEqual(XFS.Path(@"c:\a\b"), result.FullName); - } - - [Test] - public void MockDirectoryInfo_EnumerateFiles_ShouldReturnAllFiles() - { - // Arrange - var fileSystem = new MockFileSystem(new Dictionary - { - //Files "above" in folder we're querying - { XFS.Path(@"c:\temp\a.txt"), "" }, - - //Files in the folder we're querying - { XFS.Path(@"c:\temp\folder\b.txt"), "" }, - { XFS.Path(@"c:\temp\folder\c.txt"), "" }, - - //Files "below" the folder we're querying - { XFS.Path(@"c:\temp\folder\deeper\d.txt"), "" } - }); - - // Act - var directoryInfo = new MockDirectoryInfo(fileSystem, XFS.Path(@"c:\temp\folder")); - - // Assert - Assert.AreEqual(new[]{"b.txt", "c.txt"}, directoryInfo.EnumerateFiles().ToList().Select(x => x.Name).ToArray()); - } - - [Test] - public void MockDirectoryInfo_EnumerateDirectories_ShouldReturnAllDirectories() - { - // Arrange - var fileSystem = new MockFileSystem(new Dictionary - { - //A file we want to ignore entirely - { XFS.Path(@"c:\temp\folder\a.txt"), "" }, - - //Some files in sub folders (which we also want to ignore entirely) - { XFS.Path(@"c:\temp\folder\b\file.txt"), "" }, - { XFS.Path(@"c:\temp\folder\c\other.txt"), "" }, - }); - var directoryInfo = new MockDirectoryInfo(fileSystem, XFS.Path(@"c:\temp\folder")); - - // Act - var directories = directoryInfo.EnumerateDirectories().Select(a => a.Name).ToArray(); - - // Assert - Assert.AreEqual(new[] { "b", "c" }, directories); - } - - public static IEnumerable MockDirectoryInfo_FullName_Data - { - get - { - yield return new object[] { XFS.Path(@"c:\temp\\folder"), XFS.Path(@"c:\temp\folder") }; - yield return new object[] { XFS.Path(@"c:\temp//folder"), XFS.Path(@"c:\temp\folder") }; - yield return new object[] { XFS.Path(@"c:\temp//\\///folder"), XFS.Path(@"c:\temp\folder") }; - yield return new object[] { XFS.Path(@"\\unc\folder"), XFS.Path(@"\\unc\folder") }; - yield return new object[] { XFS.Path(@"\\unc/folder\\foo"), XFS.Path(@"\\unc\folder\foo") }; - } - } - - [TestCaseSource("MockDirectoryInfo_FullName_Data")] - public void MockDirectoryInfo_FullName_ShouldReturnNormalizedPath(string directoryPath, string expectedFullName) - { - // Arrange - var fileSystem = new MockFileSystem(new Dictionary - { - { XFS.Path(@"c:\temp\folder\a.txt"), "" } - }); - var directoryInfo = new MockDirectoryInfo(fileSystem, directoryPath); - - // Act - var actualFullName = directoryInfo.FullName; - - // Assert - Assert.AreEqual(expectedFullName, actualFullName); - } - - [Test] - public void MockDirectoryInfo_Constructor_ShouldThrowArgumentNullException_IfArgumentDirectoryIsNull() - { - // Arrange - var fileSystem = new MockFileSystem(); - - // Act - TestDelegate action = () => new MockDirectoryInfo(fileSystem, null); - - // Assert - var exception = Assert.Throws(action); - Assert.That(exception.Message, Is.StringStarting("Value cannot be null.")); - } - - [Test] - public void MockDirectoryInfo_Constructor_ShouldThrowArgumentNullException_IfArgumentFileSystemIsNull() - { - // Arrange - // nothing to do - - // Act - TestDelegate action = () => new MockDirectoryInfo(null, XFS.Path(@"c:\foo\bar\folder")); - - // Assert - Assert.Throws(action); - } - - [Test] - public void MockDirectoryInfo_Constructor_ShouldThrowArgumentException_IfArgumentDirectoryIsEmpty() - { - // Arrange - var fileSystem = new MockFileSystem(); - - // Act - TestDelegate action = () => new MockDirectoryInfo(fileSystem, string.Empty); - - // Assert - var exception = Assert.Throws(action); - Assert.That(exception.Message, Is.StringStarting("The path is not of a legal form.")); - } - - [Test] - public void MockDirectoryInfo_ToString_ShouldReturnDirectoryName() - { - var directoryPath = XFS.Path(@"c:\temp\folder\folder"); - - // Arrange - var fileSystem = new MockFileSystem(); - var directoryInfo = new MockDirectoryInfo(fileSystem, directoryPath); - - // Act - var str = directoryInfo.ToString(); - - // Assert - Assert.AreEqual(directoryPath, str); - } - } -} \ No newline at end of file diff --git a/TestHelpers.Tests/MockDirectoryTests.cs b/TestHelpers.Tests/MockDirectoryTests.cs deleted file mode 100644 index 7222c10a6..000000000 --- a/TestHelpers.Tests/MockDirectoryTests.cs +++ /dev/null @@ -1,1337 +0,0 @@ -using System.Collections.Generic; -using System.Linq; -using System.Security.AccessControl; -using NUnit.Framework; - -namespace System.IO.Abstractions.TestingHelpers.Tests -{ - using XFS = MockUnixSupport; - - [TestFixture] - public class MockDirectoryTests - { - [Test] - public void MockDirectory_GetFiles_ShouldReturnAllFilesBelowPathWhenPatternIsWildcardAndSearchOptionIsAllDirectories() - { - // Arrange - var fileSystem = SetupFileSystem(); - var expected = new[] - { - XFS.Path(@"c:\a\a.txt"), - XFS.Path(@"c:\a\b.gif"), - XFS.Path(@"c:\a\c.txt"), - XFS.Path(@"c:\a\a\a.txt"), - XFS.Path(@"c:\a\a\b.txt"), - XFS.Path(@"c:\a\a\c.gif") - }; - - // Act - var result = fileSystem.Directory.GetFiles(XFS.Path(@"c:\a"), "*", SearchOption.AllDirectories); - - // Assert - Assert.That(result, Is.EquivalentTo(expected)); - } - - private MockFileSystem SetupFileSystem() - { - return new MockFileSystem(new Dictionary - { - { XFS.Path(@"c:\a.gif"), new MockFileData("Demo text content") }, - { XFS.Path(@"c:\b.txt"), new MockFileData("Demo text content") }, - { XFS.Path(@"c:\c.txt"), new MockFileData("Demo text content") }, - { XFS.Path(@"c:\a\a.txt"), new MockFileData("Demo text content") }, - { XFS.Path(@"c:\a\b.gif"), new MockFileData("Demo text content") }, - { XFS.Path(@"c:\a\c.txt"), new MockFileData("Demo text content") }, - { XFS.Path(@"c:\a\a\a.txt"), new MockFileData("Demo text content") }, - { XFS.Path(@"c:\a\a\b.txt"), new MockFileData("Demo text content") }, - { XFS.Path(@"c:\a\a\c.gif"), new MockFileData("Demo text content") }, - }); - - } - - [Test] - public void MockDirectory_GetFiles_ShouldReturnFilesDirectlyBelowPathWhenPatternIsWildcardAndSearchOptionIsTopDirectoryOnly() - { - // Arrange - var fileSystem = SetupFileSystem(); - var expected = new[] - { - XFS.Path(@"c:\a\a.txt"), - XFS.Path(@"c:\a\b.gif"), - XFS.Path(@"c:\a\c.txt") - }; - - // Act - var result = fileSystem.Directory.GetFiles(XFS.Path(@"c:\a"), "*", SearchOption.TopDirectoryOnly); - - // Assert - Assert.That(result, Is.EquivalentTo(expected)); - } - - [Test] - public void MockDirectory_GetFiles_ShouldFilterByExtensionBasedSearchPattern() - { - // Arrange - var fileSystem = SetupFileSystem(); - var expected = new[] - { - XFS.Path(@"c:\a.gif"), - XFS.Path(@"c:\a\b.gif"), - XFS.Path(@"c:\a\a\c.gif") - }; - - // Act - var result = fileSystem.Directory.GetFiles(XFS.Path(@"c:\"), "*.gif", SearchOption.AllDirectories); - - // Assert - Assert.That(result, Is.EquivalentTo(expected)); - } - - [Test] - public void MockDirectory_GetFiles_ShouldFilterByExtensionBasedSearchPatternWithThreeCharacterLongFileExtension_RepectingAllDirectorySearchOption() - { - // Arrange - var additionalFilePath = XFS.Path(@"c:\a\a\c.gifx"); - var fileSystem = SetupFileSystem(); - fileSystem.AddFile(additionalFilePath, new MockFileData(string.Empty)); - fileSystem.AddFile(XFS.Path(@"c:\a\a\c.gifx.xyz"), new MockFileData(string.Empty)); - fileSystem.AddFile(XFS.Path(@"c:\a\a\c.gifx\xyz"), new MockFileData(string.Empty)); - var expected = new[] - { - XFS.Path(@"c:\a.gif"), - XFS.Path(@"c:\a\b.gif"), - XFS.Path(@"c:\a\a\c.gif"), - additionalFilePath - }; - - // Act - var result = fileSystem.Directory.GetFiles(XFS.Path(@"c:\"), "*.gif", SearchOption.AllDirectories); - - // Assert - Assert.That(result, Is.EquivalentTo(expected)); - } - - [Test] - public void MockDirectory_GetFiles_ShouldFilterByExtensionBasedSearchPatternWithThreeCharacterLongFileExtension_RepectingTopDirectorySearchOption() - { - // Arrange - var additionalFilePath = XFS.Path(@"c:\a\c.gifx"); - var fileSystem = SetupFileSystem(); - fileSystem.AddFile(additionalFilePath, new MockFileData(string.Empty)); - fileSystem.AddFile(XFS.Path(@"c:\a\a\c.gifx.xyz"), new MockFileData(string.Empty)); - fileSystem.AddFile(XFS.Path(@"c:\a\a\c.gifx"), new MockFileData(string.Empty)); - var expected = new[] - { - XFS.Path(@"c:\a\b.gif"), - additionalFilePath - }; - - // Act - var result = fileSystem.Directory.GetFiles(XFS.Path(@"c:\a"), "*.gif", SearchOption.TopDirectoryOnly); - - // Assert - Assert.That(result, Is.EquivalentTo(expected)); - } - - [Test] - public void MockDirectory_GetFiles_ShouldFilterByExtensionBasedSearchPatternOnlyIfTheFileExtensionIsThreeCharacterLong() - { - // Arrange - var additionalFilePath = XFS.Path(@"c:\a\c.gi"); - var fileSystem = SetupFileSystem(); - fileSystem.AddFile(additionalFilePath, new MockFileData(string.Empty)); - fileSystem.AddFile(XFS.Path(@"c:\a\a\c.gifx.xyz"), new MockFileData(string.Empty)); - fileSystem.AddFile(XFS.Path(@"c:\a\a\c.gif"), new MockFileData(string.Empty)); - fileSystem.AddFile(XFS.Path(@"c:\a\a\c.gifx"), new MockFileData(string.Empty)); - var expected = new[] - { - additionalFilePath - }; - - // Act - var result = fileSystem.Directory.GetFiles(XFS.Path(@"c:\a"), "*.gi", SearchOption.AllDirectories); - - // Assert - Assert.That(result, Is.EquivalentTo(expected)); - } - - [Test] - public void MockDirectory_GetFiles_ShouldFilterByExtensionBasedSearchPatternWithDotsInFilenames() - { - // Arrange - var fileSystem = new MockFileSystem(new Dictionary - { - { XFS.Path(@"c:\a.there.are.dots.in.this.filename.gif"), new MockFileData("Demo text content") }, - { XFS.Path(@"c:\b.txt"), new MockFileData("Demo text content") }, - { XFS.Path(@"c:\c.txt"), new MockFileData("Demo text content") }, - { XFS.Path(@"c:\a\a.txt"), new MockFileData("Demo text content") }, - { XFS.Path(@"c:\a\b.gif"), new MockFileData("Demo text content") }, - { XFS.Path(@"c:\a\c.txt"), new MockFileData("Demo text content") }, - { XFS.Path(@"c:\a\a\a.txt"), new MockFileData("Demo text content") }, - { XFS.Path(@"c:\a\a\b.txt"), new MockFileData("Demo text content") }, - { XFS.Path(@"c:\a\a\c.gif"), new MockFileData("Demo text content") }, - }); - var expected = new[] - { - XFS.Path(@"c:\a.there.are.dots.in.this.filename.gif"), - XFS.Path(@"c:\a\b.gif"), - XFS.Path(@"c:\a\a\c.gif") - }; - - // Act - var result = fileSystem.Directory.GetFiles(XFS.Path(@"c:\"), "*.gif", SearchOption.AllDirectories); - - // Assert - Assert.That(result, Is.EquivalentTo( expected)); - } - - [Test] - public void MockDirectory_GetFiles_FilterShouldFindFilesWithSpecialChars() - { - // Arrange - var fileSystem = new MockFileSystem(new Dictionary - { - { XFS.Path(@"c:\a.1#.pdf"), new MockFileData("Demo text content") }, - { XFS.Path(@"c:\b\b #1.txt"), new MockFileData("Demo text content") } - }); - var expected = new[] - { - XFS.Path(@"c:\a.1#.pdf"), - XFS.Path(@"c:\b\b #1.txt") - }; - - // Act - var result = fileSystem.Directory.GetFiles(XFS.Path(@"c:\"), "*.*", SearchOption.AllDirectories); - - // Assert - Assert.That(result, Is.EquivalentTo(expected)); - } - - [Test] - public void MockDirectory_GetFiles_ShouldFilterByExtensionBasedSearchPatternAndSearchOptionTopDirectoryOnly() - { - // Arrange - var fileSystem = SetupFileSystem(); - var expected = new[] { XFS.Path(@"c:\a.gif") }; - - // Act - var result = fileSystem.Directory.GetFiles(XFS.Path(@"c:\"), "*.gif", SearchOption.TopDirectoryOnly); - - // Assert - Assert.That(result, Is.EquivalentTo(expected)); - } - - private void ExecuteTimeAttributeTest(Action setter, Func getter) - { - string path = XFS.Path(@"c:\something\demo.txt"); - var fileSystem = new MockFileSystem(new Dictionary - { - { path, new MockFileData("Demo text content") } - }); - - // Act - var time = new DateTime(2010, 6, 4, 13, 26, 42); - setter(fileSystem, path, time); - var result = getter(fileSystem, path); - - // Assert - Assert.That(result, Is.EqualTo(time)); - } - - [Test] - public void MockDirectory_GetCreationTime_ShouldReturnCreationTimeFromFile() - { - ExecuteTimeAttributeTest( - (fs, p, d) => fs.File.SetCreationTime(p, d), - (fs, p) => fs.Directory.GetCreationTime(p)); - } - - [Test] - public void MockDirectory_GetCreationTimeUtc_ShouldReturnCreationTimeUtcFromFile() - { - ExecuteTimeAttributeTest( - (fs, p, d) => fs.File.SetCreationTimeUtc(p, d), - (fs, p) => fs.Directory.GetCreationTimeUtc(p)); - } - - [Test] - public void MockDirectory_GetLastAccessTime_ShouldReturnLastAccessTimeFromFile() - { - ExecuteTimeAttributeTest( - (fs, p, d) => fs.File.SetLastAccessTime(p, d), - (fs, p) => fs.Directory.GetLastAccessTime(p)); - } - - [Test] - public void MockDirectory_GetLastAccessTimeUtc_ShouldReturnLastAccessTimeUtcFromFile() - { - ExecuteTimeAttributeTest( - (fs, p, d) => fs.File.SetLastAccessTimeUtc(p, d), - (fs, p) => fs.Directory.GetLastAccessTimeUtc(p)); - } - - [Test] - public void MockDirectory_GetLastWriteTime_ShouldReturnLastWriteTimeFromFile() - { - ExecuteTimeAttributeTest( - (fs, p, d) => fs.File.SetLastWriteTime(p, d), - (fs, p) => fs.Directory.GetLastWriteTime(p)); - } - - [Test] - public void MockDirectory_GetLastWriteTimeUtc_ShouldReturnLastWriteTimeUtcFromFile() - { - ExecuteTimeAttributeTest( - (fs, p, d) => fs.File.SetLastWriteTimeUtc(p, d), - (fs, p) => fs.Directory.GetLastWriteTimeUtc(p)); - } - - [Test] - public void MockDirectory_SetCreationTime_ShouldSetCreationTimeOnFile() - { - ExecuteTimeAttributeTest( - (fs, p, d) => fs.Directory.SetCreationTime(p, d), - (fs, p) => fs.File.GetCreationTime(p)); - } - - [Test] - public void MockDirectory_SetCreationTimeUtc_ShouldSetCreationTimeUtcOnFile() - { - ExecuteTimeAttributeTest( - (fs, p, d) => fs.Directory.SetCreationTimeUtc(p, d), - (fs, p) => fs.File.GetCreationTimeUtc(p)); - } - - [Test] - public void MockDirectory_SetLastAccessTime_ShouldSetLastAccessTimeOnFile() - { - ExecuteTimeAttributeTest( - (fs, p, d) => fs.Directory.SetLastAccessTime(p, d), - (fs, p) => fs.File.GetLastAccessTime(p)); - } - - [Test] - public void MockDirectory_SetLastAccessTimeUtc_ShouldSetLastAccessTimeUtcOnFile() - { - ExecuteTimeAttributeTest( - (fs, p, d) => fs.Directory.SetLastAccessTimeUtc(p, d), - (fs, p) => fs.File.GetLastAccessTimeUtc(p)); - } - - [Test] - public void MockDirectory_SetLastWriteTime_ShouldSetLastWriteTimeOnFile() - { - ExecuteTimeAttributeTest( - (fs, p, d) => fs.Directory.SetLastWriteTime(p, d), - (fs, p) => fs.File.GetLastWriteTime(p)); - } - - [Test] - public void MockDirectory_SetLastWriteTimeUtc_ShouldSetLastWriteTimeUtcOnFile() - { - ExecuteTimeAttributeTest( - (fs, p, d) => fs.Directory.SetLastWriteTimeUtc(p, d), - (fs, p) => fs.File.GetLastWriteTimeUtc(p)); - } - - [Test] - public void MockDirectory_Exists_ShouldReturnTrueForDirectoryDefinedInMemoryFileSystemWithoutTrailingSlash() - { - // Arrange - var fileSystem = new MockFileSystem(new Dictionary - { - { XFS.Path(@"c:\foo\bar.txt"), new MockFileData("Demo text content") } - }); - - // Act - var result = fileSystem.Directory.Exists(XFS.Path(@"c:\foo")); - - // Assert - Assert.IsTrue(result); - } - - [Test] - public void MockDirectory_Exists_ShouldReturnTrueForDirectoryDefinedInMemoryFileSystemWithTrailingSlash() - { - // Arrange - var fileSystem = new MockFileSystem(new Dictionary - { - { XFS.Path(@"c:\foo\bar.txt"), new MockFileData("Demo text content") } - }); - - // Act - var result = fileSystem.Directory.Exists(XFS.Path(@"c:\foo\")); - - // Assert - Assert.IsTrue(result); - } - - [Test] - public void MockDirectory_Exists_ShouldReturnFalseForDirectoryNotDefinedInMemoryFileSystemWithoutTrailingSlash() - { - // Arrange - var fileSystem = new MockFileSystem(new Dictionary - { - { XFS.Path(@"c:\foo\bar.txt"), new MockFileData("Demo text content") } - }); - - // Act - var result = fileSystem.Directory.Exists(XFS.Path(@"c:\baz")); - - // Assert - Assert.IsFalse(result); - } - - [Test] - public void MockDirectory_Exists_ShouldReturnFalseForDirectoryNotDefinedInMemoryFileSystemWithTrailingSlash() - { - // Arrange - var fileSystem = new MockFileSystem(new Dictionary - { - { XFS.Path(@"c:\foo\bar.txt"), new MockFileData("Demo text content") } - }); - - // Act - var result = fileSystem.Directory.Exists(XFS.Path(@"c:\baz\")); - - // Assert - Assert.IsFalse(result); - } - - [Test] - public void MockDirectory_Exists_ShouldReturnFalseForDirectoryNotDefinedInMemoryFileSystemWithSimilarFileName() - { - // Arrange - var fileSystem = new MockFileSystem(new Dictionary - { - { XFS.Path(@"c:\foo\bar.txt"), new MockFileData("Demo text content") }, - { XFS.Path(@"c:\baz.txt"), new MockFileData("Demo text content") } - }); - - // Act - var result = fileSystem.Directory.Exists(XFS.Path(@"c:\baz")); - - // Assert - Assert.IsFalse(result); - } - - [Test] - public void MockDirectory_Exists_ShouldReturnTrueForDirectoryCreatedViaMocks() - { - // Arrange - var fileSystem = new MockFileSystem(new Dictionary - { - { XFS.Path(@"c:\foo\bar.txt"), new MockFileData("Demo text content") } - }); - fileSystem.Directory.CreateDirectory(XFS.Path(@"c:\bar")); - - // Act - var result = fileSystem.Directory.Exists(XFS.Path(@"c:\bar")); - - // Assert - Assert.IsTrue(result); - } - - [Test] - public void MockDirectory_Exists_ShouldReturnTrueForFolderContainingFileAddedToMockFileSystem() - { - // Arrange - var fileSystem = new MockFileSystem(); - fileSystem.AddFile(XFS.Path(@"c:\foo\bar.txt"), new MockFileData("Demo text content")); - - // Act - var result = fileSystem.Directory.Exists(XFS.Path(@"c:\foo\")); - - // Assert - Assert.IsTrue(result); - } - - [TestCase(@"\\s")] - [TestCase(@"<")] - [TestCase("\t")] - public void MockDirectory_Exists_ShouldReturnFalseForIllegalPath(string path) - { - // Arrange - var fileSystem = new MockFileSystem(); - - // Act - var result = fileSystem.Directory.Exists(path); - - // Assert - Assert.IsFalse(result); - } - - [Test] - public void MockDirectory_Exists_ShouldReturnFalseForFiles() - { - // Arrange - var fileSystem = new MockFileSystem(); - fileSystem.AddFile(XFS.Path(@"c:\foo\bar.txt"), new MockFileData("Demo text content")); - - // Act - var result = fileSystem.Directory.Exists(XFS.Path(@"c:\foo\bar.txt")); - - // Assert - Assert.IsFalse(result); - } - - [Test] - public void MockDirectory_CreateDirectory_ShouldCreateFolderInMemoryFileSystem() - { - // Arrange - var fileSystem = new MockFileSystem(new Dictionary - { - { XFS.Path(@"c:\foo.txt"), new MockFileData("Demo text content") } - }); - - // Act - fileSystem.Directory.CreateDirectory(XFS.Path(@"c:\bar")); - - // Assert - Assert.IsTrue(fileSystem.FileExists(XFS.Path(@"c:\bar\"))); - Assert.IsTrue(fileSystem.AllDirectories.Any(d => d == XFS.Path(@"c:\bar\"))); - } - - // Issue #210 - [Test] - public void MockDirectory_CreateDirectory_ShouldIgnoreExistingDirectoryRegardlessOfTrailingSlash() - { - // Arrange - var fileSystem = new MockFileSystem(new Dictionary - { - { XFS.Path(@"c:\foo\"), new MockDirectoryData() } - }); - - // Act/Assert - Assert.That(() => fileSystem.Directory.CreateDirectory(XFS.Path(@"c:\foo")), Throws.Nothing); - Assert.That(() => fileSystem.Directory.CreateDirectory(XFS.Path(@"c:\foo\")), Throws.Nothing); - } - - [Test] - public void MockDirectory_CreateDirectory_ShouldReturnDirectoryInfoBase() - { - // Arrange - var fileSystem = new MockFileSystem(new Dictionary - { - { XFS.Path(@"c:\foo.txt"), new MockFileData("Demo text content") } - }); - - // Act - var result = fileSystem.Directory.CreateDirectory(XFS.Path(@"c:\bar")); - - // Assert - Assert.IsNotNull(result); - } - - [Test] - public void MockDirectory_CreMockDirectory_CreateDirectory_ShouldReturnDirectoryInfoBaseWhenDirectoryExists() - { - // Arrange - var fileSystem = new MockFileSystem(new Dictionary - { - { XFS.Path(@"c:\foo\"), new MockDirectoryData() } - }); - - // Act - var result = fileSystem.Directory.CreateDirectory(XFS.Path(@"c:\foo\")); - - // Assert - Assert.IsNotNull(result); - } - - [Test] - public void MockDirectory_CreateDirectory_ShouldWorkWithUNCPath() - { - // Arrange - var fileSystem = new MockFileSystem(); - - // Act - fileSystem.Directory.CreateDirectory(XFS.Path(@"\\server\share\path\to\create", () => false)); - - // Assert - Assert.IsTrue(fileSystem.Directory.Exists(XFS.Path(@"\\server\share\path\to\create\", () => false))); - } - - [Test] - public void MockDirectory_CreateDirectory_ShouldFailIfTryingToCreateUNCPathOnlyServer() - { - // Arrange - var fileSystem = new MockFileSystem(); - - // Act - var ex = Assert.Throws(() => fileSystem.Directory.CreateDirectory(XFS.Path(@"\\server", () => false))); - - // Assert - StringAssert.StartsWith("The UNC path should be of the form \\\\server\\share.", ex.Message); - Assert.That(ex.ParamName, Is.EqualTo("path")); - } - - [Test] - public void MockDirectory_CreateDirectory_ShouldSucceedIfTryingToCreateUNCPathShare() - { - // Arrange - var fileSystem = new MockFileSystem(); - - // Act - fileSystem.Directory.CreateDirectory(XFS.Path(@"\\server\share", () => false)); - - // Assert - Assert.IsTrue(fileSystem.Directory.Exists(XFS.Path(@"\\server\share\", () => false))); - } - - [Test] - public void MockDirectory_Delete_ShouldDeleteDirectory() - { - // Arrange - var fileSystem = new MockFileSystem(new Dictionary - { - { XFS.Path(@"c:\bar\foo.txt"), new MockFileData("Demo text content") } - }); - - // Act - fileSystem.Directory.Delete(XFS.Path(@"c:\bar"), true); - - // Assert - Assert.IsFalse(fileSystem.Directory.Exists(XFS.Path(@"c:\bar"))); - } - - [Test] - public void MockDirectory_Delete_ShouldDeleteDirectoryCaseInsensitively() - { - // Arrange - var fileSystem = new MockFileSystem(new Dictionary - { - { XFS.Path(@"c:\bar\foo.txt"), new MockFileData("Demo text content") } - }); - - // Act - fileSystem.Directory.Delete(XFS.Path(@"c:\BAR"), true); - - // Assert - Assert.IsFalse(fileSystem.Directory.Exists(XFS.Path(@"c:\bar"))); - } - - [Test] - public void MockDirectory_Delete_ShouldThrowDirectoryNotFoundException() - { - // Arrange - var fileSystem = new MockFileSystem(new Dictionary - { - { XFS.Path(@"c:\bar\foo.txt"), new MockFileData("Demo text content") } - }); - - var ex = Assert.Throws(() => fileSystem.Directory.Delete(XFS.Path(@"c:\baz"))); - - Assert.That(ex.Message, Is.EqualTo(XFS.Path("c:\\baz\\") + " does not exist or could not be found.")); - } - - [Test] - public void MockDirectory_Delete_ShouldThrowIOException() - { - // Arrange - var fileSystem = new MockFileSystem(new Dictionary - { - { XFS.Path(@"c:\bar\foo.txt"), new MockFileData("Demo text content") }, - { XFS.Path(@"c:\bar\baz.txt"), new MockFileData("Demo text content") } - }); - - var ex = Assert.Throws(() => fileSystem.Directory.Delete(XFS.Path(@"c:\bar"))); - - Assert.That(ex.Message, Is.EqualTo("The directory specified by " + XFS.Path("c:\\bar\\") + " is read-only, or recursive is false and " + XFS.Path("c:\\bar\\") + " is not an empty directory.")); - } - - [Test] - public void MockDirectory_Delete_ShouldDeleteDirectoryRecursively() - { - // Arrange - var fileSystem = new MockFileSystem(new Dictionary - { - { XFS.Path(@"c:\bar\foo.txt"), new MockFileData("Demo text content") }, - { XFS.Path(@"c:\bar\bar2\foo.txt"), new MockFileData("Demo text content") } - }); - - // Act - fileSystem.DirectoryInfo.FromDirectoryName(XFS.Path(@"c:\bar")).Delete(true); - - // Assert - Assert.IsFalse(fileSystem.Directory.Exists(XFS.Path(@"c:\bar"))); - Assert.IsFalse(fileSystem.Directory.Exists(XFS.Path(@"c:\bar\bar2"))); - } - - [Test] - public void MockDirectory_GetFileSystemEntries_Returns_Files_And_Directories() - { - string testPath = XFS.Path(@"c:\foo\bar.txt"); - string testDir = XFS.Path(@"c:\foo\bar\"); - var fileSystem = new MockFileSystem(new Dictionary - { - { testPath, new MockFileData("Demo text content") }, - { testDir, new MockDirectoryData() } - }); - - var entries = fileSystem.Directory.GetFileSystemEntries(XFS.Path(@"c:\foo")).OrderBy(k => k); - Assert.AreEqual(2, entries.Count()); - Assert.AreEqual(testDir, entries.Last()); - Assert.AreEqual(testPath, entries.First()); - } - - [Test] - public void MockDirectory_GetFiles_ShouldThrowArgumentNullException_IfPathParamIsNull() - { - var fileSystem = new MockFileSystem(new Dictionary()); - - TestDelegate action = () => fileSystem.Directory.GetFiles(null); - Assert.Throws(action); - } - - [Test] - public void MockDirectory_GetFiles_ShouldThrowDirectoryNotFoundException_IfPathDoesNotExists() - { - // Arrange - var fileSystem = new MockFileSystem(); - - // Act - TestDelegate action = () => fileSystem.Directory.GetFiles(XFS.Path(@"c:\Foo"), "*a.txt"); - - // Assert - Assert.Throws(action); - } - - [Test] - public void MockDirectory_GetFiles_Returns_Files() - { - string testPath = XFS.Path(@"c:\foo\bar.txt"); - string testDir = XFS.Path(@"c:\foo\bar\"); - var fileSystem = new MockFileSystem(new Dictionary - { - { testPath, new MockFileData("Demo text content") }, - { testDir, new MockDirectoryData() } - }); - - var entries = fileSystem.Directory.GetFiles(XFS.Path(@"c:\foo")).OrderBy(k => k); - Assert.AreEqual(1, entries.Count()); - Assert.AreEqual(testPath, entries.First()); - } - - [Test] - public void MockDirectory_GetFiles_ShouldThrowAnArgumentNullException_IfSearchPatternIsNull() - { - // Arrange - var directoryPath = XFS.Path(@"c:\Foo"); - var fileSystem = new MockFileSystem(); - fileSystem.AddDirectory(directoryPath); - - // Act - TestDelegate action = () => fileSystem.Directory.GetFiles(directoryPath, null); - - // Assert - Assert.Throws(action); - } - - [Test] - public void MockDirectory_GetFiles_ShouldThrowAnArgumentException_IfSearchPatternEndsWithTwoDots() - { - // Arrange - var directoryPath = XFS.Path(@"c:\Foo"); - var fileSystem = new MockFileSystem(); - fileSystem.AddDirectory(directoryPath); - - // Act - TestDelegate action = () => fileSystem.Directory.GetFiles(directoryPath, "*a.."); - - // Assert - Assert.Throws(action); - } - - private IEnumerable GetSearchPatternForTwoDotsExceptions() - { - yield return @"a..\b"; - yield return @"a../b"; - yield return @"../"; - yield return @"..\"; - yield return @"aaa\vv..\"; - } - - [TestCaseSource("GetSearchPatternForTwoDotsExceptions")] - public void MockDirectory_GetFiles_ShouldThrowAnArgumentException_IfSearchPatternContainsTwoDotsFollowedByOneDirectoryPathSep(string searchPattern) - { - // Arrange - var directoryPath = XFS.Path(@"c:\Foo"); - var fileSystem = new MockFileSystem(); - fileSystem.AddDirectory(directoryPath); - - // Act - TestDelegate action = () => fileSystem.Directory.GetFiles(directoryPath, searchPattern); - - // Assert - Assert.Throws(action); - } - - [Test] - public void MockDirectory_GetFiles_ShouldFindFilesContainingTwoOrMoreDots() - { - // Arrange - string testPath = XFS.Path(@"c:\foo..r\bar.txt"); - var fileSystem = new MockFileSystem(new Dictionary - { - { testPath, new MockFileData(string.Empty) } - }); - - // Act - var actualResult = fileSystem.Directory.GetFiles(XFS.Path(@"c:\"), @"foo..r\*"); - - // Assert - Assert.That(actualResult, Is.EquivalentTo(new [] { testPath })); - } - - [TestCase(@"""")] - [TestCase("aa\t")] - public void MockDirectory_GetFiles_ShouldThrowAnArgumentException_IfSearchPatternHasIllegalCharacters(string searchPattern) - { - // Arrange - var directoryPath = XFS.Path(@"c:\Foo"); - var fileSystem = new MockFileSystem(); - fileSystem.AddDirectory(directoryPath); - - // Act - TestDelegate action = () => fileSystem.Directory.GetFiles(directoryPath, searchPattern); - - // Assert - Assert.Throws(action); - } - - [Test] - public void MockDirectory_GetRoot_Returns_Root() - { - string testDir = XFS.Path(@"c:\foo\bar\"); - var fileSystem = new MockFileSystem(new Dictionary - { - { testDir, new MockDirectoryData() } - }); - - Assert.AreEqual(XFS.Path("C:\\"), fileSystem.Directory.GetDirectoryRoot(XFS.Path(@"C:\foo\bar"))); - } - - [Test] - public void MockDirectory_GetLogicalDrives_Returns_LogicalDrives() - { - var fileSystem = new MockFileSystem(new Dictionary - { - {XFS.Path(@"c:\foo\bar\"), new MockDirectoryData()}, - {XFS.Path(@"c:\foo\baz\"), new MockDirectoryData()}, - {XFS.Path(@"d:\bash\"), new MockDirectoryData()}, - }); - - var drives = fileSystem.Directory.GetLogicalDrives(); - - if (XFS.IsUnixPlatform()) - { - Assert.AreEqual(1, drives.Length); - Assert.IsTrue(drives.Contains("/")); - } - else - { - Assert.AreEqual(2, drives.Length); - Assert.IsTrue(drives.Contains("c:\\")); - Assert.IsTrue(drives.Contains("d:\\")); - } - } - - [Test] - public void MockDirectory_GetDirectories_Returns_Child_Directories() - { - var fileSystem = new MockFileSystem(new Dictionary - { - { XFS.Path(@"A:\folder1\folder2\folder3\file.txt"), new MockFileData("Demo text content") }, - { XFS.Path(@"A:\folder1\folder4\file2.txt"), new MockFileData("Demo text content 2") }, - }); - - var directories = fileSystem.Directory.GetDirectories(XFS.Path(@"A:\folder1")).ToArray(); - - //Check that it does not returns itself - Assert.IsFalse(directories.Contains(XFS.Path(@"A:\folder1\"))); - - //Check that it correctly returns all child directories - Assert.AreEqual(2, directories.Count()); - Assert.IsTrue(directories.Contains(XFS.Path(@"A:\folder1\folder2\"))); - Assert.IsTrue(directories.Contains(XFS.Path(@"A:\folder1\folder4\"))); - } - - [Test] - public void MockDirectory_GetDirectories_WithTopDirectories_ShouldOnlyReturnTopDirectories() - { - // Arrange - var fileSystem = new MockFileSystem(); - fileSystem.AddDirectory(XFS.Path(@"C:\Folder\.foo\")); - fileSystem.AddDirectory(XFS.Path(@"C:\Folder\foo")); - fileSystem.AddDirectory(XFS.Path(@"C:\Folder\foo.foo")); - fileSystem.AddDirectory(XFS.Path(@"C:\Folder\.foo\.foo")); - fileSystem.AddFile(XFS.Path(@"C:\Folder\.foo\bar"), new MockFileData(string.Empty)); - - // Act - var actualResult = fileSystem.Directory.GetDirectories(XFS.Path(@"c:\Folder\"), "*.foo"); - - // Assert - Assert.That(actualResult, Is.EquivalentTo(new []{XFS.Path(@"C:\Folder\.foo\"), XFS.Path(@"C:\Folder\foo.foo\")})); - } - - [Test] - public void MockDirectory_GetDirectories_WithAllDirectories_ShouldReturnsAllMatchingSubFolders() - { - // Arrange - var fileSystem = new MockFileSystem(); - fileSystem.AddDirectory(XFS.Path(@"C:\Folder\.foo\")); - fileSystem.AddDirectory(XFS.Path(@"C:\Folder\foo")); - fileSystem.AddDirectory(XFS.Path(@"C:\Folder\foo.foo")); - fileSystem.AddDirectory(XFS.Path(@"C:\Folder\.foo\.foo")); - fileSystem.AddFile(XFS.Path(@"C:\Folder\.foo\bar"), new MockFileData(string.Empty)); - - // Act - var actualResult = fileSystem.Directory.GetDirectories(XFS.Path(@"c:\Folder\"), "*.foo", SearchOption.AllDirectories); - - // Assert - Assert.That(actualResult, Is.EquivalentTo(new[] { XFS.Path(@"C:\Folder\.foo\"), XFS.Path(@"C:\Folder\foo.foo\"), XFS.Path(@"C:\Folder\.foo\.foo\") })); - } - - [Test] - public void MockDirectory_GetDirectories_ShouldThrowWhenPathIsNotMocked() - { - // Arrange - var fileSystem = new MockFileSystem(new Dictionary - { - { XFS.Path(@"c:\a.gif"), new MockFileData("Demo text content") }, - { XFS.Path(@"c:\b.txt"), new MockFileData("Demo text content") }, - { XFS.Path(@"c:\c.txt"), new MockFileData("Demo text content") }, - { XFS.Path(@"c:\a\a.txt"), new MockFileData("Demo text content") }, - { XFS.Path(@"c:\a\b.gif"), new MockFileData("Demo text content") }, - { XFS.Path(@"c:\a\c.txt"), new MockFileData("Demo text content") }, - { XFS.Path(@"c:\a\a\a.txt"), new MockFileData("Demo text content") }, - { XFS.Path(@"c:\a\a\b.txt"), new MockFileData("Demo text content") }, - { XFS.Path(@"c:\a\a\c.gif"), new MockFileData("Demo text content") }, - }); - - // Act - TestDelegate action = () => fileSystem.Directory.GetDirectories(XFS.Path(@"c:\d")); - - // Assert - Assert.Throws(action); - } - - [Test] - public void MockDirectory_EnumerateDirectories_Returns_Child_Directories() - { - var fileSystem = new MockFileSystem(new Dictionary - { - { XFS.Path(@"A:\folder1\folder2\folder3\file.txt"), new MockFileData("Demo text content") }, - { XFS.Path(@"A:\folder1\folder4\file2.txt"), new MockFileData("Demo text content 2") }, - }); - - var directories = fileSystem.Directory.EnumerateDirectories(XFS.Path(@"A:\folder1")).ToArray(); - - //Check that it does not returns itself - Assert.IsFalse(directories.Contains(XFS.Path(@"A:\folder1\"))); - - //Check that it correctly returns all child directories - Assert.AreEqual(2, directories.Count()); - Assert.IsTrue(directories.Contains(XFS.Path(@"A:\folder1\folder2\"))); - Assert.IsTrue(directories.Contains(XFS.Path(@"A:\folder1\folder4\"))); - } - - [Test] - public void MockDirectory_EnumerateDirectories_WithTopDirectories_ShouldOnlyReturnTopDirectories() - { - // Arrange - var fileSystem = new MockFileSystem(); - fileSystem.AddDirectory(XFS.Path(@"C:\Folder\.foo\")); - fileSystem.AddDirectory(XFS.Path(@"C:\Folder\foo")); - fileSystem.AddDirectory(XFS.Path(@"C:\Folder\foo.foo")); - fileSystem.AddDirectory(XFS.Path(@"C:\Folder\.foo\.foo")); - fileSystem.AddFile(XFS.Path(@"C:\Folder\.foo\bar"), new MockFileData(string.Empty)); - - // Act - var actualResult = fileSystem.Directory.EnumerateDirectories(XFS.Path(@"c:\Folder\"), "*.foo"); - - // Assert - Assert.That(actualResult, Is.EquivalentTo(new[] { XFS.Path(@"C:\Folder\.foo\"), XFS.Path(@"C:\Folder\foo.foo\") })); - } - - [Test] - public void MockDirectory_EnumerateDirectories_WithAllDirectories_ShouldReturnsAllMatchingSubFolders() - { - // Arrange - var fileSystem = new MockFileSystem(); - fileSystem.AddDirectory(XFS.Path(@"C:\Folder\.foo\")); - fileSystem.AddDirectory(XFS.Path(@"C:\Folder\foo")); - fileSystem.AddDirectory(XFS.Path(@"C:\Folder\foo.foo")); - fileSystem.AddDirectory(XFS.Path(@"C:\Folder\.foo\.foo")); - fileSystem.AddFile(XFS.Path(@"C:\Folder\.foo\bar"), new MockFileData(string.Empty)); - - // Act - var actualResult = fileSystem.Directory.EnumerateDirectories(XFS.Path(@"c:\Folder\"), "*.foo", SearchOption.AllDirectories); - - // Assert - Assert.That(actualResult, Is.EquivalentTo(new[] { XFS.Path(@"C:\Folder\.foo\"), XFS.Path(@"C:\Folder\foo.foo\"), XFS.Path(@"C:\Folder\.foo\.foo\") })); - } - - [Test] - public void MockDirectory_EnumerateDirectories_ShouldThrowWhenPathIsNotMocked() - { - // Arrange - var fileSystem = new MockFileSystem(new Dictionary - { - { XFS.Path(@"c:\a.gif"), new MockFileData("Demo text content") }, - { XFS.Path(@"c:\b.txt"), new MockFileData("Demo text content") }, - { XFS.Path(@"c:\c.txt"), new MockFileData("Demo text content") }, - { XFS.Path(@"c:\a\a.txt"), new MockFileData("Demo text content") }, - { XFS.Path(@"c:\a\b.gif"), new MockFileData("Demo text content") }, - { XFS.Path(@"c:\a\c.txt"), new MockFileData("Demo text content") }, - { XFS.Path(@"c:\a\a\a.txt"), new MockFileData("Demo text content") }, - { XFS.Path(@"c:\a\a\b.txt"), new MockFileData("Demo text content") }, - { XFS.Path(@"c:\a\a\c.gif"), new MockFileData("Demo text content") }, - }); - - // Act - TestDelegate action = () => fileSystem.Directory.EnumerateDirectories(XFS.Path(@"c:\d")); - - // Assert - Assert.Throws(action); - } - - public static IEnumerable GetPathsForMoving() - { - yield return new object[] { @"a:\folder1\", @"A:\folder3\", "file.txt", @"folder2\file2.txt" }; - yield return new object[] { @"A:\folder1\", @"A:\folder3\", "file.txt", @"folder2\file2.txt" }; - yield return new object[] { @"a:\folder1\", @"a:\folder3\", "file.txt", @"folder2\file2.txt" }; - yield return new object[] { @"A:\folder1\", @"a:\folder3\", "file.txt", @"folder2\file2.txt" }; - yield return new object[] { @"A:\folder1\", @"a:\folder3\", "file.txt", @"Folder2\file2.txt" }; - yield return new object[] { @"A:\folder1\", @"a:\folder3\", "file.txt", @"Folder2\fiLe2.txt" }; - yield return new object[] { @"A:\folder1\", @"a:\folder3\", "folder444\\file.txt", @"Folder2\fiLe2.txt" }; - } - - [Test] - public void Move_DirectoryExistsWithDifferentCase_DirectorySuccessfullyMoved() - { - // Arrange - var fileSystem = new MockFileSystem(); - fileSystem.AddDirectory(@"C:\OLD_LOCATION\Data"); - fileSystem.AddFile(@"C:\old_location\Data\someFile.txt", new MockFileData("abc")); - - // Act - fileSystem.Directory.Move(@"C:\old_location", @"C:\NewLocation\"); - - // Assert - Assert.IsTrue(fileSystem.File.Exists(@"C:\NewLocation\Data\someFile.txt")); - } - - [TestCaseSource("GetPathsForMoving")] - public void MockDirectory_Move_ShouldMove(string sourceDirName, string destDirName, string filePathOne, string filePathTwo) - { - // Arrange - var fileSystem = new MockFileSystem(new Dictionary - { - { XFS.Path(sourceDirName + filePathOne) , new MockFileData("aaa") }, - { XFS.Path(sourceDirName + filePathTwo) , new MockFileData("bbb") }, - }); - - // Act - fileSystem.DirectoryInfo.FromDirectoryName(sourceDirName).MoveTo(destDirName); - - // Assert - Assert.IsFalse(fileSystem.Directory.Exists(sourceDirName)); - Assert.IsTrue(fileSystem.File.Exists(XFS.Path(destDirName + filePathOne))); - Assert.IsTrue(fileSystem.File.Exists(XFS.Path(destDirName + filePathTwo))); - } - - [Test] - public void MockDirectory_Move_ShouldMoveDirectoryAtrributes() - { - // Arrange - const string sourceDirName = @"a:\folder1\"; - const string destDirName = @"a:\folder2\"; - const string filePathOne = "file1.txt"; - const string filePathTwo = "file2.txt"; - var fileSystem = new MockFileSystem(new Dictionary - { - { XFS.Path(sourceDirName + filePathOne) , new MockFileData("aaa") }, - { XFS.Path(sourceDirName + filePathTwo) , new MockFileData("bbb") }, - }); - - var sourceDirectoryInfo = fileSystem.DirectoryInfo.FromDirectoryName(sourceDirName); - sourceDirectoryInfo.Attributes |= FileAttributes.System; - - // Act - fileSystem.DirectoryInfo.FromDirectoryName(sourceDirName).MoveTo(destDirName); - - // Assert - var destDirectoryInfo = fileSystem.DirectoryInfo.FromDirectoryName(destDirName); - Assert.IsTrue(destDirectoryInfo.Attributes.HasFlag(FileAttributes.System)); - } - - [Test] - public void MockDirectory_GetCurrentDirectory_ShouldReturnValueFromFileSystemConstructor() { - string directory = XFS.Path(@"D:\folder1\folder2"); - var fileSystem = new MockFileSystem(new Dictionary(), directory); - - var actual = fileSystem.Directory.GetCurrentDirectory(); - - Assert.AreEqual(directory, actual); - } - - - [Test] - public void MockDirectory_GetCurrentDirectory_ShouldReturnDefaultPathWhenNotSet() { - string directory = Path.GetTempPath(); - var fileSystem = new MockFileSystem(); - - var actual = fileSystem.Directory.GetCurrentDirectory(); - - Assert.AreEqual(directory, actual); - } - - [Test] - public void MockDirectory_SetCurrentDirectory_ShouldChangeCurrentDirectory() { - string directory = XFS.Path(@"D:\folder1\folder2"); - var fileSystem = new MockFileSystem(); - - // Precondition - Assert.AreNotEqual(directory, fileSystem.Directory.GetCurrentDirectory()); - - fileSystem.Directory.SetCurrentDirectory(directory); - - Assert.AreEqual(directory, fileSystem.Directory.GetCurrentDirectory()); - } - - [Test] - public void MockDirectory_GetParent_ShouldThrowArgumentNullExceptionIfPathIsNull() - { - // Arrange - var fileSystem = new MockFileSystem(); - - // Act - TestDelegate act = () => fileSystem.Directory.GetParent(null); - - // Assert - Assert.Throws(act); - } - - [Test] - public void MockDirectory_GetParent_ShouldThrowArgumentExceptionIfPathIsEmpty() - { - // Arrange - var fileSystem = new MockFileSystem(); - - // Act - TestDelegate act = () => fileSystem.Directory.GetParent(string.Empty); - - // Assert - Assert.Throws(act); - } - - [Test] - public void MockDirectory_GetParent_ShouldReturnADirectoryInfoIfPathDoesNotExist() - { - // Arrange - var fileSystem = new MockFileSystem(); - - // Act - var actualResult = fileSystem.Directory.GetParent(XFS.Path(@"c:\directory\does\not\exist")); - - // Assert - Assert.IsNotNull(actualResult); - } - - [Test] - public void MockDirectory_GetParent_ShouldThrowArgumentExceptionIfPathHasIllegalCharacters() - { - if (XFS.IsUnixPlatform()) - { - Assert.Pass("Path.GetInvalidChars() does not return anything on Mono"); - return; - } - - // Arrange - var fileSystem = new MockFileSystem(); - - // Act - TestDelegate act = () => fileSystem.Directory.GetParent(XFS.Path("c:\\director\ty\\has\\illegal\\character")); - - // Assert - Assert.Throws(act); - } - - [Test] - public void MockDirectory_GetParent_ShouldReturnNullIfPathIsRoot() - { - // Arrange - var fileSystem = new MockFileSystem(); - fileSystem.AddDirectory(XFS.Path(@"c:\")); - - // Act - var actualResult = fileSystem.Directory.GetParent(XFS.Path(@"c:\")); - - // Assert - Assert.IsNull(actualResult); - } - - public static IEnumerable MockDirectory_GetParent_Cases - { - get - { - yield return new [] { XFS.Path(@"c:\a"), XFS.Path(@"c:\") }; - yield return new [] { XFS.Path(@"c:\a\b\c\d"), XFS.Path(@"c:\a\b\c") }; - yield return new [] { XFS.Path(@"c:\a\b\c\d\"), XFS.Path(@"c:\a\b\c") }; - } - } - - public void MockDirectory_GetParent_ShouldReturnTheParentWithoutTrailingDirectorySeparatorChar(string path, string expectedResult) - { - // Arrange - var fileSystem = new MockFileSystem(); - fileSystem.AddDirectory(path); - - // Act - var actualResult = fileSystem.Directory.GetParent(path); - - // Assert - Assert.AreEqual(expectedResult, actualResult.FullName); - } - - [Test] - public void MockDirectory_Move_ShouldThrowAnIOExceptionIfBothPathAreIdentical() - { - // Arrange - string path = XFS.Path(@"c:\a"); - var fileSystem = new MockFileSystem(); - fileSystem.AddDirectory(path); - - // Act - TestDelegate action = () => fileSystem.Directory.Move(path, path); - - // Assert - Assert.Throws(action, "Source and destination path must be different."); - } - - [Test] - public void MockDirectory_Move_ShouldThrowAnIOExceptionIfDirectoriesAreOnDifferentVolumes() - { - // Arrange - string sourcePath = XFS.Path(@"c:\a"); - string destPath = XFS.Path(@"d:\v"); - var fileSystem = new MockFileSystem(); - fileSystem.AddDirectory(sourcePath); - - // Act - TestDelegate action = () => fileSystem.Directory.Move(sourcePath, destPath); - - // Assert - Assert.Throws(action, "Source and destination path must have identical roots. Move will not work across volumes."); - } - - [Test] - public void MockDirectory_EnumerateFiles_ShouldReturnAllFilesBelowPathWhenPatternIsWildcardAndSearchOptionIsAllDirectories() - { - // Arrange - var fileSystem = SetupFileSystem(); - IEnumerable expected = new[] - { - XFS.Path(@"c:\a\a.txt"), - XFS.Path(@"c:\a\b.gif"), - XFS.Path(@"c:\a\c.txt"), - XFS.Path(@"c:\a\a\a.txt"), - XFS.Path(@"c:\a\a\b.txt"), - XFS.Path(@"c:\a\a\c.gif") - }; - - // Act - var result = fileSystem.Directory.EnumerateFiles(XFS.Path(@"c:\a"), "*", SearchOption.AllDirectories); - - // Assert - Assert.That(result, Is.EquivalentTo(expected)); - } - - [Test] - public void MockDirectory_EnumerateFiles_ShouldFilterByExtensionBasedSearchPattern() - { - // Arrange - var fileSystem = SetupFileSystem(); - var expected = new[] - { - XFS.Path(@"c:\a.gif"), - XFS.Path(@"c:\a\b.gif"), - XFS.Path(@"c:\a\a\c.gif") - }; - - // Act - var result = fileSystem.Directory.EnumerateFiles(XFS.Path(@"c:\"), "*.gif", SearchOption.AllDirectories); - - // Assert - Assert.That(result, Is.EquivalentTo(expected)); - } - - [Test] - public void MockDirectory_EnumerateFileSystemEntries_ShouldReturnAllFilesBelowPathWhenPatternIsWildcardAndSearchOptionIsAllDirectories() - { - // Arrange - var fileSystem = SetupFileSystem(); - IEnumerable expected = new[] - { - XFS.Path(@"c:\a\a.txt"), - XFS.Path(@"c:\a\b.gif"), - XFS.Path(@"c:\a\c.txt"), - XFS.Path(@"c:\a\a\a.txt"), - XFS.Path(@"c:\a\a\b.txt"), - XFS.Path(@"c:\a\a\c.gif"), - XFS.Path(@"c:\a\a\") - }; - - // Act - var result = fileSystem.Directory.EnumerateFileSystemEntries(XFS.Path(@"c:\a"), "*", SearchOption.AllDirectories); - - // Assert - Assert.That(result, Is.EquivalentTo(expected)); - } - - [Test] - public void MockDirectory_EnumerateFileSystemEntries_ShouldFilterByExtensionBasedSearchPattern() - { - // Arrange - var fileSystem = SetupFileSystem(); - var expected = new[] - { - XFS.Path(@"c:\a.gif"), - XFS.Path(@"c:\a\b.gif"), - XFS.Path(@"c:\a\a\c.gif") - }; - - // Act - var result = fileSystem.Directory.EnumerateFileSystemEntries(XFS.Path(@"c:\"), "*.gif", SearchOption.AllDirectories); - - // Assert - Assert.That(result, Is.EquivalentTo(expected)); - } - - [Test] - public void MockDirectory_GetAccessControl_ShouldThrowExceptionOnDirectoryNotFound() - { - // Arrange - var fileSystem = new MockFileSystem(); - - // Act - Assert.Throws(() => fileSystem.Directory.GetAccessControl(XFS.Path(@"c:\foo"))); - } - - [Test] - public void MockDirectory_GetAccessControl_ShouldReturnNewDirectorySecurity() - { - // Arrange - var fileSystem = new MockFileSystem(); - fileSystem.Directory.CreateDirectory(XFS.Path(@"c:\foo")); - - // Act - DirectorySecurity result = fileSystem.Directory.GetAccessControl(XFS.Path(@"c:\foo")); - - // Assert - Assert.That(result, Is.Not.Null); - } - } -} \ No newline at end of file diff --git a/TestHelpers.Tests/MockDriveInfoFactoryTests.cs b/TestHelpers.Tests/MockDriveInfoFactoryTests.cs deleted file mode 100644 index 33bcc507d..000000000 --- a/TestHelpers.Tests/MockDriveInfoFactoryTests.cs +++ /dev/null @@ -1,71 +0,0 @@ -using System.Linq; -using NUnit.Framework; - -namespace System.IO.Abstractions.TestingHelpers.Tests -{ - using XFS = MockUnixSupport; - - [TestFixture] - public class MockDriveInfoFactoryTests - { - [Test] - public void MockDriveInfoFactory_GetDrives_ShouldReturnDrives() - { - // Arrange - var fileSystem = new MockFileSystem(); - fileSystem.AddDirectory(XFS.Path(@"C:\Test")); - fileSystem.AddDirectory(XFS.Path(@"Z:\Test")); - fileSystem.AddDirectory(XFS.Path(@"d:\Test")); - var factory = new MockDriveInfoFactory(fileSystem); - - // Act - var actualResults = factory.GetDrives(); - - var actualNames = actualResults.Select(d => d.Name); - - // Assert - Assert.That(actualNames, Is.EquivalentTo(new[] { @"C:\", @"Z:\", @"D:\" })); - } - - [Test] - public void MockDriveInfoFactory_GetDrives_ShouldReturnDrivesWithNoDuplicates() - { - // Arrange - var fileSystem = new MockFileSystem(); - fileSystem.AddDirectory(XFS.Path(@"C:\Test")); - fileSystem.AddDirectory(XFS.Path(@"c:\Test2")); - fileSystem.AddDirectory(XFS.Path(@"Z:\Test")); - fileSystem.AddDirectory(XFS.Path(@"d:\Test")); - fileSystem.AddDirectory(XFS.Path(@"d:\Test2")); - var factory = new MockDriveInfoFactory(fileSystem); - - // Act - var actualResults = factory.GetDrives(); - - var actualNames = actualResults.Select(d => d.Name); - - // Assert - Assert.That(actualNames, Is.EquivalentTo(new[] { @"C:\", @"Z:\", @"D:\" })); - } - - [Test] - public void MockDriveInfoFactory_GetDrives_ShouldReturnOnlyLocalDrives() - { - // Arrange - var fileSystem = new MockFileSystem(); - fileSystem.AddDirectory(XFS.Path(@"C:\Test")); - fileSystem.AddDirectory(XFS.Path(@"Z:\Test")); - fileSystem.AddDirectory(XFS.Path(@"d:\Test")); - fileSystem.AddDirectory(XFS.Path(@"\\anunc\share\Zzz")); - var factory = new MockDriveInfoFactory(fileSystem); - - // Act - var actualResults = factory.GetDrives(); - - var actualNames = actualResults.Select(d => d.Name); - - // Assert - Assert.That(actualNames, Is.EquivalentTo(new[] { @"C:\", @"Z:\", @"D:\" })); - } - } -} diff --git a/TestHelpers.Tests/MockDriveInfoTests.cs b/TestHelpers.Tests/MockDriveInfoTests.cs deleted file mode 100644 index aa655a642..000000000 --- a/TestHelpers.Tests/MockDriveInfoTests.cs +++ /dev/null @@ -1,75 +0,0 @@ -using NUnit.Framework; - -namespace System.IO.Abstractions.TestingHelpers.Tests -{ - using XFS = MockUnixSupport; - - [TestFixture] - public class MockDriveInfoTests - { - [TestCase(@"c:")] - [TestCase(@"c:\")] - public void MockDriveInfo_Constructor_ShouldInitializeLocalWindowsDrives(string driveName) - { - // Arrange - var fileSystem = new MockFileSystem(); - fileSystem.AddDirectory(XFS.Path(@"c:\Test")); - var path = XFS.Path(driveName); - - // Act - var driveInfo = new MockDriveInfo(fileSystem, path); - - // Assert - Assert.AreEqual(@"C:\", driveInfo.Name); - } - - [Test] - public void MockDriveInfo_Constructor_ShouldInitializeLocalWindowsDrives_SpecialForWindows() - { - if (XFS.IsUnixPlatform()) - { - Assert.Inconclusive("Using XFS.Path transform c into c:."); - } - - // Arrange - var fileSystem = new MockFileSystem(); - fileSystem.AddDirectory(XFS.Path(@"c:\Test")); - - // Act - var driveInfo = new MockDriveInfo(fileSystem, "c"); - - // Assert - Assert.AreEqual(@"C:\", driveInfo.Name); - } - - [TestCase(@"\\unc\share")] - [TestCase(@"\\unctoo")] - public void MockDriveInfo_Constructor_ShouldThrowExceptionIfUncPath(string driveName) - { - // Arrange - var fileSystem = new MockFileSystem(); - - // Act - TestDelegate action = () => new MockDriveInfo(fileSystem, XFS.Path(driveName)); - - // Assert - Assert.Throws(action); - } - - [Test] - public void MockDriveInfo_RootDirectory_ShouldReturnTheDirectoryBase() - { - // Arrange - var fileSystem = new MockFileSystem(); - fileSystem.AddDirectory(XFS.Path(@"c:\Test")); - var driveInfo = new MockDriveInfo(fileSystem, "c:"); - var expectedDirectory = XFS.Path(@"C:\"); - - // Act - var actualDirectory = driveInfo.RootDirectory; - - // Assert - Assert.AreEqual(expectedDirectory, actualDirectory.FullName); - } - } -} diff --git a/TestHelpers.Tests/MockFileAppendAllLinesTests.cs b/TestHelpers.Tests/MockFileAppendAllLinesTests.cs deleted file mode 100644 index e99dcb8f6..000000000 --- a/TestHelpers.Tests/MockFileAppendAllLinesTests.cs +++ /dev/null @@ -1,121 +0,0 @@ -using System.Collections.Generic; -using NUnit.Framework; -using XFS = System.IO.Abstractions.TestingHelpers.MockUnixSupport; - -namespace System.IO.Abstractions.TestingHelpers.Tests -{ - public class MockFileAppendAllLinesTests - { - [Test] - public void MockFile_AppendAllLines_ShouldPersistNewLinesToExistingFile() - { - // Arrange - string path = XFS.Path(@"c:\something\demo.txt"); - var fileSystem = new MockFileSystem(new Dictionary - { - { path, new MockFileData("Demo text content") } - }); - - var file = new MockFile(fileSystem); - - // Act - file.AppendAllLines(path, new[] { "line 1", "line 2", "line 3" }); - - // Assert - Assert.AreEqual( - "Demo text contentline 1" + Environment.NewLine + "line 2" + Environment.NewLine + "line 3" + Environment.NewLine, - file.ReadAllText(path)); - } - - [Test] - public void MockFile_AppendAllLines_ShouldPersistNewLinesToNewFile() - { - // Arrange - string path = XFS.Path(@"c:\something\demo.txt"); - var fileSystem = new MockFileSystem(new Dictionary - { - { XFS.Path(@"c:\something\"), new MockDirectoryData() } - }); - var file = new MockFile(fileSystem); - - // Act - file.AppendAllLines(path, new[] { "line 1", "line 2", "line 3" }); - - // Assert - Assert.AreEqual( - "line 1" + Environment.NewLine + "line 2" + Environment.NewLine + "line 3" + Environment.NewLine, - file.ReadAllText(path)); - } - - [Test] - public void MockFile_AppendAllLines_ShouldThrowArgumentExceptionIfPathIsZeroLength() - { - // Arrange - var fileSystem = new MockFileSystem(); - - // Act - TestDelegate action = () => fileSystem.File.AppendAllLines(string.Empty, new[] { "does not matter" }); - - // Assert - Assert.Throws(action); - } - - [TestCase(" ")] - [TestCase(" ")] - public void MockFile_AppendAllLines_ShouldThrowArgumentExceptionIfPathContainsOnlyWhitespaces(string path) - { - // Arrange - var fileSystem = new MockFileSystem(); - - // Act - TestDelegate action = () => fileSystem.File.AppendAllLines(path, new[] { "does not matter" }); - - // Assert - Assert.Throws(action); - } - - [TestCase("\"")] - [TestCase("<")] - [TestCase(">")] - [TestCase("|")] - public void MockFile_AppendAllLines_ShouldThrowArgumentExceptionIfPathContainsInvalidChar(string path) - { - // Arrange - var fileSystem = new MockFileSystem(); - - // Act - TestDelegate action = () => fileSystem.File.AppendAllLines(path, new[] { "does not matter" }); - - // Assert - Assert.Throws(action); - } - - [Test] - public void MockFile_AppendAllLines_ShouldThrowArgumentNullExceptionIfContentIsNull() - { - // Arrange - var fileSystem = new MockFileSystem(); - - // Act - TestDelegate action = () => fileSystem.File.AppendAllLines("foo", null); - - // Assert - var exception = Assert.Throws(action); - Assert.That(exception.ParamName, Is.EqualTo("contents")); - } - - [Test] - public void MockFile_AppendAllLines_ShouldThrowArgumentNullExceptionIfEncodingIsNull() - { - // Arrange - var fileSystem = new MockFileSystem(); - - // Act - TestDelegate action = () => fileSystem.File.AppendAllLines("foo.txt", new [] { "bar" }, null); - - // Assert - var exception = Assert.Throws(action); - Assert.That(exception.ParamName, Is.EqualTo("encoding")); - } - } -} diff --git a/TestHelpers.Tests/MockFileAppendAllTextTests.cs b/TestHelpers.Tests/MockFileAppendAllTextTests.cs deleted file mode 100644 index e57bca080..000000000 --- a/TestHelpers.Tests/MockFileAppendAllTextTests.cs +++ /dev/null @@ -1,158 +0,0 @@ -namespace System.IO.Abstractions.TestingHelpers.Tests -{ - using Collections.Generic; - - using Globalization; - - using NUnit.Framework; - - using Text; - - using XFS = MockUnixSupport; - - public class MockFileAppendAllTextTests - { - [Test] - public void MockFile_AppendAllText_ShouldPersistNewText() - { - // Arrange - string path = XFS.Path(@"c:\something\demo.txt"); - var fileSystem = new MockFileSystem(new Dictionary - { - {path, new MockFileData("Demo text content")} - }); - - var file = new MockFile(fileSystem); - - // Act - file.AppendAllText(path, "+ some text"); - - // Assert - Assert.AreEqual( - "Demo text content+ some text", - file.ReadAllText(path)); - } - - [Test] - public void MockFile_AppendAllText_ShouldPersistNewTextWithDifferentEncoding() - { - // Arrange - const string Path = @"c:\something\demo.txt"; - var fileSystem = new MockFileSystem(new Dictionary - { - {Path, new MockFileData("AA", Encoding.UTF32)} - }); - - var file = new MockFile(fileSystem); - - // Act - file.AppendAllText(Path, "BB", Encoding.UTF8); - - // Assert - CollectionAssert.AreEqual( - new byte[] {255, 254, 0, 0, 65, 0, 0, 0, 65, 0, 0, 0, 66, 66}, - fileSystem.GetFile(Path).Contents); - } - - [Test] - public void MockFile_AppendAllText_ShouldCreateIfNotExist() - { - // Arrange - string path = XFS.Path(@"c:\something\demo.txt"); - var fileSystem = new MockFileSystem(new Dictionary - { - {path, new MockFileData("Demo text content")} - }); - - // Act - fileSystem.File.AppendAllText(path, " some text"); - - // Assert - Assert.AreEqual( - "Demo text content some text", - fileSystem.File.ReadAllText(path)); - } - - [Test] - public void MockFile_AppendAllText_ShouldCreateIfNotExistWithBom() - { - // Arrange - var fileSystem = new MockFileSystem(new Dictionary()); - const string path = @"c:\something\demo3.txt"; - fileSystem.AddDirectory(@"c:\something\"); - - // Act - fileSystem.File.AppendAllText(path, "AA", Encoding.UTF32); - - // Assert - CollectionAssert.AreEqual( - new byte[] {255, 254, 0, 0, 65, 0, 0, 0, 65, 0, 0, 0}, - fileSystem.GetFile(path).Contents); - } - - [Test] - public void MockFile_AppendAllText_ShouldFailIfNotExistButDirectoryAlsoNotExist() - { - // Arrange - string path = XFS.Path(@"c:\something\demo.txt"); - var fileSystem = new MockFileSystem(new Dictionary - { - {path, new MockFileData("Demo text content")} - }); - - // Act - path = XFS.Path(@"c:\something2\demo.txt"); - - // Assert - Exception ex; - ex = Assert.Throws(() => fileSystem.File.AppendAllText(path, "some text")); - Assert.That(ex.Message, - Is.EqualTo(String.Format(CultureInfo.InvariantCulture, "Could not find a part of the path '{0}'.", path))); - - ex = - Assert.Throws( - () => fileSystem.File.AppendAllText(path, "some text", Encoding.Unicode)); - Assert.That(ex.Message, - Is.EqualTo(String.Format(CultureInfo.InvariantCulture, "Could not find a part of the path '{0}'.", path))); - } - - [Test] - public void MockFile_AppendAllText_ShouldPersistNewTextWithCustomEncoding() - { - // Arrange - string path = XFS.Path(@"c:\something\demo.txt"); - var fileSystem = new MockFileSystem(new Dictionary - { - {path, new MockFileData("Demo text content")} - }); - - var file = new MockFile(fileSystem); - - // Act - file.AppendAllText(path, "+ some text", Encoding.BigEndianUnicode); - - // Assert - var expected = new byte[] - { - 68, 101, 109, 111, 32, 116, 101, 120, 116, 32, 99, 111, 110, 116, - 101, 110, 116, 0, 43, 0, 32, 0, 115, 0, 111, 0, 109, 0, 101, - 0, 32, 0, 116, 0, 101, 0, 120, 0, 116 - }; - - if (XFS.IsUnixPlatform()) - { - // Remove EOF on mono - expected = new byte[] - { - 68, 101, 109, 111, 32, 116, 101, 120, 116, 32, 99, 111, 110, 116, - 101, 110, 0, 43, 0, 32, 0, 115, 0, 111, 0, 109, 0, 101, - 0, 32, 0, 116, 0, 101, 0, 120, 0, 116 - }; - } - - CollectionAssert.AreEqual( - expected, - file.ReadAllBytes(path)); - } - } -} \ No newline at end of file diff --git a/TestHelpers.Tests/MockFileArgumentPathTests.cs b/TestHelpers.Tests/MockFileArgumentPathTests.cs deleted file mode 100644 index 9994d31e5..000000000 --- a/TestHelpers.Tests/MockFileArgumentPathTests.cs +++ /dev/null @@ -1,71 +0,0 @@ -using System.Collections.Generic; -using System.Linq; -using System.Text; -using NUnit.Framework; - -namespace System.IO.Abstractions.TestingHelpers.Tests -{ - public class MockFileArgumentPathTests - { - private static IEnumerable> GetFileSystemActionsForArgumentNullException() - { - yield return fs => fs.AppendAllLines(null, new[] { "does not matter" }); - yield return fs => fs.AppendAllLines(null, new[] { "does not matter" }, Encoding.ASCII); - yield return fs => fs.AppendAllText(null, "does not matter"); - yield return fs => fs.AppendAllText(null, "does not matter", Encoding.ASCII); - yield return fs => fs.AppendText(null); - yield return fs => fs.WriteAllBytes(null, new byte[] { 0 }); - yield return fs => fs.WriteAllLines(null, new[] { "does not matter" }); - yield return fs => fs.WriteAllLines(null, new[] { "does not matter" }, Encoding.ASCII); - yield return fs => fs.WriteAllLines(null, new[] { "does not matter" }.ToArray()); - yield return fs => fs.WriteAllLines(null, new[] { "does not matter" }.ToArray(), Encoding.ASCII); - yield return fs => fs.Create(null); - yield return fs => fs.Delete(null); - yield return fs => fs.GetCreationTime(null); - yield return fs => fs.GetCreationTimeUtc(null); - yield return fs => fs.GetLastAccessTime(null); - yield return fs => fs.GetLastAccessTimeUtc(null); - yield return fs => fs.GetLastWriteTime(null); - yield return fs => fs.GetLastWriteTimeUtc(null); - yield return fs => fs.WriteAllText(null, "does not matter"); - yield return fs => fs.WriteAllText(null, "does not matter", Encoding.ASCII); - yield return fs => fs.Open(null, FileMode.OpenOrCreate); - yield return fs => fs.Open(null, FileMode.OpenOrCreate, FileAccess.Read); - yield return fs => fs.Open(null, FileMode.OpenOrCreate, FileAccess.Read, FileShare.Inheritable); - yield return fs => fs.OpenRead(null); - yield return fs => fs.OpenText(null); - yield return fs => fs.OpenWrite(null); - yield return fs => fs.ReadAllBytes(null); - yield return fs => fs.ReadAllLines(null); - yield return fs => fs.ReadAllLines(null, Encoding.ASCII); - yield return fs => fs.ReadAllText(null); - yield return fs => fs.ReadAllText(null, Encoding.ASCII); - yield return fs => fs.ReadLines(null); - yield return fs => fs.ReadLines(null, Encoding.ASCII); - yield return fs => fs.SetAttributes(null, FileAttributes.Archive); - yield return fs => fs.GetAttributes(null); - yield return fs => fs.SetCreationTime(null, DateTime.Now); - yield return fs => fs.SetCreationTimeUtc(null, DateTime.Now); - yield return fs => fs.SetLastAccessTime(null, DateTime.Now); - yield return fs => fs.SetLastAccessTimeUtc(null, DateTime.Now); - yield return fs => fs.SetLastWriteTime(null, DateTime.Now); - yield return fs => fs.SetLastWriteTimeUtc(null, DateTime.Now); - yield return fs => fs.Decrypt(null); - yield return fs => fs.Encrypt(null); - } - - [TestCaseSource("GetFileSystemActionsForArgumentNullException")] - public void Operations_ShouldThrowArgumentNullExceptionIfPathIsNull(Action action) - { - // Arrange - var fileSystem = new MockFileSystem(); - - // Act - TestDelegate wrapped = () => action(fileSystem.File); - - // Assert - var exception = Assert.Throws(wrapped); - Assert.AreEqual("path", exception.ParamName); - } - } -} diff --git a/TestHelpers.Tests/MockFileCopyTests.cs b/TestHelpers.Tests/MockFileCopyTests.cs deleted file mode 100644 index 7dffee39f..000000000 --- a/TestHelpers.Tests/MockFileCopyTests.cs +++ /dev/null @@ -1,275 +0,0 @@ -namespace System.IO.Abstractions.TestingHelpers.Tests -{ - using Collections.Generic; - - using Globalization; - - using Linq; - - using NUnit.Framework; - - using XFS = MockUnixSupport; - - public class MockFileCopyTests { - [Test] - public void MockFile_Copy_ShouldOverwriteFileWhenOverwriteFlagIsTrue() - { - string sourceFileName = XFS.Path(@"c:\source\demo.txt"); - var sourceContents = new MockFileData("Source content"); - string destFileName = XFS.Path(@"c:\destination\demo.txt"); - var fileSystem = new MockFileSystem(new Dictionary - { - {sourceFileName, sourceContents}, - {destFileName, new MockFileData("Destination content")} - }); - - fileSystem.File.Copy(sourceFileName, destFileName, true); - - var copyResult = fileSystem.GetFile(destFileName); - Assert.AreEqual(copyResult.Contents, sourceContents.Contents); - } - - [Test] - public void MockFile_Copy_ShouldCreateFileAtNewDestination() - { - string sourceFileName = XFS.Path(@"c:\source\demo.txt"); - var sourceContents = new MockFileData("Source content"); - string destFileName = XFS.Path(@"c:\source\demo_copy.txt"); - var fileSystem = new MockFileSystem(new Dictionary - { - {sourceFileName, sourceContents} - }); - - fileSystem.File.Copy(sourceFileName, destFileName, false); - - var copyResult = fileSystem.GetFile(destFileName); - Assert.AreEqual(copyResult.Contents, sourceContents.Contents); - } - - [Test] - public void MockFile_Copy_ShouldThrowExceptionWhenFileExistsAtDestination() - { - string sourceFileName = XFS.Path(@"c:\source\demo.txt"); - var sourceContents = new MockFileData("Source content"); - string destFileName = XFS.Path(@"c:\destination\demo.txt"); - var fileSystem = new MockFileSystem(new Dictionary - { - {sourceFileName, sourceContents}, - {destFileName, new MockFileData("Destination content")} - }); - - Assert.Throws(() => fileSystem.File.Copy(sourceFileName, destFileName), XFS.Path(@"The file c:\destination\demo.txt already exists.")); - } - - [TestCase(@"c:\source\demo.txt", @"c:\source\doesnotexist\demo.txt")] - [TestCase(@"c:\source\demo.txt", @"c:\doesnotexist\demo.txt")] - public void MockFile_Copy_ShouldThrowExceptionWhenFolderInDestinationDoesNotExist(string sourceFilePath, string destFilePath) - { - string sourceFileName = XFS.Path(sourceFilePath); - string destFileName = XFS.Path(destFilePath); - var fileSystem = new MockFileSystem(new Dictionary - { - {sourceFileName, MockFileData.NullObject} - }); - - Assert.Throws(() => fileSystem.File.Copy(sourceFileName, destFileName), string.Format(CultureInfo.InvariantCulture, @"Could not find a part of the path '{0}'.", destFilePath)); - } - - [Test] - public void MockFile_Copy_ShouldThrowArgumentNullExceptionWhenSourceIsNull_Message() - { - string destFilePath = XFS.Path(@"c:\something\demo.txt"); - var fileSystem = new MockFileSystem(); - - var exception = Assert.Throws(() => fileSystem.File.Copy(null, destFilePath)); - - Assert.That(exception.Message, Is.StringStarting("File name cannot be null.")); - } - - [Test] - public void MockFile_Copy_ShouldThrowArgumentNullExceptionWhenSourceIsNull_ParamName() - { - string destFilePath = XFS.Path(@"c:\something\demo.txt"); - var fileSystem = new MockFileSystem(); - - var exception = Assert.Throws(() => fileSystem.File.Copy(null, destFilePath)); - - Assert.That(exception.ParamName, Is.EqualTo("sourceFileName")); - } - - [Test] - public void MockFile_Copy_ShouldThrowNotSupportedExceptionWhenSourceFileNameContainsInvalidChars_Message() - { - if (XFS.IsUnixPlatform()) - { - Assert.Pass("Path.GetInvalidChars() does not return anything on Mono"); - return; - } - - var destFilePath = XFS.Path(@"c:\something\demo.txt"); - var fileSystem = new MockFileSystem(); - - foreach (var invalidChar in fileSystem.Path.GetInvalidFileNameChars().Where(x => x != fileSystem.Path.DirectorySeparatorChar)) - { - var sourceFilePath = XFS.Path(@"c:\something\demo.txt") + invalidChar; - - var exception = - Assert.Throws(() => fileSystem.File.Copy(sourceFilePath, destFilePath)); - - Assert.That(exception.Message, Is.EqualTo("Illegal characters in path."), - string.Format("Testing char: [{0:c}] \\{1:X4}", invalidChar, (int)invalidChar)); - } - } - - [Test] - public void MockFile_Copy_ShouldThrowNotSupportedExceptionWhenSourcePathContainsInvalidChars_Message() - { - if (XFS.IsUnixPlatform()) - { - Assert.Pass("Path.GetInvalidChars() does not return anything on Mono"); - return; - } - - var destFilePath = XFS.Path(@"c:\something\demo.txt"); - var fileSystem = new MockFileSystem(); - - foreach (var invalidChar in fileSystem.Path.GetInvalidPathChars()) - { - var sourceFilePath = XFS.Path(@"c:\some" + invalidChar + @"thing\demo.txt"); - - var exception = - Assert.Throws(() => fileSystem.File.Copy(sourceFilePath, destFilePath)); - - Assert.That(exception.Message, Is.EqualTo("Illegal characters in path."), - string.Format("Testing char: [{0:c}] \\{1:X4}", invalidChar, (int)invalidChar)); - } - } - - [Test] - public void MockFile_Copy_ShouldThrowNotSupportedExceptionWhenTargetPathContainsInvalidChars_Message() - { - if (XFS.IsUnixPlatform()) - { - Assert.Pass("Path.GetInvalidChars() does not return anything on Mono"); - return; - } - - var sourceFilePath = XFS.Path(@"c:\something\demo.txt"); - var fileSystem = new MockFileSystem(); - - foreach (var invalidChar in fileSystem.Path.GetInvalidPathChars()) - { - var destFilePath = XFS.Path(@"c:\some" + invalidChar + @"thing\demo.txt"); - - var exception = - Assert.Throws(() => fileSystem.File.Copy(sourceFilePath, destFilePath)); - - Assert.That(exception.Message, Is.EqualTo("Illegal characters in path."), - string.Format("Testing char: [{0:c}] \\{1:X4}", invalidChar, (int)invalidChar)); - } - } - - [Test] - public void MockFile_Copy_ShouldThrowNotSupportedExceptionWhenTargetFileNameContainsInvalidChars_Message() - { - if (XFS.IsUnixPlatform()) - { - Assert.Pass("Path.GetInvalidChars() does not return anything on Mono"); - return; - } - - var sourceFilePath = XFS.Path(@"c:\something\demo.txt"); - var fileSystem = new MockFileSystem(); - - foreach (var invalidChar in fileSystem.Path.GetInvalidFileNameChars().Where(x => x != fileSystem.Path.DirectorySeparatorChar)) - { - var destFilePath = XFS.Path(@"c:\something\demo.txt") + invalidChar; - - var exception = - Assert.Throws(() => fileSystem.File.Copy(sourceFilePath, destFilePath)); - - Assert.That(exception.Message, Is.EqualTo("Illegal characters in path."), - string.Format("Testing char: [{0:c}] \\{1:X4}", invalidChar, (int)invalidChar)); - } - } - - [Test] - public void MockFile_Copy_ShouldThrowArgumentExceptionWhenSourceIsEmpty_Message() - { - string destFilePath = XFS.Path(@"c:\something\demo.txt"); - var fileSystem = new MockFileSystem(); - - var exception = Assert.Throws(() => fileSystem.File.Copy(string.Empty, destFilePath)); - - Assert.That(exception.Message, Is.StringStarting("Empty file name is not legal.")); - } - - [Test] - public void MockFile_Copy_ShouldThrowArgumentExceptionWhenSourceIsEmpty_ParamName() - { - string destFilePath = XFS.Path(@"c:\something\demo.txt"); - var fileSystem = new MockFileSystem(); - - var exception = Assert.Throws(() => fileSystem.File.Copy(string.Empty, destFilePath)); - - Assert.That(exception.ParamName, Is.EqualTo("sourceFileName")); - } - - [Test] - public void MockFile_Copy_ShouldThrowArgumentExceptionWhenSourceIsStringOfBlanks() - { - string sourceFilePath = " "; - string destFilePath = XFS.Path(@"c:\something\demo.txt"); - var fileSystem = new MockFileSystem(); - - var exception = Assert.Throws(() => fileSystem.File.Copy(sourceFilePath, destFilePath)); - - Assert.That(exception.Message, Is.StringStarting("The path is not of a legal form.")); - } - - [Test] - public void MockFile_Copy_ShouldThrowArgumentNullExceptionWhenTargetIsNull_Message() - { - string sourceFilePath = XFS.Path(@"c:\something\demo.txt"); - var fileSystem = new MockFileSystem(); - - var exception = Assert.Throws(() => fileSystem.File.Copy(sourceFilePath, null)); - - Assert.That(exception.Message, Is.StringStarting("File name cannot be null.")); - } - - [Test] - public void MockFile_Copy_ShouldThrowArgumentNullExceptionWhenTargetIsNull_ParamName() - { - string sourceFilePath = XFS.Path(@"c:\something\demo.txt"); - var fileSystem = new MockFileSystem(); - - var exception = Assert.Throws(() => fileSystem.File.Copy(sourceFilePath, null)); - - Assert.That(exception.ParamName, Is.EqualTo("destFileName")); - } - - [Test] - public void MockFile_Copy_ShouldThrowArgumentExceptionWhenTargetIsStringOfBlanks() - { - string sourceFilePath = XFS.Path(@"c:\something\demo.txt"); - string destFilePath = " "; - var fileSystem = new MockFileSystem(); - - var exception = Assert.Throws(() => fileSystem.File.Copy(sourceFilePath, destFilePath)); - - Assert.That(exception.Message, Is.StringStarting("The path is not of a legal form.")); - } - - [Test] - public void MockFile_Copy_ShouldThrowArgumentExceptionWhenTargetIsEmpty_Message() - { - string sourceFilePath = XFS.Path(@"c:\something\demo.txt"); - var fileSystem = new MockFileSystem(); - - var exception = Assert.Throws(() => fileSystem.File.Copy(sourceFilePath, string.Empty)); - - Assert.That(exception.Message, Is.StringStarting("Empty file name is not legal.")); - } - } -} \ No newline at end of file diff --git a/TestHelpers.Tests/MockFileCreateTests.cs b/TestHelpers.Tests/MockFileCreateTests.cs deleted file mode 100644 index 74219e7bc..000000000 --- a/TestHelpers.Tests/MockFileCreateTests.cs +++ /dev/null @@ -1,149 +0,0 @@ -namespace System.IO.Abstractions.TestingHelpers.Tests -{ - using Collections.Generic; - - using Globalization; - - using NUnit.Framework; - - using Text; - - using XFS = MockUnixSupport; - - public class MockFileCreateTests - { - [Test] - public void Mockfile_Create_ShouldCreateNewStream() - { - string fullPath = XFS.Path(@"c:\something\demo.txt"); - var fileSystem = new MockFileSystem(); - - var sut = new MockFile(fileSystem); - - Assert.That(fileSystem.FileExists(fullPath), Is.False); - - sut.Create(fullPath).Close(); - - Assert.That(fileSystem.FileExists(fullPath), Is.True); - } - - [Test] - public void Mockfile_Create_CanWriteToNewStream() - { - string fullPath = XFS.Path(@"c:\something\demo.txt"); - var fileSystem = new MockFileSystem(); - var data = new UTF8Encoding(false).GetBytes("Test string"); - - var sut = new MockFile(fileSystem); - using (var stream = sut.Create(fullPath)) - { - stream.Write(data, 0, data.Length); - } - - var mockFileData = fileSystem.GetFile(fullPath); - var fileData = mockFileData.Contents; - - Assert.That(fileData, Is.EqualTo(data)); - } - - [Test] - public void Mockfile_Create_OverwritesExistingFile() - { - string path = XFS.Path(@"c:\some\file.txt"); - var fileSystem = new MockFileSystem(); - - var mockFile = new MockFile(fileSystem); - - // Create a file - using (var stream = mockFile.Create(path)) - { - var contents = new UTF8Encoding(false).GetBytes("Test 1"); - stream.Write(contents, 0, contents.Length); - } - - // Create new file that should overwrite existing file - var expectedContents = new UTF8Encoding(false).GetBytes("Test 2"); - using (var stream = mockFile.Create(path)) - { - stream.Write(expectedContents, 0, expectedContents.Length); - } - - var actualContents = fileSystem.GetFile(path).Contents; - - Assert.That(actualContents, Is.EqualTo(expectedContents)); - } - - [Test] - public void Mockfile_Create_ShouldThrowUnauthorizedAccessExceptionIfPathIsReadOnly() - { - // Arrange - string path = XFS.Path(@"c:\something\read-only.txt"); - var fileSystem = new MockFileSystem(new Dictionary { { path, new MockFileData("Content") } }); - var mockFile = new MockFile(fileSystem); - - // Act - mockFile.SetAttributes(path, FileAttributes.ReadOnly); - - // Assert - var exception = Assert.Throws(() => mockFile.Create(path).Close()); - Assert.That(exception.Message, Is.EqualTo(string.Format(CultureInfo.InvariantCulture, "Access to the path '{0}' is denied.", path))); - } - - [Test] - public void Mockfile_Create_ShouldThrowArgumentExceptionIfPathIsZeroLength() - { - // Arrange - var fileSystem = new MockFileSystem(); - - // Act - TestDelegate action = () => fileSystem.File.Create(""); - - // Assert - Assert.Throws(action); - } - - [TestCase("\"")] - [TestCase("<")] - [TestCase(">")] - [TestCase("|")] - public void MockFile_Create_ShouldThrowArgumentNullExceptionIfPathIsNull1(string path) - { - // Arrange - var fileSystem = new MockFileSystem(); - - // Act - TestDelegate action = () => fileSystem.File.Create(path); - - // Assert - Assert.Throws(action); - } - - [TestCase(" ")] - [TestCase(" ")] - public void MockFile_Create_ShouldThrowArgumentExceptionIfPathContainsOnlyWhitespaces(string path) - { - // Arrange - var fileSystem = new MockFileSystem(); - - // Act - TestDelegate action = () => fileSystem.File.Create(path); - - // Assert - Assert.Throws(action); - } - - [Test] - public void MockFile_Create_ShouldThrowArgumentNullExceptionIfPathIsNull() - { - // Arrange - var fileSystem = new MockFileSystem(); - - // Act - TestDelegate action = () => fileSystem.File.Create(null); - - // Assert - var exception = Assert.Throws(action); - Assert.That(exception.Message, Is.StringStarting("Path cannot be null.")); - } - } -} \ No newline at end of file diff --git a/TestHelpers.Tests/MockFileDeleteTests.cs b/TestHelpers.Tests/MockFileDeleteTests.cs deleted file mode 100644 index c5a1e9c01..000000000 --- a/TestHelpers.Tests/MockFileDeleteTests.cs +++ /dev/null @@ -1,39 +0,0 @@ -namespace System.IO.Abstractions.TestingHelpers.Tests -{ - using NUnit.Framework; - - using XFS = MockUnixSupport; - - public class MockFileDeleteTests - { - [Test] - public void MockFile_Delete_ShouldDeleteFile() - { - var fileSystem = new MockFileSystem(); - var path = XFS.Path("C:\\test"); - var directory = fileSystem.Path.GetDirectoryName(path); - fileSystem.AddFile(path, new MockFileData("Bla")); - - var fileCount1 = fileSystem.Directory.GetFiles(directory, "*").Length; - fileSystem.File.Delete(path); - var fileCount2 = fileSystem.Directory.GetFiles(directory, "*").Length; - - Assert.AreEqual(1, fileCount1, "File should have existed"); - Assert.AreEqual(0, fileCount2, "File should have been deleted"); - } - - [TestCase(" ")] - [TestCase(" ")] - public void MockFile_Delete_ShouldThrowArgumentExceptionIfPathContainsOnlyWhitespaces(string path) - { - // Arrange - var fileSystem = new MockFileSystem(); - - // Act - TestDelegate action = () => fileSystem.File.Delete(path); - - // Assert - Assert.Throws(action); - } - } -} \ No newline at end of file diff --git a/TestHelpers.Tests/MockFileExistsTests.cs b/TestHelpers.Tests/MockFileExistsTests.cs deleted file mode 100644 index 868c249ba..000000000 --- a/TestHelpers.Tests/MockFileExistsTests.cs +++ /dev/null @@ -1,94 +0,0 @@ -namespace System.IO.Abstractions.TestingHelpers.Tests -{ - using Collections.Generic; - - using NUnit.Framework; - - using XFS = MockUnixSupport; - - public class MockFileExistsTests { - [Test] - public void MockFile_Exists_ShouldReturnTrueForSamePath() - { - // Arrange - var fileSystem = new MockFileSystem(new Dictionary - { - { XFS.Path(@"c:\something\demo.txt"), new MockFileData("Demo text content") }, - { XFS.Path(@"c:\something\other.gif"), new MockFileData(new byte[] { 0x21, 0x58, 0x3f, 0xa9 }) } - }); - - var file = new MockFile(fileSystem); - - // Act - var result = file.Exists(XFS.Path(@"c:\something\other.gif")); - - // Assert - Assert.IsTrue(result); - } - - [Test] - public void MockFile_Exists_ShouldReturnTrueForPathVaryingByCase() - { - // Arrange - var fileSystem = new MockFileSystem(new Dictionary - { - { XFS.Path(@"c:\something\demo.txt"), new MockFileData("Demo text content") }, - { XFS.Path(@"c:\something\other.gif"), new MockFileData(new byte[] { 0x21, 0x58, 0x3f, 0xa9 }) } - }); - - var file = new MockFile(fileSystem); - - // Act - var result = file.Exists(XFS.Path(@"c:\SomeThing\Other.gif")); - - // Assert - Assert.IsTrue(result); - } - - [Test] - public void MockFile_Exists_ShouldReturnFalseForEntirelyDifferentPath() - { - // Arrange - var fileSystem = new MockFileSystem(new Dictionary - { - { XFS.Path(@"c:\something\demo.txt"), new MockFileData("Demo text content") }, - { XFS.Path(@"c:\something\other.gif"), new MockFileData(new byte[] { 0x21, 0x58, 0x3f, 0xa9 }) } - }); - - var file = new MockFile(fileSystem); - - // Act - var result = file.Exists(XFS.Path(@"c:\SomeThing\DoesNotExist.gif")); - - // Assert - Assert.IsFalse(result); - } - - [Test] - public void MockFile_Exists_ShouldReturnFalseForNullPath() - { - var file = new MockFile(new MockFileSystem()); - - Assert.That(file.Exists(null), Is.False); - } - - [Test] - public void MockFile_Exists_ShouldReturnFalseForDirectories() - { - // Arrange - var fileSystem = new MockFileSystem(new Dictionary - { - { XFS.Path(@"c:\something\demo.txt"), new MockFileData("Demo text content") }, - { XFS.Path(@"c:\something\other.gif"), new MockFileData(new byte[] { 0x21, 0x58, 0x3f, 0xa9 }) } - }); - - var file = new MockFile(fileSystem); - - // Act - var result = file.Exists(XFS.Path(@"c:\SomeThing\")); - - // Assert - Assert.IsFalse(result); - } - } -} \ No newline at end of file diff --git a/TestHelpers.Tests/MockFileGetAccessControlTests.cs b/TestHelpers.Tests/MockFileGetAccessControlTests.cs deleted file mode 100644 index 876bd259c..000000000 --- a/TestHelpers.Tests/MockFileGetAccessControlTests.cs +++ /dev/null @@ -1,70 +0,0 @@ -using NUnit.Framework; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Security.AccessControl; - -namespace System.IO.Abstractions.TestingHelpers.Tests -{ - using XFS = MockUnixSupport; - - [TestFixture] - public class MockFileGetAccessControlTests - { - [TestCase(" ")] - [TestCase(" ")] - public void MockFile_GetAccessControl_ShouldThrowArgumentExceptionIfPathContainsOnlyWhitespaces(string path) - { - // Arrange - var fileSystem = new MockFileSystem(); - - // Act - TestDelegate action = () => fileSystem.File.GetAccessControl(path); - - // Assert - var exception = Assert.Throws(action); - Assert.That(exception.ParamName, Is.EqualTo("path")); - } - - [Test] - public void MockFile_GetAccessControl_ShouldThrowFileNotFoundExceptionIfFileDoesNotExistInMockData() - { - // Arrange - var fileSystem = new MockFileSystem(); - var expectedFileName = XFS.Path(@"c:\a.txt"); - - // Act - TestDelegate action = () => fileSystem.File.GetAccessControl(expectedFileName); - - // Assert - var exception = Assert.Throws(action); - Assert.That(exception.FileName, Is.EqualTo(expectedFileName)); - } - - [Test] - public void MockFile_GetAccessControl_ShouldReturnAccessControlOfFileData() - { - // Arrange - var expectedFileSecurity = new FileSecurity(); - expectedFileSecurity.SetAccessRuleProtection(false, false); - - var filePath = XFS.Path(@"c:\a.txt"); - var fileData = new MockFileData("Test content") - { - AccessControl = expectedFileSecurity, - }; - - var fileSystem = new MockFileSystem(new Dictionary() - { - { filePath, fileData } - }); - - // Act - var fileSecurity = fileSystem.File.GetAccessControl(filePath); - - // Assert - Assert.That(fileSecurity, Is.EqualTo(expectedFileSecurity)); - } - } -} diff --git a/TestHelpers.Tests/MockFileGetCreationTimeTests.cs b/TestHelpers.Tests/MockFileGetCreationTimeTests.cs deleted file mode 100644 index 285948272..000000000 --- a/TestHelpers.Tests/MockFileGetCreationTimeTests.cs +++ /dev/null @@ -1,36 +0,0 @@ -using NUnit.Framework; - -namespace System.IO.Abstractions.TestingHelpers.Tests -{ - [TestFixture] - public class MockFileGetCreationTimeTests - { - [TestCase(" ")] - [TestCase(" ")] - public void MockFile_GetCreationTime_ShouldThrowArgumentExceptionIfPathContainsOnlyWhitespaces(string path) - { - // Arrange - var fileSystem = new MockFileSystem(); - - // Act - TestDelegate action = () => fileSystem.File.GetCreationTime(path); - - // Assert - var exception = Assert.Throws(action); - Assert.That(exception.ParamName, Is.EqualTo("path")); - } - - [Test] - public void MockFile_GetCreationTime_ShouldReturnDefaultTimeIfFileDoesNotExist() - { - // Arrange - var fileSystem = new MockFileSystem(); - - // Act - var actualCreationTime = fileSystem.File.GetCreationTime(@"c:\does\not\exist.txt"); - - // Assert - Assert.AreEqual(new DateTime(1601, 01, 01, 00, 00, 00, DateTimeKind.Utc).ToLocalTime(), actualCreationTime); - } - } -} diff --git a/TestHelpers.Tests/MockFileGetCreationTimeUtcTests.cs b/TestHelpers.Tests/MockFileGetCreationTimeUtcTests.cs deleted file mode 100644 index 98f80fd8f..000000000 --- a/TestHelpers.Tests/MockFileGetCreationTimeUtcTests.cs +++ /dev/null @@ -1,36 +0,0 @@ -using NUnit.Framework; - -namespace System.IO.Abstractions.TestingHelpers.Tests -{ - [TestFixture] - public class MockFileGetCreationTimeUtcTests - { - [TestCase(" ")] - [TestCase(" ")] - public void MockFile_GetCreationTimeUtc_ShouldThrowArgumentExceptionIfPathContainsOnlyWhitespaces(string path) - { - // Arrange - var fileSystem = new MockFileSystem(); - - // Act - TestDelegate action = () => fileSystem.File.GetCreationTimeUtc(path); - - // Assert - var exception = Assert.Throws(action); - Assert.That(exception.ParamName, Is.EqualTo("path")); - } - - [Test] - public void MockFile_GetCreationTimeUtc_ShouldReturnDefaultTimeIfFileDoesNotExist() - { - // Arrange - var fileSystem = new MockFileSystem(); - - // Act - var actualCreationTime = fileSystem.File.GetCreationTimeUtc(@"c:\does\not\exist.txt"); - - // Assert - Assert.AreEqual(new DateTime(1601, 01, 01, 00, 00, 00, DateTimeKind.Utc), actualCreationTime); - } - } -} diff --git a/TestHelpers.Tests/MockFileGetLastAccessTimeTests.cs b/TestHelpers.Tests/MockFileGetLastAccessTimeTests.cs deleted file mode 100644 index 8b74d23d8..000000000 --- a/TestHelpers.Tests/MockFileGetLastAccessTimeTests.cs +++ /dev/null @@ -1,36 +0,0 @@ -using NUnit.Framework; - -namespace System.IO.Abstractions.TestingHelpers.Tests -{ - [TestFixture] - public class MockFileGetLastAccessTimeTests - { - [TestCase(" ")] - [TestCase(" ")] - public void MockFile_GetLastAccessTime_ShouldThrowArgumentExceptionIfPathContainsOnlyWhitespaces(string path) - { - // Arrange - var fileSystem = new MockFileSystem(); - - // Act - TestDelegate action = () => fileSystem.File.GetLastAccessTime(path); - - // Assert - var exception = Assert.Throws(action); - Assert.That(exception.ParamName, Is.EqualTo("path")); - } - - [Test] - public void MockFile_GetLastAccessTime_ShouldReturnDefaultTimeIfFileDoesNotExist() - { - // Arrange - var fileSystem = new MockFileSystem(); - - // Act - var actualLastAccessTime = fileSystem.File.GetLastAccessTime(@"c:\does\not\exist.txt"); - - // Assert - Assert.AreEqual(new DateTime(1601, 01, 01, 00, 00, 00, DateTimeKind.Utc).ToLocalTime(), actualLastAccessTime); - } - } -} diff --git a/TestHelpers.Tests/MockFileGetLastAccessTimeUtcTests.cs b/TestHelpers.Tests/MockFileGetLastAccessTimeUtcTests.cs deleted file mode 100644 index b72ff9adf..000000000 --- a/TestHelpers.Tests/MockFileGetLastAccessTimeUtcTests.cs +++ /dev/null @@ -1,36 +0,0 @@ -using NUnit.Framework; - -namespace System.IO.Abstractions.TestingHelpers.Tests -{ - [TestFixture] - public class MockFileGetLastAccessTimeUtcTests - { - [TestCase(" ")] - [TestCase(" ")] - public void MockFile_GetLastAccessTimeUtc_ShouldThrowArgumentExceptionIfPathContainsOnlyWhitespaces(string path) - { - // Arrange - var fileSystem = new MockFileSystem(); - - // Act - TestDelegate action = () => fileSystem.File.GetLastAccessTimeUtc(path); - - // Assert - var exception = Assert.Throws(action); - Assert.That(exception.ParamName, Is.EqualTo("path")); - } - - [Test] - public void MockFile_GetLastAccessTimeUtc_ShouldReturnDefaultTimeIfFileDoesNotExist() - { - // Arrange - var fileSystem = new MockFileSystem(); - - // Act - var actualLastAccessTime = fileSystem.File.GetLastAccessTimeUtc(@"c:\does\not\exist.txt"); - - // Assert - Assert.AreEqual(new DateTime(1601, 01, 01, 00, 00, 00, DateTimeKind.Utc), actualLastAccessTime); - } - } -} diff --git a/TestHelpers.Tests/MockFileGetLastWriteTimeTests.cs b/TestHelpers.Tests/MockFileGetLastWriteTimeTests.cs deleted file mode 100644 index c6e519583..000000000 --- a/TestHelpers.Tests/MockFileGetLastWriteTimeTests.cs +++ /dev/null @@ -1,36 +0,0 @@ -using NUnit.Framework; - -namespace System.IO.Abstractions.TestingHelpers.Tests -{ - [TestFixture] - public class MockFileGetLastWriteTimeTests - { - [TestCase(" ")] - [TestCase(" ")] - public void MockFile_GetLastWriteTime_ShouldThrowArgumentExceptionIfPathContainsOnlyWhitespaces(string path) - { - // Arrange - var fileSystem = new MockFileSystem(); - - // Act - TestDelegate action = () => fileSystem.File.GetLastWriteTime(path); - - // Assert - var exception = Assert.Throws(action); - Assert.That(exception.ParamName, Is.EqualTo("path")); - } - - [Test] - public void MockFile_GetLastWriteTime_ShouldReturnDefaultTimeIfFileDoesNotExist() - { - // Arrange - var fileSystem = new MockFileSystem(); - - // Act - var actualLastWriteTime = fileSystem.File.GetLastWriteTime(@"c:\does\not\exist.txt"); - - // Assert - Assert.AreEqual(new DateTime(1601, 01, 01, 00, 00, 00, DateTimeKind.Utc).ToLocalTime(), actualLastWriteTime); - } - } -} diff --git a/TestHelpers.Tests/MockFileGetLastWriteTimeUtcTests.cs b/TestHelpers.Tests/MockFileGetLastWriteTimeUtcTests.cs deleted file mode 100644 index 5a14d41d9..000000000 --- a/TestHelpers.Tests/MockFileGetLastWriteTimeUtcTests.cs +++ /dev/null @@ -1,35 +0,0 @@ -using NUnit.Framework; - -namespace System.IO.Abstractions.TestingHelpers.Tests -{ - public class MockFileGetLastWriteTimeUtcTests - { - [TestCase(" ")] - [TestCase(" ")] - public void MockFile_GetLastWriteTimeUtc_ShouldThrowArgumentExceptionIfPathContainsOnlyWhitespaces(string path) - { - // Arrange - var fileSystem = new MockFileSystem(); - - // Act - TestDelegate action = () => fileSystem.File.GetLastWriteTimeUtc(path); - - // Assert - var exception = Assert.Throws(action); - Assert.That(exception.ParamName, Is.EqualTo("path")); - } - - [Test] - public void MockFile_GetLastWriteTimeUtc_ShouldReturnDefaultTimeIfFileDoesNotExist() - { - // Arrange - var fileSystem = new MockFileSystem(); - - // Act - var actualLastWriteTime = fileSystem.File.GetLastWriteTimeUtc(@"c:\does\not\exist.txt"); - - // Assert - Assert.AreEqual(new DateTime(1601, 01, 01, 00, 00, 00, DateTimeKind.Utc), actualLastWriteTime); - } - } -} \ No newline at end of file diff --git a/TestHelpers.Tests/MockFileInfoFactoryTests.cs b/TestHelpers.Tests/MockFileInfoFactoryTests.cs deleted file mode 100644 index 9d49bfb00..000000000 --- a/TestHelpers.Tests/MockFileInfoFactoryTests.cs +++ /dev/null @@ -1,45 +0,0 @@ -using System.Collections.Generic; -using NUnit.Framework; - -namespace System.IO.Abstractions.TestingHelpers.Tests -{ - [TestFixture] - public class MockFileInfoFactoryTests - { - [Test] - public void MockFileInfoFactory_FromFileName_ShouldReturnFileInfoForExistingFile() - { - // Arrange - var fileSystem = new MockFileSystem(new Dictionary - { - { @"c:\a.txt", new MockFileData("Demo text content") }, - { @"c:\a\b\c.txt", new MockFileData("Demo text content") }, - }); - var fileInfoFactory = new MockFileInfoFactory(fileSystem); - - // Act - var result = fileInfoFactory.FromFileName(@"c:\a.txt"); - - // Assert - Assert.IsNotNull(result); - } - - [Test] - public void MockFileInfoFactory_FromFileName_ShouldReturnFileInfoForNonExistantFile() - { - // Arrange - var fileSystem = new MockFileSystem(new Dictionary - { - { @"c:\a.txt", new MockFileData("Demo text content") }, - { @"c:\a\b\c.txt", new MockFileData("Demo text content") }, - }); - var fileInfoFactory = new MockFileInfoFactory(fileSystem); - - // Act - var result = fileInfoFactory.FromFileName(@"c:\foo.txt"); - - // Assert - Assert.IsNotNull(result); - } - } -} \ No newline at end of file diff --git a/TestHelpers.Tests/MockFileInfoTests.cs b/TestHelpers.Tests/MockFileInfoTests.cs deleted file mode 100644 index 659820d56..000000000 --- a/TestHelpers.Tests/MockFileInfoTests.cs +++ /dev/null @@ -1,480 +0,0 @@ -using System.Collections.Generic; -using System.Globalization; -using NUnit.Framework; - -namespace System.IO.Abstractions.TestingHelpers.Tests -{ - using XFS = MockUnixSupport; - - [TestFixture] - public class MockFileInfoTests - { - [Test] - public void MockFileInfo_Exists_ShouldReturnTrueIfFileExistsInMemoryFileSystem() - { - // Arrange - var fileSystem = new MockFileSystem(new Dictionary - { - { XFS.Path(@"c:\a.txt"), new MockFileData("Demo text content") }, - { XFS.Path(@"c:\a\b\c.txt"), new MockFileData("Demo text content") }, - }); - var fileInfo = new MockFileInfo(fileSystem, XFS.Path(@"c:\a.txt")); - - // Act - var result = fileInfo.Exists; - - // Assert - Assert.IsTrue(result); - } - - [Test] - public void MockFileInfo_Exists_ShouldReturnFalseIfFileDoesNotExistInMemoryFileSystem() - { - // Arrange - var fileSystem = new MockFileSystem(new Dictionary - { - { XFS.Path(@"c:\a.txt"), new MockFileData("Demo text content") }, - { XFS.Path(@"c:\a\b\c.txt"), new MockFileData("Demo text content") }, - }); - var fileInfo = new MockFileInfo(fileSystem, XFS.Path(@"c:\foo.txt")); - - // Act - var result = fileInfo.Exists; - - // Assert - Assert.IsFalse(result); - } - - [Test] - public void MockFileInfo_Length_ShouldReturnLengthOfFileInMemoryFileSystem() - { - // Arrange - const string fileContent = "Demo text content"; - var fileSystem = new MockFileSystem(new Dictionary - { - { XFS.Path(@"c:\a.txt"), new MockFileData(fileContent) }, - { XFS.Path(@"c:\a\b\c.txt"), new MockFileData(fileContent) }, - }); - var fileInfo = new MockFileInfo(fileSystem, XFS.Path(@"c:\a.txt")); - - // Act - var result = fileInfo.Length; - - // Assert - Assert.AreEqual(fileContent.Length, result); - } - - [Test] - public void MockFileInfo_Length_ShouldThrowFileNotFoundExceptionIfFileDoesNotExistInMemoryFileSystem() - { - // Arrange - const string fileContent = "Demo text content"; - var fileSystem = new MockFileSystem(new Dictionary - { - { XFS.Path(@"c:\a.txt"), new MockFileData(fileContent) }, - { XFS.Path(@"c:\a\b\c.txt"), new MockFileData(fileContent) }, - }); - var fileInfo = new MockFileInfo(fileSystem, XFS.Path(@"c:\foo.txt")); - -// ReSharper disable ReturnValueOfPureMethodIsNotUsed - var ex = Assert.Throws(() => fileInfo.Length.ToString(CultureInfo.InvariantCulture)); -// ReSharper restore ReturnValueOfPureMethodIsNotUsed - Assert.AreEqual(XFS.Path(@"c:\foo.txt"), ex.FileName); - } - - [Test] - public void MockFileInfo_CreationTimeUtc_ShouldReturnCreationTimeUtcOfFileInMemoryFileSystem() - { - // Arrange - var creationTime = DateTime.Now.AddHours(-4); - var fileData = new MockFileData("Demo text content") { CreationTime = creationTime }; - var fileSystem = new MockFileSystem(new Dictionary - { - { XFS.Path(@"c:\a.txt"), fileData } - }); - var fileInfo = new MockFileInfo(fileSystem, XFS.Path(@"c:\a.txt")); - - // Act - var result = fileInfo.CreationTimeUtc; - - // Assert - Assert.AreEqual(creationTime.ToUniversalTime(), result); - } - - [Test] - public void MockFileInfo_CreationTimeUtc_ShouldSetCreationTimeUtcOfFileInMemoryFileSystem() - { - // Arrange - var creationTime = DateTime.Now.AddHours(-4); - var fileData = new MockFileData("Demo text content") { CreationTime = creationTime }; - var fileSystem = new MockFileSystem(new Dictionary - { - { XFS.Path(@"c:\a.txt"), fileData } - }); - var fileInfo = new MockFileInfo(fileSystem, XFS.Path(@"c:\a.txt")); - - // Act - var newUtcTime = DateTime.UtcNow; - fileInfo.CreationTimeUtc = newUtcTime; - - // Assert - Assert.AreEqual(newUtcTime, fileInfo.CreationTimeUtc); - } - - - [Test] - public void MockFileInfo_CreationTime_ShouldReturnCreationTimeOfFileInMemoryFileSystem() - { - // Arrange - var creationTime = DateTime.Now.AddHours(-4); - var fileData = new MockFileData("Demo text content") { CreationTime = creationTime }; - var fileSystem = new MockFileSystem(new Dictionary - { - { XFS.Path(@"c:\a.txt"), fileData } - }); - var fileInfo = new MockFileInfo(fileSystem, XFS.Path(@"c:\a.txt")); - - // Act - var result = fileInfo.CreationTime; - - // Assert - Assert.AreEqual(creationTime, result); - } - - [Test] - public void MockFileInfo_CreationTime_ShouldSetCreationTimeOfFileInMemoryFileSystem() - { - // Arrange - var creationTime = DateTime.Now.AddHours(-4); - var fileData = new MockFileData("Demo text content") { CreationTime = creationTime }; - var fileSystem = new MockFileSystem(new Dictionary - { - { XFS.Path(@"c:\a.txt"), fileData } - }); - var fileInfo = new MockFileInfo(fileSystem, XFS.Path(@"c:\a.txt")); - - // Act - var newTime = DateTime.Now; - fileInfo.CreationTime = newTime; - - // Assert - Assert.AreEqual(newTime, fileInfo.CreationTime); - } - - [Test] - public void MockFileInfo_IsReadOnly_ShouldSetReadOnlyAttributeOfFileInMemoryFileSystem() - { - // Arrange - var fileData = new MockFileData("Demo text content"); - var fileSystem = new MockFileSystem(new Dictionary - { - { XFS.Path(@"c:\a.txt"), fileData } - }); - var fileInfo = new MockFileInfo(fileSystem, XFS.Path(@"c:\a.txt")); - - // Act - fileInfo.IsReadOnly = true; - - // Assert - Assert.AreEqual(FileAttributes.ReadOnly, fileData.Attributes & FileAttributes.ReadOnly); - } - - [Test] - public void MockFileInfo_IsReadOnly_ShouldSetNotReadOnlyAttributeOfFileInMemoryFileSystem() - { - // Arrange - var fileData = new MockFileData("Demo text content") {Attributes = FileAttributes.ReadOnly}; - var fileSystem = new MockFileSystem(new Dictionary - { - { XFS.Path(@"c:\a.txt"), fileData } - }); - var fileInfo = new MockFileInfo(fileSystem, XFS.Path(@"c:\a.txt")); - - // Act - fileInfo.IsReadOnly = false; - - // Assert - Assert.AreNotEqual(FileAttributes.ReadOnly, fileData.Attributes & FileAttributes.ReadOnly); - } - - [Test] - public void MockFileInfo_AppendText_ShouldAddTextToFileInMemoryFileSystem() - { - // Arrange - var fileData = new MockFileData("Demo text content"); - var fileSystem = new MockFileSystem(new Dictionary - { - { XFS.Path(@"c:\a.txt"), fileData } - }); - var fileInfo = new MockFileInfo(fileSystem, XFS.Path(@"c:\a.txt")); - - // Act - using (var file = fileInfo.AppendText()) - file.WriteLine("This should be at the end"); - - string newcontents; - using (var newfile = fileInfo.OpenText()) - newcontents = newfile.ReadToEnd(); - - // Assert - Assert.AreEqual("Demo text contentThis should be at the end\r\n", newcontents); - } - - [Test] - public void MockFileInfo_OpenWrite_ShouldAddDataToFileInMemoryFileSystem() - { - // Arrange - var fileData = new MockFileData("Demo text content"); - var fileSystem = new MockFileSystem(new Dictionary - { - { XFS.Path(@"c:\a.txt"), fileData } - }); - var fileInfo = new MockFileInfo(fileSystem, XFS.Path(@"c:\a.txt")); - var bytesToAdd = new byte[] {65, 66, 67, 68, 69}; - - // Act - using (var file = fileInfo.OpenWrite()) - file.Write(bytesToAdd, 0, bytesToAdd.Length); - - string newcontents; - using (var newfile = fileInfo.OpenText()) - newcontents = newfile.ReadToEnd(); - - // Assert - Assert.AreEqual("ABCDEtext content", newcontents); - } - - [Test] - public void MockFileInfo_Encrypt_ShouldReturnXorOfFileInMemoryFileSystem() - { - // Arrange - var fileData = new MockFileData("Demo text content"); - var fileSystem = new MockFileSystem(new Dictionary - { - { XFS.Path(@"c:\a.txt"), fileData } - }); - var fileInfo = new MockFileInfo(fileSystem, XFS.Path(@"c:\a.txt")); - - // Act - fileInfo.Encrypt(); - - string newcontents; - using (var newfile = fileInfo.OpenText()) - { - newcontents = newfile.ReadToEnd(); - } - - // Assert - Assert.AreNotEqual("Demo text content", newcontents); - } - - [Test] - public void MockFileInfo_Decrypt_ShouldReturnCorrectContentsFileInMemoryFileSystem() - { - // Arrange - var fileData = new MockFileData("Demo text content"); - var fileSystem = new MockFileSystem(new Dictionary - { - { XFS.Path(@"c:\a.txt"), fileData } - }); - var fileInfo = new MockFileInfo(fileSystem, XFS.Path(@"c:\a.txt")); - fileInfo.Encrypt(); - - // Act - fileInfo.Decrypt(); - - string newcontents; - using (var newfile = fileInfo.OpenText()) - { - newcontents = newfile.ReadToEnd(); - } - - // Assert - Assert.AreEqual("Demo text content", newcontents); - } - - [Test] - public void MockFileInfo_LastAccessTimeUtc_ShouldReturnLastAccessTimeUtcOfFileInMemoryFileSystem() - { - // Arrange - var lastAccessTime = DateTime.Now.AddHours(-4); - var fileData = new MockFileData("Demo text content") { LastAccessTime = lastAccessTime }; - var fileSystem = new MockFileSystem(new Dictionary - { - { XFS.Path(@"c:\a.txt"), fileData } - }); - var fileInfo = new MockFileInfo(fileSystem, XFS.Path(@"c:\a.txt")); - - // Act - var result = fileInfo.LastAccessTimeUtc; - - // Assert - Assert.AreEqual(lastAccessTime.ToUniversalTime(), result); - } - - [Test] - public void MockFileInfo_LastAccessTimeUtc_ShouldSetCreationTimeUtcOfFileInMemoryFileSystem() - { - // Arrange - var lastAccessTime = DateTime.Now.AddHours(-4); - var fileData = new MockFileData("Demo text content") { LastAccessTime = lastAccessTime }; - var fileSystem = new MockFileSystem(new Dictionary - { - { XFS.Path(@"c:\a.txt"), fileData } - }); - var fileInfo = new MockFileInfo(fileSystem, XFS.Path(@"c:\a.txt")); - - // Act - var newUtcTime = DateTime.UtcNow; - fileInfo.LastAccessTimeUtc = newUtcTime; - - // Assert - Assert.AreEqual(newUtcTime, fileInfo.LastAccessTimeUtc); - } - - [Test] - public void MockFileInfo_LastWriteTimeUtc_ShouldReturnLastWriteTimeUtcOfFileInMemoryFileSystem() - { - // Arrange - var lastWriteTime = DateTime.Now.AddHours(-4); - var fileData = new MockFileData("Demo text content") { LastWriteTime = lastWriteTime }; - var fileSystem = new MockFileSystem(new Dictionary - { - { XFS.Path(@"c:\a.txt"), fileData } - }); - var fileInfo = new MockFileInfo(fileSystem, XFS.Path(@"c:\a.txt")); - - // Act - var result = fileInfo.LastWriteTimeUtc; - - // Assert - Assert.AreEqual(lastWriteTime.ToUniversalTime(), result); - } - - [Test] - public void MockFileInfo_LastWriteTimeUtc_ShouldSetLastWriteTimeUtcOfFileInMemoryFileSystem() - { - // Arrange - var lastWriteTime = DateTime.Now.AddHours(-4); - var fileData = new MockFileData("Demo text content") { LastWriteTime = lastWriteTime }; - var fileSystem = new MockFileSystem(new Dictionary - { - { XFS.Path(@"c:\a.txt"), fileData } - }); - var fileInfo = new MockFileInfo(fileSystem, XFS.Path(@"c:\a.txt")); - - // Act - var newUtcTime = DateTime.UtcNow; - fileInfo.LastWriteTime = newUtcTime; - - // Assert - Assert.AreEqual(newUtcTime, fileInfo.LastWriteTime); - } - - [Test] - public void MockFileInfo_GetExtension_ShouldReturnExtension() - { - // Arrange - var fileSystem = new MockFileSystem(new Dictionary()); - var fileInfo = new MockFileInfo(fileSystem, XFS.Path(@"c:\a.txt")); - - // Act - var result = fileInfo.Extension; - - // Assert - Assert.AreEqual(".txt", result); - } - - [Test] - public void MockFileInfo_GetExtensionWithoutExtension_ShouldReturnEmptyString() - { - // Arrange - var fileSystem = new MockFileSystem(new Dictionary()); - var fileInfo = new MockFileInfo(fileSystem, XFS.Path(@"c:\a")); - - // Act - var result = fileInfo.Extension; - - // Assert - Assert.AreEqual(string.Empty, result); - } - - [Test] - public void MockFileInfo_GetDirectoryName_ShouldReturnCompleteDirectoryPath() - { - // Arrange - var fileInfo = new MockFileInfo(new MockFileSystem(), XFS.Path(@"c:\temp\level1\level2\file.txt")); - - // Act - var result = fileInfo.DirectoryName; - - Assert.AreEqual(XFS.Path(@"c:\temp\level1\level2"), result); - } - - [Test] - public void MockFileInfo_GetDirectory_ShouldReturnDirectoryInfoWithCorrectPath() - { - // Arrange - var fileInfo = new MockFileInfo(new MockFileSystem(), XFS.Path(@"c:\temp\level1\level2\file.txt")); - - // Act - var result = fileInfo.Directory; - - Assert.AreEqual(XFS.Path(@"c:\temp\level1\level2"), result.FullName); - } - - [Test] - public void MockFileInfo_OpenRead_ShouldReturnByteContentOfFile() - { - // Arrange - var fileSystem = new MockFileSystem(); - fileSystem.AddFile(XFS.Path(@"c:\temp\file.txt"), new MockFileData(new byte[] { 1, 2 })); - var fileInfo = fileSystem.FileInfo.FromFileName(XFS.Path(@"c:\temp\file.txt")); - - // Act - byte[] result = new byte[2]; - using (var stream = fileInfo.OpenRead()) - { - stream.Read(result, 0, 2); - } - - Assert.AreEqual(new byte[] { 1, 2 }, result); - } - - [Test] - public void MockFileInfo_OpenText_ShouldReturnStringContentOfFile() - { - // Arrange - var fileSystem = new MockFileSystem(); - fileSystem.AddFile(XFS.Path(@"c:\temp\file.txt"), new MockFileData(@"line 1\r\nline 2")); - var fileInfo = fileSystem.FileInfo.FromFileName(XFS.Path(@"c:\temp\file.txt")); - - // Act - string result; - using (var streamReader = fileInfo.OpenText()) - { - result = streamReader.ReadToEnd(); - } - - Assert.AreEqual(@"line 1\r\nline 2", result); - } - - [Test] - public void MockFileInfo_MoveTo_ShouldUpdateFileInfoDirectoryAndFullName() - { - // Arrange - var fileSystem = new MockFileSystem(); - fileSystem.AddFile(XFS.Path(@"c:\temp\file.txt"), new MockFileData(@"line 1\r\nline 2")); - var fileInfo = fileSystem.FileInfo.FromFileName(XFS.Path(@"c:\temp\file.txt")); - - // Act - string destinationFolder = XFS.Path(@"c:\temp2"); - string destination = XFS.Path(destinationFolder + @"\file.txt"); - fileSystem.AddDirectory(destination); - fileInfo.MoveTo(destination); - - Assert.AreEqual(fileInfo.DirectoryName, destinationFolder); - Assert.AreEqual(fileInfo.FullName, destination); - } - } -} \ No newline at end of file diff --git a/TestHelpers.Tests/MockFileMoveTests.cs b/TestHelpers.Tests/MockFileMoveTests.cs deleted file mode 100644 index 090a6b23f..000000000 --- a/TestHelpers.Tests/MockFileMoveTests.cs +++ /dev/null @@ -1,290 +0,0 @@ -namespace System.IO.Abstractions.TestingHelpers.Tests -{ - using Collections.Generic; - - using Linq; - - using NUnit.Framework; - - using XFS = MockUnixSupport; - - public class MockFileMoveTests { - [Test] - public void MockFile_Move_ShouldMoveFileWithinMemoryFileSystem() - { - string sourceFilePath = XFS.Path(@"c:\something\demo.txt"); - string sourceFileContent = "this is some content"; - var fileSystem = new MockFileSystem(new Dictionary - { - {sourceFilePath, new MockFileData(sourceFileContent)}, - {XFS.Path(@"c:\somethingelse\dummy.txt"), new MockFileData(new byte[] {0})} - }); - - string destFilePath = XFS.Path(@"c:\somethingelse\demo1.txt"); - - fileSystem.File.Move(sourceFilePath, destFilePath); - - Assert.That(fileSystem.FileExists(destFilePath), Is.True); - Assert.That(fileSystem.GetFile(destFilePath).TextContents, Is.EqualTo(sourceFileContent)); - Assert.That(fileSystem.FileExists(sourceFilePath), Is.False); - } - - [Test] - public void MockFile_Move_ShouldThrowIOExceptionWhenTargetAlreadyExists() - { - string sourceFilePath = XFS.Path(@"c:\something\demo.txt"); - string sourceFileContent = "this is some content"; - string destFilePath = XFS.Path(@"c:\somethingelse\demo1.txt"); - var fileSystem = new MockFileSystem(new Dictionary - { - {sourceFilePath, new MockFileData(sourceFileContent)}, - {destFilePath, new MockFileData(sourceFileContent)} - }); - - var exception = Assert.Throws(() => fileSystem.File.Move(sourceFilePath, destFilePath)); - - Assert.That(exception.Message, Is.EqualTo("A file can not be created if it already exists.")); - } - - [Test] - public void MockFile_Move_ShouldThrowArgumentNullExceptionWhenSourceIsNull_Message() - { - string destFilePath = XFS.Path(@"c:\something\demo.txt"); - var fileSystem = new MockFileSystem(); - - var exception = Assert.Throws(() => fileSystem.File.Move(null, destFilePath)); - - Assert.That(exception.Message, Is.StringStarting("File name cannot be null.")); - } - - [Test] - public void MockFile_Move_ShouldThrowArgumentNullExceptionWhenSourceIsNull_ParamName() { - string destFilePath = XFS.Path(@"c:\something\demo.txt"); - var fileSystem = new MockFileSystem(); - - var exception = Assert.Throws(() => fileSystem.File.Move(null, destFilePath)); - - Assert.That(exception.ParamName, Is.EqualTo("sourceFileName")); - } - - [Test] - public void MockFile_Move_ShouldThrowNotSupportedExceptionWhenSourceFileNameContainsInvalidChars_Message() - { - if (XFS.IsUnixPlatform()) - { - Assert.Pass("Path.GetInvalidChars() does not return anything on Mono"); - return; - } - - var destFilePath = XFS.Path(@"c:\something\demo.txt"); - var fileSystem = new MockFileSystem(); - - foreach (var invalidChar in fileSystem.Path.GetInvalidFileNameChars().Where(x => x != fileSystem.Path.DirectorySeparatorChar)) - { - var sourceFilePath = XFS.Path(@"c:\something\demo.txt") + invalidChar; - - var exception = - Assert.Throws(() => fileSystem.File.Move(sourceFilePath, destFilePath)); - - Assert.That(exception.Message, Is.EqualTo("Illegal characters in path."), - string.Format("Testing char: [{0:c}] \\{1:X4}", invalidChar, (int)invalidChar)); - } - } - - [Test] - public void MockFile_Move_ShouldThrowNotSupportedExceptionWhenSourcePathContainsInvalidChars_Message() - { - if (XFS.IsUnixPlatform()) - { - Assert.Pass("Path.GetInvalidChars() does not return anything on Mono"); - return; - } - - var destFilePath = XFS.Path(@"c:\something\demo.txt"); - var fileSystem = new MockFileSystem(); - - foreach (var invalidChar in fileSystem.Path.GetInvalidPathChars()) - { - var sourceFilePath = XFS.Path(@"c:\some" + invalidChar + @"thing\demo.txt"); - - var exception = - Assert.Throws(() => fileSystem.File.Move(sourceFilePath, destFilePath)); - - Assert.That(exception.Message, Is.EqualTo("Illegal characters in path."), - string.Format("Testing char: [{0:c}] \\{1:X4}", invalidChar, (int)invalidChar)); - } - } - - [Test] - public void MockFile_Move_ShouldThrowNotSupportedExceptionWhenTargetPathContainsInvalidChars_Message() - { - if (XFS.IsUnixPlatform()) - { - Assert.Pass("Path.GetInvalidChars() does not return anything on Mono"); - return; - } - - var sourceFilePath = XFS.Path(@"c:\something\demo.txt"); - var fileSystem = new MockFileSystem(); - - foreach (var invalidChar in fileSystem.Path.GetInvalidPathChars()) - { - var destFilePath = XFS.Path(@"c:\some" + invalidChar + @"thing\demo.txt"); - - var exception = - Assert.Throws(() => fileSystem.File.Move(sourceFilePath, destFilePath)); - - Assert.That(exception.Message, Is.EqualTo("Illegal characters in path."), - string.Format("Testing char: [{0:c}] \\{1:X4}", invalidChar, (int)invalidChar)); - } - } - - [Test] - public void MockFile_Move_ShouldThrowNotSupportedExceptionWhenTargetFileNameContainsInvalidChars_Message() - { - if (XFS.IsUnixPlatform()) - { - Assert.Pass("Path.GetInvalidChars() does not return anything on Mono"); - return; - } - - var sourceFilePath = XFS.Path(@"c:\something\demo.txt"); - var fileSystem = new MockFileSystem(); - - foreach (var invalidChar in fileSystem.Path.GetInvalidFileNameChars().Where(x => x != fileSystem.Path.DirectorySeparatorChar)) - { - var destFilePath = XFS.Path(@"c:\something\demo.txt") + invalidChar; - - var exception = - Assert.Throws(() => fileSystem.File.Move(sourceFilePath, destFilePath)); - - Assert.That(exception.Message, Is.EqualTo("Illegal characters in path."), - string.Format("Testing char: [{0:c}] \\{1:X4}", invalidChar, (int)invalidChar)); - } - } - - [Test] - public void MockFile_Move_ShouldThrowArgumentExceptionWhenSourceIsEmpty_Message() - { - string destFilePath = XFS.Path(@"c:\something\demo.txt"); - var fileSystem = new MockFileSystem(); - - var exception = Assert.Throws(() => fileSystem.File.Move(string.Empty, destFilePath)); - - Assert.That(exception.Message, Is.StringStarting("Empty file name is not legal.")); - } - - [Test] - public void MockFile_Move_ShouldThrowArgumentExceptionWhenSourceIsEmpty_ParamName() { - string destFilePath = XFS.Path(@"c:\something\demo.txt"); - var fileSystem = new MockFileSystem(); - - var exception = Assert.Throws(() => fileSystem.File.Move(string.Empty, destFilePath)); - - Assert.That(exception.ParamName, Is.EqualTo("sourceFileName")); - } - - [Test] - public void MockFile_Move_ShouldThrowArgumentExceptionWhenSourceIsStringOfBlanks() - { - string sourceFilePath = " "; - string destFilePath = XFS.Path(@"c:\something\demo.txt"); - var fileSystem = new MockFileSystem(); - - var exception = Assert.Throws(() => fileSystem.File.Move(sourceFilePath, destFilePath)); - - Assert.That(exception.Message, Is.StringStarting("The path is not of a legal form.")); - } - - [Test] - public void MockFile_Move_ShouldThrowArgumentNullExceptionWhenTargetIsNull_Message() - { - string sourceFilePath = XFS.Path(@"c:\something\demo.txt"); - var fileSystem = new MockFileSystem(); - - var exception = Assert.Throws(() => fileSystem.File.Move(sourceFilePath, null)); - - Assert.That(exception.Message, Is.StringStarting("File name cannot be null.")); - } - - [Test] - public void MockFile_Move_ShouldThrowArgumentNullExceptionWhenTargetIsNull_ParamName() { - string sourceFilePath = XFS.Path(@"c:\something\demo.txt"); - var fileSystem = new MockFileSystem(); - - var exception = Assert.Throws(() => fileSystem.File.Move(sourceFilePath, null)); - - Assert.That(exception.ParamName, Is.EqualTo("destFileName")); - } - - [Test] - public void MockFile_Move_ShouldThrowArgumentExceptionWhenTargetIsStringOfBlanks() - { - string sourceFilePath = XFS.Path(@"c:\something\demo.txt"); - string destFilePath = " "; - var fileSystem = new MockFileSystem(); - - var exception = Assert.Throws(() => fileSystem.File.Move(sourceFilePath, destFilePath)); - - Assert.That(exception.Message, Is.StringStarting("The path is not of a legal form.")); - } - - [Test] - public void MockFile_Move_ShouldThrowArgumentExceptionWhenTargetIsEmpty_Message() - { - string sourceFilePath = XFS.Path(@"c:\something\demo.txt"); - var fileSystem = new MockFileSystem(); - - var exception = Assert.Throws(() => fileSystem.File.Move(sourceFilePath, string.Empty)); - - Assert.That(exception.Message, Is.StringStarting("Empty file name is not legal.")); - } - - [Test] - public void MockFile_Move_ShouldThrowArgumentExceptionWhenTargetIsEmpty_ParamName() { - string sourceFilePath = XFS.Path(@"c:\something\demo.txt"); - var fileSystem = new MockFileSystem(); - - var exception = Assert.Throws(() => fileSystem.File.Move(sourceFilePath, string.Empty)); - - Assert.That(exception.ParamName, Is.EqualTo("destFileName")); - } - - [Test] - public void MockFile_Move_ShouldThrowFileNotFoundExceptionWhenSourceDoesNotExist_Message() - { - string sourceFilePath = XFS.Path(@"c:\something\demo.txt"); - string destFilePath = XFS.Path(@"c:\something\demo1.txt"); - var fileSystem = new MockFileSystem(); - - var exception = Assert.Throws(() => fileSystem.File.Move(sourceFilePath, destFilePath)); - - Assert.That(exception.Message, Is.EqualTo("The file \"" + XFS.Path("c:\\something\\demo.txt") + "\" could not be found.")); - } - - [Test] - public void MockFile_Move_ShouldThrowFileNotFoundExceptionWhenSourceDoesNotExist_FileName() { - string sourceFilePath = XFS.Path(@"c:\something\demo.txt"); - string destFilePath = XFS.Path(@"c:\something\demo1.txt"); - var fileSystem = new MockFileSystem(); - - var exception = Assert.Throws(() => fileSystem.File.Move(sourceFilePath, destFilePath)); - - Assert.That(exception.FileName, Is.EqualTo(XFS.Path(@"c:\something\demo.txt"))); - } - - [Test] - public void MockFile_Move_ShouldThrowDirectoryNotFoundExceptionWhenSourcePathDoesNotExist_Message() - { - string sourceFilePath = XFS.Path(@"c:\something\demo.txt"); - string destFilePath = XFS.Path(@"c:\somethingelse\demo.txt"); - var fileSystem = new MockFileSystem(new Dictionary - { - {sourceFilePath, new MockFileData(new byte[] {0})} - }); - - Assert.That(() => fileSystem.File.Move(sourceFilePath, destFilePath), - Throws.InstanceOf().With.Message.StartsWith(@"Could not find a part of the path")); - } - } -} \ No newline at end of file diff --git a/TestHelpers.Tests/MockFileOpenTests.cs b/TestHelpers.Tests/MockFileOpenTests.cs deleted file mode 100644 index 0e8024f39..000000000 --- a/TestHelpers.Tests/MockFileOpenTests.cs +++ /dev/null @@ -1,244 +0,0 @@ -namespace System.IO.Abstractions.TestingHelpers.Tests -{ - using Collections.Generic; - - using NUnit.Framework; - - using XFS = MockUnixSupport; - - public class MockFileOpenTests { - [Test] - public void MockFile_Open_ThrowsOnCreateNewWithExistingFile() - { - string filepath = XFS.Path(@"c:\something\already\exists.txt"); - var filesystem = new MockFileSystem(new Dictionary - { - { filepath, new MockFileData("I'm here") } - }); - - Assert.Throws(() => filesystem.File.Open(filepath, FileMode.CreateNew)); - } - - [Test] - public void MockFile_Open_ThrowsOnOpenWithMissingFile() - { - string filepath = XFS.Path(@"c:\something\doesnt\exist.txt"); - var filesystem = new MockFileSystem(new Dictionary()); - - Assert.Throws(() => filesystem.File.Open(filepath, FileMode.Open)); - } - - [Test] - public void MockFile_Open_ThrowsOnTruncateWithMissingFile() - { - string filepath = XFS.Path(@"c:\something\doesnt\exist.txt"); - var filesystem = new MockFileSystem(new Dictionary()); - - Assert.Throws(() => filesystem.File.Open(filepath, FileMode.Truncate)); - } - - [Test] - public void MockFile_Open_CreatesNewFileFileOnCreate() - { - string filepath = XFS.Path(@"c:\something\doesnt\exist.txt"); - var filesystem = new MockFileSystem(new Dictionary()); - - var stream = filesystem.File.Open(filepath, FileMode.Create); - - Assert.That(filesystem.File.Exists(filepath), Is.True); - Assert.That(stream.Position, Is.EqualTo(0)); - Assert.That(stream.Length, Is.EqualTo(0)); - } - - [Test] - public void MockFile_Open_CreatesNewFileFileOnCreateNew() - { - string filepath = XFS.Path(@"c:\something\doesnt\exist.txt"); - var filesystem = new MockFileSystem(new Dictionary()); - - var stream = filesystem.File.Open(filepath, FileMode.CreateNew); - - Assert.That(filesystem.File.Exists(filepath), Is.True); - Assert.That(stream.Position, Is.EqualTo(0)); - Assert.That(stream.Length, Is.EqualTo(0)); - } - - [Test] - public void MockFile_Open_OpensExistingFileOnAppend() - { - string filepath = XFS.Path(@"c:\something\does\exist.txt"); - var filesystem = new MockFileSystem(new Dictionary - { - { filepath, new MockFileData("I'm here") } - }); - - var stream = filesystem.File.Open(filepath, FileMode.Append); - var file = filesystem.GetFile(filepath); - - Assert.That(stream.Position, Is.EqualTo(file.Contents.Length)); - Assert.That(stream.Length, Is.EqualTo(file.Contents.Length)); - - stream.Seek(0, SeekOrigin.Begin); - - byte[] data; - using (var br = new BinaryReader(stream)) - data = br.ReadBytes((int)stream.Length); - - CollectionAssert.AreEqual(file.Contents, data); - } - - [Test] - public void MockFile_Open_OpensExistingFileOnTruncate() - { - string filepath = XFS.Path(@"c:\something\does\exist.txt"); - var filesystem = new MockFileSystem(new Dictionary - { - { filepath, new MockFileData("I'm here") } - }); - - var stream = filesystem.File.Open(filepath, FileMode.Truncate); - var file = filesystem.GetFile(filepath); - - Assert.That(stream.Position, Is.EqualTo(0)); - Assert.That(stream.Length, Is.EqualTo(0)); - Assert.That(file.Contents.Length, Is.EqualTo(0)); - } - - [Test] - public void MockFile_Open_OpensExistingFileOnOpen() - { - string filepath = XFS.Path(@"c:\something\does\exist.txt"); - var filesystem = new MockFileSystem(new Dictionary - { - { filepath, new MockFileData("I'm here") } - }); - - var stream = filesystem.File.Open(filepath, FileMode.Open); - var file = filesystem.GetFile(filepath); - - Assert.That(stream.Position, Is.EqualTo(0)); - Assert.That(stream.Length, Is.EqualTo(file.Contents.Length)); - - byte[] data; - using (var br = new BinaryReader(stream)) - data = br.ReadBytes((int)stream.Length); - - CollectionAssert.AreEqual(file.Contents, data); - } - - [Test] - public void MockFile_Open_OpensExistingFileOnOpenOrCreate() - { - string filepath = XFS.Path(@"c:\something\does\exist.txt"); - var filesystem = new MockFileSystem(new Dictionary - { - { filepath, new MockFileData("I'm here") } - }); - - var stream = filesystem.File.Open(filepath, FileMode.OpenOrCreate); - var file = filesystem.GetFile(filepath); - - Assert.That(stream.Position, Is.EqualTo(0)); - Assert.That(stream.Length, Is.EqualTo(file.Contents.Length)); - - byte[] data; - using (var br = new BinaryReader(stream)) - data = br.ReadBytes((int)stream.Length); - - CollectionAssert.AreEqual(file.Contents, data); - } - - [Test] - public void MockFile_Open_CreatesNewFileOnOpenOrCreate() - { - string filepath = XFS.Path(@"c:\something\doesnt\exist.txt"); - var filesystem = new MockFileSystem(new Dictionary()); - - var stream = filesystem.File.Open(filepath, FileMode.OpenOrCreate); - - Assert.That(filesystem.File.Exists(filepath), Is.True); - Assert.That(stream.Position, Is.EqualTo(0)); - Assert.That(stream.Length, Is.EqualTo(0)); - } - - [Test] - public void MockFile_Open_OverwritesExistingFileOnCreate() - { - string filepath = XFS.Path(@"c:\something\doesnt\exist.txt"); - var filesystem = new MockFileSystem(new Dictionary - { - { filepath, new MockFileData("I'm here") } - }); - - var stream = filesystem.File.Open(filepath, FileMode.Create); - var file = filesystem.GetFile(filepath); - - Assert.That(stream.Position, Is.EqualTo(0)); - Assert.That(stream.Length, Is.EqualTo(0)); - Assert.That(file.Contents.Length, Is.EqualTo(0)); - } - - [Test] - public void MockFile_OpenText_ShouldRetainLastWriteTime() - { - // Arrange - var fs = new MockFileSystem(); - string filepath = XFS.Path(@"C:\TestData\test.txt"); - var file = new MockFileData(@"I'm here"); - var lastWriteTime = new DateTime(2012, 03, 21); - file.LastWriteTime = lastWriteTime; - fs.AddFile(filepath, file); - - // Act - using (var reader = fs.File.OpenText(filepath)) - { - reader.ReadLine(); - } - - // Assert - Assert.AreEqual(lastWriteTime, fs.FileInfo.FromFileName(filepath).LastWriteTime); - } - - [Test] - public void MockFile_OpenText_ShouldRetainLastAccessTime() - { - // Arrange - var fs = new MockFileSystem(); - string filepath = XFS.Path(@"C:\TestData\test.txt"); - var file = new MockFileData(@"I'm here"); - var lastAccessTime = new DateTime(2012, 03, 21); - file.LastAccessTime = lastAccessTime; - fs.AddFile(filepath, file); - - // Act - using (var reader = fs.File.OpenText(filepath)) - { - reader.ReadLine(); - } - - // Assert - Assert.AreEqual(lastAccessTime, fs.FileInfo.FromFileName(filepath).LastAccessTime); - } - - [Test] - public void MockFile_OpenText_ShouldRetainCreationTime() - { - // Arrange - var fs = new MockFileSystem(); - string filepath = XFS.Path(@"C:\TestData\test.txt"); - var file = new MockFileData(@"I'm here"); - var creationTime = new DateTime(2012, 03, 21); - file.CreationTime = creationTime; - fs.AddFile(filepath, file); - - // Act - using (var reader = fs.File.OpenText(filepath)) - { - reader.ReadLine(); - } - - // Assert - Assert.AreEqual(creationTime, fs.FileInfo.FromFileName(filepath).CreationTime); - } - } -} \ No newline at end of file diff --git a/TestHelpers.Tests/MockFileReadAllLinesTests.cs b/TestHelpers.Tests/MockFileReadAllLinesTests.cs deleted file mode 100644 index 327f11e02..000000000 --- a/TestHelpers.Tests/MockFileReadAllLinesTests.cs +++ /dev/null @@ -1,55 +0,0 @@ -namespace System.IO.Abstractions.TestingHelpers.Tests -{ - using Collections.Generic; - - using NUnit.Framework; - - using Text; - - using XFS = MockUnixSupport; - - public class MockFileReadAllLinesTests { - [Test] - public void MockFile_ReadAllLines_ShouldReturnOriginalTextData() - { - // Arrange - var fileSystem = new MockFileSystem(new Dictionary - { - { XFS.Path(@"c:\something\demo.txt"), new MockFileData("Demo\r\ntext\ncontent\rvalue") }, - { XFS.Path(@"c:\something\other.gif"), new MockFileData(new byte[] { 0x21, 0x58, 0x3f, 0xa9 }) } - }); - - var file = new MockFile(fileSystem); - - // Act - var result = file.ReadAllLines(XFS.Path(@"c:\something\demo.txt")); - - // Assert - CollectionAssert.AreEqual( - new[] { "Demo", "text", "content", "value" }, - result); - } - - [Test] - public void MockFile_ReadAllLines_ShouldReturnOriginalDataWithCustomEncoding() - { - // Arrange - string text = "Hello\r\nthere\rBob\nBob!"; - var encodedText = Encoding.BigEndianUnicode.GetBytes(text); - var fileSystem = new MockFileSystem(new Dictionary - { - { XFS.Path(@"c:\something\demo.txt"), new MockFileData(encodedText) } - }); - - var file = new MockFile(fileSystem); - - // Act - var result = file.ReadAllLines(XFS.Path(@"c:\something\demo.txt"), Encoding.BigEndianUnicode); - - // Assert - CollectionAssert.AreEqual( - new [] { "Hello", "there", "Bob", "Bob!" }, - result); - } - } -} \ No newline at end of file diff --git a/TestHelpers.Tests/MockFileReadLinesTests.cs b/TestHelpers.Tests/MockFileReadLinesTests.cs deleted file mode 100644 index e9439b502..000000000 --- a/TestHelpers.Tests/MockFileReadLinesTests.cs +++ /dev/null @@ -1,55 +0,0 @@ -namespace System.IO.Abstractions.TestingHelpers.Tests -{ - using Collections.Generic; - - using NUnit.Framework; - - using Text; - - using XFS = MockUnixSupport; - - public class MockFileReadLinesTests { - [Test] - public void MockFile_ReadLines_ShouldReturnOriginalTextData() - { - // Arrange - var fileSystem = new MockFileSystem(new Dictionary - { - { XFS.Path(@"c:\something\demo.txt"), new MockFileData("Demo\r\ntext\ncontent\rvalue") }, - { XFS.Path(@"c:\something\other.gif"), new MockFileData(new byte[] { 0x21, 0x58, 0x3f, 0xa9 }) } - }); - - var file = new MockFile(fileSystem); - - // Act - var result = file.ReadLines(XFS.Path(@"c:\something\demo.txt")); - - // Assert - CollectionAssert.AreEqual( - new[] { "Demo", "text", "content", "value" }, - result); - } - - [Test] - public void MockFile_ReadLines_ShouldReturnOriginalDataWithCustomEncoding() - { - // Arrange - string text = "Hello\r\nthere\rBob\nBob!"; - var encodedText = Encoding.BigEndianUnicode.GetBytes(text); - var fileSystem = new MockFileSystem(new Dictionary - { - { XFS.Path(@"c:\something\demo.txt"), new MockFileData(encodedText) } - }); - - var file = new MockFile(fileSystem); - - // Act - var result = file.ReadLines(XFS.Path(@"c:\something\demo.txt"), Encoding.BigEndianUnicode); - - // Assert - CollectionAssert.AreEqual( - new [] { "Hello", "there", "Bob", "Bob!" }, - result); - } - } -} diff --git a/TestHelpers.Tests/MockFileSetAccessControlTests.cs b/TestHelpers.Tests/MockFileSetAccessControlTests.cs deleted file mode 100644 index 19a99c8b4..000000000 --- a/TestHelpers.Tests/MockFileSetAccessControlTests.cs +++ /dev/null @@ -1,69 +0,0 @@ -using NUnit.Framework; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - -namespace System.IO.Abstractions.TestingHelpers.Tests -{ - using Security.AccessControl; - using XFS = MockUnixSupport; - - [TestFixture] - public class MockFileSetAccessControlTests - { - [TestCase(" ")] - [TestCase(" ")] - public void MockFile_SetAccessControl_ShouldThrowArgumentExceptionIfPathContainsOnlyWhitespaces(string path) - { - // Arrange - var fileSystem = new MockFileSystem(); - var fileSecurity = new FileSecurity(); - - // Act - TestDelegate action = () => fileSystem.File.SetAccessControl(path, fileSecurity); - - // Assert - var exception = Assert.Throws(action); - Assert.That(exception.ParamName, Is.EqualTo("path")); - } - - [Test] - public void MockFile_SetAccessControl_ShouldThrowFileNotFoundExceptionIfFileDoesNotExistInMockData() - { - // Arrange - var fileSystem = new MockFileSystem(); - var expectedFileName = XFS.Path(@"c:\a.txt"); - var fileSecurity = new FileSecurity(); - - // Act - TestDelegate action = () => fileSystem.File.SetAccessControl(expectedFileName, fileSecurity); - - // Assert - var exception = Assert.Throws(action); - Assert.That(exception.FileName, Is.EqualTo(expectedFileName)); - } - - [Test] - public void MockFile_SetAccessControl_ShouldReturnAccessControlOfFileData() - { - // Arrange - var filePath = XFS.Path(@"c:\a.txt"); - var fileData = new MockFileData("Test content"); - - var fileSystem = new MockFileSystem(new Dictionary() - { - { filePath, fileData } - }); - - // Act - var expectedAccessControl = new FileSecurity(); - expectedAccessControl.SetAccessRuleProtection(false, false); - fileSystem.File.SetAccessControl(filePath, expectedAccessControl); - - // Assert - var accessControl = fileSystem.File.GetAccessControl(filePath); - Assert.That(accessControl, Is.EqualTo(expectedAccessControl)); - } - } -} diff --git a/TestHelpers.Tests/MockFileStreamTests.cs b/TestHelpers.Tests/MockFileStreamTests.cs deleted file mode 100644 index 66b6412b9..000000000 --- a/TestHelpers.Tests/MockFileStreamTests.cs +++ /dev/null @@ -1,48 +0,0 @@ -namespace System.IO.Abstractions.TestingHelpers.Tests -{ - using System.Collections.Generic; - - using NUnit.Framework; - - using XFS = MockUnixSupport; - - [TestFixture] - public class MockFileStreamTests - { - [Test] - public void MockFileStream_Flush_WritesByteToFile() - { - // Arrange - var filepath = XFS.Path(@"c:\something\foo.txt"); - var filesystem = new MockFileSystem(new Dictionary()); - var cut = new MockFileStream(filesystem, filepath); - - // Act - cut.WriteByte(255); - cut.Flush(); - - // Assert - CollectionAssert.AreEqual(new byte[]{255}, filesystem.GetFile(filepath).Contents); - } - - [Test] - public void MockFileStream_Dispose_ShouldNotResurrectFile() - { - var fileSystem = new MockFileSystem(); - var path = XFS.Path("C:\\test"); - var directory = fileSystem.Path.GetDirectoryName(path); - fileSystem.AddFile(path, new MockFileData("Bla")); - var stream = fileSystem.File.Open(path, FileMode.Open, FileAccess.ReadWrite, FileShare.Delete); - - var fileCount1 = fileSystem.Directory.GetFiles(directory, "*").Length; - fileSystem.File.Delete(path); - var fileCount2 = fileSystem.Directory.GetFiles(directory, "*").Length; - stream.Dispose(); - var fileCount3 = fileSystem.Directory.GetFiles(directory, "*").Length; - - Assert.AreEqual(1, fileCount1, "File should have existed"); - Assert.AreEqual(0, fileCount2, "File should have been deleted"); - Assert.AreEqual(0, fileCount3, "Disposing stream should not have resurrected the file"); - } - } -} diff --git a/TestHelpers.Tests/MockFileSystemTests.cs b/TestHelpers.Tests/MockFileSystemTests.cs deleted file mode 100644 index a111fc05e..000000000 --- a/TestHelpers.Tests/MockFileSystemTests.cs +++ /dev/null @@ -1,144 +0,0 @@ -using System.Collections; -using System.Collections.Generic; -using System.Linq; -using NUnit.Framework; - -namespace System.IO.Abstractions.TestingHelpers.Tests -{ - [TestFixture] - public class MockFileSystemTests - { - [Test] - public void MockFileSystem_GetFile_ShouldReturnNullWhenFileIsNotRegistered() - { - // Arrange - var fileSystem = new MockFileSystem(new Dictionary - { - { @"c:\something\demo.txt", new MockFileData("Demo\r\ntext\ncontent\rvalue") }, - { @"c:\something\other.gif", new MockFileData(new byte[] { 0x21, 0x58, 0x3f, 0xa9 }) } - }); - - // Act - var result = fileSystem.GetFile(@"c:\something\else.txt"); - - // Assert - Assert.IsNull(result); - } - - [Test] - public void MockFileSystem_GetFile_ShouldReturnFileRegisteredInConstructor() - { - // Arrange - var file1 = new MockFileData("Demo\r\ntext\ncontent\rvalue"); - var fileSystem = new MockFileSystem(new Dictionary - { - { @"c:\something\demo.txt", file1 }, - { @"c:\something\other.gif", new MockFileData(new byte[] { 0x21, 0x58, 0x3f, 0xa9 }) } - }); - - // Act - var result = fileSystem.GetFile(@"c:\something\demo.txt"); - - // Assert - Assert.AreEqual(file1, result); - } - - [Test] - public void MockFileSystem_GetFile_ShouldReturnFileRegisteredInConstructorWhenPathsDifferByCase() - { - // Arrange - var file1 = new MockFileData("Demo\r\ntext\ncontent\rvalue"); - var fileSystem = new MockFileSystem(new Dictionary - { - { @"c:\something\demo.txt", file1 }, - { @"c:\something\other.gif", new MockFileData(new byte[] { 0x21, 0x58, 0x3f, 0xa9 }) } - }); - - // Act - var result = fileSystem.GetFile(@"c:\SomeThing\DEMO.txt"); - - // Assert - Assert.AreEqual(file1, result); - } - - [Test] - public void MockFileSystem_AddFile_ShouldRepaceExistingFile() - { - const string path = @"c:\some\file.txt"; - const string existingContent = "Existing content"; - var fileSystem = new MockFileSystem(new Dictionary - { - { path, new MockFileData(existingContent) } - }); - Assert.That(fileSystem.GetFile(path).TextContents, Is.EqualTo(existingContent)); - - const string newContent = "New content"; - fileSystem.AddFile(path, new MockFileData(newContent)); - - Assert.That(fileSystem.GetFile(path).TextContents, Is.EqualTo(newContent)); - } - - [Test] - public void Is_Serializable() - { - var file1 = new MockFileData("Demo\r\ntext\ncontent\rvalue"); - var fileSystem = new MockFileSystem(new Dictionary - { - { @"c:\something\demo.txt", file1 }, - { @"c:\something\other.gif", new MockFileData(new byte[] { 0x21, 0x58, 0x3f, 0xa9 }) } - }); - var memoryStream = new MemoryStream(); - - var serializer = new Runtime.Serialization.Formatters.Binary.BinaryFormatter(); - serializer.Serialize(memoryStream, fileSystem); - - Assert.That(memoryStream.Length > 0, "Length didn't increase after serialization task."); - } - - [Test] - public void MockFileSystem_AddDirectory_ShouldCreateDirectory() - { - // Arrange - string baseDirectory = MockUnixSupport.Path(@"C:\Test"); - var fileSystem = new MockFileSystem(); - - // Act - fileSystem.AddDirectory(baseDirectory); - - // Assert - Assert.IsTrue(fileSystem.Directory.Exists(baseDirectory)); - } - - [Test] - public void MockFileSystem_AddDirectory_ShouldThrowExceptionIfDirectoryIsReadOnly() - { - // Arrange - string baseDirectory = MockUnixSupport.Path(@"C:\Test"); - var fileSystem = new MockFileSystem(); - fileSystem.AddFile(baseDirectory, new MockFileData(string.Empty)); - fileSystem.File.SetAttributes(baseDirectory, FileAttributes.ReadOnly); - - // Act - TestDelegate act = () => fileSystem.AddDirectory(baseDirectory); - - // Assert - Assert.Throws(act); - } - - [Test] - public void MockFileSystem_DriveInfo_ShouldNotThrowAnyException() - { - // Arrange - var fileSystem = new MockFileSystem(); - fileSystem.AddDirectory(MockUnixSupport.Path(@"C:\Test")); - fileSystem.AddDirectory(MockUnixSupport.Path(@"Z:\Test")); - fileSystem.AddDirectory(MockUnixSupport.Path(@"d:\Test")); - - // Act - var actualResults = fileSystem.DriveInfo.GetDrives(); - - // Assert - Assert.IsNotNull(actualResults); - } - } -} \ No newline at end of file diff --git a/TestHelpers.Tests/MockFileTests.cs b/TestHelpers.Tests/MockFileTests.cs deleted file mode 100644 index 827b42c3b..000000000 --- a/TestHelpers.Tests/MockFileTests.cs +++ /dev/null @@ -1,639 +0,0 @@ -using System.Collections.Generic; -using System.Linq; -using System.Runtime.Serialization; -using System.Runtime.Serialization.Formatters.Binary; -using System.Text; -using NUnit.Framework; - -namespace System.IO.Abstractions.TestingHelpers.Tests -{ - using XFS = MockUnixSupport; - - [TestFixture] - public class MockFileTests - { - [Test] - public void MockFile_Constructor_ShouldThrowArgumentNullExceptionIfMockFileDataAccessorIsNull() - { - // Arrange - // nothing to do - - // Act - TestDelegate action = () => new MockFile(null); - - // Assert - Assert.Throws(action); - } - - [Test] - public void MockFile_GetSetCreationTime_ShouldPersist() - { - // Arrange - string path = XFS.Path(@"c:\something\demo.txt"); - var fileSystem = new MockFileSystem(new Dictionary - { - { path, new MockFileData("Demo text content") } - }); - var file = new MockFile(fileSystem); - - // Act - var creationTime = new DateTime(2010, 6, 4, 13, 26, 42); - file.SetCreationTime(path, creationTime); - var result = file.GetCreationTime(path); - - // Assert - Assert.AreEqual(creationTime, result); - } - - [Test] - public void MockFile_SetCreationTimeUtc_ShouldAffectCreationTime() - { - // Arrange - string path = XFS.Path(@"c:\something\demo.txt"); - var fileSystem = new MockFileSystem(new Dictionary - { - { path, new MockFileData("Demo text content") } - }); - var file = new MockFile(fileSystem); - - // Act - var creationTime = new DateTime(2010, 6, 4, 13, 26, 42); - file.SetCreationTimeUtc(path, creationTime.ToUniversalTime()); - var result = file.GetCreationTime(path); - - // Assert - Assert.AreEqual(creationTime, result); - } - - [Test] - public void MockFile_SetCreationTime_ShouldAffectCreationTimeUtc() - { - // Arrange - string path = XFS.Path(@"c:\something\demo.txt"); - var fileSystem = new MockFileSystem(new Dictionary - { - { path, new MockFileData("Demo text content") } - }); - var file = new MockFile(fileSystem); - - // Act - var creationTime = new DateTime(2010, 6, 4, 13, 26, 42); - file.SetCreationTime(path, creationTime); - var result = file.GetCreationTimeUtc(path); - - // Assert - Assert.AreEqual(creationTime.ToUniversalTime(), result); - } - - [Test] - public void MockFile_GetSetLastAccessTime_ShouldPersist() - { - // Arrange - string path = XFS.Path(@"c:\something\demo.txt"); - var fileSystem = new MockFileSystem(new Dictionary - { - { path, new MockFileData("Demo text content") } - }); - var file = new MockFile(fileSystem); - - // Act - var lastAccessTime = new DateTime(2010, 6, 4, 13, 26, 42); - file.SetLastAccessTime(path, lastAccessTime); - var result = file.GetLastAccessTime(path); - - // Assert - Assert.AreEqual(lastAccessTime, result); - } - - [Test] - public void MockFile_SetLastAccessTimeUtc_ShouldAffectLastAccessTime() - { - // Arrange - string path = XFS.Path(@"c:\something\demo.txt"); - var fileSystem = new MockFileSystem(new Dictionary - { - { path, new MockFileData("Demo text content") } - }); - var file = new MockFile(fileSystem); - - // Act - var lastAccessTime = new DateTime(2010, 6, 4, 13, 26, 42); - file.SetLastAccessTimeUtc(path, lastAccessTime.ToUniversalTime()); - var result = file.GetLastAccessTime(path); - - // Assert - Assert.AreEqual(lastAccessTime, result); - } - - [Test] - public void MockFile_SetLastAccessTime_ShouldAffectLastAccessTimeUtc() - { - // Arrange - string path = XFS.Path(@"c:\something\demo.txt"); - var fileSystem = new MockFileSystem(new Dictionary - { - { path, new MockFileData("Demo text content") } - }); - var file = new MockFile(fileSystem); - - // Act - var lastAccessTime = new DateTime(2010, 6, 4, 13, 26, 42); - file.SetLastAccessTime(path, lastAccessTime); - var result = file.GetLastAccessTimeUtc(path); - - // Assert - Assert.AreEqual(lastAccessTime.ToUniversalTime(), result); - } - - [Test] - public void MockFile_GetSetLastWriteTime_ShouldPersist() - { - // Arrange - string path = XFS.Path(@"c:\something\demo.txt"); - var fileSystem = new MockFileSystem(new Dictionary - { - { path, new MockFileData("Demo text content") } - }); - var file = new MockFile(fileSystem); - - // Act - var lastWriteTime = new DateTime(2010, 6, 4, 13, 26, 42); - file.SetLastWriteTime(path, lastWriteTime); - var result = file.GetLastWriteTime(path); - - // Assert - Assert.AreEqual(lastWriteTime, result); - } - - static void ExecuteDefaultValueTest(Func getDateValue) - { - var expected = new DateTime(1601, 01, 01, 00, 00, 00, DateTimeKind.Utc); - string path = XFS.Path(@"c:\something\demo.txt"); - var fileSystem = new MockFileSystem(); - var file = new MockFile(fileSystem); - - var actual = getDateValue(file, path); - - Assert.That(actual.ToUniversalTime(), Is.EqualTo(expected)); - } - - [Test] - public void MockFile_GetLastWriteTimeOfNonExistantFile_ShouldReturnDefaultValue() - { - ExecuteDefaultValueTest((f, p) => f.GetLastWriteTime(p)); - } - - [Test] - public void MockFile_GetLastWriteTimeUtcOfNonExistantFile_ShouldReturnDefaultValue() { - ExecuteDefaultValueTest((f, p) => f.GetLastWriteTimeUtc(p)); - } - - [Test] - public void MockFile_GetLastAccessTimeUtcOfNonExistantFile_ShouldReturnDefaultValue() { - ExecuteDefaultValueTest((f, p) => f.GetLastAccessTimeUtc(p)); - } - - [Test] - public void MockFile_GetLastAccessTimeOfNonExistantFile_ShouldReturnDefaultValue() { - ExecuteDefaultValueTest((f, p) => f.GetLastAccessTime(p)); - } - - [Test] - public void MockFile_GetAttributeOfNonExistantFileButParentDirectoryExists_ShouldThrowOneFileNotFoundException() - { - // Arrange - var fileSystem = new MockFileSystem(); - fileSystem.AddDirectory(XFS.Path(@"c:\something")); - - // Act - TestDelegate action = () => fileSystem.File.GetAttributes(XFS.Path(@"c:\something\demo.txt")); - - // Assert - Assert.Throws(action); - } - - [Test] - public void MockFile_GetAttributeOfNonExistantFile_ShouldThrowOneDirectoryNotFoundException() - { - // Arrange - var fileSystem = new MockFileSystem(); - - // Act - TestDelegate action = () => fileSystem.File.GetAttributes(XFS.Path(@"c:\something\demo.txt")); - - // Assert - Assert.Throws(action); - } - - [Test] - public void MockFile_GetAttributeOfExistingFile_ShouldReturnCorrectValue() - { - var filedata = new MockFileData("test") - { - Attributes = FileAttributes.Hidden - }; - var fileSystem = new MockFileSystem(new Dictionary - { - { XFS.Path(@"c:\something\demo.txt"), filedata } - }); - - var attributes = fileSystem.File.GetAttributes(XFS.Path(@"c:\something\demo.txt")); - Assert.That(attributes, Is.EqualTo(FileAttributes.Hidden)); - } - - [Test] - public void MockFile_GetAttributeOfExistingUncDirectory_ShouldReturnCorrectValue() - { - var filedata = new MockFileData("test"); - var fileSystem = new MockFileSystem(new Dictionary - { - { XFS.Path(@"\\share\folder\demo.txt"), filedata } - }); - - var attributes = fileSystem.File.GetAttributes(XFS.Path(@"\\share\folder")); - Assert.That(attributes, Is.EqualTo(FileAttributes.Directory)); - } - - [Test] - public void MockFile_GetAttributeWithEmptyParameter_ShouldThrowOneArgumentException() - { - // Arrange - var fileSystem = new MockFileSystem(); - - // Act - TestDelegate action = () => fileSystem.File.GetAttributes(string.Empty); - - // Assert - var exception = Assert.Throws(action); - Assert.That(exception.Message, Is.StringStarting("The path is not of a legal form.")); - } - - [Test] - public void MockFile_GetAttributeWithIllegalParameter_ShouldThrowOneArgumentException() - { - // Arrange - var fileSystem = new MockFileSystem(); - - // Act - TestDelegate action = () => fileSystem.File.GetAttributes(string.Empty); - - // Assert - // Note: The actual type of the exception differs from the documentation. - // According to the documentation it should be of type NotSupportedException. - Assert.Throws(action); - } - - [Test] - public void MockFile_GetCreationTimeOfNonExistantFile_ShouldReturnDefaultValue() { - ExecuteDefaultValueTest((f, p) => f.GetCreationTime(p)); - } - - [Test] - public void MockFile_GetCreationTimeUtcOfNonExistantFile_ShouldReturnDefaultValue() { - ExecuteDefaultValueTest((f, p) => f.GetCreationTimeUtc(p)); - } - - [Test] - public void MockFile_SetLastWriteTimeUtc_ShouldAffectLastWriteTime() - { - // Arrange - string path = XFS.Path(@"c:\something\demo.txt"); - var fileSystem = new MockFileSystem(new Dictionary - { - { path, new MockFileData("Demo text content") } - }); - var file = new MockFile(fileSystem); - - // Act - var lastWriteTime = new DateTime(2010, 6, 4, 13, 26, 42); - file.SetLastWriteTimeUtc(path, lastWriteTime.ToUniversalTime()); - var result = file.GetLastWriteTime(path); - - // Assert - Assert.AreEqual(lastWriteTime, result); - } - - [Test] - public void MockFile_SetLastWriteTime_ShouldAffectLastWriteTimeUtc() - { - // Arrange - string path = XFS.Path(@"c:\something\demo.txt"); - var fileSystem = new MockFileSystem(new Dictionary - { - { path, new MockFileData("Demo text content") } - }); - var file = new MockFile(fileSystem); - - // Act - var lastWriteTime = new DateTime(2010, 6, 4, 13, 26, 42); - file.SetLastWriteTime(path, lastWriteTime); - var result = file.GetLastWriteTimeUtc(path); - - // Assert - Assert.AreEqual(lastWriteTime.ToUniversalTime(), result); - } - - [Test] - public void MockFile_ReadAllBytes_ShouldReturnOriginalByteData() - { - // Arrange - var fileSystem = new MockFileSystem(new Dictionary - { - { XFS.Path(@"c:\something\demo.txt"), new MockFileData("Demo text content") }, - { XFS.Path(@"c:\something\other.gif"), new MockFileData(new byte[] { 0x21, 0x58, 0x3f, 0xa9 }) } - }); - - var file = new MockFile(fileSystem); - - // Act - var result = file.ReadAllBytes(XFS.Path(@"c:\something\other.gif")); - - // Assert - CollectionAssert.AreEqual( - new byte[] { 0x21, 0x58, 0x3f, 0xa9 }, - result); - } - - [Test] - public void MockFile_ReadAllText_ShouldReturnOriginalTextData() - { - // Arrange - var fileSystem = new MockFileSystem(new Dictionary - { - { XFS.Path(@"c:\something\demo.txt"), new MockFileData("Demo text content") }, - { XFS.Path(@"c:\something\other.gif"), new MockFileData(new byte[] { 0x21, 0x58, 0x3f, 0xa9 }) } - }); - - var file = new MockFile(fileSystem); - - // Act - var result = file.ReadAllText(XFS.Path(@"c:\something\demo.txt")); - - // Assert - Assert.AreEqual( - "Demo text content", - result); - } - - [Test] - public void MockFile_ReadAllText_ShouldReturnOriginalDataWithCustomEncoding() - { - // Arrange - string text = "Hello there!"; - var encodedText = Encoding.BigEndianUnicode.GetBytes(text); - var fileSystem = new MockFileSystem(new Dictionary - { - { XFS.Path(@"c:\something\demo.txt"), new MockFileData(encodedText) } - }); - - var file = new MockFile(fileSystem); - - // Act - var result = file.ReadAllText(XFS.Path(@"c:\something\demo.txt"), Encoding.BigEndianUnicode); - - // Assert - Assert.AreEqual(text, result); - } - - private IEnumerable GetEncodingsForReadAllText() - { - // little endian - yield return new UTF32Encoding(false, true, true); - - // big endian - yield return new UTF32Encoding(true, true, true); - yield return new UTF8Encoding(true, true); - - yield return new ASCIIEncoding(); - } - - [TestCaseSource("GetEncodingsForReadAllText")] - public void MockFile_ReadAllText_ShouldReturnTheOriginalContentWhenTheFileContainsDifferentEncodings(Encoding encoding) - { - // Arrange - string text = "Hello there!"; - var encodedText = encoding.GetPreamble().Concat(encoding.GetBytes(text)).ToArray(); - var path = XFS.Path(@"c:\something\demo.txt"); - var fileSystem = new MockFileSystem(new Dictionary - { - { path, new MockFileData(encodedText) } - }); - - // Act - var actualText = fileSystem.File.ReadAllText(path); - - // Assert - Assert.AreEqual(text, actualText); - } - - [Test] - public void MockFile_ReadAllBytes_ShouldReturnDataSavedByWriteAllBytes() - { - // Arrange - string path = XFS.Path(@"c:\something\demo.txt"); - var fileSystem = new MockFileSystem(); - var fileContent = new byte[] { 1, 2, 3, 4 }; - fileSystem.AddDirectory(@"c:\something"); - - // Act - fileSystem.File.WriteAllBytes(path, fileContent); - - // Assert - Assert.AreEqual( - fileContent, - fileSystem.File.ReadAllBytes(path)); - } - - [Test] - public void MockFile_OpenWrite_ShouldCreateNewFiles() { - string filePath = XFS.Path(@"c:\something\demo.txt"); - string fileContent = "this is some content"; - var fileSystem = new MockFileSystem(); - - var bytes = new UTF8Encoding(true).GetBytes(fileContent); - var stream = fileSystem.File.OpenWrite(filePath); - stream.Write(bytes, 0, bytes.Length); - stream.Close(); - - Assert.That(fileSystem.FileExists(filePath), Is.True); - Assert.That(fileSystem.GetFile(filePath).TextContents, Is.EqualTo(fileContent)); - } - - [Test] - public void MockFile_OpenWrite_ShouldOverwriteExistingFiles() - { - string filePath = XFS.Path(@"c:\something\demo.txt"); - string startFileContent = "this is some content"; - string endFileContent = "this is some other content"; - var fileSystem = new MockFileSystem(new Dictionary - { - {filePath, new MockFileData(startFileContent)} - }); - - var bytes = new UTF8Encoding(true).GetBytes(endFileContent); - var stream = fileSystem.File.OpenWrite(filePath); - stream.Write(bytes, 0, bytes.Length); - stream.Close(); - - Assert.That(fileSystem.FileExists(filePath), Is.True); - Assert.That(fileSystem.GetFile(filePath).TextContents, Is.EqualTo(endFileContent)); - } - - [Test] - public void MockFile_Delete_ShouldRemoveFileFromFileSystem() - { - string fullPath = XFS.Path(@"c:\something\demo.txt"); - var fileSystem = new MockFileSystem(new Dictionary - { - { fullPath, new MockFileData("Demo text content") } - }); - - var file = new MockFile(fileSystem); - - file.Delete(fullPath); - - Assert.That(fileSystem.FileExists(fullPath), Is.False); - } - - [Test] - public void MockFile_Delete_Should_RemoveFiles() - { - string filePath = XFS.Path(@"c:\something\demo.txt"); - string fileContent = "this is some content"; - var fileSystem = new MockFileSystem(new Dictionary { { filePath, new MockFileData(fileContent) } }); - Assert.AreEqual(1, fileSystem.AllFiles.Count()); - fileSystem.File.Delete(filePath); - Assert.AreEqual(0, fileSystem.AllFiles.Count()); - } - - [Test] - public void MockFile_Delete_No_File_Does_Nothing() - { - string filePath = XFS.Path(@"c:\something\demo.txt"); - var fileSystem = new MockFileSystem(); - fileSystem.File.Delete(filePath); - } - - [Test] - public void MockFile_AppendText_AppendTextToanExistingFile() - { - string filepath = XFS.Path(@"c:\something\does\exist.txt"); - var filesystem = new MockFileSystem(new Dictionary - { - { filepath, new MockFileData("I'm here. ") } - }); - - var stream = filesystem.File.AppendText(filepath); - - stream.Write("Me too!"); - stream.Flush(); - stream.Close(); - - var file = filesystem.GetFile(filepath); - Assert.That(file.TextContents, Is.EqualTo("I'm here. Me too!")); - } - - [Test] - public void MockFile_AppendText_CreatesNewFileForAppendToNonExistingFile() - { - string filepath = XFS.Path(@"c:\something\doesnt\exist.txt"); - var filesystem = new MockFileSystem(new Dictionary()); - - var stream = filesystem.File.AppendText(filepath); - - stream.Write("New too!"); - stream.Flush(); - stream.Close(); - - var file = filesystem.GetFile(filepath); - Assert.That(file.TextContents, Is.EqualTo("New too!")); - Assert.That(filesystem.FileExists(filepath)); - } - - [Test] - public void Serializable_works() - { - //Arrange - MockFileData data = new MockFileData("Text Contents"); - - //Act - IFormatter formatter = new BinaryFormatter(); - Stream stream = new MemoryStream(); - formatter.Serialize(stream, data); - - //Assert - Assert.Pass(); - } - - [Test] - public void Serializable_can_deserialize() - { - //Arrange - string textContentStr = "Text Contents"; - - //Act - MockFileData data = new MockFileData(textContentStr); - - IFormatter formatter = new BinaryFormatter(); - Stream stream = new MemoryStream(); - formatter.Serialize(stream, data); - - stream.Seek(0, SeekOrigin.Begin); - - MockFileData deserialized = (MockFileData)formatter.Deserialize(stream); - - //Assert - Assert.That(deserialized.TextContents, Is.EqualTo(textContentStr)); - } - - [Test] - public void MockFile_Encrypt_ShouldEncryptTheFile() - { - // Arrange - const string Content = "Demo text content"; - var fileData = new MockFileData(Content); - var filePath = XFS.Path(@"c:\a.txt"); - var fileSystem = new MockFileSystem(new Dictionary - { - {filePath, fileData } - }); - - // Act - fileSystem.File.Encrypt(filePath); - - string newcontents; - using (var newfile = fileSystem.File.OpenText(filePath)) - { - newcontents = newfile.ReadToEnd(); - } - - // Assert - Assert.AreNotEqual(Content, newcontents); - } - - [Test] - public void MockFile_Decrypt_ShouldDecryptTheFile() - { - // Arrange - const string Content = "Demo text content"; - var fileData = new MockFileData(Content); - var filePath = XFS.Path(@"c:\a.txt"); - var fileSystem = new MockFileSystem(new Dictionary - { - {filePath, fileData } - }); - - // Act - fileSystem.File.Decrypt(filePath); - - string newcontents; - using (var newfile = fileSystem.File.OpenText(filePath)) - { - newcontents = newfile.ReadToEnd(); - } - - // Assert - Assert.AreNotEqual(Content, newcontents); - } - } -} diff --git a/TestHelpers.Tests/MockFileWriteAllBytesTests.cs b/TestHelpers.Tests/MockFileWriteAllBytesTests.cs deleted file mode 100644 index b1cf0d272..000000000 --- a/TestHelpers.Tests/MockFileWriteAllBytesTests.cs +++ /dev/null @@ -1,105 +0,0 @@ -using System.Collections.Generic; - -using NUnit.Framework; -using XFS = System.IO.Abstractions.TestingHelpers.MockUnixSupport; - -namespace System.IO.Abstractions.TestingHelpers.Tests -{ - public class MockFileWriteAllBytesTests - { - [Test] - public void MockFile_WriteAllBytes_ShouldThrowDirectoryNotFoundExceptionIfPathDoesNotExists() - { - // Arrange - var fileSystem = new MockFileSystem(); - string path = XFS.Path(@"c:\something\file.txt"); - var fileContent = new byte[] { 1, 2, 3, 4 }; - - // Act - TestDelegate action = () => fileSystem.File.WriteAllBytes(path, fileContent); - - // Assert - Assert.Throws(action); - } - - [Test] - public void MockFile_WriteAllBytes_ShouldWriteDataToMemoryFileSystem() - { - // Arrange - string path = XFS.Path(@"c:\something\demo.txt"); - var fileSystem = new MockFileSystem(); - var fileContent = new byte[] { 1, 2, 3, 4 }; - fileSystem.AddDirectory(@"c:\something"); - - // Act - fileSystem.File.WriteAllBytes(path, fileContent); - - // Assert - Assert.AreEqual( - fileContent, - fileSystem.GetFile(path).Contents); - } - - [Test] - public void MockFile_WriteAllBytes_ShouldThrowAnUnauthorizedAccessExceptionIfFileIsHidden() - { - // Arrange - string path = XFS.Path(@"c:\something\demo.txt"); - var fileSystem = new MockFileSystem(new Dictionary - { - { path, new MockFileData("this is hidden") }, - }); - fileSystem.File.SetAttributes(path, FileAttributes.Hidden); - - // Act - TestDelegate action = () => fileSystem.File.WriteAllBytes(path, new byte[] { 123 }); - - // Assert - Assert.Throws(action, "Access to the path '{0}' is denied.", path); - } - - [Test] - public void MockFile_WriteAllBytes_ShouldThrowAnArgumentExceptionIfContainsIllegalCharacters() - { - // Arrange - var fileSystem = new MockFileSystem(); - - // Act - TestDelegate action = () => fileSystem.File.WriteAllBytes("<<<", new byte[] { 123 }); - - // Assert - Assert.Throws(action); - } - - [Test] - public void MockFile_WriteAllBytes_ShouldThrowAnArgumentNullExceptionIfContainsIllegalCharacters() - { - // Arrange - var fileSystem = new MockFileSystem(); - - // Act - TestDelegate action = () => fileSystem.File.WriteAllBytes(null, new byte[] { 123 }); - - // Assert - var exception = Assert.Throws(action); - Assert.That(exception.Message, Is.StringStarting("Path cannot be null.")); - Assert.That(exception.ParamName, Is.EqualTo("path")); - } - - [Test] - public void MockFile_WriteAllBytes_ShouldThrowAnArgumentNullExceptionIfBytesAreNull() - { - // Arrange - var fileSystem = new MockFileSystem(); - string path = XFS.Path(@"c:\something\demo.txt"); - - // Act - TestDelegate action = () => fileSystem.File.WriteAllBytes(path, null); - - // Assert - var exception = Assert.Throws(action); - Assert.That(exception.Message, Is.StringStarting("Value cannot be null.")); - Assert.That(exception.ParamName, Is.EqualTo("bytes")); - } - } -} diff --git a/TestHelpers.Tests/MockFileWriteAllLinesTests.cs b/TestHelpers.Tests/MockFileWriteAllLinesTests.cs deleted file mode 100644 index 8ab2fefea..000000000 --- a/TestHelpers.Tests/MockFileWriteAllLinesTests.cs +++ /dev/null @@ -1,302 +0,0 @@ -using System.Collections; -using System.Collections.Generic; -using System.Globalization; -using System.Text; -using NUnit.Framework; -using XFS = System.IO.Abstractions.TestingHelpers.MockUnixSupport; - -namespace System.IO.Abstractions.TestingHelpers.Tests -{ - public class MockFileWriteAllLinesTests - { - private class TestDataForWriteAllLines - { - public static readonly string Path = XFS.Path(@"c:\something\demo.txt"); - - public static IEnumerable ForDifferentEncoding - { - get - { - var fileSystem = new MockFileSystem(); - fileSystem.AddDirectory(@"c:\something"); - var fileContentEnumerable = new List { "first line", "second line", "third line", "fourth and last line" }; - var fileContentArray = fileContentEnumerable.ToArray(); - Action writeEnumberable = () => fileSystem.File.WriteAllLines(Path, fileContentEnumerable); - Action writeEnumberableUtf32 = () => fileSystem.File.WriteAllLines(Path, fileContentEnumerable, Encoding.UTF32); - Action writeArray = () => fileSystem.File.WriteAllLines(Path, fileContentArray); - Action writeArrayUtf32 = () => fileSystem.File.WriteAllLines(Path, fileContentArray, Encoding.UTF32); - var expectedContent = string.Format(CultureInfo.InvariantCulture, - "first line{0}second line{0}third line{0}fourth and last line{0}", Environment.NewLine); - - // IEnumerable - yield return new TestCaseData(fileSystem, writeEnumberable, expectedContent) - .SetName("WriteAllLines(string, IEnumerable)"); - yield return new TestCaseData(fileSystem, writeEnumberableUtf32, expectedContent) - .SetName("WriteAllLines(string, IEnumerable, Encoding.UTF32)"); - - // string[] - yield return new TestCaseData(fileSystem, writeArray, expectedContent) - .SetName("WriteAllLines(string, string[])"); - yield return new TestCaseData(fileSystem, writeArrayUtf32, expectedContent) - .SetName("WriteAllLines(string, string[], Encoding.UTF32)"); - } - } - - public static IEnumerable ForIllegalPath - { - get - { - const string illegalPath = "<<<"; - return GetCasesForArgumentChecking(illegalPath); - } - } - - public static IEnumerable ForNullPath - { - get - { - const string illegalPath = null; - return GetCasesForArgumentChecking(illegalPath); - } - } - - private static IEnumerable GetCasesForArgumentChecking(string path) - { - var fileSystem = new MockFileSystem(); - var fileContentEnumerable = new List(); - var fileContentArray = fileContentEnumerable.ToArray(); - TestDelegate writeEnumberable = () => fileSystem.File.WriteAllLines(path, fileContentEnumerable); - TestDelegate writeEnumberableUtf32 = () => fileSystem.File.WriteAllLines(path, fileContentEnumerable, Encoding.UTF32); - TestDelegate writeArray = () => fileSystem.File.WriteAllLines(path, fileContentArray); - TestDelegate writeArrayUtf32 = () => fileSystem.File.WriteAllLines(path, fileContentArray, Encoding.UTF32); - - // IEnumerable - yield return new TestCaseData(writeEnumberable) - .SetName("WriteAllLines(string, IEnumerable) input: " + path); - yield return new TestCaseData(writeEnumberableUtf32) - .SetName("WriteAllLines(string, IEnumerable, Encoding.UTF32) input: " + path); - - // string[] - yield return new TestCaseData(writeArray) - .SetName("WriteAllLines(string, string[]) input: " + path); - yield return new TestCaseData(writeArrayUtf32) - .SetName("WriteAllLines(string, string[], Encoding.UTF32) input: " + path); - } - - private static IEnumerable ForNullEncoding - { - get - { - var fileSystem = new MockFileSystem(); - var fileContentEnumerable = new List(); - var fileContentArray = fileContentEnumerable.ToArray(); - TestDelegate writeEnumberableNull = () => fileSystem.File.WriteAllLines(Path, fileContentEnumerable, null); - TestDelegate writeArrayNull = () => fileSystem.File.WriteAllLines(Path, fileContentArray, null); - - // IEnumerable - yield return new TestCaseData(writeEnumberableNull) - .SetName("WriteAllLines(string, IEnumerable, Encoding.UTF32)"); - - // string[] - yield return new TestCaseData(writeArrayNull) - .SetName("WriteAllLines(string, string[], Encoding.UTF32)"); - } - } - - public static IEnumerable ForPathIsDirectory - { - get - { - var fileSystem = new MockFileSystem(); - var path = XFS.Path(@"c:\something"); - fileSystem.Directory.CreateDirectory(path); - var fileContentEnumerable = new List(); - var fileContentArray = fileContentEnumerable.ToArray(); - TestDelegate writeEnumberable = () => fileSystem.File.WriteAllLines(path, fileContentEnumerable); - TestDelegate writeEnumberableUtf32 = () => fileSystem.File.WriteAllLines(path, fileContentEnumerable, Encoding.UTF32); - TestDelegate writeArray = () => fileSystem.File.WriteAllLines(path, fileContentArray); - TestDelegate writeArrayUtf32 = () => fileSystem.File.WriteAllLines(path, fileContentArray, Encoding.UTF32); - - // IEnumerable - yield return new TestCaseData(writeEnumberable, path) - .SetName("WriteAllLines(string, IEnumerable)"); - yield return new TestCaseData(writeEnumberableUtf32, path) - .SetName("WriteAllLines(string, IEnumerable, Encoding.UTF32)"); - - // string[] - yield return new TestCaseData(writeArray, path) - .SetName("WriteAllLines(string, string[])"); - yield return new TestCaseData(writeArrayUtf32, path) - .SetName("WriteAllLines(string, string[], Encoding.UTF32)"); - } - } - - public static IEnumerable ForFileIsReadOnly - { - get - { - var fileSystem = new MockFileSystem(); - var path = XFS.Path(@"c:\something\file.txt"); - var mockFileData = new MockFileData(string.Empty); - mockFileData.Attributes = FileAttributes.ReadOnly; - fileSystem.AddFile(path, mockFileData); - var fileContentEnumerable = new List(); - var fileContentArray = fileContentEnumerable.ToArray(); - TestDelegate writeEnumberable = () => fileSystem.File.WriteAllLines(path, fileContentEnumerable); - TestDelegate writeEnumberableUtf32 = () => fileSystem.File.WriteAllLines(path, fileContentEnumerable, Encoding.UTF32); - TestDelegate writeArray = () => fileSystem.File.WriteAllLines(path, fileContentArray); - TestDelegate writeArrayUtf32 = () => fileSystem.File.WriteAllLines(path, fileContentArray, Encoding.UTF32); - - // IEnumerable - yield return new TestCaseData(writeEnumberable, path) - .SetName("WriteAllLines(string, IEnumerable)"); - yield return new TestCaseData(writeEnumberableUtf32, path) - .SetName("WriteAllLines(string, IEnumerable, Encoding.UTF32)"); - - // string[] - yield return new TestCaseData(writeArray, path) - .SetName("WriteAllLines(string, string[])"); - yield return new TestCaseData(writeArrayUtf32, path) - .SetName("WriteAllLines(string, string[], Encoding.UTF32)"); - } - } - - public static IEnumerable ForContentsIsNull - { - get - { - var fileSystem = new MockFileSystem(); - var path = XFS.Path(@"c:\something\file.txt"); - var mockFileData = new MockFileData(string.Empty); - mockFileData.Attributes = FileAttributes.ReadOnly; - fileSystem.AddDirectory(@"c:\something"); - fileSystem.AddFile(path, mockFileData); - List fileContentEnumerable = null; - string[] fileContentArray = null; - - // ReSharper disable ExpressionIsAlwaysNull - TestDelegate writeEnumberable = () => fileSystem.File.WriteAllLines(path, fileContentEnumerable); - TestDelegate writeEnumberableUtf32 = () => fileSystem.File.WriteAllLines(path, fileContentEnumerable, Encoding.UTF32); - TestDelegate writeArray = () => fileSystem.File.WriteAllLines(path, fileContentArray); - TestDelegate writeArrayUtf32 = () => fileSystem.File.WriteAllLines(path, fileContentArray, Encoding.UTF32); - // ReSharper restore ExpressionIsAlwaysNull - - // IEnumerable - yield return new TestCaseData(writeEnumberable) - .SetName("WriteAllLines(string, IEnumerable)"); - yield return new TestCaseData(writeEnumberableUtf32) - .SetName("WriteAllLines(string, IEnumerable, Encoding.UTF32)"); - - // string[] - yield return new TestCaseData(writeArray) - .SetName("WriteAllLines(string, string[])"); - yield return new TestCaseData(writeArrayUtf32) - .SetName("WriteAllLines(string, string[], Encoding.UTF32)"); - } - } - } - - [TestCaseSource(typeof(TestDataForWriteAllLines), "ForDifferentEncoding")] - public void MockFile_WriteAllLinesGeneric_ShouldWriteTheCorrectContent(IMockFileDataAccessor fileSystem, Action action, string expectedContent) - { - // Arrange - // is done in the test case source - - // Act - action(); - - // Assert - var actualContent = fileSystem.GetFile(TestDataForWriteAllLines.Path).TextContents; - Assert.That(actualContent, Is.EqualTo(expectedContent)); - } - - [TestCaseSource(typeof(TestDataForWriteAllLines), "ForNullPath")] - public void MockFile_WriteAllLinesGeneric_ShouldThrowAnArgumentNullExceptionIfPathIsNull(TestDelegate action) - { - // Arrange - // is done in the test case source - - // Act - // is done in the test case source - - // Assert - var exception = Assert.Throws(action); - Assert.That(exception.Message, Is.StringStarting("Value cannot be null.")); - Assert.That(exception.ParamName, Is.StringStarting("path")); - } - - [TestCaseSource(typeof(TestDataForWriteAllLines), "ForNullEncoding")] - public void MockFile_WriteAllLinesGeneric_ShouldThrowAnArgumentNullExceptionIfEncodingIsNull(TestDelegate action) - { - // Arrange - // is done in the test case source - - // Act - // is done in the test case source - - // Assert - var exception = Assert.Throws(action); - Assert.That(exception.Message, Is.StringStarting("Value cannot be null.")); - Assert.That(exception.ParamName, Is.StringStarting("encoding")); - } - - [TestCaseSource(typeof(TestDataForWriteAllLines), "ForIllegalPath")] - public void MockFile_WriteAllLinesGeneric_ShouldThrowAnArgumentExceptionIfPathContainsIllegalCharacters(TestDelegate action) - { - // Arrange - // is done in the test case source - - // Act - // is done in the test case source - - // Assert - var exception = Assert.Throws(action); - Assert.That(exception.Message, Is.EqualTo("Illegal characters in path.")); - } - - [TestCaseSource(typeof(TestDataForWriteAllLines), "ForPathIsDirectory")] - public void MockFile_WriteAllLinesGeneric_ShouldThrowAnUnauthorizedAccessExceptionIfPathIsOneDirectory(TestDelegate action, string path) - { - // Arrange - // is done in the test case source - - // Act - // is done in the test case source - - // Assert - var exception = Assert.Throws(action); - var expectedMessage = string.Format(CultureInfo.InvariantCulture, "Access to the path '{0}' is denied.", path); - Assert.That(exception.Message, Is.EqualTo(expectedMessage)); - } - - [TestCaseSource(typeof(TestDataForWriteAllLines), "ForFileIsReadOnly")] - public void MockFile_WriteAllLinesGeneric_ShouldThrowOneUnauthorizedAccessExceptionIfFileIsReadOnly(TestDelegate action, string path) - { - // Arrange - // is done in the test case source - - // Act - // is done in the test case source - - // Assert - var exception = Assert.Throws(action); - var expectedMessage = string.Format(CultureInfo.InvariantCulture, "Access to the path '{0}' is denied.", path); - Assert.That(exception.Message, Is.EqualTo(expectedMessage)); - } - - [TestCaseSource(typeof(TestDataForWriteAllLines), "ForContentsIsNull")] - public void MockFile_WriteAllLinesGeneric_ShouldThrowAnArgumentNullExceptionIfContentsIsNull(TestDelegate action) - { - // Arrange - // is done in the test case source - - // Act - // is done in the test case sourceForContentsIsNull - - // Assert - var exception = Assert.Throws(action); - Assert.That(exception.Message, Is.StringStarting("Value cannot be null.")); - Assert.That(exception.ParamName, Is.EqualTo("contents")); - } - } -} diff --git a/TestHelpers.Tests/MockFileWriteAllTextTests.cs b/TestHelpers.Tests/MockFileWriteAllTextTests.cs deleted file mode 100644 index 400088982..000000000 --- a/TestHelpers.Tests/MockFileWriteAllTextTests.cs +++ /dev/null @@ -1,226 +0,0 @@ -namespace System.IO.Abstractions.TestingHelpers.Tests -{ - using Collections.Generic; - - using NUnit.Framework; - - using Text; - - using XFS = MockUnixSupport; - - public class MockFileWriteAllTextTests { - [Test] - public void MockFile_WriteAllText_ShouldWriteTextFileToMemoryFileSystem() - { - // Arrange - string path = XFS.Path(@"c:\something\demo.txt"); - string fileContent = "Hello there!"; - var fileSystem = new MockFileSystem(); - fileSystem.AddDirectory(@"c:\something"); - - // Act - fileSystem.File.WriteAllText(path, fileContent); - - // Assert - Assert.AreEqual( - fileContent, - fileSystem.GetFile(path).TextContents); - } - - [Test] - public void MockFile_WriteAllText_ShouldOverriteAnExistingFile() - { - // http://msdn.microsoft.com/en-us/library/ms143375.aspx - - // Arrange - string path = XFS.Path(@"c:\something\demo.txt"); - var fileSystem = new MockFileSystem(); - fileSystem.AddDirectory(@"c:\something"); - - // Act - fileSystem.File.WriteAllText(path, "foo"); - fileSystem.File.WriteAllText(path, "bar"); - - // Assert - Assert.AreEqual("bar", fileSystem.GetFile(path).TextContents); - } - - [Test] - public void MockFile_WriteAllText_ShouldThrowAnUnauthorizedAccessExceptionIfFileIsHidden() - { - // Arrange - string path = XFS.Path(@"c:\something\demo.txt"); - var fileSystem = new MockFileSystem(new Dictionary - { - { path, new MockFileData("this is hidden") }, - }); - fileSystem.File.SetAttributes(path, FileAttributes.Hidden); - - // Act - TestDelegate action = () => fileSystem.File.WriteAllText(path, "hello world"); - - // Assert - Assert.Throws(action, "Access to the path '{0}' is denied.", path); - } - - [Test] - public void MockFile_WriteAllText_ShouldThrowAnArgumentExceptionIfThePathIsEmpty() - { - // Arrange - var fileSystem = new MockFileSystem(); - - // Act - TestDelegate action = () => fileSystem.File.WriteAllText(string.Empty, "hello world"); - - // Assert - Assert.Throws(action); - } - - [Test] - public void MockFile_WriteAllText_ShouldNotThrowAnArgumentNullExceptionIfTheContentIsNull() - { - // Arrange - var fileSystem = new MockFileSystem(); - string directoryPath = XFS.Path(@"c:\something"); - string filePath = XFS.Path(@"c:\something\demo.txt"); - fileSystem.AddDirectory(directoryPath); - - // Act - fileSystem.File.WriteAllText(filePath, null); - - // Assert - // no exception should be thrown, also the documentation says so - var data = fileSystem.GetFile(filePath); - Assert.That(data.Contents, Is.Empty); - } - - [Test] - public void MockFile_WriteAllText_ShouldThrowAnUnauthorizedAccessExceptionIfTheFileIsReadOnly() - { - // Arrange - var fileSystem = new MockFileSystem(); - string filePath = XFS.Path(@"c:\something\demo.txt"); - var mockFileData = new MockFileData(new byte[0]); - mockFileData.Attributes = FileAttributes.ReadOnly; - fileSystem.AddFile(filePath, mockFileData); - - // Act - TestDelegate action = () => fileSystem.File.WriteAllText(filePath, null); - - // Assert - Assert.Throws(action); - } - - [Test] - public void MockFile_WriteAllText_ShouldThrowAnUnauthorizedAccessExceptionIfThePathIsOneDirectory() - { - // Arrange - var fileSystem = new MockFileSystem(); - string directoryPath = XFS.Path(@"c:\something"); - fileSystem.AddDirectory(directoryPath); - - // Act - TestDelegate action = () => fileSystem.File.WriteAllText(directoryPath, null); - - // Assert - Assert.Throws(action); - } - - [Test] - public void MockFile_WriteAllText_ShouldThrowDirectoryNotFoundExceptionIfPathDoesNotExists() - { - // Arrange - var fileSystem = new MockFileSystem(); - string path = XFS.Path(@"c:\something\file.txt"); - - // Act - TestDelegate action = () => fileSystem.File.WriteAllText(path, string.Empty); - - // Assert - Assert.Throws(action); - } - - private IEnumerable> GetEncodingsWithExpectedBytes() - { - Encoding utf8WithoutBom = new UTF8Encoding(false, true); - return new Dictionary - { - // ASCII does not need a BOM - { Encoding.ASCII, new byte[] { 72, 101, 108, 108, 111, 32, 116, - 104, 101, 114, 101, 33, 32, 68, 122, 105, 63, 107, 105, 46 } }, - - // BigEndianUnicode needs a BOM, the BOM is the first two bytes - { Encoding.BigEndianUnicode, new byte [] { 254, 255, 0, 72, 0, 101, - 0, 108, 0, 108, 0, 111, 0, 32, 0, 116, 0, 104, 0, 101, 0, 114, - 0, 101, 0, 33, 0, 32, 0, 68, 0, 122, 0, 105, 1, 25, 0, 107, 0, 105, 0, 46 } }, - - // Default encoding does not need a BOM - { Encoding.Default, new byte [] { 72, 101, 108, 108, 111, 32, 116, - 104, 101, 114, 101, 33, 32, 68, 122, 105, 101, 107, 105, 46 } }, - - // UTF-32 needs a BOM, the BOM is the first four bytes - { Encoding.UTF32, new byte [] {255, 254, 0, 0, 72, 0, 0, 0, 101, - 0, 0, 0, 108, 0, 0, 0, 108, 0, 0, 0, 111, 0, 0, 0, 32, 0, 0, - 0, 116, 0, 0, 0, 104, 0, 0, 0, 101, 0, 0, 0, 114, 0, 0, 0, - 101, 0, 0, 0, 33, 0, 0, 0, 32, 0, 0, 0, 68, 0, 0, 0, 122, 0, - 0, 0, 105, 0, 0, 0, 25, 1, 0, 0, 107, 0, 0, 0, 105, 0, 0, 0, 46, 0, 0, 0 } }, - - // UTF-7 does not need a BOM - { Encoding.UTF7, new byte [] {72, 101, 108, 108, 111, 32, 116, - 104, 101, 114, 101, 43, 65, 67, 69, 45, 32, 68, 122, 105, - 43, 65, 82, 107, 45, 107, 105, 46 } }, - - // The default encoding does not need a BOM - { utf8WithoutBom, new byte [] { 72, 101, 108, 108, 111, 32, 116, - 104, 101, 114, 101, 33, 32, 68, 122, 105, 196, 153, 107, 105, 46 } }, - - // Unicode needs a BOM, the BOM is the first two bytes - { Encoding.Unicode, new byte [] { 255, 254, 72, 0, 101, 0, 108, - 0, 108, 0, 111, 0, 32, 0, 116, 0, 104, 0, 101, 0, 114, 0, - 101, 0, 33, 0, 32, 0, 68, 0, 122, 0, 105, 0, 25, 1, 107, 0, - 105, 0, 46, 0 } } - }; - } - - [TestCaseSource("GetEncodingsWithExpectedBytes")] - public void MockFile_WriteAllText_Encoding_ShouldWriteTextFileToMemoryFileSystem(KeyValuePair encodingsWithContents) - { - // Arrange - const string FileContent = "Hello there! Dzięki."; - string path = XFS.Path(@"c:\something\demo.txt"); - byte[] expectedBytes = encodingsWithContents.Value; - Encoding encoding = encodingsWithContents.Key; - var fileSystem = new MockFileSystem(); - fileSystem.AddDirectory(@"c:\something"); - - // Act - fileSystem.File.WriteAllText(path, FileContent, encoding); - - // Assert - var actualBytes = fileSystem.GetFile(path).Contents; - Assert.AreEqual(expectedBytes, actualBytes); - } - - [Test] - public void MockFile_WriteAllTextMultipleLines_ShouldWriteTextFileToMemoryFileSystem() - { - // Arrange - string path = XFS.Path(@"c:\something\demo.txt"); - - var fileContent = new List {"Hello there!", "Second line!"}; - var expected = "Hello there!" + Environment.NewLine + "Second line!" + Environment.NewLine; - - var fileSystem = new MockFileSystem(); - fileSystem.AddDirectory(@"c:\something"); - - // Act - fileSystem.File.WriteAllLines(path, fileContent); - - // Assert - Assert.AreEqual( - expected, - fileSystem.GetFile(path).TextContents); - } - - } -} \ No newline at end of file diff --git a/TestHelpers.Tests/MockPathTests.cs b/TestHelpers.Tests/MockPathTests.cs deleted file mode 100644 index 3c59d6646..000000000 --- a/TestHelpers.Tests/MockPathTests.cs +++ /dev/null @@ -1,401 +0,0 @@ -using NUnit.Framework; -using System.Collections.Generic; - -namespace System.IO.Abstractions.TestingHelpers.Tests -{ - using XFS = MockUnixSupport; - - public class MockPathTests - { - static readonly string TestPath = XFS.Path("C:\\test\\test.bmp"); - - [Test] - public void ChangeExtension_ExtensionNoPeriod_PeriodAdded() - { - //Arrange - var mockPath = new MockPath(new MockFileSystem()); - - //Act - var result = mockPath.ChangeExtension(TestPath, "doc"); - - //Assert - Assert.AreEqual(XFS.Path("C:\\test\\test.doc"), result); - } - - [Test] - public void Combine_SentTwoPaths_Combines() - { - //Arrange - var mockPath = new MockPath(new MockFileSystem()); - - //Act - var result = mockPath.Combine(XFS.Path("C:\\test"), "test.bmp"); - - //Assert - Assert.AreEqual(XFS.Path("C:\\test\\test.bmp"), result); - } - - [Test] - public void Combine_SentThreePaths_Combines() - { - //Arrange - var mockPath = new MockPath(new MockFileSystem()); - - //Act - var result = mockPath.Combine(XFS.Path("C:\\test"), "subdir1", "test.bmp"); - - //Assert - Assert.AreEqual(XFS.Path("C:\\test\\subdir1\\test.bmp"), result); - } - - [Test] - public void Combine_SentFourPaths_Combines() - { - //Arrange - var mockPath = new MockPath(new MockFileSystem()); - - //Act - var result = mockPath.Combine(XFS.Path("C:\\test"), "subdir1", "subdir2", "test.bmp"); - - //Assert - Assert.AreEqual(XFS.Path("C:\\test\\subdir1\\subdir2\\test.bmp"), result); - } - - [Test] - public void Combine_SentFivePaths_Combines() - { - //Arrange - var mockPath = new MockPath(new MockFileSystem()); - - //Act - var result = mockPath.Combine(XFS.Path("C:\\test"), "subdir1", "subdir2", "subdir3", "test.bmp"); - - //Assert - Assert.AreEqual(XFS.Path("C:\\test\\subdir1\\subdir2\\subdir3\\test.bmp"), result); - } - - [Test] - public void GetDirectoryName_SentPath_ReturnsDirectory() - { - //Arrange - var mockPath = new MockPath(new MockFileSystem()); - - //Act - var result = mockPath.GetDirectoryName(TestPath); - - //Assert - Assert.AreEqual(XFS.Path("C:\\test"), result); - } - - [Test] - public void GetExtension_SendInPath_ReturnsExtension() - { - //Arrange - var mockPath = new MockPath(new MockFileSystem()); - - //Act - var result = mockPath.GetExtension(TestPath); - - //Assert - Assert.AreEqual(".bmp", result); - } - - [Test] - public void GetFileName_SendInPath_ReturnsFilename() - { - //Arrange - var mockPath = new MockPath(new MockFileSystem()); - - //Act - var result = mockPath.GetFileName(TestPath); - - //Assert - Assert.AreEqual("test.bmp", result); - } - - [Test] - public void GetFileNameWithoutExtension_SendInPath_ReturnsFileNameNoExt() - { - //Arrange - var mockPath = new MockPath(new MockFileSystem()); - - //Act - var result = mockPath.GetFileNameWithoutExtension(TestPath); - - //Assert - Assert.AreEqual("test", result); - } - - [Test] - public void GetFullPath_SendInPath_ReturnsFullPath() - { - //Arrange - var mockPath = new MockPath(new MockFileSystem()); - - //Act - var result = mockPath.GetFullPath(TestPath); - - //Assert - Assert.AreEqual(TestPath, result); - } - - public static IEnumerable GetFullPath_RelativePaths_Cases - { - get - { - yield return new [] { XFS.Path(@"c:\a"), "b", XFS.Path(@"c:\a\b") }; - yield return new [] { XFS.Path(@"c:\a\b"), "c", XFS.Path(@"c:\a\b\c") }; - yield return new [] { XFS.Path(@"c:\a\b"), XFS.Path(@"c\"), XFS.Path(@"c:\a\b\c\") }; - yield return new [] { XFS.Path(@"c:\a\b"), XFS.Path(@"..\c"), XFS.Path(@"c:\a\c") }; - yield return new [] { XFS.Path(@"c:\a\b\c"), XFS.Path(@"..\c\..\"), XFS.Path(@"c:\a\b\") }; - yield return new [] { XFS.Path(@"c:\a\b\c"), XFS.Path(@"..\..\..\..\..\d"), XFS.Path(@"c:\d") }; - yield return new [] { XFS.Path(@"c:\a\b\c"), XFS.Path(@"..\..\..\..\..\d\"), XFS.Path(@"c:\d\") }; - } - } - - [TestCaseSource("GetFullPath_RelativePaths_Cases")] - public void GetFullPath_RelativePaths_ShouldReturnTheAbsolutePathWithCurrentDirectory(string currentDir, string relativePath, string expectedResult) - { - //Arrange - var mockFileSystem = new MockFileSystem(); - mockFileSystem.Directory.SetCurrentDirectory(currentDir); - var mockPath = new MockPath(mockFileSystem); - - //Act - var actualResult = mockPath.GetFullPath(relativePath); - - //Assert - Assert.AreEqual(expectedResult, actualResult); - } - - public static IEnumerable GetFullPath_RootedPathWithRelativeSegments_Cases - { - get - { - yield return new [] { XFS.Path(@"c:\a\b\..\c"), XFS.Path(@"c:\a\c") }; - yield return new [] { XFS.Path(@"c:\a\b\.\.\..\.\c"), XFS.Path(@"c:\a\c") }; - yield return new [] { XFS.Path(@"c:\a\b\.\c"), XFS.Path(@"c:\a\b\c") }; - yield return new [] { XFS.Path(@"c:\a\b\.\.\.\.\c"), XFS.Path(@"c:\a\b\c") }; - yield return new [] { XFS.Path(@"c:\a\..\..\c"), XFS.Path(@"c:\c") }; - } - } - - [TestCaseSource("GetFullPath_RootedPathWithRelativeSegments_Cases")] - public void GetFullPath_RootedPathWithRelativeSegments_ShouldReturnAnRootedAbsolutePath(string rootedPath, string expectedResult) - { - //Arrange - var mockFileSystem = new MockFileSystem(); - var mockPath = new MockPath(mockFileSystem); - - //Act - var actualResult = mockPath.GetFullPath(rootedPath); - - //Assert - Assert.AreEqual(expectedResult, actualResult); - } - - public static IEnumerable GetFullPath_AbsolutePaths_Cases - { - get - { - yield return new [] { XFS.Path(@"c:\a"), XFS.Path(@"/b"), XFS.Path(@"c:\b") }; - yield return new [] { XFS.Path(@"c:\a"), XFS.Path(@"/b\"), XFS.Path(@"c:\b\") }; - yield return new [] { XFS.Path(@"c:\a"), XFS.Path(@"\b"), XFS.Path(@"c:\b") }; - yield return new [] { XFS.Path(@"c:\a"), XFS.Path(@"\b\..\c"), XFS.Path(@"c:\c") }; - yield return new [] { XFS.Path(@"z:\a"), XFS.Path(@"\b\..\c"), XFS.Path(@"z:\c") }; - yield return new [] { XFS.Path(@"z:\a"), XFS.Path(@"\\computer\share\c"), XFS.Path(@"\\computer\share\c") }; - yield return new [] { XFS.Path(@"z:\a"), XFS.Path(@"\\computer\share\c\..\d"), XFS.Path(@"\\computer\share\d") }; - yield return new [] { XFS.Path(@"z:\a"), XFS.Path(@"\\computer\share\c\..\..\d"), XFS.Path(@"\\computer\share\d") }; - } - } - - [TestCaseSource("GetFullPath_AbsolutePaths_Cases")] - public void GetFullPath_AbsolutePaths_ShouldReturnThePathWithTheRoot_Or_Unc(string currentDir, string absolutePath, string expectedResult) - { - //Arrange - var mockFileSystem = new MockFileSystem(); - mockFileSystem.Directory.SetCurrentDirectory(currentDir); - var mockPath = new MockPath(mockFileSystem); - - //Act - var actualResult = mockPath.GetFullPath(absolutePath); - - //Assert - Assert.AreEqual(expectedResult, actualResult); - } - - [Test] - public void GetFullPath_InvalidUNCPaths_ShouldThrowArgumentException() - { - //Arrange - var mockFileSystem = new MockFileSystem(); - var mockPath = new MockPath(mockFileSystem); - - //Act - TestDelegate action = () => mockPath.GetFullPath(XFS.Path(@"\\shareZ")); - - //Assert - Assert.Throws(action); - } - - [Test] - public void GetFullPath_NullValue_ShouldThrowArgumentNullException() - { - //Arrange - var mockFileSystem = new MockFileSystem(); - var mockPath = new MockPath(mockFileSystem); - - //Act - TestDelegate action = () => mockPath.GetFullPath(null); - - //Assert - Assert.Throws(action); - } - - [Test] - public void GetFullPath_EmptyValue_ShouldThrowArgumentException() - { - //Arrange - var mockFileSystem = new MockFileSystem(); - var mockPath = new MockPath(mockFileSystem); - - //Act - TestDelegate action = () => mockPath.GetFullPath(string.Empty); - - //Assert - Assert.Throws(action); - } - - [Test] - public void GetFullPath_WithMultipleDirectorySeparators_ShouldReturnTheNormalizedForm() - { - //Arrange - var mockFileSystem = new MockFileSystem(); - var mockPath = new MockPath(mockFileSystem); - - //Act - var actualFullPath = mockPath.GetFullPath(XFS.Path(@"c:\foo\\//bar\file.dat")); - - //Assert - Assert.AreEqual(XFS.Path(@"c:\foo\bar\file.dat"), actualFullPath); - } - - [Test] - public void GetInvalidFileNameChars_Called_ReturnsChars() - { - //Arrange - var mockPath = new MockPath(new MockFileSystem()); - - //Act - var result = mockPath.GetInvalidFileNameChars(); - - //Assert - Assert.IsTrue(result.Length > 0); - } - - [Test] - public void GetInvalidPathChars_Called_ReturnsChars() - { - //Arrange - var mockPath = new MockPath(new MockFileSystem()); - - //Act - var result = mockPath.GetInvalidPathChars(); - - //Assert - Assert.IsTrue(result.Length > 0); - } - - [Test] - public void GetPathRoot_SendInPath_ReturnsRoot() - { - //Arrange - var mockPath = new MockPath(new MockFileSystem()); - - //Act - var result = mockPath.GetPathRoot(TestPath); - - //Assert - Assert.AreEqual(XFS.Path("C:\\"), result); - } - - [Test] - public void GetRandomFileName_Called_ReturnsStringLengthGreaterThanZero() - { - //Arrange - var mockPath = new MockPath(new MockFileSystem()); - - //Act - var result = mockPath.GetRandomFileName(); - - //Assert - Assert.IsTrue(result.Length > 0); - } - - [Test] - public void GetTempFileName_Called_ReturnsStringLengthGreaterThanZero() - { - //Arrange - var mockPath = new MockPath(new MockFileSystem()); - - //Act - var result = mockPath.GetTempFileName(); - - //Assert - Assert.IsTrue(result.Length > 0); - } - - [Test] - public void GetTempFileName_Called_CreatesEmptyFileInTempDirectory() - { - //Arrange - var fileSystem = new MockFileSystem(); - var mockPath = new MockPath(fileSystem); - - //Act - var result = mockPath.GetTempFileName(); - - Assert.True(fileSystem.FileExists(result)); - Assert.AreEqual(0, fileSystem.FileInfo.FromFileName(result).Length); - } - - [Test] - public void GetTempPath_Called_ReturnsStringLengthGreaterThanZero() - { - //Arrange - var mockPath = new MockPath(new MockFileSystem()); - - //Act - var result = mockPath.GetTempPath(); - - //Assert - Assert.IsTrue(result.Length > 0); - } - - [Test] - public void HasExtension_PathSentIn_DeterminesExtension() - { - //Arrange - var mockPath = new MockPath(new MockFileSystem()); - - //Act - var result = mockPath.HasExtension(TestPath); - - //Assert - Assert.AreEqual(true, result); - } - - [Test] - public void IsPathRooted_PathSentIn_DeterminesPathExists() - { - //Arrange - var mockPath = new MockPath(new MockFileSystem()); - - //Act - var result = mockPath.IsPathRooted(TestPath); - - //Assert - Assert.AreEqual(true, result); - } - } -} diff --git a/TestHelpers.Tests/MockUnixSupportTests.cs b/TestHelpers.Tests/MockUnixSupportTests.cs deleted file mode 100644 index 30dd6c0de..000000000 --- a/TestHelpers.Tests/MockUnixSupportTests.cs +++ /dev/null @@ -1,20 +0,0 @@ -using NUnit.Framework; - -namespace System.IO.Abstractions.TestingHelpers.Tests -{ - [TestFixture] - public class MockUnixSupportTests - { - [Test] - public void Should_Convert_Backslashes_To_Slashes_On_Unix() - { - Assert.AreEqual("/test/", MockUnixSupport.Path(@"\test\", () => true)); - } - - [Test] - public void Should_Remove_Drive_Letter_On_Unix() - { - Assert.AreEqual("/test/", MockUnixSupport.Path(@"c:\test\", () => true)); - } - } -} diff --git a/TestHelpers.Tests/Properties/AssemblyInfo.cs b/TestHelpers.Tests/Properties/AssemblyInfo.cs deleted file mode 100644 index 0de51bf5a..000000000 --- a/TestHelpers.Tests/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,19 +0,0 @@ -using System; -using System.Reflection; -using System.Runtime.InteropServices; - -[assembly: AssemblyVersion("0.0.0.1")] -[assembly: AssemblyFileVersion("0.0.0.1")] - -[assembly: AssemblyTitle("System.IO.Abstractions.TestingHelpers.Tests")] -[assembly: AssemblyDescription("The unit tests for our pre-built mocks.")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("System.IO.Abstractions")] -[assembly: AssemblyCopyright("Copyright © Tatham Oddie 2010")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -[assembly: ComVisible(false)] - -[assembly: CLSCompliant(true)] \ No newline at end of file diff --git a/TestHelpers.Tests/StringExtensionsTests.cs b/TestHelpers.Tests/StringExtensionsTests.cs deleted file mode 100644 index 8d5da0ea9..000000000 --- a/TestHelpers.Tests/StringExtensionsTests.cs +++ /dev/null @@ -1,60 +0,0 @@ -using NUnit.Framework; - -namespace System.IO.Abstractions.TestingHelpers.Tests -{ - [TestFixture] - public class StringExtensions - { - [Test] - public void SplitLines_InputWithOneLine_ShouldReturnOnlyOneLine() - { - var input = "This is row one"; - var expected = new[] { "This is row one" }; - - var result = input.SplitLines(); - - Assert.That(result, Is.EquivalentTo(expected)); - } - - [Test] - public void SplitLines_InputWithTwoLinesSeparatedWithLf_ShouldReturnBothLines() { - var input = "This is row one\nThis is row two"; - var expected = new[] { "This is row one", "This is row two" }; - - var result = input.SplitLines(); - - Assert.That(result, Is.EquivalentTo(expected)); - } - - [Test] - public void SplitLines_InputWithTwoLinesSeparatedWithCr_ShouldReturnBothLines() { - var input = "This is row one\rThis is row two"; - var expected = new[] { "This is row one", "This is row two" }; - - var result = input.SplitLines(); - - Assert.That(result, Is.EquivalentTo(expected)); - } - - [Test] - public void SplitLines_InputWithTwoLinesSeparatedWithCrLf_ShouldReturnBothLines() { - var input = "This is row one\r\nThis is row two"; - var expected = new[] { "This is row one", "This is row two" }; - - var result = input.SplitLines(); - - Assert.That(result, Is.EquivalentTo(expected)); - } - - [Test] - public void SplitLines_InputWithTwoLinesSeparatedWithAllLineEndings_ShouldReturnAllLines() { - var input = "one\r\ntwo\rthree\nfour"; - var expected = new[] { "one", "two", "three", "four" }; - - var result = input.SplitLines(); - - Assert.That(result, Is.EquivalentTo(expected)); - } - - } -} diff --git a/TestHelpers.Tests/TestHelpers.Tests.csproj b/TestHelpers.Tests/TestHelpers.Tests.csproj deleted file mode 100644 index 4a506a458..000000000 --- a/TestHelpers.Tests/TestHelpers.Tests.csproj +++ /dev/null @@ -1,172 +0,0 @@ - - - - Debug - AnyCPU - {20B02738-952A-40F5-9C10-E2F83013E9FC} - Library - Properties - System.IO.Abstractions.TestingHelpers.Tests - System.IO.Abstractions.TestingHelpers.Tests - v4.0 - 512 - - - 3.5 - - publish\ - true - Disk - false - Foreground - 7 - Days - false - false - true - 0 - 1.0.0.%2a - false - false - true - ..\ - true - - - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - AllRules.ruleset - 5 - - - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - AllRules.ruleset - true - - - ..\StrongName.pfx - - - - ..\packages\NUnitTestAdapter.1.2\lib\nunit.core.dll - False - - - ..\packages\NUnitTestAdapter.1.2\lib\nunit.core.interfaces.dll - False - - - False - ..\packages\NUnit.2.6.4\lib\nunit.framework.dll - - - ..\packages\NUnitTestAdapter.1.2\lib\nunit.util.dll - False - - - ..\packages\NUnitTestAdapter.1.2\lib\NUnit.VisualStudio.TestAdapter.dll - False - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - {4D398F3A-0784-4401-93CD-46CD2FBD6B92} - System.IO.Abstractions - - - {251BD5E5-8133-47A4-AB19-17CF0F43D6AE} - TestingHelpers - - - - - False - Microsoft .NET Framework 4 %28x86 and x64%29 - true - - - False - .NET Framework 3.5 SP1 Client Profile - false - - - False - .NET Framework 3.5 SP1 - false - - - False - Windows Installer 3.1 - true - - - - - - - - - - - Designer - - - - - \ No newline at end of file diff --git a/TestHelpers.Tests/TestHelpers.Tests.ncrunchproject b/TestHelpers.Tests/TestHelpers.Tests.ncrunchproject deleted file mode 100644 index 575717ac8..000000000 --- a/TestHelpers.Tests/TestHelpers.Tests.ncrunchproject +++ /dev/null @@ -1,20 +0,0 @@ - - false - false - false - true - false - false - false - false - true - true - false - true - true - 60000 - - - - AutoDetect - \ No newline at end of file diff --git a/TestHelpers.Tests/packages.config b/TestHelpers.Tests/packages.config deleted file mode 100644 index 6929b63de..000000000 --- a/TestHelpers.Tests/packages.config +++ /dev/null @@ -1,5 +0,0 @@ - - - - - \ No newline at end of file diff --git a/TestingHelpers/IMockFileDataAccessor.cs b/TestingHelpers/IMockFileDataAccessor.cs deleted file mode 100644 index 8333b3636..000000000 --- a/TestingHelpers/IMockFileDataAccessor.cs +++ /dev/null @@ -1,59 +0,0 @@ -using System.Collections.Generic; - -namespace System.IO.Abstractions.TestingHelpers -{ - /// - /// Provides access to the file system storage. - /// - public interface IMockFileDataAccessor - { - /// - /// Gets a file. - /// - /// The path of the file to get. - /// The file. if the file does not exist. - MockFileData GetFile(string path); - - void AddFile(string path, MockFileData mockFile); - void AddDirectory(string path); - - /// - /// Removes the file. - /// - /// The file to remove. - /// - /// The file must not exist. - /// - void RemoveFile(string path); - - /// - /// Determines whether the file exists. - /// - /// The file to check. - /// if the file exists; otherwise, . - bool FileExists(string path); - - /// - /// Gets all unique paths of all files and directories. - /// - IEnumerable AllPaths { get; } - - /// - /// Gets the paths of all files. - /// - IEnumerable AllFiles { get; } - - /// - /// Gets the paths of all directories. - /// - IEnumerable AllDirectories { get; } - - DirectoryBase Directory { get; } - IFileInfoFactory FileInfo {get; } - PathBase Path { get; } - IDirectoryInfoFactory DirectoryInfo { get; } - IDriveInfoFactory DriveInfo { get; } - - PathVerifier PathVerifier { get; } - } -} \ No newline at end of file diff --git a/TestingHelpers/MockDirectory.cs b/TestingHelpers/MockDirectory.cs deleted file mode 100644 index eebf82d18..000000000 --- a/TestingHelpers/MockDirectory.cs +++ /dev/null @@ -1,513 +0,0 @@ -using System.Collections.Generic; -using System.Globalization; -using System.Linq; -using System.Security.AccessControl; -using System.Text.RegularExpressions; - -namespace System.IO.Abstractions.TestingHelpers -{ - using XFS = MockUnixSupport; - - [Serializable] - public class MockDirectory : DirectoryBase - { - private readonly FileBase fileBase; - - private readonly IMockFileDataAccessor mockFileDataAccessor; - - private string currentDirectory; - - public MockDirectory(IMockFileDataAccessor mockFileDataAccessor, FileBase fileBase, string currentDirectory) - { - if (mockFileDataAccessor == null) - { - throw new ArgumentNullException("mockFileDataAccessor"); - } - - this.currentDirectory = currentDirectory; - this.mockFileDataAccessor = mockFileDataAccessor; - this.fileBase = fileBase; - } - - public override DirectoryInfoBase CreateDirectory(string path) - { - return CreateDirectory(path, null); - } - - public override DirectoryInfoBase CreateDirectory(string path, DirectorySecurity directorySecurity) - { - if (path == null) - { - throw new ArgumentNullException("path"); - } - - if (path.Length == 0) - { - throw new ArgumentException(Properties.Resources.PATH_CANNOT_BE_THE_EMPTY_STRING_OR_ALL_WHITESPACE, "path"); - } - - path = EnsurePathEndsWithDirectorySeparator(mockFileDataAccessor.Path.GetFullPath(path)); - - if (!Exists(path)) - { - mockFileDataAccessor.AddDirectory(path); - } - - var created = new MockDirectoryInfo(mockFileDataAccessor, path); - return created; - } - - public override void Delete(string path) - { - Delete(path, false); - } - - public override void Delete(string path, bool recursive) - { - path = EnsurePathEndsWithDirectorySeparator(mockFileDataAccessor.Path.GetFullPath(path)); - var affectedPaths = mockFileDataAccessor - .AllPaths - .Where(p => p.StartsWith(path, StringComparison.OrdinalIgnoreCase)) - .ToList(); - - if (!affectedPaths.Any()) - throw new DirectoryNotFoundException(path + " does not exist or could not be found."); - - if (!recursive && - affectedPaths.Count > 1) - throw new IOException("The directory specified by " + path + " is read-only, or recursive is false and " + path + " is not an empty directory."); - - foreach (var affectedPath in affectedPaths) - mockFileDataAccessor.RemoveFile(affectedPath); - } - - public override bool Exists(string path) - { - try - { - path = EnsurePathEndsWithDirectorySeparator(path); - - path = mockFileDataAccessor.Path.GetFullPath(path); - return mockFileDataAccessor.AllDirectories.Any(p => p.Equals(path, StringComparison.OrdinalIgnoreCase)); - } - catch (Exception) - { - return false; - } - } - - public override DirectorySecurity GetAccessControl(string path) - { - // First crude implementation to avoid NotImplementedException - if (Exists(path)) - { - return new DirectorySecurity(); - } - - throw new DirectoryNotFoundException(path); - } - - public override DirectorySecurity GetAccessControl(string path, AccessControlSections includeSections) - { - // First crude implementation to avoid NotImplementedException - return GetAccessControl(path); - } - - public override DateTime GetCreationTime(string path) - { - return fileBase.GetCreationTime(path); - } - - public override DateTime GetCreationTimeUtc(string path) - { - return fileBase.GetCreationTimeUtc(path); - } - - public override string GetCurrentDirectory() - { - return currentDirectory; - } - - public override string[] GetDirectories(string path) - { - return GetDirectories(path, "*"); - } - - public override string[] GetDirectories(string path, string searchPattern) - { - return GetDirectories(path, searchPattern, SearchOption.TopDirectoryOnly); - } - - public override string[] GetDirectories(string path, string searchPattern, SearchOption searchOption) - { - return EnumerateDirectories(path, searchPattern, searchOption).ToArray(); - } - - public override string GetDirectoryRoot(string path) - { - return Path.GetPathRoot(path); - } - - public override string[] GetFiles(string path) - { - // Same as what the real framework does - return GetFiles(path, "*"); - } - - public override string[] GetFiles(string path, string searchPattern) - { - // Same as what the real framework does - return GetFiles(path, searchPattern, SearchOption.TopDirectoryOnly); - } - - public override string[] GetFiles(string path, string searchPattern, SearchOption searchOption) - { - if(path == null) - throw new ArgumentNullException(); - - if (!Exists(path)) - { - throw new DirectoryNotFoundException(string.Format(CultureInfo.InvariantCulture, Properties.Resources.COULD_NOT_FIND_PART_OF_PATH_EXCEPTION, path)); - } - - return GetFilesInternal(mockFileDataAccessor.AllFiles, path, searchPattern, searchOption); - } - - private string[] GetFilesInternal(IEnumerable files, string path, string searchPattern, SearchOption searchOption) - { - CheckSearchPattern(searchPattern); - path = EnsurePathEndsWithDirectorySeparator(path); - path = mockFileDataAccessor.Path.GetFullPath(path); - - bool isUnix = XFS.IsUnixPlatform(); - - string allDirectoriesPattern = isUnix - ? @"([^<>:""/|?*]*/)*" - : @"([^<>:""/\\|?*]*\\)*"; - - string fileNamePattern; - string pathPatternSpecial = null; - if (searchPattern == "*") - { - fileNamePattern = isUnix ? @"[^/]*?/?" : @"[^\\]*?\\?"; - } - else - { - fileNamePattern = Regex.Escape(searchPattern) - .Replace(@"\*", isUnix ? @"[^<>:""/|?*]*?" : @"[^<>:""/\\|?*]*?") - .Replace(@"\?", isUnix ? @"[^<>:""/|?*]?" : @"[^<>:""/\\|?*]?"); - - var extension = Path.GetExtension(searchPattern); - bool hasExtensionLengthOfThree = extension != null && extension.Length == 4 && !extension.Contains("*") && !extension.Contains("?"); - if (hasExtensionLengthOfThree) - { - var fileNamePatternSpecial = string.Format(CultureInfo.InvariantCulture, "{0}[^.]", fileNamePattern); - pathPatternSpecial = string.Format( - CultureInfo.InvariantCulture, - isUnix ? @"(?i:^{0}{1}{2}(?:/?)$)" : @"(?i:^{0}{1}{2}(?:\\?)$)", - Regex.Escape(path), - searchOption == SearchOption.AllDirectories ? allDirectoriesPattern : string.Empty, - fileNamePatternSpecial); - } - } - - var pathPattern = string.Format( - CultureInfo.InvariantCulture, - isUnix ? @"(?i:^{0}{1}{2}(?:/?)$)" : @"(?i:^{0}{1}{2}(?:\\?)$)", - Regex.Escape(path), - searchOption == SearchOption.AllDirectories ? allDirectoriesPattern : string.Empty, - fileNamePattern); - - - return files - .Where(p => - { - if (Regex.IsMatch(p, pathPattern)) - { - return true; - } - - if (pathPatternSpecial != null && Regex.IsMatch(p, pathPatternSpecial)) - { - return true; - } - - return false; - }) - .ToArray(); - } - - public override string[] GetFileSystemEntries(string path) - { - return GetFileSystemEntries(path, "*"); - } - - public override string[] GetFileSystemEntries(string path, string searchPattern) - { - var dirs = GetDirectories(path, searchPattern); - var files = GetFiles(path, searchPattern); - - return dirs.Union(files).ToArray(); - } - - public override DateTime GetLastAccessTime(string path) - { - return fileBase.GetLastAccessTime(path); - } - - public override DateTime GetLastAccessTimeUtc(string path) - { - return fileBase.GetLastAccessTimeUtc(path); - } - - public override DateTime GetLastWriteTime(string path) - { - return fileBase.GetLastWriteTime(path); - } - - public override DateTime GetLastWriteTimeUtc(string path) - { - return fileBase.GetLastWriteTimeUtc(path); - } - - public override string[] GetLogicalDrives() - { - return mockFileDataAccessor - .AllDirectories - .Select(d => new MockDirectoryInfo(mockFileDataAccessor, d).Root.FullName) - .Select(r => r.ToLowerInvariant()) - .Distinct() - .ToArray(); - } - - public override DirectoryInfoBase GetParent(string path) - { - if (path == null) - { - throw new ArgumentNullException("path"); - } - - if (path.Length == 0) - { - throw new ArgumentException(Properties.Resources.PATH_CANNOT_BE_THE_EMPTY_STRING_OR_ALL_WHITESPACE, "path"); - } - - if (MockPath.HasIllegalCharacters(path, false)) - { - throw new ArgumentException("Path contains invalid path characters.", "path"); - } - - var absolutePath = mockFileDataAccessor.Path.GetFullPath(path); - var sepAsString = mockFileDataAccessor.Path.DirectorySeparatorChar.ToString(CultureInfo.InvariantCulture); - - var lastIndex = 0; - if (absolutePath != sepAsString) - { - var startIndex = absolutePath.EndsWith(sepAsString, StringComparison.OrdinalIgnoreCase) ? absolutePath.Length - 1 : absolutePath.Length; - lastIndex = absolutePath.LastIndexOf(mockFileDataAccessor.Path.DirectorySeparatorChar, startIndex - 1); - if (lastIndex < 0) - { - return null; - } - } - - var parentPath = absolutePath.Substring(0, lastIndex); - if (string.IsNullOrEmpty(parentPath)) - { - return null; - } - - var parent = new MockDirectoryInfo(mockFileDataAccessor, parentPath); - return parent; - } - - public override void Move(string sourceDirName, string destDirName) - { - var fullSourcePath = EnsurePathEndsWithDirectorySeparator(mockFileDataAccessor.Path.GetFullPath(sourceDirName)); - var fullDestPath = EnsurePathEndsWithDirectorySeparator(mockFileDataAccessor.Path.GetFullPath(destDirName)); - - if (string.Equals(fullSourcePath, fullDestPath, StringComparison.OrdinalIgnoreCase)) - { - throw new IOException("Source and destination path must be different."); - } - - var sourceRoot = mockFileDataAccessor.Path.GetPathRoot(fullSourcePath); - var destinationRoot = mockFileDataAccessor.Path.GetPathRoot(fullDestPath); - if (!string.Equals(sourceRoot, destinationRoot, StringComparison.OrdinalIgnoreCase)) - { - throw new IOException("Source and destination path must have identical roots. Move will not work across volumes."); - } - - //Make sure that the destination exists - mockFileDataAccessor.Directory.CreateDirectory(fullDestPath); - - //Copy over the attributes - var sourceDirectoryInfo = mockFileDataAccessor.DirectoryInfo.FromDirectoryName(sourceDirName); - var destDirectoryInfo = mockFileDataAccessor.DirectoryInfo.FromDirectoryName(destDirName); - destDirectoryInfo.Attributes = sourceDirectoryInfo.Attributes; - - //Recursively move all the subdirectories from the source into the destination directory - var subdirectories = GetDirectories(fullSourcePath); - foreach (var subdirectory in subdirectories) - { - var newSubdirPath = subdirectory.Replace(fullSourcePath, fullDestPath, StringComparison.OrdinalIgnoreCase); - Move(subdirectory, newSubdirPath); - } - - //Move the files in destination directory - var files = GetFiles(fullSourcePath); - foreach (var file in files) - { - var newFilePath = file.Replace(fullSourcePath, fullDestPath, StringComparison.OrdinalIgnoreCase); - mockFileDataAccessor.FileInfo.FromFileName(file).MoveTo(newFilePath); - } - - //Delete the source directory - Delete(fullSourcePath); - } - - public override void SetAccessControl(string path, DirectorySecurity directorySecurity) - { - throw new NotImplementedException(Properties.Resources.NOT_IMPLEMENTED_EXCEPTION); - } - - public override void SetCreationTime(string path, DateTime creationTime) - { - fileBase.SetCreationTime(path, creationTime); - } - - public override void SetCreationTimeUtc(string path, DateTime creationTimeUtc) - { - fileBase.SetCreationTimeUtc(path, creationTimeUtc); - } - - public override void SetCurrentDirectory(string path) - { - currentDirectory = path; - } - - public override void SetLastAccessTime(string path, DateTime lastAccessTime) - { - fileBase.SetLastAccessTime(path, lastAccessTime); - } - - public override void SetLastAccessTimeUtc(string path, DateTime lastAccessTimeUtc) - { - fileBase.SetLastAccessTimeUtc(path, lastAccessTimeUtc); - } - - public override void SetLastWriteTime(string path, DateTime lastWriteTime) - { - fileBase.SetLastWriteTime(path, lastWriteTime); - } - - public override void SetLastWriteTimeUtc(string path, DateTime lastWriteTimeUtc) - { - fileBase.SetLastWriteTimeUtc(path, lastWriteTimeUtc); - } - - public override IEnumerable EnumerateDirectories(string path) - { - mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); - - return EnumerateDirectories(path, "*"); - } - - public override IEnumerable EnumerateDirectories(string path, string searchPattern) - { - mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); - - return EnumerateDirectories(path, searchPattern, SearchOption.TopDirectoryOnly); - } - - public override IEnumerable EnumerateDirectories(string path, string searchPattern, SearchOption searchOption) - { - mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); - - path = EnsurePathEndsWithDirectorySeparator(path); - - if (!Exists(path)) - { - throw new DirectoryNotFoundException(string.Format(CultureInfo.InvariantCulture, Properties.Resources.COULD_NOT_FIND_PART_OF_PATH_EXCEPTION, path)); - } - - var dirs = GetFilesInternal(mockFileDataAccessor.AllDirectories, path, searchPattern, searchOption); - return dirs.Where(p => string.Compare(p, path, StringComparison.OrdinalIgnoreCase) != 0); - } - - public override IEnumerable EnumerateFiles(string path) - { - return GetFiles(path); - } - - public override IEnumerable EnumerateFiles(string path, string searchPattern) - { - return GetFiles(path, searchPattern); - } - - public override IEnumerable EnumerateFiles(string path, string searchPattern, SearchOption searchOption) - { - return GetFiles(path, searchPattern, searchOption); - } - - public override IEnumerable EnumerateFileSystemEntries(string path) - { - var fileSystemEntries = new List(GetFiles(path)); - fileSystemEntries.AddRange(GetDirectories(path)); - return fileSystemEntries; - } - - public override IEnumerable EnumerateFileSystemEntries(string path, string searchPattern) - { - var fileSystemEntries = new List(GetFiles(path, searchPattern)); - fileSystemEntries.AddRange(GetDirectories(path, searchPattern)); - return fileSystemEntries; - } - - public override IEnumerable EnumerateFileSystemEntries(string path, string searchPattern, SearchOption searchOption) - { - var fileSystemEntries = new List(GetFiles(path, searchPattern, searchOption)); - fileSystemEntries.AddRange(GetDirectories(path, searchPattern, searchOption)); - return fileSystemEntries; - } - - static string EnsurePathEndsWithDirectorySeparator(string path) - { - if (!path.EndsWith(Path.DirectorySeparatorChar.ToString(CultureInfo.InvariantCulture), StringComparison.OrdinalIgnoreCase)) - path += Path.DirectorySeparatorChar; - return path; - } - - static void CheckSearchPattern(string searchPattern) - { - if (searchPattern == null) - { - throw new ArgumentNullException("searchPattern"); - } - - const string TWO_DOTS = ".."; - Func createException = () => new ArgumentException(@"Search pattern cannot contain "".."" to move up directories and can be contained only internally in file/directory names, as in ""a..b"".", searchPattern); - - if (searchPattern.EndsWith(TWO_DOTS, StringComparison.OrdinalIgnoreCase)) - { - throw createException(); - } - - int position; - if ((position = searchPattern.IndexOf(TWO_DOTS, StringComparison.OrdinalIgnoreCase)) >= 0) - { - var characterAfterTwoDots = searchPattern[position + 2]; - if (characterAfterTwoDots == Path.DirectorySeparatorChar || characterAfterTwoDots == Path.AltDirectorySeparatorChar) - { - throw createException(); - } - } - - var invalidPathChars = Path.GetInvalidPathChars(); - if (searchPattern.IndexOfAny(invalidPathChars) > -1) - { - throw new ArgumentException(Properties.Resources.ILLEGAL_CHARACTERS_IN_PATH_EXCEPTION, "searchPattern"); - } - } - } -} \ No newline at end of file diff --git a/TestingHelpers/MockDirectoryData.cs b/TestingHelpers/MockDirectoryData.cs deleted file mode 100644 index 547486826..000000000 --- a/TestingHelpers/MockDirectoryData.cs +++ /dev/null @@ -1,13 +0,0 @@ -namespace System.IO.Abstractions.TestingHelpers -{ - [Serializable] - public class MockDirectoryData : MockFileData - { - public override bool IsDirectory { get { return true; } } - - public MockDirectoryData() : base(string.Empty) - { - Attributes = FileAttributes.Directory; - } - } -} \ No newline at end of file diff --git a/TestingHelpers/MockDirectoryInfo.cs b/TestingHelpers/MockDirectoryInfo.cs deleted file mode 100644 index a7fec2ed5..000000000 --- a/TestingHelpers/MockDirectoryInfo.cs +++ /dev/null @@ -1,310 +0,0 @@ -using System.Collections.Generic; -using System.Globalization; -using System.Linq; -using System.Security.AccessControl; - -namespace System.IO.Abstractions.TestingHelpers -{ - [Serializable] - public class MockDirectoryInfo : DirectoryInfoBase - { - private readonly IMockFileDataAccessor mockFileDataAccessor; - private readonly string directoryPath; - - /// - /// Initializes a new instance of the class. - /// - /// The mock file data accessor. - /// The directory path. - /// Thrown if or is . - public MockDirectoryInfo(IMockFileDataAccessor mockFileDataAccessor, string directoryPath) - { - if (mockFileDataAccessor == null) - { - throw new ArgumentNullException("mockFileDataAccessor"); - } - - this.mockFileDataAccessor = mockFileDataAccessor; - - directoryPath = mockFileDataAccessor.Path.GetFullPath(directoryPath); - - this.directoryPath = EnsurePathEndsWithDirectorySeparator(directoryPath); - } - - MockFileData MockFileData - { - get { return mockFileDataAccessor.GetFile(directoryPath); } - } - - public override void Delete() - { - mockFileDataAccessor.Directory.Delete(directoryPath); - } - - public override void Refresh() - { - } - - public override FileAttributes Attributes - { - get { return MockFileData.Attributes; } - set { MockFileData.Attributes = value; } - } - - public override DateTime CreationTime - { - get { throw new NotImplementedException(Properties.Resources.NOT_IMPLEMENTED_EXCEPTION); } - set { throw new NotImplementedException(Properties.Resources.NOT_IMPLEMENTED_EXCEPTION); } - } - - public override DateTime CreationTimeUtc - { - get { throw new NotImplementedException(Properties.Resources.NOT_IMPLEMENTED_EXCEPTION); } - set { throw new NotImplementedException(Properties.Resources.NOT_IMPLEMENTED_EXCEPTION); } - } - - public override bool Exists - { - get { return mockFileDataAccessor.Directory.Exists(FullName); } - } - - public override string Extension - { - get - { - // System.IO.Path.GetExtension does only string manipulation, - // so it's safe to delegate. - return Path.GetExtension(directoryPath); - } - } - - public override string FullName - { - get - { - var root = mockFileDataAccessor.Path.GetPathRoot(directoryPath); - if (string.Equals(directoryPath, root, StringComparison.OrdinalIgnoreCase)) - { - // drives have the trailing slash - return directoryPath; - } - - // directories do not have a trailing slash - return directoryPath.TrimEnd('\\').TrimEnd('/'); - } - } - - public override DateTime LastAccessTime - { - get { throw new NotImplementedException(Properties.Resources.NOT_IMPLEMENTED_EXCEPTION); } - set { throw new NotImplementedException(Properties.Resources.NOT_IMPLEMENTED_EXCEPTION); } - } - - public override DateTime LastAccessTimeUtc - { - get { - if (MockFileData == null) throw new FileNotFoundException("File not found", directoryPath); - return MockFileData.LastAccessTime.UtcDateTime; - } - set { throw new NotImplementedException(Properties.Resources.NOT_IMPLEMENTED_EXCEPTION); } - } - - public override DateTime LastWriteTime - { - get { throw new NotImplementedException(Properties.Resources.NOT_IMPLEMENTED_EXCEPTION); } - set { throw new NotImplementedException(Properties.Resources.NOT_IMPLEMENTED_EXCEPTION); } - } - - public override DateTime LastWriteTimeUtc - { - get { throw new NotImplementedException(Properties.Resources.NOT_IMPLEMENTED_EXCEPTION); } - set { throw new NotImplementedException(Properties.Resources.NOT_IMPLEMENTED_EXCEPTION); } - } - - public override string Name - { - get { return new MockPath(mockFileDataAccessor).GetFileName(directoryPath.TrimEnd('\\')); } - } - - public override void Create() - { - mockFileDataAccessor.Directory.CreateDirectory(FullName); - } - - public override void Create(DirectorySecurity directorySecurity) - { - mockFileDataAccessor.Directory.CreateDirectory(FullName, directorySecurity); - } - - public override DirectoryInfoBase CreateSubdirectory(string path) - { - return mockFileDataAccessor.Directory.CreateDirectory(Path.Combine(FullName, path)); - } - - public override DirectoryInfoBase CreateSubdirectory(string path, DirectorySecurity directorySecurity) - { - return mockFileDataAccessor.Directory.CreateDirectory(Path.Combine(FullName, path), directorySecurity); - } - - public override void Delete(bool recursive) - { - mockFileDataAccessor.Directory.Delete(directoryPath, recursive); - } - - public override IEnumerable EnumerateDirectories() - { - return GetDirectories(); - } - - public override IEnumerable EnumerateDirectories(string searchPattern) - { - return GetDirectories(searchPattern); - } - - public override IEnumerable EnumerateDirectories(string searchPattern, SearchOption searchOption) - { - return GetDirectories(searchPattern, searchOption); - } - - public override IEnumerable EnumerateFiles() - { - return GetFiles(); - } - - public override IEnumerable EnumerateFiles(string searchPattern) - { - return GetFiles(searchPattern); - } - - public override IEnumerable EnumerateFiles(string searchPattern, SearchOption searchOption) - { - return GetFiles(searchPattern, searchOption); - } - - public override IEnumerable EnumerateFileSystemInfos() - { - return GetFileSystemInfos(); - } - - public override IEnumerable EnumerateFileSystemInfos(string searchPattern) - { - return GetFileSystemInfos(searchPattern); - } - - public override IEnumerable EnumerateFileSystemInfos(string searchPattern, SearchOption searchOption) - { - return GetFileSystemInfos(searchPattern, searchOption); - } - - public override DirectorySecurity GetAccessControl() - { - return mockFileDataAccessor.Directory.GetAccessControl(directoryPath); - } - - public override DirectorySecurity GetAccessControl(AccessControlSections includeSections) - { - return mockFileDataAccessor.Directory.GetAccessControl(directoryPath, includeSections); - } - - public override DirectoryInfoBase[] GetDirectories() - { - return ConvertStringsToDirectories(mockFileDataAccessor.Directory.GetDirectories(directoryPath)); - } - - public override DirectoryInfoBase[] GetDirectories(string searchPattern) - { - return ConvertStringsToDirectories(mockFileDataAccessor.Directory.GetDirectories(directoryPath, searchPattern)); - } - - public override DirectoryInfoBase[] GetDirectories(string searchPattern, SearchOption searchOption) - { - return ConvertStringsToDirectories(mockFileDataAccessor.Directory.GetDirectories(directoryPath, searchPattern, searchOption)); - } - - private DirectoryInfoBase[] ConvertStringsToDirectories(IEnumerable paths) - { - return paths - .Select(path => new MockDirectoryInfo(mockFileDataAccessor, path)) - .Cast() - .ToArray(); - } - - public override FileInfoBase[] GetFiles() - { - return ConvertStringsToFiles(mockFileDataAccessor.Directory.GetFiles(FullName)); - } - - public override FileInfoBase[] GetFiles(string searchPattern) - { - return ConvertStringsToFiles(mockFileDataAccessor.Directory.GetFiles(FullName, searchPattern)); - } - - public override FileInfoBase[] GetFiles(string searchPattern, SearchOption searchOption) - { - return ConvertStringsToFiles(mockFileDataAccessor.Directory.GetFiles(FullName, searchPattern, searchOption)); - } - - FileInfoBase[] ConvertStringsToFiles(IEnumerable paths) - { - return paths - .Select(mockFileDataAccessor.FileInfo.FromFileName) - .ToArray(); - } - - public override FileSystemInfoBase[] GetFileSystemInfos() - { - return GetFileSystemInfos("*"); - } - - public override FileSystemInfoBase[] GetFileSystemInfos(string searchPattern) - { - return GetFileSystemInfos(searchPattern, SearchOption.TopDirectoryOnly); - } - - public override FileSystemInfoBase[] GetFileSystemInfos(string searchPattern, SearchOption searchOption) - { - return GetDirectories(searchPattern, searchOption).OfType().Concat(GetFiles(searchPattern, searchOption)).ToArray(); - } - - public override void MoveTo(string destDirName) - { - mockFileDataAccessor.Directory.Move(directoryPath, destDirName); - } - - public override void SetAccessControl(DirectorySecurity directorySecurity) - { - mockFileDataAccessor.Directory.SetAccessControl(directoryPath, directorySecurity); - } - - public override DirectoryInfoBase Parent - { - get - { - return mockFileDataAccessor.Directory.GetParent(directoryPath); - } - } - - public override DirectoryInfoBase Root - { - get - { - return new MockDirectoryInfo(mockFileDataAccessor, mockFileDataAccessor.Directory.GetDirectoryRoot(FullName)); - } - } - - private string EnsurePathEndsWithDirectorySeparator(string path) - { - if (!path.EndsWith(mockFileDataAccessor.Path.DirectorySeparatorChar.ToString(CultureInfo.InvariantCulture), StringComparison.OrdinalIgnoreCase)) - { - path += mockFileDataAccessor.Path.DirectorySeparatorChar; - } - - return path; - } - - public override string ToString() - { - return FullName; - } - } -} diff --git a/TestingHelpers/MockDirectoryInfoFactory.cs b/TestingHelpers/MockDirectoryInfoFactory.cs deleted file mode 100644 index 51f638feb..000000000 --- a/TestingHelpers/MockDirectoryInfoFactory.cs +++ /dev/null @@ -1,18 +0,0 @@ -namespace System.IO.Abstractions.TestingHelpers -{ - [Serializable] - public class MockDirectoryInfoFactory : IDirectoryInfoFactory - { - readonly IMockFileDataAccessor mockFileSystem; - - public MockDirectoryInfoFactory(IMockFileDataAccessor mockFileSystem) - { - this.mockFileSystem = mockFileSystem; - } - - public DirectoryInfoBase FromDirectoryName(string directoryName) - { - return new MockDirectoryInfo(mockFileSystem, directoryName); - } - } -} \ No newline at end of file diff --git a/TestingHelpers/MockDriveInfo.cs b/TestingHelpers/MockDriveInfo.cs deleted file mode 100644 index 87d31a6f0..000000000 --- a/TestingHelpers/MockDriveInfo.cs +++ /dev/null @@ -1,70 +0,0 @@ -namespace System.IO.Abstractions.TestingHelpers -{ - [Serializable] - public class MockDriveInfo : DriveInfoBase - { - private readonly IMockFileDataAccessor mockFileDataAccessor; - - public MockDriveInfo(IMockFileDataAccessor mockFileDataAccessor, string name) - { - if (mockFileDataAccessor == null) - { - throw new ArgumentNullException("mockFileDataAccessor"); - } - - if (name == null) - { - throw new ArgumentNullException("name"); - } - - const string DRIVE_SEPARATOR = @":\"; - if (name.Length == 1) - { - name = char.ToUpperInvariant(name[0]) + DRIVE_SEPARATOR; - } - else if (name.Length == 2 && name[1] == ':') - { - name = char.ToUpperInvariant(name[0]) + DRIVE_SEPARATOR; - } - else if (name.Length == 3 && name.EndsWith(DRIVE_SEPARATOR, StringComparison.Ordinal)) - { - name = char.ToUpperInvariant(name[0]) + DRIVE_SEPARATOR; - } - else - { - MockPath.CheckInvalidPathChars(name); - name = mockFileDataAccessor.Path.GetPathRoot(name); - - if (string.IsNullOrEmpty(name) || name.StartsWith(@"\\", StringComparison.Ordinal)) - { - throw new ArgumentException( - @"Object must be a root directory (""C:\"") or a drive letter (""C"")."); - } - } - - this.mockFileDataAccessor = mockFileDataAccessor; - - Name = name; - IsReady = true; - } - - public new long AvailableFreeSpace { get; set; } - public new string DriveFormat { get; set; } - public new DriveType DriveType { get; set; } - public new bool IsReady { get; protected set; } - public override string Name { get; protected set; } - - public override DirectoryInfoBase RootDirectory - { - get - { - var directory = mockFileDataAccessor.DirectoryInfo.FromDirectoryName(Name); - return directory; - } - } - - public new long TotalFreeSpace { get; protected set; } - public new long TotalSize { get; protected set; } - public override string VolumeLabel { get; set; } - } -} diff --git a/TestingHelpers/MockDriveInfoFactory.cs b/TestingHelpers/MockDriveInfoFactory.cs deleted file mode 100644 index b342585ab..000000000 --- a/TestingHelpers/MockDriveInfoFactory.cs +++ /dev/null @@ -1,94 +0,0 @@ -using System.Collections.Generic; - -namespace System.IO.Abstractions.TestingHelpers -{ - [Serializable] - public class MockDriveInfoFactory : IDriveInfoFactory - { - private readonly IMockFileDataAccessor mockFileSystem; - - public MockDriveInfoFactory(IMockFileDataAccessor mockFileSystem) - { - if (mockFileSystem == null) - { - throw new ArgumentNullException("mockFileSystem"); - } - - this.mockFileSystem = mockFileSystem; - } - - public DriveInfoBase[] GetDrives() - { - var driveLetters = new HashSet(new DriveEqualityComparer()); - foreach (var path in mockFileSystem.AllPaths) - { - var pathRoot = mockFileSystem.Path.GetPathRoot(path); - driveLetters.Add(pathRoot); - } - - var result = new List(); - foreach (string driveLetter in driveLetters) - { - try - { - var mockDriveInfo = new MockDriveInfo(mockFileSystem, driveLetter); - result.Add(mockDriveInfo); - } - catch (ArgumentException) - { - // invalid drives should be ignored - } - } - - return result.ToArray(); - } - - private string NormalizeDriveName(string driveName) - { - if (driveName.Length == 3 && driveName.EndsWith(@":\", StringComparison.OrdinalIgnoreCase)) - { - return char.ToUpperInvariant(driveName[0]) + @":\"; - } - - if (driveName.StartsWith(@"\\", StringComparison.OrdinalIgnoreCase)) - { - return null; - } - - return driveName; - } - - private class DriveEqualityComparer : IEqualityComparer - { - public bool Equals(string x, string y) - { - if (ReferenceEquals(x, y)) - { - return true; - } - - if (ReferenceEquals(x, null)) - { - return false; - } - - if (ReferenceEquals(y, null)) - { - return false; - } - - if (x[1] == ':' && y[1] == ':') - { - return char.ToUpperInvariant(x[0]) == char.ToUpperInvariant(y[0]); - } - - return false; - } - - public int GetHashCode(string obj) - { - return obj.ToUpperInvariant().GetHashCode(); - } - } - } -} diff --git a/TestingHelpers/MockFile.cs b/TestingHelpers/MockFile.cs deleted file mode 100644 index f083f415c..000000000 --- a/TestingHelpers/MockFile.cs +++ /dev/null @@ -1,910 +0,0 @@ -using System.Collections.Generic; -using System.Globalization; -using System.Linq; -using System.Security.AccessControl; -using System.Text; - -namespace System.IO.Abstractions.TestingHelpers -{ - [Serializable] - public class MockFile : FileBase - { - private readonly IMockFileDataAccessor mockFileDataAccessor; - private readonly MockPath mockPath; - - public MockFile(IMockFileDataAccessor mockFileDataAccessor) - { - if (mockFileDataAccessor == null) - { - throw new ArgumentNullException("mockFileDataAccessor"); - } - - this.mockFileDataAccessor = mockFileDataAccessor; - mockPath = new MockPath(mockFileDataAccessor); - } - - public override void AppendAllLines(string path, IEnumerable contents) - { - mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); - VerifyValueIsNotNull(contents, "contents"); - - AppendAllLines(path, contents, MockFileData.DefaultEncoding); - } - - public override void AppendAllLines(string path, IEnumerable contents, Encoding encoding) - { - if (encoding == null) - { - throw new ArgumentNullException("encoding"); - } - - mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); - - var concatContents = contents.Aggregate("", (a, b) => a + b + Environment.NewLine); - AppendAllText(path, concatContents, encoding); - } - - public override void AppendAllText(string path, string contents) - { - mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); - - AppendAllText(path, contents, MockFileData.DefaultEncoding); - } - - public override void AppendAllText(string path, string contents, Encoding encoding) - { - if (encoding == null) - { - throw new ArgumentNullException("encoding"); - } - - mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); - - if (!mockFileDataAccessor.FileExists(path)) - { - var dir = mockFileDataAccessor.Path.GetDirectoryName(path); - if (!mockFileDataAccessor.Directory.Exists(dir)) - { - throw new DirectoryNotFoundException(string.Format(CultureInfo.InvariantCulture, Properties.Resources.COULD_NOT_FIND_PART_OF_PATH_EXCEPTION, path)); - } - - mockFileDataAccessor.AddFile(path, new MockFileData(contents, encoding)); - } - else - { - var file = mockFileDataAccessor.GetFile(path); - var bytesToAppend = encoding.GetBytes(contents); - file.Contents = file.Contents.Concat(bytesToAppend).ToArray(); - } - } - - public override StreamWriter AppendText(string path) - { - mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); - - if (mockFileDataAccessor.FileExists(path)) - { - StreamWriter sw = new StreamWriter(OpenWrite(path)); - sw.BaseStream.Seek(0, SeekOrigin.End); //push the stream pointer at the end for append. - return sw; - } - - return new StreamWriter(Create(path)); - } - - public override void Copy(string sourceFileName, string destFileName) - { - Copy(sourceFileName, destFileName, false); - } - - public override void Copy(string sourceFileName, string destFileName, bool overwrite) - { - if (sourceFileName == null) - { - throw new ArgumentNullException("sourceFileName", Properties.Resources.FILENAME_CANNOT_BE_NULL); - } - - if (destFileName == null) - { - throw new ArgumentNullException("destFileName", Properties.Resources.FILENAME_CANNOT_BE_NULL); - } - - mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(sourceFileName, "sourceFileName"); - mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(destFileName, "destFileName"); - - var directoryNameOfDestination = mockPath.GetDirectoryName(destFileName); - if (!mockFileDataAccessor.Directory.Exists(directoryNameOfDestination)) - { - throw new DirectoryNotFoundException(string.Format(CultureInfo.InvariantCulture, Properties.Resources.COULD_NOT_FIND_PART_OF_PATH_EXCEPTION, destFileName)); - } - - var fileExists = mockFileDataAccessor.FileExists(destFileName); - if (fileExists) - { - if (!overwrite) - { - throw new IOException(string.Format(CultureInfo.InvariantCulture, "The file {0} already exists.", destFileName)); - } - - mockFileDataAccessor.RemoveFile(destFileName); - } - - var sourceFile = mockFileDataAccessor.GetFile(sourceFileName); - mockFileDataAccessor.AddFile(destFileName, sourceFile); - } - - public override Stream Create(string path) - { - if (path == null) - { - throw new ArgumentNullException("path", "Path cannot be null."); - } - mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); - - mockFileDataAccessor.AddFile(path, new MockFileData(new byte[0])); - var stream = OpenWrite(path); - return stream; - } - - public override Stream Create(string path, int bufferSize) - { - throw new NotImplementedException(Properties.Resources.NOT_IMPLEMENTED_EXCEPTION); - } - - public override Stream Create(string path, int bufferSize, FileOptions options) - { - throw new NotImplementedException(Properties.Resources.NOT_IMPLEMENTED_EXCEPTION); - } - - public override Stream Create(string path, int bufferSize, FileOptions options, FileSecurity fileSecurity) - { - throw new NotImplementedException(Properties.Resources.NOT_IMPLEMENTED_EXCEPTION); - } - - public override StreamWriter CreateText(string path) - { - return new StreamWriter(Create(path)); - } - - public override void Decrypt(string path) - { - mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); - - new MockFileInfo(mockFileDataAccessor, path).Decrypt(); - } - - public override void Delete(string path) - { - mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); - - mockFileDataAccessor.RemoveFile(path); - } - - public override void Encrypt(string path) - { - mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); - - new MockFileInfo(mockFileDataAccessor, path).Encrypt(); - } - - public override bool Exists(string path) - { - return mockFileDataAccessor.FileExists(path) && !mockFileDataAccessor.AllDirectories.Any(d => d.Equals(path, StringComparison.OrdinalIgnoreCase)); - } - - public override FileSecurity GetAccessControl(string path) - { - mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); - - if (!mockFileDataAccessor.FileExists(path)) - { - throw new FileNotFoundException(string.Format(CultureInfo.InvariantCulture, "Can't find {0}", path), path); - } - - var fileData = mockFileDataAccessor.GetFile(path); - return fileData.AccessControl; - } - - public override FileSecurity GetAccessControl(string path, AccessControlSections includeSections) - { - return GetAccessControl(path); - } - - /// - /// Gets the of the file on the path. - /// - /// The path to the file. - /// The of the file on the path. - /// is empty, contains only white spaces, or contains invalid characters. - /// The specified path, file name, or both exceed the system-defined maximum length. For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters. - /// is in an invalid format. - /// represents a file and is invalid, such as being on an unmapped drive, or the file cannot be found. - /// represents a directory and is invalid, such as being on an unmapped drive, or the directory cannot be found. - /// This file is being used by another process. - /// The caller does not have the required permission. - public override FileAttributes GetAttributes(string path) - { - if (path != null) - { - if (path.Length == 0) - { - throw new ArgumentException(Properties.Resources.THE_PATH_IS_NOT_OF_A_LEGAL_FORM, "path"); - } - } - - mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); - - var possibleFileData = mockFileDataAccessor.GetFile(path); - FileAttributes result; - if (possibleFileData != null) - { - result = possibleFileData.Attributes; - } - else - { - var directoryInfo = mockFileDataAccessor.DirectoryInfo.FromDirectoryName(path); - if (directoryInfo.Exists) - { - result = directoryInfo.Attributes; - } - else - { - VerifyDirectoryExists(path); - - throw new FileNotFoundException(string.Format(CultureInfo.InvariantCulture, "Could not find file '{0}'.", path)); - } - } - - return result; - } - - public override DateTime GetCreationTime(string path) - { - mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); - - return GetTimeFromFile(path, data => data.CreationTime.LocalDateTime, () => MockFileData.DefaultDateTimeOffset.LocalDateTime); - } - - public override DateTime GetCreationTimeUtc(string path) - { - mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); - - return GetTimeFromFile(path, data => data.CreationTime.UtcDateTime, () => MockFileData.DefaultDateTimeOffset.UtcDateTime); - } - - public override DateTime GetLastAccessTime(string path) - { - mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); - - return GetTimeFromFile(path, data => data.LastAccessTime.LocalDateTime, () => MockFileData.DefaultDateTimeOffset.LocalDateTime); - } - - public override DateTime GetLastAccessTimeUtc(string path) - { - mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); - - return GetTimeFromFile(path, data => data.LastAccessTime.UtcDateTime, () => MockFileData.DefaultDateTimeOffset.UtcDateTime); - } - - public override DateTime GetLastWriteTime(string path) { - mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); - - return GetTimeFromFile(path, data => data.LastWriteTime.LocalDateTime, () => MockFileData.DefaultDateTimeOffset.LocalDateTime); - } - - public override DateTime GetLastWriteTimeUtc(string path) - { - mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); - - return GetTimeFromFile(path, data => data.LastWriteTime.UtcDateTime, () => MockFileData.DefaultDateTimeOffset.UtcDateTime); - } - - private DateTime GetTimeFromFile(string path, Func existingFileFunction, Func nonExistingFileFunction) - { - DateTime result; - MockFileData file = mockFileDataAccessor.GetFile(path); - if (file != null) - { - result = existingFileFunction(file); - } - else - { - result = nonExistingFileFunction(); - } - - return result; - } - - public override void Move(string sourceFileName, string destFileName) - { - if (sourceFileName == null) - { - throw new ArgumentNullException("sourceFileName", Properties.Resources.FILENAME_CANNOT_BE_NULL); - } - - if (destFileName == null) - { - throw new ArgumentNullException("destFileName", Properties.Resources.FILENAME_CANNOT_BE_NULL); - } - - mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(sourceFileName, "sourceFileName"); - mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(destFileName, "destFileName"); - - if (mockFileDataAccessor.GetFile(destFileName) != null) - throw new IOException("A file can not be created if it already exists."); - - var sourceFile = mockFileDataAccessor.GetFile(sourceFileName); - - if (sourceFile == null) - throw new FileNotFoundException(string.Format(CultureInfo.InvariantCulture, "The file \"{0}\" could not be found.", sourceFileName), sourceFileName); - - VerifyDirectoryExists(destFileName); - - mockFileDataAccessor.AddFile(destFileName, new MockFileData(sourceFile.Contents)); - mockFileDataAccessor.RemoveFile(sourceFileName); - } - - public override Stream Open(string path, FileMode mode) - { - mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); - - return Open(path, mode, (mode == FileMode.Append ? FileAccess.Write : FileAccess.ReadWrite), FileShare.None); - } - - public override Stream Open(string path, FileMode mode, FileAccess access) - { - mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); - - return Open(path, mode, access, FileShare.None); - } - - public override Stream Open(string path, FileMode mode, FileAccess access, FileShare share) - { - mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); - - bool exists = mockFileDataAccessor.FileExists(path); - - if (mode == FileMode.CreateNew && exists) - throw new IOException(string.Format(CultureInfo.InvariantCulture, "The file '{0}' already exists.", path)); - - if ((mode == FileMode.Open || mode == FileMode.Truncate) && !exists) - throw new FileNotFoundException(path); - - if (!exists || mode == FileMode.CreateNew) - return Create(path); - - if (mode == FileMode.Create || mode == FileMode.Truncate) - { - Delete(path); - return Create(path); - } - - var length = mockFileDataAccessor.GetFile(path).Contents.Length; - var stream = OpenWrite(path); - - if (mode == FileMode.Append) - stream.Seek(length, SeekOrigin.Begin); - - return stream; - } - - public override Stream OpenRead(string path) - { - mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); - - return Open(path, FileMode.Open, FileAccess.Read, FileShare.Read); - } - - public override StreamReader OpenText(string path) - { - mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); - - return new StreamReader( - OpenRead(path)); - } - - public override Stream OpenWrite(string path) - { - mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); - - return new MockFileStream(mockFileDataAccessor, path); - } - - public override byte[] ReadAllBytes(string path) - { - mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); - - return mockFileDataAccessor.GetFile(path).Contents; - } - - public override string[] ReadAllLines(string path) - { - mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); - - if (!mockFileDataAccessor.FileExists(path)) - { - throw new FileNotFoundException(string.Format(CultureInfo.InvariantCulture, "Can't find {0}", path)); - } - - return mockFileDataAccessor - .GetFile(path) - .TextContents - .SplitLines(); - } - - public override string[] ReadAllLines(string path, Encoding encoding) - { - mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); - - if (encoding == null) - { - throw new ArgumentNullException("encoding"); - } - - if (!mockFileDataAccessor.FileExists(path)) - { - throw new FileNotFoundException(string.Format(CultureInfo.InvariantCulture, "Can't find {0}", path)); - } - - return encoding - .GetString(mockFileDataAccessor.GetFile(path).Contents) - .SplitLines(); - } - - public override string ReadAllText(string path) - { - mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); - - if (!mockFileDataAccessor.FileExists(path)) - { - throw new FileNotFoundException(string.Format(CultureInfo.InvariantCulture, "Can't find {0}", path)); - } - - return ReadAllText(path, MockFileData.DefaultEncoding); - } - - public override string ReadAllText(string path, Encoding encoding) - { - mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); - - if (encoding == null) - { - throw new ArgumentNullException("encoding"); - } - - return ReadAllTextInternal(path, encoding); - } - - public override IEnumerable ReadLines(string path) - { - mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); - - return ReadAllLines(path); - } - - public override IEnumerable ReadLines(string path, Encoding encoding) - { - mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); - VerifyValueIsNotNull(encoding, "encoding"); - - return ReadAllLines(path, encoding); - } - - public override void Replace(string sourceFileName, string destinationFileName, string destinationBackupFileName) - { - throw new NotImplementedException(Properties.Resources.NOT_IMPLEMENTED_EXCEPTION); - } - - public override void Replace(string sourceFileName, string destinationFileName, string destinationBackupFileName, bool ignoreMetadataErrors) - { - throw new NotImplementedException(Properties.Resources.NOT_IMPLEMENTED_EXCEPTION); - } - - public override void SetAccessControl(string path, FileSecurity fileSecurity) - { - mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); - - if (!mockFileDataAccessor.FileExists(path)) - { - throw new FileNotFoundException(string.Format(CultureInfo.InvariantCulture, "Can't find {0}", path), path); - } - - var fileData = mockFileDataAccessor.GetFile(path); - fileData.AccessControl = fileSecurity; - } - - public override void SetAttributes(string path, FileAttributes fileAttributes) - { - mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); - - mockFileDataAccessor.GetFile(path).Attributes = fileAttributes; - } - - public override void SetCreationTime(string path, DateTime creationTime) - { - mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); - - mockFileDataAccessor.GetFile(path).CreationTime = new DateTimeOffset(creationTime); - } - - public override void SetCreationTimeUtc(string path, DateTime creationTimeUtc) - { - mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); - - mockFileDataAccessor.GetFile(path).CreationTime = new DateTimeOffset(creationTimeUtc, TimeSpan.Zero); - } - - public override void SetLastAccessTime(string path, DateTime lastAccessTime) - { - mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); - - mockFileDataAccessor.GetFile(path).LastAccessTime = new DateTimeOffset(lastAccessTime); - } - - public override void SetLastAccessTimeUtc(string path, DateTime lastAccessTimeUtc) - { - mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); - - mockFileDataAccessor.GetFile(path).LastAccessTime = new DateTimeOffset(lastAccessTimeUtc, TimeSpan.Zero); - } - - public override void SetLastWriteTime(string path, DateTime lastWriteTime) - { - mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); - - mockFileDataAccessor.GetFile(path).LastWriteTime = new DateTimeOffset(lastWriteTime); - } - - public override void SetLastWriteTimeUtc(string path, DateTime lastWriteTimeUtc) - { - mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); - - mockFileDataAccessor.GetFile(path).LastWriteTime = new DateTimeOffset(lastWriteTimeUtc, TimeSpan.Zero); - } - - /// - /// Creates a new file, writes the specified byte array to the file, and then closes the file. - /// If the target file already exists, it is overwritten. - /// - /// The file to write to. - /// The bytes to write to the file. - /// is a zero-length string, contains only white space, or contains one or more invalid characters as defined by . - /// is or contents is empty. - /// - /// The specified path, file name, or both exceed the system-defined maximum length. - /// For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters. - /// - /// The specified path is invalid (for example, it is on an unmapped drive). - /// An I/O error occurred while opening the file. - /// - /// path specified a file that is read-only. - /// -or- - /// This operation is not supported on the current platform. - /// -or- - /// path specified a directory. - /// -or- - /// The caller does not have the required permission. - /// - /// The file specified in was not found. - /// is in an invalid format. - /// The caller does not have the required permission. - /// - /// Given a byte array and a file path, this method opens the specified file, writes the contents of the byte array to the file, and then closes the file. - /// - public override void WriteAllBytes(string path, byte[] bytes) - { - if (path == null) - { - throw new ArgumentNullException("path", "Path cannot be null."); - } - - VerifyValueIsNotNull(bytes, "bytes"); - - VerifyDirectoryExists(path); - - mockFileDataAccessor.AddFile(path, new MockFileData(bytes)); - } - - /// - /// Creates a new file, writes a collection of strings to the file, and then closes the file. - /// - /// The file to write to. - /// The lines to write to the file. - /// is a zero-length string, contains only white space, or contains one or more invalid characters as defined by . - /// Either or is . - /// The specified path is invalid (for example, it is on an unmapped drive). - /// The file specified in was not found. - /// An I/O error occurred while opening the file. - /// - /// The specified path, file name, or both exceed the system-defined maximum length. - /// For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters. - /// - /// is in an invalid format. - /// The caller does not have the required permission. - /// - /// specified a file that is read-only. - /// -or- - /// This operation is not supported on the current platform. - /// -or- - /// specified a directory. - /// -or- - /// The caller does not have the required permission. - /// - /// - /// - /// If the target file already exists, it is overwritten. - /// - /// - /// You can use this method to create the contents for a collection class that takes an in its constructor, such as a , , or a class. - /// - /// - public override void WriteAllLines(string path, IEnumerable contents) - { - mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); - VerifyValueIsNotNull(contents, "contents"); - - WriteAllLines(path, contents, MockFileData.DefaultEncoding); - } - - /// - /// Creates a new file by using the specified encoding, writes a collection of strings to the file, and then closes the file. - /// - /// The file to write to. - /// The lines to write to the file. - /// The character encoding to use. - /// is a zero-length string, contains only white space, or contains one or more invalid characters as defined by . - /// Either , , or is . - /// The specified path is invalid (for example, it is on an unmapped drive). - /// The file specified in was not found. - /// An I/O error occurred while opening the file. - /// - /// The specified path, file name, or both exceed the system-defined maximum length. - /// For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters. - /// - /// is in an invalid format. - /// The caller does not have the required permission. - /// - /// specified a file that is read-only. - /// -or- - /// This operation is not supported on the current platform. - /// -or- - /// specified a directory. - /// -or- - /// The caller does not have the required permission. - /// - /// - /// - /// If the target file already exists, it is overwritten. - /// - /// - /// You can use this method to create a file that contains the following: - /// - /// - /// The results of a LINQ to Objects query on the lines of a file, as obtained by using the ReadLines method. - /// - /// - /// The contents of a collection that implements an of strings. - /// - /// - /// - /// - public override void WriteAllLines(string path, IEnumerable contents, Encoding encoding) - { - mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); - VerifyValueIsNotNull(contents, "contents"); - VerifyValueIsNotNull(encoding, "encoding"); - - var sb = new StringBuilder(); - foreach (var line in contents) - { - sb.AppendLine(line); - } - - WriteAllText(path, sb.ToString(), encoding); - } - - /// - /// Creates a new file, writes the specified string array to the file by using the specified encoding, and then closes the file. - /// - /// The file to write to. - /// The string array to write to the file. - /// is a zero-length string, contains only white space, or contains one or more invalid characters as defined by . - /// Either or is . - /// - /// The specified path, file name, or both exceed the system-defined maximum length. - /// For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters. - /// - /// The specified path is invalid (for example, it is on an unmapped drive). - /// An I/O error occurred while opening the file. - /// - /// specified a file that is read-only. - /// -or- - /// This operation is not supported on the current platform. - /// -or- - /// specified a directory. - /// -or- - /// The caller does not have the required permission. - /// - /// The file specified in was not found. - /// is in an invalid format. - /// The caller does not have the required permission. - /// - /// - /// If the target file already exists, it is overwritten. - /// - /// - /// The default behavior of the WriteAllLines method is to write out data using UTF-8 encoding without a byte order mark (BOM). If it is necessary to include a UTF-8 identifier, such as a byte order mark, at the beginning of a file, use the method overload with encoding. - /// - /// - /// Given a string array and a file path, this method opens the specified file, writes the string array to the file using the specified encoding, - /// and then closes the file. - /// - /// - public override void WriteAllLines(string path, string[] contents) - { - mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); - VerifyValueIsNotNull(contents, "contents"); - - WriteAllLines(path, contents, MockFileData.DefaultEncoding); - } - - /// - /// Creates a new file, writes the specified string array to the file by using the specified encoding, and then closes the file. - /// - /// The file to write to. - /// The string array to write to the file. - /// An object that represents the character encoding applied to the string array. - /// is a zero-length string, contains only white space, or contains one or more invalid characters as defined by . - /// Either or is . - /// - /// The specified path, file name, or both exceed the system-defined maximum length. - /// For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters. - /// - /// The specified path is invalid (for example, it is on an unmapped drive). - /// An I/O error occurred while opening the file. - /// - /// specified a file that is read-only. - /// -or- - /// This operation is not supported on the current platform. - /// -or- - /// specified a directory. - /// -or- - /// The caller does not have the required permission. - /// - /// The file specified in was not found. - /// is in an invalid format. - /// The caller does not have the required permission. - /// - /// - /// If the target file already exists, it is overwritten. - /// - /// - /// Given a string array and a file path, this method opens the specified file, writes the string array to the file using the specified encoding, - /// and then closes the file. - /// - /// - public override void WriteAllLines(string path, string[] contents, Encoding encoding) - { - mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); - VerifyValueIsNotNull(contents, "contents"); - VerifyValueIsNotNull(encoding, "encoding"); - - WriteAllLines(path, new List(contents), encoding); - } - - /// - /// Creates a new file, writes the specified string to the file using the specified encoding, and then closes the file. If the target file already exists, it is overwritten. - /// - /// The file to write to. - /// The string to write to the file. - /// is a zero-length string, contains only white space, or contains one or more invalid characters as defined by . - /// is or contents is empty. - /// - /// The specified path, file name, or both exceed the system-defined maximum length. - /// For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters. - /// - /// The specified path is invalid (for example, it is on an unmapped drive). - /// An I/O error occurred while opening the file. - /// - /// path specified a file that is read-only. - /// -or- - /// This operation is not supported on the current platform. - /// -or- - /// path specified a directory. - /// -or- - /// The caller does not have the required permission. - /// - /// The file specified in was not found. - /// is in an invalid format. - /// The caller does not have the required permission. - /// - /// This method uses UTF-8 encoding without a Byte-Order Mark (BOM), so using the method will return an empty byte array. - /// If it is necessary to include a UTF-8 identifier, such as a byte order mark, at the beginning of a file, use the method overload with encoding. - /// - /// Given a string and a file path, this method opens the specified file, writes the string to the file, and then closes the file. - /// - /// - public override void WriteAllText(string path, string contents) - { - WriteAllText(path, contents, MockFileData.DefaultEncoding); - } - - /// - /// Creates a new file, writes the specified string to the file using the specified encoding, and then closes the file. If the target file already exists, it is overwritten. - /// - /// The file to write to. - /// The string to write to the file. - /// The encoding to apply to the string. - /// is a zero-length string, contains only white space, or contains one or more invalid characters as defined by . - /// is or contents is empty. - /// - /// The specified path, file name, or both exceed the system-defined maximum length. - /// For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters. - /// - /// The specified path is invalid (for example, it is on an unmapped drive). - /// An I/O error occurred while opening the file. - /// - /// path specified a file that is read-only. - /// -or- - /// This operation is not supported on the current platform. - /// -or- - /// path specified a directory. - /// -or- - /// The caller does not have the required permission. - /// - /// The file specified in was not found. - /// is in an invalid format. - /// The caller does not have the required permission. - /// - /// Given a string and a file path, this method opens the specified file, writes the string to the file using the specified encoding, and then closes the file. - /// The file handle is guaranteed to be closed by this method, even if exceptions are raised. - /// - public override void WriteAllText(string path, string contents, Encoding encoding) - { - mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); - VerifyValueIsNotNull(path, "path"); - - if (mockFileDataAccessor.Directory.Exists(path)) - { - throw new UnauthorizedAccessException(string.Format(CultureInfo.InvariantCulture, Properties.Resources.ACCESS_TO_THE_PATH_IS_DENIED, path)); - } - - VerifyDirectoryExists(path); - - MockFileData data = contents == null ? new MockFileData(new byte[0]) : new MockFileData(contents, encoding); - mockFileDataAccessor.AddFile(path, data); - } - - internal static string ReadAllBytes(byte[] contents, Encoding encoding) - { - using (var ms = new MemoryStream(contents)) - using (var sr = new StreamReader(ms, encoding)) - { - return sr.ReadToEnd(); - } - } - - private string ReadAllTextInternal(string path, Encoding encoding) - { - var mockFileData = mockFileDataAccessor.GetFile(path); - return ReadAllBytes(mockFileData.Contents, encoding); - } - - private void VerifyValueIsNotNull(object value, string parameterName) - { - if (value == null) - { - throw new ArgumentNullException(parameterName, Properties.Resources.VALUE_CANNOT_BE_NULL); - } - } - - private void VerifyDirectoryExists(string path) - { - DirectoryInfoBase dir = mockFileDataAccessor.Directory.GetParent(path); - if (!dir.Exists) - { - throw new DirectoryNotFoundException(string.Format(CultureInfo.InvariantCulture, Properties.Resources.COULD_NOT_FIND_PART_OF_PATH_EXCEPTION, dir)); - } - } - } -} \ No newline at end of file diff --git a/TestingHelpers/MockFileData.cs b/TestingHelpers/MockFileData.cs deleted file mode 100644 index 0d9945bc4..000000000 --- a/TestingHelpers/MockFileData.cs +++ /dev/null @@ -1,188 +0,0 @@ -using System.Linq; -using System.Security.AccessControl; -using System.Text; - -namespace System.IO.Abstractions.TestingHelpers -{ - /// - /// The class represents the associated data of a file. - /// - [Serializable] - public class MockFileData - { - /// - /// The default encoding. - /// - public static readonly Encoding DefaultEncoding = new UTF8Encoding(false, true); - - /// - /// The null object. - /// - public static readonly MockFileData NullObject = new MockFileData(string.Empty) - { - LastWriteTime = new DateTime(1601, 01, 01, 00, 00, 00, DateTimeKind.Utc), - LastAccessTime = new DateTime(1601, 01, 01, 00, 00, 00, DateTimeKind.Utc), - CreationTime = new DateTime(1601, 01, 01, 00, 00, 00, DateTimeKind.Utc), - }; - - /// - /// Gets the default date time offset. - /// E.g. for not existing files. - /// - public static readonly DateTimeOffset DefaultDateTimeOffset = new DateTime(1601, 01, 01, 00, 00, 00, DateTimeKind.Utc); - - /// - /// The actual contents of the file. - /// - private byte[] contents; - - /// - /// The date and time the was created. - /// - private DateTimeOffset creationTime = new DateTimeOffset(2010, 01, 02, 00, 00, 00, TimeSpan.FromHours(4)); - - /// - /// The date and time of the was last accessed to. - /// - private DateTimeOffset lastAccessTime = new DateTimeOffset(2010, 02, 04, 00, 00, 00, TimeSpan.FromHours(4)); - - /// - /// The date and time of the was last written to. - /// - private DateTimeOffset lastWriteTime = new DateTimeOffset(2010, 01, 04, 00, 00, 00, TimeSpan.FromHours(4)); - - /// - /// The attributes of the . - /// - private FileAttributes attributes = FileAttributes.Normal; - - /// - /// The access control of the . - /// - [NonSerialized] - private FileSecurity accessControl = new FileSecurity(); - - /// - /// Gets a value indicating whether the is a directory or not. - /// - public virtual bool IsDirectory { get { return false; } } - - /// - /// Initializes a new instance of the class with an empty content. - /// - private MockFileData() - { - // empty - } - - /// - /// Initializes a new instance of the class with the content of using the encoding of . - /// - /// The textual content encoded into bytes with . - public MockFileData(string textContents) - : this(DefaultEncoding.GetBytes(textContents)) - {} - - /// - /// Initializes a new instance of the class with the content of using the encoding of . - /// - /// The textual content. - /// The specific encoding used the encode the text. - /// The constructor respect the BOM of . - public MockFileData(string textContents, Encoding encoding) - : this() - { - contents = encoding.GetPreamble().Concat(encoding.GetBytes(textContents)).ToArray(); - } - - /// - /// Initializes a new instance of the class with the content of . - /// - /// The actual content. - /// Thrown if is . - public MockFileData(byte[] contents) - { - if (contents == null) - { - throw new ArgumentNullException("contents"); - } - - this.contents = contents; - } - - /// - /// Gets or sets the byte contents of the . - /// - public byte[] Contents - { - get { return contents; } - set { contents = value; } - } - - /// - /// Gets or sets the string contents of the . - /// - /// - /// The setter uses the using this can scramble the actual contents. - /// - public string TextContents - { - get { return MockFile.ReadAllBytes(contents, DefaultEncoding); } - set { contents = DefaultEncoding.GetBytes(value); } - } - - /// - /// Gets or sets the date and time the was created. - /// - public DateTimeOffset CreationTime - { - get { return creationTime; } - set { creationTime = value; } - } - - /// - /// Gets or sets the date and time of the was last accessed to. - /// - public DateTimeOffset LastAccessTime - { - get { return lastAccessTime; } - set { lastAccessTime = value; } - } - - /// - /// Gets or sets the date and time of the was last written to. - /// - public DateTimeOffset LastWriteTime - { - get { return lastWriteTime; } - set { lastWriteTime = value; } - } - - /// - /// Casts a string into . - /// - /// The path of the to be created. - public static implicit operator MockFileData(string s) - { - return new MockFileData(s); - } - - /// - /// Gets or sets the specified of the . - /// - public FileAttributes Attributes - { - get { return attributes; } - set { attributes = value; } - } - - /// - /// Gets or sets of the . This is the object that is returned for this when calling . - /// - public FileSecurity AccessControl - { - get { return accessControl; } - set { accessControl = value; } - } - } -} \ No newline at end of file diff --git a/TestingHelpers/MockFileInfo.cs b/TestingHelpers/MockFileInfo.cs deleted file mode 100644 index d881af155..000000000 --- a/TestingHelpers/MockFileInfo.cs +++ /dev/null @@ -1,306 +0,0 @@ -using System.Security.AccessControl; - -namespace System.IO.Abstractions.TestingHelpers -{ - [Serializable] - public class MockFileInfo : FileInfoBase - { - private readonly IMockFileDataAccessor mockFileSystem; - private string path; - - public MockFileInfo(IMockFileDataAccessor mockFileSystem, string path) - { - if (mockFileSystem == null) - { - throw new ArgumentNullException("mockFileSystem"); - } - - this.mockFileSystem = mockFileSystem; - this.path = path; - } - - MockFileData MockFileData - { - get { return mockFileSystem.GetFile(path); } - } - - public override void Delete() - { - mockFileSystem.RemoveFile(path); - } - - public override void Refresh() - { - } - - public override FileAttributes Attributes - { - get - { - if (MockFileData == null) - throw new FileNotFoundException("File not found", path); - return MockFileData.Attributes; - } - set { MockFileData.Attributes = value; } - } - - public override DateTime CreationTime - { - get - { - if (MockFileData == null) throw new FileNotFoundException("File not found", path); - return MockFileData.CreationTime.DateTime; - } - set - { - if (MockFileData == null) throw new FileNotFoundException("File not found", path); - MockFileData.CreationTime = value; - } - } - - public override DateTime CreationTimeUtc - { - get - { - if (MockFileData == null) throw new FileNotFoundException("File not found", path); - return MockFileData.CreationTime.UtcDateTime; - } - set - { - if (MockFileData == null) throw new FileNotFoundException("File not found", path); - MockFileData.CreationTime = value.ToLocalTime(); - } - } - - public override bool Exists - { - get { return MockFileData != null; } - } - - public override string Extension - { - get - { - // System.IO.Path.GetExtension does only string manipulation, - // so it's safe to delegate. - return Path.GetExtension(path); - } - } - - public override string FullName - { - get { return path; } - } - - public override DateTime LastAccessTime - { - get - { - if (MockFileData == null) throw new FileNotFoundException("File not found", path); - return MockFileData.LastAccessTime.DateTime; - } - set - { - if (MockFileData == null) throw new FileNotFoundException("File not found", path); - MockFileData.LastAccessTime = value; - } - } - - public override DateTime LastAccessTimeUtc - { - get - { - if (MockFileData == null) throw new FileNotFoundException("File not found", path); - return MockFileData.LastAccessTime.UtcDateTime; - } - set - { - if (MockFileData == null) throw new FileNotFoundException("File not found", path); - MockFileData.LastAccessTime = value; - } - } - - public override DateTime LastWriteTime - { - get - { - if (MockFileData == null) throw new FileNotFoundException("File not found", path); - return MockFileData.LastWriteTime.DateTime; - } - set - { - if (MockFileData == null) throw new FileNotFoundException("File not found", path); - MockFileData.LastWriteTime = value; - } - } - - public override DateTime LastWriteTimeUtc - { - get - { - if (MockFileData == null) throw new FileNotFoundException("File not found", path); - return MockFileData.LastWriteTime.UtcDateTime; - } - set - { - if (MockFileData == null) throw new FileNotFoundException("File not found", path); - MockFileData.LastWriteTime = value.ToLocalTime(); - } - } - - public override string Name { - get { return new MockPath(mockFileSystem).GetFileName(path); } - } - - public override StreamWriter AppendText() - { - if (MockFileData == null) throw new FileNotFoundException("File not found", path); - return new StreamWriter(new MockFileStream(mockFileSystem, FullName, true)); - //return ((MockFileDataModifier) MockFileData).AppendText(); - } - - public override FileInfoBase CopyTo(string destFileName) - { - new MockFile(mockFileSystem).Copy(FullName, destFileName); - return mockFileSystem.FileInfo.FromFileName(destFileName); - } - - public override FileInfoBase CopyTo(string destFileName, bool overwrite) - { - new MockFile(mockFileSystem).Copy(FullName, destFileName, overwrite); - return mockFileSystem.FileInfo.FromFileName(destFileName); - } - - public override Stream Create() - { - return new MockFile(mockFileSystem).Create(FullName); - } - - public override StreamWriter CreateText() - { - return new MockFile(mockFileSystem).CreateText(FullName); - } - - public override void Decrypt() - { - if (MockFileData == null) throw new FileNotFoundException("File not found", path); - var contents = MockFileData.Contents; - for (var i = 0; i < contents.Length; i++) - contents[i] ^= (byte)(i % 256); - } - - public override void Encrypt() - { - if (MockFileData == null) throw new FileNotFoundException("File not found", path); - var contents = MockFileData.Contents; - for(var i = 0; i < contents.Length; i++) - contents[i] ^= (byte) (i % 256); - } - - public override FileSecurity GetAccessControl() - { - throw new NotImplementedException(Properties.Resources.NOT_IMPLEMENTED_EXCEPTION); - } - - public override FileSecurity GetAccessControl(AccessControlSections includeSections) - { - throw new NotImplementedException(Properties.Resources.NOT_IMPLEMENTED_EXCEPTION); - } - - public override void MoveTo(string destFileName) - { - var movedFileInfo = CopyTo(destFileName); - Delete(); - path = movedFileInfo.FullName; - } - - public override Stream Open(FileMode mode) - { - return new MockFile(mockFileSystem).Open(FullName, mode); - } - - public override Stream Open(FileMode mode, FileAccess access) - { - return new MockFile(mockFileSystem).Open(FullName, mode, access); - } - - public override Stream Open(FileMode mode, FileAccess access, FileShare share) - { - return new MockFile(mockFileSystem).Open(FullName, mode, access, share); - } - - public override Stream OpenRead() - { - return new MockFileStream(mockFileSystem, path); - } - - public override StreamReader OpenText() - { - return new StreamReader(OpenRead()); - } - - public override Stream OpenWrite() - { - return new MockFileStream(mockFileSystem, path); - } - - public override FileInfoBase Replace(string destinationFileName, string destinationBackupFileName) - { - throw new NotImplementedException(Properties.Resources.NOT_IMPLEMENTED_EXCEPTION); - } - - public override FileInfoBase Replace(string destinationFileName, string destinationBackupFileName, bool ignoreMetadataErrors) - { - throw new NotImplementedException(Properties.Resources.NOT_IMPLEMENTED_EXCEPTION); - } - - public override void SetAccessControl(FileSecurity fileSecurity) - { - throw new NotImplementedException(Properties.Resources.NOT_IMPLEMENTED_EXCEPTION); - } - - public override DirectoryInfoBase Directory - { - get - { - return mockFileSystem.DirectoryInfo.FromDirectoryName(DirectoryName); - } - } - - public override string DirectoryName - { - get - { - // System.IO.Path.GetDirectoryName does only string manipulation, - // so it's safe to delegate. - return Path.GetDirectoryName(path); - } - } - - public override bool IsReadOnly - { - get - { - if (MockFileData == null) throw new FileNotFoundException("File not found", path); - return (MockFileData.Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly; - } - set - { - if (MockFileData == null) throw new FileNotFoundException("File not found", path); - if(value) - MockFileData.Attributes |= FileAttributes.ReadOnly; - else - MockFileData.Attributes &= ~FileAttributes.ReadOnly; - } - } - - public override long Length - { - get - { - if (MockFileData == null) throw new FileNotFoundException("File not found", path); - return MockFileData.Contents.LongLength; - } - } - } -} \ No newline at end of file diff --git a/TestingHelpers/MockFileInfoFactory.cs b/TestingHelpers/MockFileInfoFactory.cs deleted file mode 100644 index c0ed0453d..000000000 --- a/TestingHelpers/MockFileInfoFactory.cs +++ /dev/null @@ -1,23 +0,0 @@ -namespace System.IO.Abstractions.TestingHelpers -{ - [Serializable] - public class MockFileInfoFactory : IFileInfoFactory - { - private readonly IMockFileDataAccessor mockFileSystem; - - public MockFileInfoFactory(IMockFileDataAccessor mockFileSystem) - { - if (mockFileSystem == null) - { - throw new ArgumentNullException("mockFileSystem"); - } - - this.mockFileSystem = mockFileSystem; - } - - public FileInfoBase FromFileName(string fileName) - { - return new MockFileInfo(mockFileSystem, fileName); - } - } -} \ No newline at end of file diff --git a/TestingHelpers/MockFileStream.cs b/TestingHelpers/MockFileStream.cs deleted file mode 100644 index 0af1ac962..000000000 --- a/TestingHelpers/MockFileStream.cs +++ /dev/null @@ -1,62 +0,0 @@ -namespace System.IO.Abstractions.TestingHelpers -{ - [Serializable] - public class MockFileStream : MemoryStream - { - private readonly IMockFileDataAccessor mockFileDataAccessor; - private readonly string path; - - public MockFileStream(IMockFileDataAccessor mockFileDataAccessor, string path, bool forAppend = false) - { - if (mockFileDataAccessor == null) - { - throw new ArgumentNullException("mockFileDataAccessor"); - } - - this.mockFileDataAccessor = mockFileDataAccessor; - this.path = path; - - if (mockFileDataAccessor.FileExists(path)) - { - /* only way to make an expandable MemoryStream that starts with a particular content */ - var data = mockFileDataAccessor.GetFile(path).Contents; - if (data != null && data.Length > 0) - { - Write(data, 0, data.Length); - Seek(0, forAppend - ? SeekOrigin.End - : SeekOrigin.Begin); - } - } - else - { - mockFileDataAccessor.AddFile(path, new MockFileData(new byte[] { })); - } - } - - public override void Close() - { - InternalFlush(); - } - - public override void Flush() - { - InternalFlush(); - } - - private void InternalFlush() - { - if (mockFileDataAccessor.FileExists(path)) - { - var mockFileData = mockFileDataAccessor.GetFile(path); - /* reset back to the beginning .. */ - Seek(0, SeekOrigin.Begin); - /* .. read everything out */ - var data = new byte[Length]; - Read(data, 0, (int)Length); - /* .. put it in the mock system */ - mockFileData.Contents = data; - } - } - } -} \ No newline at end of file diff --git a/TestingHelpers/MockFileSystem.cs b/TestingHelpers/MockFileSystem.cs deleted file mode 100644 index bddec18e1..000000000 --- a/TestingHelpers/MockFileSystem.cs +++ /dev/null @@ -1,224 +0,0 @@ -using System.Collections.Generic; -using System.Globalization; -using System.Linq; - -namespace System.IO.Abstractions.TestingHelpers -{ - using XFS = MockUnixSupport; - - [Serializable] - public class MockFileSystem : IFileSystem, IMockFileDataAccessor - { - private readonly IDictionary files; - private readonly FileBase file; - private readonly DirectoryBase directory; - private readonly IFileInfoFactory fileInfoFactory; - private readonly PathBase pathField; - private readonly IDirectoryInfoFactory directoryInfoFactory; - private readonly IDriveInfoFactory driveInfoFactory; - - [NonSerialized] - private readonly PathVerifier pathVerifier; - - public MockFileSystem() : this(null) { } - - public MockFileSystem(IDictionary files, string currentDirectory = "") - { - if (string.IsNullOrEmpty(currentDirectory)) - currentDirectory = IO.Path.GetTempPath(); - - pathVerifier = new PathVerifier(this); - - this.files = new Dictionary(StringComparer.OrdinalIgnoreCase); - pathField = new MockPath(this); - file = new MockFile(this); - directory = new MockDirectory(this, file, currentDirectory); - fileInfoFactory = new MockFileInfoFactory(this); - directoryInfoFactory = new MockDirectoryInfoFactory(this); - driveInfoFactory = new MockDriveInfoFactory(this); - - if (files != null) - { - foreach (var entry in files) - { - AddFile(entry.Key, entry.Value); - } - } - } - - public FileBase File - { - get { return file; } - } - - public DirectoryBase Directory - { - get { return directory; } - } - - public IFileInfoFactory FileInfo - { - get { return fileInfoFactory; } - } - - public PathBase Path - { - get { return pathField; } - } - - public IDirectoryInfoFactory DirectoryInfo - { - get { return directoryInfoFactory; } - } - - public IDriveInfoFactory DriveInfo - { - get { return driveInfoFactory; } - } - - public PathVerifier PathVerifier - { - get { return pathVerifier; } - } - - private string FixPath(string path) - { - var pathSeparatorFixed = path.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar); - return pathField.GetFullPath(pathSeparatorFixed); - } - - public MockFileData GetFile(string path) - { - path = FixPath(path); - - return GetFileWithoutFixingPath(path); - } - - public void AddFile(string path, MockFileData mockFile) - { - var fixedPath = FixPath(path); - lock (files) - { - if (FileExists(fixedPath)) - { - var isReadOnly = (files[fixedPath].Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly; - var isHidden = (files[fixedPath].Attributes & FileAttributes.Hidden) == FileAttributes.Hidden; - - if (isReadOnly || isHidden) - { - throw new UnauthorizedAccessException(string.Format(CultureInfo.InvariantCulture, Properties.Resources.ACCESS_TO_THE_PATH_IS_DENIED, path)); - } - } - - var directoryPath = Path.GetDirectoryName(fixedPath); - - if (!directory.Exists(directoryPath)) - { - AddDirectory(directoryPath); - } - - files[fixedPath] = mockFile; - } - } - - public void AddDirectory(string path) - { - var fixedPath = FixPath(path); - var separator = XFS.Separator(); - - lock (files) - { - if (FileExists(path) && - (files[fixedPath].Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly) - throw new UnauthorizedAccessException(string.Format(CultureInfo.InvariantCulture, Properties.Resources.ACCESS_TO_THE_PATH_IS_DENIED, path)); - - var lastIndex = 0; - - bool isUnc = - path.StartsWith(@"\\", StringComparison.OrdinalIgnoreCase) || - path.StartsWith(@"//", StringComparison.OrdinalIgnoreCase); - - if (isUnc) - { - //First, confirm they aren't trying to create '\\server\' - lastIndex = path.IndexOf(separator, 2, StringComparison.OrdinalIgnoreCase); - if (lastIndex < 0) - throw new ArgumentException(@"The UNC path should be of the form \\server\share.", "path"); - - /* - * Although CreateDirectory(@"\\server\share\") is not going to work in real code, we allow it here for the purposes of setting up test doubles. - * See PR https://github.com/tathamoddie/System.IO.Abstractions/pull/90 for conversation - */ - } - - while ((lastIndex = path.IndexOf(separator, lastIndex + 1, StringComparison.OrdinalIgnoreCase)) > -1) - { - var segment = path.Substring(0, lastIndex + 1); - if (!directory.Exists(segment)) - { - files[segment] = new MockDirectoryData(); - } - } - - var s = path.EndsWith(separator, StringComparison.OrdinalIgnoreCase) ? path : path + separator; - files[s] = new MockDirectoryData(); - } - } - - public void RemoveFile(string path) - { - path = FixPath(path); - - lock (files) - files.Remove(path); - } - - public bool FileExists(string path) - { - if (string.IsNullOrEmpty(path)) - return false; - - path = FixPath(path); - - lock (files) - return files.ContainsKey(path); - } - - public IEnumerable AllPaths - { - get - { - lock (files) - return files.Keys.ToArray(); - } - } - - public IEnumerable AllFiles - { - get - { - lock (file) - return files.Where(f => !f.Value.IsDirectory).Select(f => f.Key).ToArray(); - } - } - - public IEnumerable AllDirectories - { - get - { - lock (files) - return files.Where(f => f.Value.IsDirectory).Select(f => f.Key).ToArray(); - } - } - - private MockFileData GetFileWithoutFixingPath(string path) - { - lock (files) - { - MockFileData result; - files.TryGetValue(path, out result); - return result; - } - } - } -} diff --git a/TestingHelpers/MockPath.cs b/TestingHelpers/MockPath.cs deleted file mode 100644 index fdb5d1c88..000000000 --- a/TestingHelpers/MockPath.cs +++ /dev/null @@ -1,174 +0,0 @@ -using System.Collections.Generic; -using System.Globalization; -using System.Linq; - -namespace System.IO.Abstractions.TestingHelpers -{ - /// - /// PathWrapper calls direct to Path but all this does is string manipulation so we can inherit directly from PathWrapper as no IO is done - /// - [Serializable] - public class MockPath : PathWrapper - { - private readonly IMockFileDataAccessor mockFileDataAccessor; - - private static readonly char[] InvalidAdditionalPathChars = { '*', '?' }; - - public MockPath(IMockFileDataAccessor mockFileDataAccessor) - { - if (mockFileDataAccessor == null) - { - throw new ArgumentNullException("mockFileDataAccessor"); - } - - this.mockFileDataAccessor = mockFileDataAccessor; - } - - public override string GetFullPath(string path) - { - if (path == null) - { - throw new ArgumentNullException("path", Properties.Resources.VALUE_CANNOT_BE_NULL); - } - - if (path.Length == 0) - { - throw new ArgumentException(Properties.Resources.THE_PATH_IS_NOT_OF_A_LEGAL_FORM, "path"); - } - - path = path.Replace(AltDirectorySeparatorChar, DirectorySeparatorChar); - - bool isUnc = - path.StartsWith(@"\\", StringComparison.OrdinalIgnoreCase) || - path.StartsWith(@"//", StringComparison.OrdinalIgnoreCase); - - string root = GetPathRoot(path); - - bool hasTrailingSlash = path.Length > 1 && path[path.Length - 1] == DirectorySeparatorChar; - - string[] pathSegments; - - if (root.Length == 0) - { - // relative path on the current drive or volume - path = mockFileDataAccessor.Directory.GetCurrentDirectory() + DirectorySeparatorChar + path; - pathSegments = GetSegments(path); - } - else if (isUnc) - { - // unc path - pathSegments = GetSegments(path); - if (pathSegments.Length < 2) - { - throw new ArgumentException(@"The UNC path should be of the form \\server\share.", "path"); - } - } - else if (@"\".Equals(root, StringComparison.OrdinalIgnoreCase) || @"/".Equals(root, StringComparison.OrdinalIgnoreCase)) - { - // absolute path on the current drive or volume - pathSegments = GetSegments(GetPathRoot(mockFileDataAccessor.Directory.GetCurrentDirectory()), path); - } - else - { - pathSegments = GetSegments(path); - } - - // unc paths need at least two segments, the others need one segment - bool isUnixRooted = - mockFileDataAccessor.Directory.GetCurrentDirectory() - .StartsWith(DirectorySeparatorChar.ToString(CultureInfo.InvariantCulture), StringComparison.OrdinalIgnoreCase); - - var minPathSegments = isUnc - ? 2 - : isUnixRooted ? 0 : 1; - - var stack = new Stack(); - foreach (var segment in pathSegments) - { - if ("..".Equals(segment, StringComparison.OrdinalIgnoreCase)) - { - // only pop, if afterwards are at least the minimal amount of path segments - if (stack.Count > minPathSegments) - { - stack.Pop(); - } - } - else if (".".Equals(segment, StringComparison.OrdinalIgnoreCase)) - { - // ignore . - } - else - { - stack.Push(segment); - } - } - - var fullPath = string.Join(DirectorySeparatorChar.ToString(CultureInfo.InvariantCulture), stack.Reverse().ToArray()); - - if (hasTrailingSlash) - { - fullPath += DirectorySeparatorChar; - } - - if (isUnixRooted && !isUnc) - { - fullPath = DirectorySeparatorChar + fullPath; - } - else if (isUnixRooted) - { - fullPath = @"//" + fullPath; - } - else if (isUnc) - { - fullPath = @"\\" + fullPath; - } - - return fullPath; - } - - private string[] GetSegments(params string[] paths) - { - return paths.SelectMany(path => path.Split(new[] { DirectorySeparatorChar }, StringSplitOptions.RemoveEmptyEntries)).ToArray(); - } - - public override string GetTempFileName() - { - string fileName = mockFileDataAccessor.Path.GetRandomFileName(); - string tempDir = mockFileDataAccessor.Path.GetTempPath(); - - string fullPath = mockFileDataAccessor.Path.Combine(tempDir, fileName); - - mockFileDataAccessor.AddFile(fullPath, new MockFileData(string.Empty)); - - return fullPath; - } - - internal static bool HasIllegalCharacters(string path, bool checkAdditional) - { - if (path == null) - { - throw new ArgumentNullException("path"); - } - - if (checkAdditional) - { - return path.IndexOfAny(Path.GetInvalidPathChars().Concat(InvalidAdditionalPathChars).ToArray()) >= 0; - } - - return path.IndexOfAny(Path.GetInvalidPathChars()) >= 0; - } - - internal static void CheckInvalidPathChars(string path, bool checkAdditional = false) - { - if (path == null) - { - throw new ArgumentNullException("path"); - } - - if (HasIllegalCharacters(path, checkAdditional)) - { - throw new ArgumentException(Properties.Resources.ILLEGAL_CHARACTERS_IN_PATH_EXCEPTION); - } - } - } -} diff --git a/TestingHelpers/MockUnixSupport.cs b/TestingHelpers/MockUnixSupport.cs deleted file mode 100644 index 763e33e36..000000000 --- a/TestingHelpers/MockUnixSupport.cs +++ /dev/null @@ -1,32 +0,0 @@ -using System.Text.RegularExpressions; - -namespace System.IO.Abstractions.TestingHelpers -{ - internal static class MockUnixSupport - { - internal static string Path(string path, Func isUnixF = null) - { - var isUnix = isUnixF ?? IsUnixPlatform; - - if (isUnix()) - { - path = Regex.Replace(path, @"^[a-zA-Z]:(?.*)$", "${path}"); - path = path.Replace(@"\", "/"); - } - - return path; - } - - internal static string Separator(Func isUnixF = null) - { - var isUnix = isUnixF ?? IsUnixPlatform; - return isUnix() ? "/" : @"\"; - } - - internal static bool IsUnixPlatform() - { - int p = (int)Environment.OSVersion.Platform; - return (p == 4) || (p == 6) || (p == 128); - } - } -} diff --git a/TestingHelpers/PathVerifier.cs b/TestingHelpers/PathVerifier.cs deleted file mode 100644 index de3d7cd17..000000000 --- a/TestingHelpers/PathVerifier.cs +++ /dev/null @@ -1,59 +0,0 @@ -using System.Linq; - -namespace System.IO.Abstractions.TestingHelpers -{ - public class PathVerifier - { - private readonly IMockFileDataAccessor _mockFileDataAccessor; - - internal PathVerifier(IMockFileDataAccessor mockFileDataAccessor) - { - if (mockFileDataAccessor == null) - { - throw new ArgumentNullException("mockFileDataAccessor"); - } - - _mockFileDataAccessor = mockFileDataAccessor; - } - - public void IsLegalAbsoluteOrRelative(string path, string paramName) - { - if (path == null) - { - throw new ArgumentNullException(paramName, Properties.Resources.VALUE_CANNOT_BE_NULL); - } - - if (path == string.Empty) - { - throw new ArgumentException("Empty file name is not legal.", paramName); - } - - if (path.Trim() == string.Empty) - { - throw new ArgumentException(Properties.Resources.THE_PATH_IS_NOT_OF_A_LEGAL_FORM, paramName); - } - - if (ExtractFileName(path).IndexOfAny(_mockFileDataAccessor.Path.GetInvalidFileNameChars()) > -1) - { - throw new ArgumentException(Properties.Resources.ILLEGAL_CHARACTERS_IN_PATH_EXCEPTION); - } - - var filePath = ExtractFilePath(path); - if (MockPath.HasIllegalCharacters(filePath, false)) - { - throw new ArgumentException(Properties.Resources.ILLEGAL_CHARACTERS_IN_PATH_EXCEPTION); - } - } - - private string ExtractFileName(string fullFileName) - { - return fullFileName.Split(_mockFileDataAccessor.Path.DirectorySeparatorChar).Last(); - } - - private string ExtractFilePath(string fullFileName) - { - var extractFilePath = fullFileName.Split(_mockFileDataAccessor.Path.DirectorySeparatorChar); - return string.Join(_mockFileDataAccessor.Path.DirectorySeparatorChar.ToString(), extractFilePath.Take(extractFilePath.Length - 1)); - } - } -} diff --git a/TestingHelpers/Properties/AssemblyInfo.cs b/TestingHelpers/Properties/AssemblyInfo.cs deleted file mode 100644 index f0e86b9dd..000000000 --- a/TestingHelpers/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,26 +0,0 @@ -using System; -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -[assembly: AssemblyVersion("0.0.0.1")] -[assembly: AssemblyFileVersion("0.0.0.1")] - -[assembly: AssemblyTitle("System.IO.Abstractions.TestingHelpers")] -[assembly: AssemblyDescription("A set of pre-built mocks to help when testing file system interactions.")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("System.IO.Abstractions")] -[assembly: AssemblyCopyright("Copyright © Tatham Oddie 2010")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -[assembly: ComVisible(false)] - -[assembly: CLSCompliant(true)] - -#if DEBUG - [assembly: InternalsVisibleTo("System.IO.Abstractions.TestingHelpers.Tests")] -#else - [assembly: InternalsVisibleTo("System.IO.Abstractions.TestingHelpers.Tests, PublicKey=002400000480000094000000060200000024000052534131000400000100010051bf2aa00ba30d507d4cebcab1751dfa13768a6f5235ce52da572260e33a11f52b87707f858fe4bbe32cd51830a8dd73245f688902707fa797c07205ff9b5212f93760d52f6d13022a286ff7daa13a0cd9eb958e888fcd7d9ed1f7cf76b19a5391835a7b633418a5f584d10925d76810f782f6b814cc34a2326b438abdc3b5bd")] -#endif diff --git a/TestingHelpers/Properties/Resources.Designer.cs b/TestingHelpers/Properties/Resources.Designer.cs deleted file mode 100644 index ece6e4eaf..000000000 --- a/TestingHelpers/Properties/Resources.Designer.cs +++ /dev/null @@ -1,135 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// Runtime Version:4.0.30319.42000 -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -namespace System.IO.Abstractions.TestingHelpers.Properties { - using System; - - - /// - /// A strongly-typed resource class, for looking up localized strings, etc. - /// - // This class was auto-generated by the StronglyTypedResourceBuilder - // class via a tool like ResGen or Visual Studio. - // To add or remove a member, edit your .ResX file then rerun ResGen - // with the /str option, or rebuild your VS project. - [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] - internal class Resources { - - private static global::System.Resources.ResourceManager resourceMan; - - private static global::System.Globalization.CultureInfo resourceCulture; - - [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] - internal Resources() { - } - - /// - /// Returns the cached ResourceManager instance used by this class. - /// - [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Resources.ResourceManager ResourceManager { - get { - if (object.ReferenceEquals(resourceMan, null)) { - global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("System.IO.Abstractions.TestingHelpers.Properties.Resources", typeof(Resources).Assembly); - resourceMan = temp; - } - return resourceMan; - } - } - - /// - /// Overrides the current thread's CurrentUICulture property for all - /// resource lookups using this strongly typed resource class. - /// - [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Globalization.CultureInfo Culture { - get { - return resourceCulture; - } - set { - resourceCulture = value; - } - } - - /// - /// Looks up a localized string similar to Access to the path '{0}' is denied.. - /// - internal static string ACCESS_TO_THE_PATH_IS_DENIED { - get { - return ResourceManager.GetString("ACCESS_TO_THE_PATH_IS_DENIED", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Could not find a part of the path '{0}'.. - /// - internal static string COULD_NOT_FIND_PART_OF_PATH_EXCEPTION { - get { - return ResourceManager.GetString("COULD_NOT_FIND_PART_OF_PATH_EXCEPTION", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to File name cannot be null.. - /// - internal static string FILENAME_CANNOT_BE_NULL { - get { - return ResourceManager.GetString("FILENAME_CANNOT_BE_NULL", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Illegal characters in path.. - /// - internal static string ILLEGAL_CHARACTERS_IN_PATH_EXCEPTION { - get { - return ResourceManager.GetString("ILLEGAL_CHARACTERS_IN_PATH_EXCEPTION", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to This test helper hasn't been implemented yet. They are implemented on an as-needed basis. As it seems like you need it, now would be a great time to send us a pull request over at https://github.com/tathamoddie/System.IO.Abstractions. You know, because it's open source and all.. - /// - internal static string NOT_IMPLEMENTED_EXCEPTION { - get { - return ResourceManager.GetString("NOT_IMPLEMENTED_EXCEPTION", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Path cannot be the empty string or all whitespace.. - /// - internal static string PATH_CANNOT_BE_THE_EMPTY_STRING_OR_ALL_WHITESPACE { - get { - return ResourceManager.GetString("PATH_CANNOT_BE_THE_EMPTY_STRING_OR_ALL_WHITESPACE", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to The path is not of a legal form.. - /// - internal static string THE_PATH_IS_NOT_OF_A_LEGAL_FORM { - get { - return ResourceManager.GetString("THE_PATH_IS_NOT_OF_A_LEGAL_FORM", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Value cannot be null.. - /// - internal static string VALUE_CANNOT_BE_NULL { - get { - return ResourceManager.GetString("VALUE_CANNOT_BE_NULL", resourceCulture); - } - } - } -} diff --git a/TestingHelpers/StringExtensions.cs b/TestingHelpers/StringExtensions.cs deleted file mode 100644 index 7eb17e1c5..000000000 --- a/TestingHelpers/StringExtensions.cs +++ /dev/null @@ -1,59 +0,0 @@ -using System.Collections.Generic; -using System.Diagnostics.Contracts; -using System.Text; - -namespace System.IO.Abstractions.TestingHelpers -{ - internal static class StringExtensions - { - [Pure] - internal static string[] SplitLines(this string input) - { - var list = new List(); - using (var reader = new StringReader(input)) - { - string str; - while ((str = reader.ReadLine()) != null) - { - list.Add(str); - } - } - - return list.ToArray(); - } - - [Pure] - public static string Replace(this string source, string oldValue, string newValue, StringComparison comparisonType) - { - // from http://stackoverflow.com/a/22565605 with some adaptions - if (string.IsNullOrEmpty(oldValue)) - { - throw new ArgumentNullException("oldValue"); - } - - if (source.Length == 0) - { - return source; - } - - if (newValue == null) - { - newValue = string.Empty; - } - - var result = new StringBuilder(); - int startingPos = 0; - int nextMatch; - while ((nextMatch = source.IndexOf(oldValue, startingPos, comparisonType)) > -1) - { - result.Append(source, startingPos, nextMatch - startingPos); - result.Append(newValue); - startingPos = nextMatch + oldValue.Length; - } - - result.Append(source, startingPos, source.Length - startingPos); - - return result.ToString(); - } - } -} \ No newline at end of file diff --git a/TestingHelpers/TestingHelpers.csproj b/TestingHelpers/TestingHelpers.csproj deleted file mode 100644 index 4ef1904a7..000000000 --- a/TestingHelpers/TestingHelpers.csproj +++ /dev/null @@ -1,132 +0,0 @@ - - - - Debug - AnyCPU - {251BD5E5-8133-47A4-AB19-17CF0F43D6AE} - Library - Properties - System.IO.Abstractions.TestingHelpers - System.IO.Abstractions.TestingHelpers - v4.0 - 512 - - - 3.5 - - publish\ - true - Disk - false - Foreground - 7 - Days - false - false - true - 0 - 1.0.0.%2a - false - false - true - ..\ - true - - - - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - AllRules.ruleset - false - 5 - - - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - AllRules.ruleset - true - false - - - ..\StrongName.pfx - - - - - - - - - - - - - - - - - - - - - - - - True - True - Resources.resx - - - - - - - False - .NET Framework 3.5 SP1 Client Profile - false - - - False - .NET Framework 3.5 SP1 - true - - - False - Windows Installer 3.1 - true - - - - - - - - {4D398F3A-0784-4401-93CD-46CD2FBD6B92} - System.IO.Abstractions - - - - - ResXFileCodeGenerator - Resources.Designer.cs - Designer - - - - - \ No newline at end of file diff --git a/TestingHelpers/TestingHelpers.ncrunchproject b/TestingHelpers/TestingHelpers.ncrunchproject deleted file mode 100644 index 59d3df4c1..000000000 --- a/TestingHelpers/TestingHelpers.ncrunchproject +++ /dev/null @@ -1,20 +0,0 @@ - - false - false - false - true - false - false - false - false - true - true - false - true - true - 60000 - - - - AutoDetect - \ No newline at end of file diff --git a/TestingHelpers/TestingHelpers.nuspec b/TestingHelpers/TestingHelpers.nuspec deleted file mode 100644 index 18b4f893c..000000000 --- a/TestingHelpers/TestingHelpers.nuspec +++ /dev/null @@ -1,17 +0,0 @@ - - - - System.IO.Abstractions.TestingHelpers - $version$ - Tatham Oddie - Tatham Oddie - https://github.com/tathamoddie/System.IO.Abstractions/blob/master/License.txt - https://github.com/tathamoddie/System.IO.Abstractions - false - Testing helpers for the System.IO.Abstractions package to save having to manually mock everything. - testing - - - - - \ No newline at end of file diff --git a/appveyor.yml b/appveyor.yml deleted file mode 100644 index 8b78e11d1..000000000 --- a/appveyor.yml +++ /dev/null @@ -1,28 +0,0 @@ -version: 2.0.0.{build} - -pull_requests: - do_not_increment_build_number: true - -assembly_info: - patch: true - file: '**\AssemblyInfo.*' - assembly_version: '{version}' - assembly_file_version: '{version}' - -cache: -- packages -> packages\packages.config - -before_build: -- nuget restore - -build: - publish_nuget: true - -deploy: -- provider: NuGet - api_key: - secure: kTNf1aNQVwwimPmGQreJV8UrGI1jBSUiwiTgThlyLZM4tKPguC0ZmSPi8+s7hd4M - skip_symbols: false - artifact: /.*\.nupkg/ - on: - branch: master diff --git a/benchmarks/TestableIO.System.IO.Abstractions.Benchmarks/FileSystemAbstractionBenchmarks.cs b/benchmarks/TestableIO.System.IO.Abstractions.Benchmarks/FileSystemAbstractionBenchmarks.cs new file mode 100644 index 000000000..17b002e48 --- /dev/null +++ b/benchmarks/TestableIO.System.IO.Abstractions.Benchmarks/FileSystemAbstractionBenchmarks.cs @@ -0,0 +1,44 @@ +using System.IO.Abstractions.Benchmarks.Support; +using BenchmarkDotNet.Attributes; +using BenchmarkDotNet.Order; + +namespace System.IO.Abstractions.Benchmarks; + +//[SimpleJob(launchCount: 3, warmupCount: 10, targetCount: 30)] +[RPlotExporter] +[MemoryDiagnoser] +[Orderer(summaryOrderPolicy: SummaryOrderPolicy.FastestToSlowest)] +[RankColumn] +public class FileSystemAbstractionBenchmarks +{ + /// + /// FileSupport type to avoid counting object initialisation on the benchmark + /// + private readonly FileSupport _fileSupport; + private readonly DirectorySupport _directorySupport; + + private readonly string _path = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile); + + public FileSystemAbstractionBenchmarks() + { + // Initialize file support + _fileSupport = new FileSupport(); + _directorySupport = new DirectorySupport(); + } + + #region File IsFile + [Benchmark] + public void FileExists_DotNet() => FileSupportStatic.IsFile(_path); + + [Benchmark] + public void FileExists_Abstraction() => _fileSupport.IsFile(_path); + #endregion + + #region Directory Exists + [Benchmark] + public void DirectoryExists_DotNet() => DirectorySupportStatic.Exists(_path); + + [Benchmark] + public void DirectoryExists_Abstraction() => _directorySupport.Exists(_path); + #endregion +} \ No newline at end of file diff --git a/benchmarks/TestableIO.System.IO.Abstractions.Benchmarks/MockFileSystemBenchmarks.cs b/benchmarks/TestableIO.System.IO.Abstractions.Benchmarks/MockFileSystemBenchmarks.cs new file mode 100644 index 000000000..df2a85038 --- /dev/null +++ b/benchmarks/TestableIO.System.IO.Abstractions.Benchmarks/MockFileSystemBenchmarks.cs @@ -0,0 +1,26 @@ +using BenchmarkDotNet.Attributes; +using System.Collections.Generic; +using System.IO.Abstractions.TestingHelpers; +using System.Linq; +using XFS = System.IO.Abstractions.TestingHelpers.MockUnixSupport; + +namespace System.IO.Abstractions.Benchmarks; + +[RPlotExporter] +[MemoryDiagnoser] +public class MockFileSystemBenchmarks +{ + private readonly Dictionary testData = CreateTestData(); + + private static Dictionary CreateTestData() + { + var filesCount = 100000; + var maxDirectoryDepth = 8; + return Enumerable.Range(0, filesCount).ToDictionary( + i => XFS.Path(@$"C:\{string.Join(@"\", Enumerable.Range(0, i % maxDirectoryDepth + 1).Select(i => i.ToString()))}\{i}.bin"), + i => new MockFileData(i.ToString())); + } + + [Benchmark] + public MockFileSystem MockFileSystem_Constructor() => new(testData); +} \ No newline at end of file diff --git a/benchmarks/TestableIO.System.IO.Abstractions.Benchmarks/Program.cs b/benchmarks/TestableIO.System.IO.Abstractions.Benchmarks/Program.cs new file mode 100644 index 000000000..028896dc1 --- /dev/null +++ b/benchmarks/TestableIO.System.IO.Abstractions.Benchmarks/Program.cs @@ -0,0 +1,11 @@ +namespace System.IO.Abstractions.Benchmarks; + +using BenchmarkDotNet.Running; + +static class Program +{ + public static void Main(string[] args) + { + BenchmarkRunner.Run(typeof(Program).Assembly); + } +} \ No newline at end of file diff --git a/benchmarks/TestableIO.System.IO.Abstractions.Benchmarks/Properties/launchSettings.json b/benchmarks/TestableIO.System.IO.Abstractions.Benchmarks/Properties/launchSettings.json new file mode 100644 index 000000000..a02220af5 --- /dev/null +++ b/benchmarks/TestableIO.System.IO.Abstractions.Benchmarks/Properties/launchSettings.json @@ -0,0 +1,8 @@ +{ + "profiles": { + "yapm": { + "commandName": "Project", + "commandLineArgs": "apply" + } + } +} \ No newline at end of file diff --git a/benchmarks/TestableIO.System.IO.Abstractions.Benchmarks/Support/DirectorySupport.cs b/benchmarks/TestableIO.System.IO.Abstractions.Benchmarks/Support/DirectorySupport.cs new file mode 100644 index 000000000..53ef219f8 --- /dev/null +++ b/benchmarks/TestableIO.System.IO.Abstractions.Benchmarks/Support/DirectorySupport.cs @@ -0,0 +1,83 @@ +namespace System.IO.Abstractions.Benchmarks.Support; + +public class DirectorySupport +{ + private readonly IFileSystem _fileSystem; + + public DirectorySupport(IFileSystem fileSystem) + { + _fileSystem = fileSystem; + } + + public DirectorySupport() : this(new FileSystem()) + { + // Default implementation for FileSystem + } + + public bool IsDirectory(string path) + { + return _fileSystem.Directory.Exists(path); + } + + private static string GetRandomTempDirectory() + { + return Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); + } + + public string CreateRandomDirectory() + { + var randomPath = GetRandomTempDirectory(); + _fileSystem.Directory.CreateDirectory(randomPath); + return randomPath; + } + + private void DirectoryCopy(string sourceDirName, string destDirName, bool copySubDirs = true, bool overwrite = true) + { + // Get the subdirectories for the specified directory. + var dir = _fileSystem.DirectoryInfo.New(sourceDirName); + if (!dir.Exists) + { + throw new DirectoryNotFoundException( + "Source directory does not exist or could not be found: " + + sourceDirName); + } + + var dirs = dir.GetDirectories(); + // If the destination directory doesn't exist, create it. + if (!_fileSystem.Directory.Exists(destDirName)) + { + _fileSystem.Directory.CreateDirectory(destDirName); + } + + // Get the files in the directory and copy them to the new location. + var files = dir.GetFiles(); + foreach (var file in files) + { + string temppath = Path.Combine(destDirName, file.Name); + file.CopyTo(temppath, overwrite); + } + + // If copying subdirectories, copy them and their contents to new location. + if (copySubDirs) + { + foreach (var subdir in dirs) + { + string temppath = Path.Combine(destDirName, subdir.Name); + DirectoryCopy(subdir.FullName, temppath, copySubDirs); + } + } + } + + public void CreateIfNotExists(string directory) + { + if (!_fileSystem.Directory.Exists(directory)) + { + _fileSystem.Directory.CreateDirectory(directory); + } + } + + public bool Exists(string directory) + { + return _fileSystem.Directory.Exists(directory); + } +} \ No newline at end of file diff --git a/benchmarks/TestableIO.System.IO.Abstractions.Benchmarks/Support/DirectorySupportStatic.cs b/benchmarks/TestableIO.System.IO.Abstractions.Benchmarks/Support/DirectorySupportStatic.cs new file mode 100644 index 000000000..bb610f014 --- /dev/null +++ b/benchmarks/TestableIO.System.IO.Abstractions.Benchmarks/Support/DirectorySupportStatic.cs @@ -0,0 +1,69 @@ +namespace System.IO.Abstractions.Benchmarks.Support; + +public static class DirectorySupportStatic +{ + public static bool IsDirectory(string path) + { + return Directory.Exists(path); + } + + private static string GetRandomTempDirectory() + { + return Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); + } + + public static string CreateDirectory() + { + var randomPath = GetRandomTempDirectory(); + Directory.CreateDirectory(randomPath); + return randomPath; + } + + private static void DirectoryCopy(string sourceDirName, string destDirName, bool copySubDirs = true, bool overwrite = true) + { + // Get the subdirectories for the specified directory. + DirectoryInfo dir = new DirectoryInfo(sourceDirName); + + if (!dir.Exists) + { + throw new DirectoryNotFoundException( + "Source directory does not exist or could not be found: " + + sourceDirName); + } + + DirectoryInfo[] dirs = dir.GetDirectories(); + // If the destination directory doesn't exist, create it. + if (!Directory.Exists(destDirName)) + { + Directory.CreateDirectory(destDirName); + } + + // Get the files in the directory and copy them to the new location. + FileInfo[] files = dir.GetFiles(); + foreach (FileInfo file in files) + { + string temppath = Path.Combine(destDirName, file.Name); + file.CopyTo(temppath, overwrite); + } + + // If copying subdirectories, copy them and their contents to new location. + if (copySubDirs) + { + foreach (DirectoryInfo subdir in dirs) + { + string temppath = Path.Combine(destDirName, subdir.Name); + DirectoryCopy(subdir.FullName, temppath, copySubDirs); + } + } + } + + public static void CreateIfNotExists(string directory) + { + if (!Directory.Exists(directory)) + { + Directory.CreateDirectory(directory); + } + } + + public static bool Exists(string directory) => Directory.Exists(directory); +} \ No newline at end of file diff --git a/benchmarks/TestableIO.System.IO.Abstractions.Benchmarks/Support/FileSupport.cs b/benchmarks/TestableIO.System.IO.Abstractions.Benchmarks/Support/FileSupport.cs new file mode 100644 index 000000000..b075f61e1 --- /dev/null +++ b/benchmarks/TestableIO.System.IO.Abstractions.Benchmarks/Support/FileSupport.cs @@ -0,0 +1,38 @@ +namespace System.IO.Abstractions.Benchmarks.Support; + +public class FileSupport +{ + private readonly IFileSystem _fileSystem; + + public FileSupport(IFileSystem fileSystem) + { + _fileSystem = fileSystem; + } + + public FileSupport() : this(new FileSystem()) + { + // Default implementation for FileSystem + } + + private static string GetRandomTempFile() + { + return Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); + } + + public bool IsFile(string path) + { + return _fileSystem.File.Exists(path); + } + + /// + /// Checks and deletes given file if it does exists. + /// + /// Path of the file + public void DeleteIfExists(string filePath) + { + if (_fileSystem.File.Exists(filePath)) + { + _fileSystem.File.Delete(filePath); + } + } +} \ No newline at end of file diff --git a/benchmarks/TestableIO.System.IO.Abstractions.Benchmarks/Support/FileSupportStatic.cs b/benchmarks/TestableIO.System.IO.Abstractions.Benchmarks/Support/FileSupportStatic.cs new file mode 100644 index 000000000..b8eae68e9 --- /dev/null +++ b/benchmarks/TestableIO.System.IO.Abstractions.Benchmarks/Support/FileSupportStatic.cs @@ -0,0 +1,26 @@ +namespace System.IO.Abstractions.Benchmarks.Support; + +public static class FileSupportStatic +{ + public static string GetRandomTempFile() + { + return Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); + } + + public static bool IsFile(string path) + { + return File.Exists(path); + } + + /// + /// Checks and deletes given file if it does exists. + /// + /// Path of the file + public static void DeleteIfExists(string filePath) + { + if (File.Exists(filePath)) + { + File.Delete(filePath); + } + } +} \ No newline at end of file diff --git a/benchmarks/TestableIO.System.IO.Abstractions.Benchmarks/TestableIO.System.IO.Abstractions.Benchmarks.csproj b/benchmarks/TestableIO.System.IO.Abstractions.Benchmarks/TestableIO.System.IO.Abstractions.Benchmarks.csproj new file mode 100644 index 000000000..46aa4724f --- /dev/null +++ b/benchmarks/TestableIO.System.IO.Abstractions.Benchmarks/TestableIO.System.IO.Abstractions.Benchmarks.csproj @@ -0,0 +1,22 @@ + + + TestableIO.System.IO.Abstractions.Benchmarks + TestableIO.System.IO.Abstractions.Benchmarks + Bencharmks comparisons. + net9.0 + https://github.com/TestableIO/System.IO.Abstractions + MIT + testing + false + false + Exe + Exe + + + + + + + + + diff --git a/build.cmd b/build.cmd new file mode 100755 index 000000000..b08cc590f --- /dev/null +++ b/build.cmd @@ -0,0 +1,7 @@ +:; set -eo pipefail +:; SCRIPT_DIR=$(cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd) +:; ${SCRIPT_DIR}/build.sh "$@" +:; exit $? + +@ECHO OFF +powershell -ExecutionPolicy ByPass -NoProfile -File "%~dp0build.ps1" %* diff --git a/build.ps1 b/build.ps1 new file mode 100644 index 000000000..8b218a560 --- /dev/null +++ b/build.ps1 @@ -0,0 +1,74 @@ +[CmdletBinding()] +Param( + [Parameter(Position=0,Mandatory=$false,ValueFromRemainingArguments=$true)] + [string[]]$BuildArguments +) + +Write-Output "PowerShell $($PSVersionTable.PSEdition) version $($PSVersionTable.PSVersion)" + +Set-StrictMode -Version 2.0; $ErrorActionPreference = "Stop"; $ConfirmPreference = "None"; trap { Write-Error $_ -ErrorAction Continue; exit 1 } +$PSScriptRoot = Split-Path $MyInvocation.MyCommand.Path -Parent + +########################################################################### +# CONFIGURATION +########################################################################### + +$BuildProjectFile = "$PSScriptRoot\Pipeline\Build.csproj" +$TempDirectory = "$PSScriptRoot\\.nuke\temp" + +$DotNetGlobalFile = "$PSScriptRoot\\global.json" +$DotNetInstallUrl = "https://dot.net/v1/dotnet-install.ps1" +$DotNetChannel = "STS" + +$env:DOTNET_CLI_TELEMETRY_OPTOUT = 1 +$env:DOTNET_NOLOGO = 1 + +########################################################################### +# EXECUTION +########################################################################### + +function ExecSafe([scriptblock] $cmd) { + & $cmd + if ($LASTEXITCODE) { exit $LASTEXITCODE } +} + +# If dotnet CLI is installed globally and it matches requested version, use for execution +if ($null -ne (Get-Command "dotnet" -ErrorAction SilentlyContinue) -and ` + $(dotnet --version) -and $LASTEXITCODE -eq 0) { + $env:DOTNET_EXE = (Get-Command "dotnet").Path +} +else { + # Download install script + $DotNetInstallFile = "$TempDirectory\dotnet-install.ps1" + New-Item -ItemType Directory -Path $TempDirectory -Force | Out-Null + [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 + (New-Object System.Net.WebClient).DownloadFile($DotNetInstallUrl, $DotNetInstallFile) + + # If global.json exists, load expected version + if (Test-Path $DotNetGlobalFile) { + $DotNetGlobal = $(Get-Content $DotNetGlobalFile | Out-String | ConvertFrom-Json) + if ($DotNetGlobal.PSObject.Properties["sdk"] -and $DotNetGlobal.sdk.PSObject.Properties["version"]) { + $DotNetVersion = $DotNetGlobal.sdk.version + } + } + + # Install by channel or version + $DotNetDirectory = "$TempDirectory\dotnet-win" + if (!(Test-Path variable:DotNetVersion)) { + ExecSafe { & powershell $DotNetInstallFile -InstallDir $DotNetDirectory -Channel $DotNetChannel -NoPath } + } else { + ExecSafe { & powershell $DotNetInstallFile -InstallDir $DotNetDirectory -Version $DotNetVersion -NoPath } + } + $env:DOTNET_EXE = "$DotNetDirectory\dotnet.exe" + $env:PATH = "$DotNetDirectory;$env:PATH" +} + +Write-Output "Microsoft (R) .NET SDK version $(& $env:DOTNET_EXE --version)" + +if (Test-Path env:NUKE_ENTERPRISE_TOKEN) { + & $env:DOTNET_EXE nuget remove source "nuke-enterprise" > $null + & $env:DOTNET_EXE nuget add source "https://f.feedz.io/nuke/enterprise/nuget" --name "nuke-enterprise" --username "PAT" --password $env:NUKE_ENTERPRISE_TOKEN > $null +} + +ExecSafe { & $env:DOTNET_EXE build $BuildProjectFile /nodeReuse:false /p:UseSharedCompilation=false -nologo -clp:NoSummary --verbosity quiet } +ExecSafe { & $env:DOTNET_EXE run --project $BuildProjectFile --no-build -- $BuildArguments } diff --git a/build.sh b/build.sh new file mode 100755 index 000000000..46f2bac0a --- /dev/null +++ b/build.sh @@ -0,0 +1,67 @@ +#!/usr/bin/env bash + +bash --version 2>&1 | head -n 1 + +set -eo pipefail +SCRIPT_DIR=$(cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd) + +########################################################################### +# CONFIGURATION +########################################################################### + +BUILD_PROJECT_FILE="$SCRIPT_DIR/Pipeline/Build.csproj" +TEMP_DIRECTORY="$SCRIPT_DIR//.nuke/temp" + +DOTNET_GLOBAL_FILE="$SCRIPT_DIR//global.json" +DOTNET_INSTALL_URL="https://dot.net/v1/dotnet-install.sh" +DOTNET_CHANNEL="STS" + +export DOTNET_CLI_TELEMETRY_OPTOUT=1 +export DOTNET_NOLOGO=1 + +########################################################################### +# EXECUTION +########################################################################### + +function FirstJsonValue { + perl -nle 'print $1 if m{"'"$1"'": "([^"]+)",?}' <<< "${@:2}" +} + +# If dotnet CLI is installed globally and it matches requested version, use for execution +if [ -x "$(command -v dotnet)" ] && dotnet --version &>/dev/null; then + export DOTNET_EXE="$(command -v dotnet)" +else + # Download install script + DOTNET_INSTALL_FILE="$TEMP_DIRECTORY/dotnet-install.sh" + mkdir -p "$TEMP_DIRECTORY" + curl -Lsfo "$DOTNET_INSTALL_FILE" "$DOTNET_INSTALL_URL" + chmod +x "$DOTNET_INSTALL_FILE" + + # If global.json exists, load expected version + if [[ -f "$DOTNET_GLOBAL_FILE" ]]; then + DOTNET_VERSION=$(FirstJsonValue "version" "$(cat "$DOTNET_GLOBAL_FILE")") + if [[ "$DOTNET_VERSION" == "" ]]; then + unset DOTNET_VERSION + fi + fi + + # Install by channel or version + DOTNET_DIRECTORY="$TEMP_DIRECTORY/dotnet-unix" + if [[ -z ${DOTNET_VERSION+x} ]]; then + "$DOTNET_INSTALL_FILE" --install-dir "$DOTNET_DIRECTORY" --channel "$DOTNET_CHANNEL" --no-path + else + "$DOTNET_INSTALL_FILE" --install-dir "$DOTNET_DIRECTORY" --version "$DOTNET_VERSION" --no-path + fi + export DOTNET_EXE="$DOTNET_DIRECTORY/dotnet" + export PATH="$DOTNET_DIRECTORY:$PATH" +fi + +echo "Microsoft (R) .NET SDK version $("$DOTNET_EXE" --version)" + +if [[ ! -z ${NUKE_ENTERPRISE_TOKEN+x} && "$NUKE_ENTERPRISE_TOKEN" != "" ]]; then + "$DOTNET_EXE" nuget remove source "nuke-enterprise" &>/dev/null || true + "$DOTNET_EXE" nuget add source "https://f.feedz.io/nuke/enterprise/nuget" --name "nuke-enterprise" --username "PAT" --password "$NUKE_ENTERPRISE_TOKEN" --store-password-in-clear-text &>/dev/null || true +fi + +"$DOTNET_EXE" build "$BUILD_PROJECT_FILE" /nodeReuse:false /p:UseSharedCompilation=false -nologo -clp:NoSummary --verbosity quiet +"$DOTNET_EXE" run --project "$BUILD_PROJECT_FILE" --no-build -- "$@" diff --git a/global.json b/global.json new file mode 100644 index 000000000..bb6205592 --- /dev/null +++ b/global.json @@ -0,0 +1,6 @@ +{ + "sdk": { + "version": "10.0.102", + "rollForward": "latestMinor" + } +} diff --git a/images/icon_256x256.png b/images/icon_256x256.png new file mode 100644 index 000000000..4857cc1b8 Binary files /dev/null and b/images/icon_256x256.png differ diff --git a/nuget.config b/nuget.config new file mode 100644 index 000000000..3a9f6b327 --- /dev/null +++ b/nuget.config @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/packages/packages.config b/packages/packages.config deleted file mode 100644 index 29e6765ff..000000000 --- a/packages/packages.config +++ /dev/null @@ -1,5 +0,0 @@ - - - - - \ No newline at end of file diff --git a/renovate.json5 b/renovate.json5 new file mode 100644 index 000000000..486427d2c --- /dev/null +++ b/renovate.json5 @@ -0,0 +1,6 @@ +{ + extends: ["config:base"], + ignorePaths: [ + // Clear the default list to enable Renovate for all files + ], +} diff --git a/src/Directory.Build.props b/src/Directory.Build.props new file mode 100644 index 000000000..6d9dbc7e8 --- /dev/null +++ b/src/Directory.Build.props @@ -0,0 +1,32 @@ + + + + + + net472;netstandard2.0;netstandard2.1;net6.0;net8.0;net9.0;net10.0 + + + + https://github.com/TestableIO/System.IO.Abstractions.git + true + snupkg + true + true + + + + icon_256x256.png + + + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + diff --git a/src/System.IO.Abstractions.TestingHelpers/System.IO.Abstractions.TestingHelpers.csproj b/src/System.IO.Abstractions.TestingHelpers/System.IO.Abstractions.TestingHelpers.csproj new file mode 100644 index 000000000..c3852465d --- /dev/null +++ b/src/System.IO.Abstractions.TestingHelpers/System.IO.Abstractions.TestingHelpers.csproj @@ -0,0 +1,13 @@ + + + + System.IO.Abstractions.TestingHelpers + System.IO.Abstractions.TestingHelpers + A set of pre-built mocks to help when testing file system interactions. + + + + + + + diff --git a/src/System.IO.Abstractions/System.IO.Abstractions.csproj b/src/System.IO.Abstractions/System.IO.Abstractions.csproj new file mode 100644 index 000000000..931a4b5e1 --- /dev/null +++ b/src/System.IO.Abstractions/System.IO.Abstractions.csproj @@ -0,0 +1,14 @@ + + + + System.IO.Abstractions + System.IO.Abstractions + A set of abstractions to help make file system interactions testable. + + + + + + + + diff --git a/src/TestableIO.System.IO.Abstractions.TestingHelpers/CommonExceptions.cs b/src/TestableIO.System.IO.Abstractions.TestingHelpers/CommonExceptions.cs new file mode 100644 index 000000000..1fa682a82 --- /dev/null +++ b/src/TestableIO.System.IO.Abstractions.TestingHelpers/CommonExceptions.cs @@ -0,0 +1,106 @@ +using System.Globalization; +using System.Runtime.InteropServices; + +namespace System.IO.Abstractions.TestingHelpers; + +internal static class CommonExceptions +{ + private const int _fileLockHResult = unchecked((int)0x80070020); + + public static FileNotFoundException FileNotFound(string path) => + new FileNotFoundException( + string.Format( + CultureInfo.InvariantCulture, + StringResources.Manager.GetString("COULD_NOT_FIND_FILE_EXCEPTION"), + path + ), + path + ); + + public static DirectoryNotFoundException CouldNotFindPartOfPath(string path) => + new DirectoryNotFoundException( + string.Format( + CultureInfo.InvariantCulture, + StringResources.Manager.GetString("COULD_NOT_FIND_PART_OF_PATH_EXCEPTION"), + path + ) + ); + + public static UnauthorizedAccessException AccessDenied(string path) => + new UnauthorizedAccessException( + string.Format( + CultureInfo.InvariantCulture, + StringResources.Manager.GetString("ACCESS_TO_THE_PATH_IS_DENIED"), + path + ) + ); + + public static NotSupportedException InvalidUseOfVolumeSeparator() => + new NotSupportedException(StringResources.Manager.GetString("THE_PATH_IS_NOT_OF_A_LEGAL_FORM")); + + public static ArgumentException PathIsNotOfALegalForm(string paramName) => + new ArgumentException( + StringResources.Manager.GetString("THE_PATH_IS_NOT_OF_A_LEGAL_FORM"), + paramName + ); + + public static ArgumentNullException FilenameCannotBeNull(string paramName) => + new ArgumentNullException( + paramName, + StringResources.Manager.GetString("FILENAME_CANNOT_BE_NULL") + ); + + public static ArgumentException IllegalCharactersInPath(string paramName = null) => + paramName != null + ? new ArgumentException(StringResources.Manager.GetString("ILLEGAL_CHARACTERS_IN_PATH_EXCEPTION"), paramName) + : new ArgumentException(StringResources.Manager.GetString("ILLEGAL_CHARACTERS_IN_PATH_EXCEPTION")); + + public static ArgumentException InvalidUncPath(string paramName) => + RuntimeInformation.IsOSPlatform(OSPlatform.Windows) + ? new ArgumentException(@"The UNC path should be of the form \\server\share.", paramName) + : new ArgumentException(@"The UNC path should be of the form //server/share.", paramName); + + public static IOException ProcessCannotAccessFileInUse(string paramName = null) => + paramName != null + ? new IOException(string.Format(StringResources.Manager.GetString("PROCESS_CANNOT_ACCESS_FILE_IN_USE_WITH_FILENAME"), paramName), _fileLockHResult) + : new IOException(StringResources.Manager.GetString("PROCESS_CANNOT_ACCESS_FILE_IN_USE"), _fileLockHResult); + + public static IOException FileAlreadyExists(string paramName) => + new IOException(string.Format(StringResources.Manager.GetString("FILE_ALREADY_EXISTS"), paramName)); + + public static ArgumentException InvalidAccessCombination(FileMode mode, FileAccess access) + => new ArgumentException(string.Format(StringResources.Manager.GetString("INVALID_ACCESS_COMBINATION"), mode, access), nameof(access)); + + public static ArgumentException AppendAccessOnlyInWriteOnlyMode() + => new ArgumentException(string.Format(StringResources.Manager.GetString("APPEND_ACCESS_ONLY_IN_WRITE_ONLY_MODE")), "access"); + + public static NotImplementedException NotImplemented() => + new NotImplementedException(StringResources.Manager.GetString("NOT_IMPLEMENTED_EXCEPTION")); + + public static IOException CannotCreateBecauseSameNameAlreadyExists(string path) => + new IOException( + string.Format( + CultureInfo.InvariantCulture, + StringResources.Manager.GetString("CANNOT_CREATE_BECAUSE_SAME_NAME_ALREADY_EXISTS"), + path + ) + ); + + public static IOException NameCannotBeResolvedByTheSystem(string path) => + new IOException( + string.Format( + CultureInfo.InvariantCulture, + StringResources.Manager.GetString("NAME_CANNOT_BE_RESOLVED_BY_THE_SYSTEM"), + path + ) + ); + + public static DirectoryNotFoundException PathDoesNotExistOrCouldNotBeFound(string path) => + new DirectoryNotFoundException( + string.Format( + CultureInfo.InvariantCulture, + StringResources.Manager.GetString("PATH_DOES_NOT_EXIST_OR_COULD_NOT_BE_FOUND"), + path + ) + ); +} \ No newline at end of file diff --git a/src/TestableIO.System.IO.Abstractions.TestingHelpers/FileHandles.cs b/src/TestableIO.System.IO.Abstractions.TestingHelpers/FileHandles.cs new file mode 100644 index 000000000..06923b6b1 --- /dev/null +++ b/src/TestableIO.System.IO.Abstractions.TestingHelpers/FileHandles.cs @@ -0,0 +1,56 @@ +using System; +using System.Collections.Concurrent; +using System.IO; +using System.IO.Abstractions.TestingHelpers; + +public class FileHandles +{ + private readonly ConcurrentDictionary> handles = new(); + + public void AddHandle(string path, Guid guid, FileAccess access, FileShare share) + { + var pathHandles = handles.GetOrAdd( + path, + _ => new ConcurrentDictionary()); + + var requiredShare = AccessToShare(access); + foreach (var (existingAccess, existingShare) in pathHandles.Values) + { + var existingRequiredShare = AccessToShare(existingAccess); + var existingBlocksNew = (existingShare & requiredShare) != requiredShare; + var newBlocksExisting = (share & existingRequiredShare) != existingRequiredShare; + if (existingBlocksNew || newBlocksExisting) + { + throw CommonExceptions.ProcessCannotAccessFileInUse(path); + } + } + + pathHandles[guid] = (access, share); + } + + public void RemoveHandle(string path, Guid guid) + { + if (handles.TryGetValue(path, out var pathHandles)) + { + pathHandles.TryRemove(guid, out _); + if (pathHandles.IsEmpty) + { + handles.TryRemove(path, out _); + } + } + } + + private static FileShare AccessToShare(FileAccess access) + { + var share = FileShare.None; + if (access.HasFlag(FileAccess.Read)) + { + share |= FileShare.Read; + } + if (access.HasFlag(FileAccess.Write)) + { + share |= FileShare.Write; + } + return share; + } +} \ No newline at end of file diff --git a/src/TestableIO.System.IO.Abstractions.TestingHelpers/IMockFileDataAccessor.cs b/src/TestableIO.System.IO.Abstractions.TestingHelpers/IMockFileDataAccessor.cs new file mode 100644 index 000000000..5b6c92e15 --- /dev/null +++ b/src/TestableIO.System.IO.Abstractions.TestingHelpers/IMockFileDataAccessor.cs @@ -0,0 +1,118 @@ +using System.Collections.Generic; +using System.Reflection; + +namespace System.IO.Abstractions.TestingHelpers; + +/// +/// Provides access to the file system storage. +/// +public interface IMockFileDataAccessor : IFileSystem +{ + /// + /// Adjust the times of the . + /// + /// The for which the times should be adjusted. + /// The adjustments to make on the . + /// The adjusted file. + MockFileData AdjustTimes(MockFileData fileData, TimeAdjustments timeAdjustments); + + /// + /// Gets a file. + /// + /// The path of the file to get. + /// The file. if the file does not exist. + MockFileData GetFile(string path); + + /// + /// Gets a drive. + /// + /// The name of the drive to get. + /// The drive. if the drive does not exist. + MockDriveData GetDrive(string name); + + /// + /// Adds the file. + /// + /// The path of the file to add. + /// The file data to add. + /// Flag indicating if the access conditions should be verified. + void AddFile(string path, MockFileData mockFile, bool verifyAccess = true); + + /// + /// + void AddDirectory(string path); + + /// + /// + void AddDrive(string name, MockDriveData mockDrive); + + /// + /// + void AddFileFromEmbeddedResource(string path, Assembly resourceAssembly, string embeddedResourcePath); + + /// + /// + void AddFilesFromEmbeddedNamespace(string path, Assembly resourceAssembly, string embeddedResourcePath); + + /// + /// + void MoveDirectory(string sourcePath, string destPath); + + /// + /// Removes the file. + /// + /// The file to remove. + /// Flag indicating if the access conditions should be verified. + /// + /// The file must not exist. + /// + void RemoveFile(string path, bool verifyAccess = true); + + /// + /// Determines whether the file exists. + /// + /// The file to check. + /// if the file exists; otherwise, . + bool FileExists(string path); + + /// + /// Gets all unique paths of all files and directories. + /// + IEnumerable AllPaths { get; } + + /// + /// Gets the paths of all files. + /// + IEnumerable AllFiles { get; } + + /// + /// Gets the paths of all directories. + /// + IEnumerable AllDirectories { get; } + + /// + /// Gets the names of all drives. + /// + IEnumerable AllDrives { get; } + + /// + /// Gets a helper for string operations. + /// + + StringOperations StringOperations { get; } + + /// + /// Gets a helper for verifying file system paths. + /// + PathVerifier PathVerifier { get; } + + /// + /// Gets a reference to the underlying file system. + /// + IFileSystem FileSystem { get; } + + /// + /// Gets a reference to the open file handles. + /// + FileHandles FileHandles { get; } +} \ No newline at end of file diff --git a/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockDirectory.cs b/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockDirectory.cs new file mode 100644 index 000000000..242bb0d5e --- /dev/null +++ b/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockDirectory.cs @@ -0,0 +1,829 @@ +using System.Collections.Generic; +using System.Globalization; +using System.Linq; +using System.Text.RegularExpressions; + +namespace System.IO.Abstractions.TestingHelpers; + +using XFS = MockUnixSupport; + + + +/// +#if FEATURE_SERIALIZABLE +[Serializable] +#endif +public class MockDirectory : DirectoryBase +{ + private readonly IMockFileDataAccessor mockFileDataAccessor; + private string currentDirectory; + + /// + public MockDirectory(IMockFileDataAccessor mockFileDataAccessor, FileBase fileBase, string currentDirectory) : + this(mockFileDataAccessor, currentDirectory) + { + } + + /// + public MockDirectory(IMockFileDataAccessor mockFileDataAccessor, string currentDirectory) : base( + mockFileDataAccessor?.FileSystem) + { + this.currentDirectory = currentDirectory; + this.mockFileDataAccessor = + mockFileDataAccessor ?? throw new ArgumentNullException(nameof(mockFileDataAccessor)); + } + + + /// + public override IDirectoryInfo CreateDirectory(string path) + { + return CreateDirectoryInternal(path); + } + +#if FEATURE_UNIX_FILE_MODE + /// + public override IDirectoryInfo CreateDirectory(string path, UnixFileMode unixCreateMode) + { + throw CommonExceptions.NotImplemented(); + } +#endif + + private IDirectoryInfo CreateDirectoryInternal(string path) + { + if (path == null) + { + throw new ArgumentNullException(nameof(path)); + } + + if (path.Length == 0) + { + throw new ArgumentException( + StringResources.Manager.GetString("PATH_CANNOT_BE_THE_EMPTY_STRING_OR_ALL_WHITESPACE"), "path"); + } + + if (mockFileDataAccessor.PathVerifier.HasIllegalCharacters(path, true)) + { + throw CommonExceptions.IllegalCharactersInPath(nameof(path)); + } + + path = mockFileDataAccessor.Path.GetFullPath(path).TrimSlashes(); + if (XFS.IsWindowsPlatform()) + { + path = path.TrimEnd(' '); + } + + var existingFile = mockFileDataAccessor.GetFile(path); + if (existingFile == null) + { + mockFileDataAccessor.AddDirectory(path); + } + else if (!existingFile.IsDirectory) + { + throw CommonExceptions.FileAlreadyExists("path"); + } + + var created = new MockDirectoryInfo(mockFileDataAccessor, path); + + return created; + } + +#if FEATURE_CREATE_SYMBOLIC_LINK + /// + public override IFileSystemInfo CreateSymbolicLink(string path, string pathToTarget) + { + mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, nameof(path)); + mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(pathToTarget, nameof(pathToTarget)); + + if (Exists(path)) + { + throw CommonExceptions.FileAlreadyExists(nameof(path)); + } + + mockFileDataAccessor.AddDirectory(path); + mockFileDataAccessor.GetFile(path).LinkTarget = pathToTarget; + + var directoryInfo = new MockDirectoryInfo(mockFileDataAccessor, path); + directoryInfo.Attributes |= FileAttributes.ReparsePoint; + return directoryInfo; + } +#endif + +#if FEATURE_CREATE_TEMP_SUBDIRECTORY + /// + public override IDirectoryInfo CreateTempSubdirectory(string prefix = null) + { + prefix ??= ""; + string potentialTempDirectory; + + // Perform directory name generation in a loop, just in case the randomly generated name already exists. + do + { + var randomDir = $"{prefix}{FileSystem.Path.GetRandomFileName()}"; + potentialTempDirectory = Path.Combine(FileSystem.Path.GetTempPath(), randomDir); + } while (Exists(potentialTempDirectory)); + + return CreateDirectoryInternal(potentialTempDirectory); + } +#endif + + /// + public override void Delete(string path) + { + Delete(path, false); + } + + + /// + public override void Delete(string path, bool recursive) + { + path = mockFileDataAccessor.Path.GetFullPath(path).TrimSlashes(); + + var stringOps = mockFileDataAccessor.StringOperations; + var pathWithDirectorySeparatorChar = $"{path}{Path.DirectorySeparatorChar}"; + + var affectedPaths = mockFileDataAccessor + .AllPaths + .Where(p => stringOps.Equals(p, path) || stringOps.StartsWith(p, pathWithDirectorySeparatorChar)) + .ToList(); + + if (!affectedPaths.Any()) + { + throw CommonExceptions.PathDoesNotExistOrCouldNotBeFound(path); + } + + if (!recursive && affectedPaths.Count > 1) + { + throw new IOException("The directory specified by " + path + + " is read-only, or recursive is false and " + path + + " is not an empty directory."); + } + + bool isFile = !mockFileDataAccessor.GetFile(path).IsDirectory; + if (isFile) + { + throw new IOException("The directory name is invalid."); + } + + foreach (var affectedPath in affectedPaths) + { + mockFileDataAccessor.RemoveFile(affectedPath); + } + } + + + /// + public override bool Exists(string path) + { + if (path == "/") + { + return true; + } + + try + { + path = path.TrimSlashes(); + path = mockFileDataAccessor.Path.GetFullPath(path); + return mockFileDataAccessor.GetFile(path)?.IsDirectory ?? false; + } + catch (Exception) + { + return false; + } + } + + + /// + public override DateTime GetCreationTime(string path) + { + return mockFileDataAccessor.File.GetCreationTime(path); + } + + + /// + public override DateTime GetCreationTimeUtc(string path) + { + return mockFileDataAccessor.File.GetCreationTimeUtc(path); + } + + /// + public override string GetCurrentDirectory() + { + return currentDirectory; + } + + /// + public override string[] GetDirectories(string path) + { + return GetDirectories(path, "*"); + } + + /// + public override string[] GetDirectories(string path, string searchPattern) + { + return GetDirectories(path, searchPattern, SearchOption.TopDirectoryOnly); + } + + /// + public override string[] GetDirectories(string path, string searchPattern, SearchOption searchOption) + { + return EnumerateDirectories(path, searchPattern, searchOption).ToArray(); + } + +#if FEATURE_ENUMERATION_OPTIONS + /// + public override string[] GetDirectories(string path, string searchPattern, + EnumerationOptions enumerationOptions) + { + return GetDirectories(path, "*", EnumerationOptionsToSearchOption(enumerationOptions)); + } +#endif + + /// + public override string GetDirectoryRoot(string path) + { + return Path.GetPathRoot(path); + } + + /// + public override string[] GetFiles(string path) + { + // Same as what the real framework does + return GetFiles(path, "*"); + } + + /// + public override string[] GetFiles(string path, string searchPattern) + { + // Same as what the real framework does + return GetFiles(path, searchPattern, SearchOption.TopDirectoryOnly); + } + + /// + public override string[] GetFiles(string path, string searchPattern, SearchOption searchOption) + { + return GetFilesInternal(mockFileDataAccessor.AllFiles, path, searchPattern, searchOption); + } + +#if FEATURE_ENUMERATION_OPTIONS + /// + public override string[] GetFiles(string path, string searchPattern, EnumerationOptions enumerationOptions) + { + return GetFiles(path, searchPattern, EnumerationOptionsToSearchOption(enumerationOptions)); + } +#endif + + private string[] GetFilesInternal( + IEnumerable files, + string path, + string searchPattern, + SearchOption searchOption) + { + if (path == null) + { + throw new ArgumentNullException(nameof(path)); + } + + if (path.Any(c => Path.GetInvalidPathChars().Contains(c))) + { + throw new ArgumentException("Invalid character(s) in path", nameof(path)); + } + + CheckSearchPattern(searchPattern); + if (searchPattern.Equals(string.Empty, StringComparison.OrdinalIgnoreCase)) + { + searchPattern = "*"; + } + + path = path.TrimSlashes(); + path = path.NormalizeSlashes(); + path = mockFileDataAccessor.Path.GetFullPath(path); + + if (!Exists(path)) + { + throw CommonExceptions.CouldNotFindPartOfPath(path); + } + + if (!path.EndsWith(Path.DirectorySeparatorChar.ToString())) + { + path += Path.DirectorySeparatorChar; + } + + var isUnix = XFS.IsUnixPlatform(); + + var allDirectoriesPattern = isUnix + ? @"([^<>:""/|?*]*/)*" + : @"([^<>:""/\\|?*]*\\)*"; + + var searchEndInStarDot = searchPattern.EndsWith(@"*."); + + string fileNamePattern; + string pathPatternNoExtension = string.Empty; + string pathPatternEndsInDot = string.Empty; + string pathPatternSpecial = null; + + if (searchPattern == "*") + { + fileNamePattern = isUnix ? @"[^/]*?/?" : @"[^\\]*?\\?"; + } + else + { + fileNamePattern = Regex.Escape(searchPattern) + .Replace(@"\*", isUnix ? @"[^<>:""/|?*]*?" : @"[^<>:""/\\|?*]*?") + .Replace(@"\?", isUnix ? @"[^<>:""/|?*]?" : @"[^<>:""/\\|?*]?"); + + var extension = Path.GetExtension(searchPattern); + bool hasExtensionLengthOfThree = extension != null && extension.Length == 4 && + !extension.Contains("*") && !extension.Contains("?"); + if (hasExtensionLengthOfThree) + { + var fileNamePatternSpecial = + string.Format(CultureInfo.InvariantCulture, "{0}[^.]", fileNamePattern); + pathPatternSpecial = string.Format( + CultureInfo.InvariantCulture, + isUnix ? @"(?i:^{0}{1}{2}(?:/?)$)" : @"(?i:^{0}{1}{2}(?:\\?)$)", + Regex.Escape(path), + searchOption == SearchOption.AllDirectories ? allDirectoriesPattern : string.Empty, + fileNamePatternSpecial); + } + } + + var pathPattern = string.Format( + CultureInfo.InvariantCulture, + isUnix ? @"(?i:^{0}{1}{2}(?:/?)$)" : @"(?i:^{0}{1}{2}(?:\\?)$)", + Regex.Escape(path), + searchOption == SearchOption.AllDirectories ? allDirectoriesPattern : string.Empty, + fileNamePattern); + + if (searchEndInStarDot) + { + pathPatternNoExtension = ReplaceLastOccurrence(pathPattern, @"]*?\.", @"\.]*?[.]*"); + pathPatternEndsInDot = ReplaceLastOccurrence(pathPattern, @"]*?\.", @"]*?[.]{1,}"); + } + + return files.Where(p => + !searchEndInStarDot + ? (Regex.IsMatch(p, pathPattern) || + (pathPatternSpecial != null && Regex.IsMatch(p, pathPatternSpecial))) + : (Regex.IsMatch(p, pathPatternNoExtension) || Regex.IsMatch(p, pathPatternEndsInDot)) + ) + .ToArray(); + } + + /// + public override string[] GetFileSystemEntries(string path) + { + return GetFileSystemEntries(path, "*"); + } + + /// + public override string[] GetFileSystemEntries(string path, string searchPattern) + { + var dirs = GetDirectories(path, searchPattern); + var files = GetFiles(path, searchPattern); + + return dirs.Union(files).ToArray(); + } + + /// + public override string[] GetFileSystemEntries(string path, string searchPattern, SearchOption searchOption) + { + var dirs = GetDirectories(path, searchPattern, searchOption); + var files = GetFiles(path, searchPattern, searchOption); + + return dirs.Union(files).ToArray(); + } + +#if FEATURE_ENUMERATION_OPTIONS + /// + public override string[] GetFileSystemEntries(string path, string searchPattern, + EnumerationOptions enumerationOptions) + { + return GetFileSystemEntries(path, "*", EnumerationOptionsToSearchOption(enumerationOptions)); + } +#endif + + /// + public override DateTime GetLastAccessTime(string path) + { + return mockFileDataAccessor.File.GetLastAccessTime(path); + } + + /// + public override DateTime GetLastAccessTimeUtc(string path) + { + return mockFileDataAccessor.File.GetLastAccessTimeUtc(path); + } + + /// + public override DateTime GetLastWriteTime(string path) + { + return mockFileDataAccessor.File.GetLastWriteTime(path); + } + + /// + public override DateTime GetLastWriteTimeUtc(string path) + { + return mockFileDataAccessor.File.GetLastWriteTimeUtc(path); + } + + /// + public override string[] GetLogicalDrives() + { + return mockFileDataAccessor + .AllDirectories + .Select(d => new MockDirectoryInfo(mockFileDataAccessor, d).Root.FullName) + .Select(r => mockFileDataAccessor.StringOperations.ToUpper(r)) + .Distinct() + .ToArray(); + } + + /// + public override IDirectoryInfo GetParent(string path) + { + if (path == null) + { + throw new ArgumentNullException(nameof(path)); + } + + if (path.Length == 0) + { + throw new ArgumentException( + StringResources.Manager.GetString("PATH_CANNOT_BE_THE_EMPTY_STRING_OR_ALL_WHITESPACE"), "path"); + } + + if (mockFileDataAccessor.PathVerifier.HasIllegalCharacters(path, false)) + { + throw new ArgumentException("Path contains invalid path characters.", "path"); + } + + var absolutePath = mockFileDataAccessor.Path.GetFullPath(path); + var sepAsString = mockFileDataAccessor.Path.DirectorySeparatorChar.ToString(); + var lastIndex = 0; + + if (absolutePath != sepAsString) + { + var startIndex = mockFileDataAccessor.StringOperations.EndsWith(absolutePath, sepAsString) + ? absolutePath.Length - 1 + : absolutePath.Length; + lastIndex = absolutePath.LastIndexOf(mockFileDataAccessor.Path.DirectorySeparatorChar, startIndex - 1); + + if (lastIndex < 0) + { + return null; + } + } + + var parentPath = absolutePath.Substring(0, lastIndex); + + if (string.IsNullOrEmpty(parentPath)) + { + // On the Unix platform, the parent of a path consisting of a slash followed by + // non-slashes is the root, '/'. + if (XFS.IsUnixPlatform()) + { + absolutePath = absolutePath.TrimSlashes(); + + if (absolutePath.Length > 1 && + absolutePath.LastIndexOf(mockFileDataAccessor.Path.DirectorySeparatorChar) == 0) + { + return new MockDirectoryInfo(mockFileDataAccessor, + mockFileDataAccessor.Path.DirectorySeparatorChar.ToString()); + } + } + + return null; + } + + return new MockDirectoryInfo(mockFileDataAccessor, parentPath); + } + + /// + public override void Move(string sourceDirName, string destDirName) + { + var fullSourcePath = mockFileDataAccessor.Path.GetFullPath(sourceDirName).TrimSlashes(); + var fullDestPath = mockFileDataAccessor.Path.GetFullPath(destDirName).TrimSlashes(); + + if (string.Equals(fullSourcePath, fullDestPath, StringComparison.Ordinal)) + { + throw new IOException("Source and destination path must be different."); + } + + //if we're moving a file, not a directory, call the appropriate file moving function. + var fileData = mockFileDataAccessor.GetFile(fullSourcePath); + if (fileData?.Attributes.HasFlag(FileAttributes.Directory) == false) + { + mockFileDataAccessor.File.Move(fullSourcePath, fullDestPath); + return; + } + + var sourceRoot = mockFileDataAccessor.Path.GetPathRoot(fullSourcePath); + var destinationRoot = mockFileDataAccessor.Path.GetPathRoot(fullDestPath); + + if (!mockFileDataAccessor.StringOperations.Equals(sourceRoot, destinationRoot)) + { + throw new IOException( + "Source and destination path must have identical roots. Move will not work across volumes."); + } + + if (!mockFileDataAccessor.Directory.Exists(fullSourcePath)) + { + throw CommonExceptions.CouldNotFindPartOfPath(sourceDirName); + } + + if (!mockFileDataAccessor.Directory.GetParent(fullDestPath).Exists) + { + throw CommonExceptions.CouldNotFindPartOfPath(destDirName); + } + + if (mockFileDataAccessor.Directory.Exists(fullDestPath) || mockFileDataAccessor.File.Exists(fullDestPath)) + { + // In Windows, file/dir names are case sensetive, C:\\temp\\src and C:\\temp\\SRC and treated different + if (XFS.IsUnixPlatform() || + !string.Equals(fullSourcePath, fullDestPath, StringComparison.OrdinalIgnoreCase)) + { + throw CommonExceptions.CannotCreateBecauseSameNameAlreadyExists(fullDestPath); + } + } + mockFileDataAccessor.MoveDirectory(fullSourcePath, fullDestPath); + } + +#if FEATURE_CREATE_SYMBOLIC_LINK + /// + public override IFileSystemInfo ResolveLinkTarget(string linkPath, bool returnFinalTarget) + { + var initialContainer = mockFileDataAccessor.GetFile(linkPath); + if (initialContainer.LinkTarget != null) + { + var nextLocation = initialContainer.LinkTarget; + var nextContainer = mockFileDataAccessor.GetFile(nextLocation); + + if (returnFinalTarget) + { + // The maximum number of symbolic links that are followed: + // https://learn.microsoft.com/en-us/dotnet/api/system.io.directory.resolvelinktarget?view=net-6.0#remarks + int maxResolveLinks = XFS.IsWindowsPlatform() ? 63 : 40; + for (int i = 1; i < maxResolveLinks; i++) + { + if (nextContainer.LinkTarget == null) + { + break; + } + nextLocation = nextContainer.LinkTarget; + nextContainer = mockFileDataAccessor.GetFile(nextLocation); + } + + if (nextContainer.LinkTarget != null) + { + throw CommonExceptions.NameCannotBeResolvedByTheSystem(linkPath); + } + } + + if (nextContainer.IsDirectory) + { + return new MockDirectoryInfo(mockFileDataAccessor, nextLocation); + } + else + { + return new MockFileInfo(mockFileDataAccessor, nextLocation); + } + } + throw CommonExceptions.NameCannotBeResolvedByTheSystem(linkPath); + } + +#endif + + /// + public override void SetCreationTime(string path, DateTime creationTime) + { + mockFileDataAccessor.File.SetCreationTime(path, creationTime); + } + + /// + public override void SetCreationTimeUtc(string path, DateTime creationTimeUtc) + { + mockFileDataAccessor.File.SetCreationTimeUtc(path, creationTimeUtc); + } + + /// + public override void SetCurrentDirectory(string path) + { + currentDirectory = mockFileDataAccessor.Path.GetFullPath(path); + } + + /// + public override void SetLastAccessTime(string path, DateTime lastAccessTime) + { + mockFileDataAccessor.File.SetLastAccessTime(path, lastAccessTime); + } + + /// + public override void SetLastAccessTimeUtc(string path, DateTime lastAccessTimeUtc) + { + mockFileDataAccessor.File.SetLastAccessTimeUtc(path, lastAccessTimeUtc); + } + + /// + public override void SetLastWriteTime(string path, DateTime lastWriteTime) + { + mockFileDataAccessor.File.SetLastWriteTime(path, lastWriteTime); + } + + /// + public override void SetLastWriteTimeUtc(string path, DateTime lastWriteTimeUtc) + { + mockFileDataAccessor.File.SetLastWriteTimeUtc(path, lastWriteTimeUtc); + } + + /// + public override IEnumerable EnumerateDirectories(string path) + { + return EnumerateDirectories(path, "*"); + } + + /// + public override IEnumerable EnumerateDirectories(string path, string searchPattern) + { + return EnumerateDirectories(path, searchPattern, SearchOption.TopDirectoryOnly); + } + + /// + public override IEnumerable EnumerateDirectories(string path, string searchPattern, SearchOption searchOption) + { + mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); + var originalPath = path; + path = path.TrimSlashes(); + path = mockFileDataAccessor.Path.GetFullPath(path); + return GetFilesInternal(mockFileDataAccessor.AllDirectories, path, searchPattern, searchOption) + .Where(p => !mockFileDataAccessor.StringOperations.Equals(p, path)) + .Select(p => FixPrefix(p, originalPath)); + } + + private string FixPrefix(string path, string originalPath) + { + var normalizedOriginalPath = mockFileDataAccessor.Path.GetFullPath(originalPath); + var pathWithoutOriginalPath = path.Substring(normalizedOriginalPath.Length) + .TrimStart(mockFileDataAccessor.Path.DirectorySeparatorChar); + return mockFileDataAccessor.Path.Combine(originalPath, pathWithoutOriginalPath); + } + +#if FEATURE_ENUMERATION_OPTIONS + /// + public override IEnumerable EnumerateDirectories(string path, string searchPattern, EnumerationOptions enumerationOptions) + { + var searchOption = enumerationOptions.RecurseSubdirectories ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly; + return EnumerateDirectories(path, searchPattern, searchOption); + } +#endif + + /// + public override IEnumerable EnumerateFiles(string path) + { + return GetFiles(path); + } + + /// + public override IEnumerable EnumerateFiles(string path, string searchPattern) + { + return GetFiles(path, searchPattern); + } + + /// + public override IEnumerable EnumerateFiles(string path, string searchPattern, SearchOption searchOption) + { + return GetFiles(path, searchPattern, searchOption); + } + +#if FEATURE_ENUMERATION_OPTIONS + /// + public override IEnumerable EnumerateFiles(string path, string searchPattern, EnumerationOptions enumerationOptions) + { + var searchOption = enumerationOptions.RecurseSubdirectories ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly; + return GetFiles(path, searchPattern, searchOption); + } +#endif + + /// + public override IEnumerable EnumerateFileSystemEntries(string path) + { + return GetFileSystemEntries(path); + } + + /// + public override IEnumerable EnumerateFileSystemEntries(string path, string searchPattern) + { + return GetFileSystemEntries(path, searchPattern); + } + + /// + public override IEnumerable EnumerateFileSystemEntries(string path, string searchPattern, SearchOption searchOption) + { + return GetFileSystemEntries(path, searchPattern, searchOption); + } + +#if FEATURE_ENUMERATION_OPTIONS + /// + public override IEnumerable EnumerateFileSystemEntries(string path, string searchPattern, EnumerationOptions enumerationOptions) + { + var searchOption = enumerationOptions.RecurseSubdirectories ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly; + var fileSystemEntries = new List(GetFiles(path, searchPattern, searchOption)); + fileSystemEntries.AddRange(GetDirectories(path, searchPattern, searchOption)); + return fileSystemEntries; + } +#endif + + private string EnsureAbsolutePath(string path) + { + return Path.IsPathRooted(path) + ? path + : Path.Combine(GetCurrentDirectory(), path); + } + + private void CheckSearchPattern(string searchPattern) + { + if (searchPattern == null) + { + throw new ArgumentNullException(nameof(searchPattern)); + } + + const string TWO_DOTS = ".."; + Func createException = () => new ArgumentException(@"Search pattern cannot contain "".."" to move up directories and can be contained only internally in file/directory names, as in ""a..b"".", searchPattern); + + if (mockFileDataAccessor.StringOperations.EndsWith(searchPattern, TWO_DOTS)) + { + throw createException(); + } + + var position = mockFileDataAccessor.StringOperations.IndexOf(searchPattern, TWO_DOTS); + + if (position >= 0) + { + var characterAfterTwoDots = searchPattern[position + 2]; + + if (characterAfterTwoDots == Path.DirectorySeparatorChar || characterAfterTwoDots == Path.AltDirectorySeparatorChar) + { + throw createException(); + } + } + + var invalidPathChars = Path.GetInvalidPathChars(); + if (searchPattern.IndexOfAny(invalidPathChars) > -1) + { + throw CommonExceptions.IllegalCharactersInPath(nameof(searchPattern)); + } + } + + private string ReplaceLastOccurrence(string source, string find, string replace) + { + if (source == null) + { + return source; + } + + var place = source.LastIndexOf(find); + + if (place == -1) + { + return source; + } + + var result = source.Remove(place, find.Length).Insert(place, replace); + return result; + } + +#if FEATURE_ENUMERATION_OPTIONS + private SearchOption EnumerationOptionsToSearchOption(EnumerationOptions enumerationOptions) + { + static Exception CreateExceptionForUnsupportedProperty(string propertyName) + { + return new NotSupportedException( + $"Changing EnumerationOptions.{propertyName} is not yet implemented for the mock file system." + ); + } + + if (enumerationOptions.AttributesToSkip != (FileAttributes.System | FileAttributes.Hidden)) + { + throw CreateExceptionForUnsupportedProperty("AttributesToSkip"); + } + if (!enumerationOptions.IgnoreInaccessible) + { + throw CreateExceptionForUnsupportedProperty("IgnoreInaccessible"); + } + if (enumerationOptions.MatchCasing != MatchCasing.PlatformDefault) + { + throw CreateExceptionForUnsupportedProperty("MatchCasing"); + } + if (enumerationOptions.MatchType != MatchType.Simple) + { + throw CreateExceptionForUnsupportedProperty("MatchType"); + } + if (enumerationOptions.ReturnSpecialDirectories) + { + throw CreateExceptionForUnsupportedProperty("ReturnSpecialDirectories"); + } + + return enumerationOptions.RecurseSubdirectories + ? SearchOption.AllDirectories + : SearchOption.TopDirectoryOnly; + } +#endif +} \ No newline at end of file diff --git a/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockDirectoryData.cs b/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockDirectoryData.cs new file mode 100644 index 000000000..77293dd2b --- /dev/null +++ b/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockDirectoryData.cs @@ -0,0 +1,35 @@ +using System.Runtime.Versioning; +using System.Security.AccessControl; + +namespace System.IO.Abstractions.TestingHelpers; + +/// +#if FEATURE_SERIALIZABLE +[Serializable] +#endif +public class MockDirectoryData : MockFileData +{ +#if FEATURE_SERIALIZABLE + [NonSerialized] +#endif + private DirectorySecurity accessControl; + + /// + public MockDirectoryData() : base(string.Empty) + { + Attributes = FileAttributes.Directory; + } + + /// + [SupportedOSPlatform("windows")] + public new DirectorySecurity AccessControl + { + get + { + // DirectorySecurity's constructor will throw PlatformNotSupportedException on non-Windows platform, so we initialize it in lazy way. + // This let's us use this class as long as we don't use AccessControl property. + return accessControl ?? (accessControl = new DirectorySecurity()); + } + set { accessControl = value; } + } +} \ No newline at end of file diff --git a/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockDirectoryInfo.cs b/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockDirectoryInfo.cs new file mode 100644 index 000000000..8099ead93 --- /dev/null +++ b/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockDirectoryInfo.cs @@ -0,0 +1,458 @@ +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Versioning; +using System.Security.AccessControl; + +namespace System.IO.Abstractions.TestingHelpers; + +using XFS = MockUnixSupport; + +/// +#if FEATURE_SERIALIZABLE +[Serializable] +#endif +public class MockDirectoryInfo : DirectoryInfoBase, IFileSystemAclSupport +{ + private readonly IMockFileDataAccessor mockFileDataAccessor; + private string directoryPath; + private string originalPath; + private MockFileData cachedMockFileData; + private bool refreshOnNextRead; + + /// + /// Initializes a new instance of the class. + /// + /// The mock file data accessor. + /// The directory path. + /// Thrown if or is . + public MockDirectoryInfo(IMockFileDataAccessor mockFileDataAccessor, string directoryPath) : base(mockFileDataAccessor?.FileSystem) + { + this.mockFileDataAccessor = mockFileDataAccessor ?? throw new ArgumentNullException(nameof(mockFileDataAccessor)); + + if (directoryPath == null) + { + throw new ArgumentNullException("path", StringResources.Manager.GetString("VALUE_CANNOT_BE_NULL")); + } + if (directoryPath.Trim() == string.Empty) + { + throw CommonExceptions.PathIsNotOfALegalForm("path"); + } + + SetDirectoryPath(directoryPath); + Refresh(); + } + +#if FEATURE_CREATE_SYMBOLIC_LINK + /// + public override void CreateAsSymbolicLink(string pathToTarget) + { + FileSystem.Directory.CreateSymbolicLink(FullName, pathToTarget); + } +#endif + + /// + public override void Delete() + { + mockFileDataAccessor.Directory.Delete(directoryPath); + refreshOnNextRead = true; + } + + /// + public override void Refresh() + { + var mockFileData = mockFileDataAccessor.GetFile(directoryPath) ?? MockFileData.NullObject; + cachedMockFileData = mockFileData.Clone(); + } + +#if FEATURE_CREATE_SYMBOLIC_LINK + /// + public override IFileSystemInfo ResolveLinkTarget(bool returnFinalTarget) + { + return FileSystem.Directory.ResolveLinkTarget(FullName, returnFinalTarget); + } +#endif + + /// + public override FileAttributes Attributes + { + get { return GetMockFileDataForRead().Attributes; } + set { GetMockFileDataForWrite().Attributes = value | FileAttributes.Directory; } + } + + /// + public override DateTime CreationTime + { + get { return GetMockFileDataForRead().CreationTime.LocalDateTime; } + set { GetMockFileDataForWrite().CreationTime = value; } + } + + /// + public override DateTime CreationTimeUtc + { + get { return GetMockFileDataForRead().CreationTime.UtcDateTime; } + set { GetMockFileDataForWrite().CreationTime = value; } + } + + /// + public override bool Exists + { + get { + var mockFileData = GetMockFileDataForRead(); + return (int)mockFileData.Attributes != -1 && mockFileData.IsDirectory; + } + } + + /// + public override string Extension + { + get + { + // System.IO.Path.GetExtension does only string manipulation, + // so it's safe to delegate. + return Path.GetExtension(directoryPath); + } + } + + /// + public override string FullName + { + get + { + var root = mockFileDataAccessor.Path.GetPathRoot(directoryPath); + + if (mockFileDataAccessor.StringOperations.Equals(directoryPath, root)) + { + // drives have the trailing slash + return directoryPath; + } + + // directories do not have a trailing slash + return directoryPath.TrimEnd('\\').TrimEnd('/'); + } + } + + /// + public override DateTime LastAccessTime + { + get { return GetMockFileDataForRead().LastAccessTime.LocalDateTime; } + set { GetMockFileDataForWrite().LastAccessTime = value; } + } + + /// + public override DateTime LastAccessTimeUtc + { + get { return GetMockFileDataForRead().LastAccessTime.UtcDateTime; } + set { GetMockFileDataForWrite().LastAccessTime = value; } + } + + /// + public override DateTime LastWriteTime + { + get { return GetMockFileDataForRead().LastWriteTime.LocalDateTime; } + set { GetMockFileDataForWrite().LastWriteTime = value; } + } + + /// + public override DateTime LastWriteTimeUtc + { + get { return GetMockFileDataForRead().LastWriteTime.UtcDateTime; } + set { GetMockFileDataForWrite().LastWriteTime = value; } + } + +#if FEATURE_FILE_SYSTEM_INFO_LINK_TARGET + /// + public override string LinkTarget + { + get { return GetMockFileDataForRead().LinkTarget; } + } +#endif + + /// + public override string Name + { + get + { + var mockPath = new MockPath(mockFileDataAccessor); + return string.Equals(mockPath.GetPathRoot(directoryPath), directoryPath) ? directoryPath : mockPath.GetFileName(directoryPath.TrimEnd(mockFileDataAccessor.Path.DirectorySeparatorChar)); + } + } + + /// + public override void Create() + { + mockFileDataAccessor.Directory.CreateDirectory(FullName); + refreshOnNextRead = true; + } + + /// + public override IDirectoryInfo CreateSubdirectory(string path) + { + return mockFileDataAccessor.Directory.CreateDirectory(Path.Combine(FullName, path)); + } + + /// + public override void Delete(bool recursive) + { + mockFileDataAccessor.Directory.Delete(directoryPath, recursive); + refreshOnNextRead = true; + } + + /// + public override IEnumerable EnumerateDirectories() + { + return GetDirectories(); + } + + /// + public override IEnumerable EnumerateDirectories(string searchPattern) + { + return GetDirectories(searchPattern); + } + + /// + public override IEnumerable EnumerateDirectories(string searchPattern, SearchOption searchOption) + { + return GetDirectories(searchPattern, searchOption); + } + +#if FEATURE_ENUMERATION_OPTIONS + /// + public override IEnumerable EnumerateDirectories(string searchPattern, EnumerationOptions enumerationOptions) + { + return GetDirectories(searchPattern, enumerationOptions); + } +#endif + + /// + public override IEnumerable EnumerateFiles() + { + return GetFiles(); + } + + /// + public override IEnumerable EnumerateFiles(string searchPattern) + { + return GetFiles(searchPattern); + } + + /// + public override IEnumerable EnumerateFiles(string searchPattern, SearchOption searchOption) + { + return GetFiles(searchPattern, searchOption); + } + +#if FEATURE_ENUMERATION_OPTIONS + /// + public override IEnumerable EnumerateFiles(string searchPattern, EnumerationOptions enumerationOptions) + { + return GetFiles(searchPattern, enumerationOptions); + } +#endif + + /// + public override IEnumerable EnumerateFileSystemInfos() + { + return GetFileSystemInfos(); + } + + /// + public override IEnumerable EnumerateFileSystemInfos(string searchPattern) + { + return GetFileSystemInfos(searchPattern); + } + + /// + public override IEnumerable EnumerateFileSystemInfos(string searchPattern, SearchOption searchOption) + { + return GetFileSystemInfos(searchPattern, searchOption); + } + +#if FEATURE_ENUMERATION_OPTIONS + /// + public override IEnumerable EnumerateFileSystemInfos(string searchPattern, EnumerationOptions enumerationOptions) + { + return GetFileSystemInfos(searchPattern, enumerationOptions); + } +#endif + + /// + public override IDirectoryInfo[] GetDirectories() + { + return ConvertStringsToDirectories(mockFileDataAccessor.Directory.GetDirectories(directoryPath)); + } + + /// + public override IDirectoryInfo[] GetDirectories(string searchPattern) + { + return ConvertStringsToDirectories(mockFileDataAccessor.Directory.GetDirectories(directoryPath, searchPattern)); + } + + /// + public override IDirectoryInfo[] GetDirectories(string searchPattern, SearchOption searchOption) + { + return ConvertStringsToDirectories(mockFileDataAccessor.Directory.GetDirectories(directoryPath, searchPattern, searchOption)); + } + +#if FEATURE_ENUMERATION_OPTIONS + /// + public override IDirectoryInfo[] GetDirectories(string searchPattern, EnumerationOptions enumerationOptions) + { + return ConvertStringsToDirectories(mockFileDataAccessor.Directory.GetDirectories(directoryPath, searchPattern, enumerationOptions)); + } +#endif + + private DirectoryInfoBase[] ConvertStringsToDirectories(IEnumerable paths) + { + return paths + .Select(path => new MockDirectoryInfo(mockFileDataAccessor, path)) + .Cast() + .ToArray(); + } + + /// + public override IFileInfo[] GetFiles() + { + return ConvertStringsToFiles(mockFileDataAccessor.Directory.GetFiles(FullName)); + } + + /// + public override IFileInfo[] GetFiles(string searchPattern) + { + return ConvertStringsToFiles(mockFileDataAccessor.Directory.GetFiles(FullName, searchPattern)); + } + + /// + public override IFileInfo[] GetFiles(string searchPattern, SearchOption searchOption) + { + return ConvertStringsToFiles(mockFileDataAccessor.Directory.GetFiles(FullName, searchPattern, searchOption)); + } + +#if FEATURE_ENUMERATION_OPTIONS + /// + public override IFileInfo[] GetFiles(string searchPattern, EnumerationOptions enumerationOptions) + { + return ConvertStringsToFiles(mockFileDataAccessor.Directory.GetFiles(FullName, searchPattern, enumerationOptions)); + } +#endif + + IFileInfo[] ConvertStringsToFiles(IEnumerable paths) + { + return paths + .Select(mockFileDataAccessor.FileInfo.New) + .ToArray(); + } + + /// + public override IFileSystemInfo[] GetFileSystemInfos() + { + return GetFileSystemInfos("*"); + } + + /// + public override IFileSystemInfo[] GetFileSystemInfos(string searchPattern) + { + return GetFileSystemInfos(searchPattern, SearchOption.TopDirectoryOnly); + } + + /// + public override IFileSystemInfo[] GetFileSystemInfos(string searchPattern, SearchOption searchOption) + { + return GetDirectories(searchPattern, searchOption).OfType().Concat(GetFiles(searchPattern, searchOption)).ToArray(); + } + +#if FEATURE_ENUMERATION_OPTIONS + /// + public override IFileSystemInfo[] GetFileSystemInfos(string searchPattern, EnumerationOptions enumerationOptions) + { + return GetDirectories(searchPattern, enumerationOptions).OfType().Concat(GetFiles(searchPattern, enumerationOptions)).ToArray(); + } +#endif + + /// + public override void MoveTo(string destDirName) + { + mockFileDataAccessor.Directory.Move(directoryPath, destDirName); + SetDirectoryPath(destDirName); + } + + /// + public override IDirectoryInfo Parent + { + get + { + return mockFileDataAccessor.Directory.GetParent(directoryPath); + } + } + + /// + public override IDirectoryInfo Root + { + get + { + return new MockDirectoryInfo(mockFileDataAccessor, mockFileDataAccessor.Directory.GetDirectoryRoot(FullName)); + } + } + + private MockFileData GetMockFileDataForRead() + { + if (refreshOnNextRead) + { + Refresh(); + refreshOnNextRead = false; + } + return cachedMockFileData; + } + + private MockFileData GetMockFileDataForWrite() + { + refreshOnNextRead = true; + return mockFileDataAccessor.GetFile(directoryPath) + ?? throw CommonExceptions.CouldNotFindPartOfPath(directoryPath); + } + + /// + public override string ToString() + { + return originalPath; + } + + /// + [SupportedOSPlatform("windows")] + public object GetAccessControl() + { + return GetMockDirectoryData().AccessControl; + } + + /// + [SupportedOSPlatform("windows")] + public object GetAccessControl(IFileSystemAclSupport.AccessControlSections includeSections) + { + return GetMockDirectoryData().AccessControl; + } + + /// + [SupportedOSPlatform("windows")] + public void SetAccessControl(object value) + { + GetMockDirectoryData().AccessControl = value as DirectorySecurity; + } + + private void SetDirectoryPath(string path) + { + originalPath = path; + path = mockFileDataAccessor.Path.GetFullPath(path); + + path = path.TrimSlashes(); + if (XFS.IsWindowsPlatform()) + { + path = path.TrimEnd(' '); + } + this.directoryPath = path; + } + + private MockDirectoryData GetMockDirectoryData() + { + return mockFileDataAccessor.GetFile(directoryPath) as MockDirectoryData + ?? throw CommonExceptions.CouldNotFindPartOfPath(directoryPath); + } +} \ No newline at end of file diff --git a/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockDirectoryInfoFactory.cs b/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockDirectoryInfoFactory.cs new file mode 100644 index 000000000..0c025098b --- /dev/null +++ b/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockDirectoryInfoFactory.cs @@ -0,0 +1,37 @@ +namespace System.IO.Abstractions.TestingHelpers; + +/// +#if FEATURE_SERIALIZABLE +[Serializable] +#endif +public class MockDirectoryInfoFactory : IDirectoryInfoFactory +{ + readonly IMockFileDataAccessor mockFileSystem; + + /// + public MockDirectoryInfoFactory(IMockFileDataAccessor mockFileSystem) + { + this.mockFileSystem = mockFileSystem; + } + + /// + public IFileSystem FileSystem + => mockFileSystem; + + /// + public IDirectoryInfo New(string path) + { + return new MockDirectoryInfo(mockFileSystem, path); + } + + /// + public IDirectoryInfo Wrap(DirectoryInfo directoryInfo) + { + if (directoryInfo == null) + { + return null; + } + + return new MockDirectoryInfo(mockFileSystem, directoryInfo.FullName); + } +} \ No newline at end of file diff --git a/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockDriveData.cs b/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockDriveData.cs new file mode 100644 index 000000000..0ae4d7e65 --- /dev/null +++ b/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockDriveData.cs @@ -0,0 +1,75 @@ + +namespace System.IO.Abstractions.TestingHelpers; + +/// +/// The class represents the associated data of a drive. +/// +#if FEATURE_SERIALIZABLE +[Serializable] +#endif +public class MockDriveData +{ + /// + /// Initializes a new instance of the class. + /// + public MockDriveData() + { + IsReady = true; + } + + /// + /// Initializes a new instance of the class by copying the given . + /// + /// The template instance. + /// Thrown if is . + public MockDriveData(MockDriveData template) + { + if (template == null) + { + throw new ArgumentNullException(nameof(template)); + } + + AvailableFreeSpace = template.AvailableFreeSpace; + DriveFormat = template.DriveFormat; + DriveType = template.DriveType; + IsReady = template.IsReady; + TotalFreeSpace = template.TotalFreeSpace; + TotalSize = template.TotalSize; + VolumeLabel = template.VolumeLabel; + } + + /// + /// Gets or sets the amount of available free space of the , in bytes. + /// + public long AvailableFreeSpace { get; set; } + + /// + /// Gets or sets the name of the file system of the , such as NTFS or FAT32. + /// + public string DriveFormat { get; set; } + + /// + /// Gets or sets the drive type of the , such as CD-ROM, removable, network, or fixed. + /// + public DriveType DriveType { get; set; } + + /// + /// Gets or sets the value that indicates whether the is ready. + /// + public bool IsReady { get; set; } + + /// + /// Gets or sets the total amount of free space available on the , in bytes. + /// + public long TotalFreeSpace { get; set; } + + /// + /// Gets or sets the total size of storage space on the , in bytes. + /// + public long TotalSize { get; set; } + + /// + /// Gets or sets the volume label of the . + /// + public string VolumeLabel { get; set; } +} \ No newline at end of file diff --git a/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockDriveInfo.cs b/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockDriveInfo.cs new file mode 100644 index 000000000..c6d85c787 --- /dev/null +++ b/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockDriveInfo.cs @@ -0,0 +1,120 @@ +namespace System.IO.Abstractions.TestingHelpers; + +/// +#if FEATURE_SERIALIZABLE +[Serializable] +#endif +public class MockDriveInfo : DriveInfoBase +{ + private readonly IMockFileDataAccessor mockFileDataAccessor; + private readonly string name; + + /// + public MockDriveInfo(IMockFileDataAccessor mockFileDataAccessor, string name) : base(mockFileDataAccessor?.FileSystem) + { + this.mockFileDataAccessor = mockFileDataAccessor ?? throw new ArgumentNullException(nameof(mockFileDataAccessor)); + this.name = mockFileDataAccessor.PathVerifier.NormalizeDriveName(name); + } + + /// + public override long AvailableFreeSpace + { + get + { + var mockDriveData = GetMockDriveData(); + return mockDriveData.AvailableFreeSpace; + } + } + + /// + public override string DriveFormat + { + get + { + var mockDriveData = GetMockDriveData(); + return mockDriveData.DriveFormat; + } + } + + /// + public override DriveType DriveType + { + get + { + var mockDriveData = GetMockDriveData(); + return mockDriveData.DriveType; + } + } + + /// + public override bool IsReady + { + get + { + var mockDriveData = GetMockDriveData(); + return mockDriveData.IsReady; + } + } + + /// + public override string Name + { + get { return name; } + } + + /// + public override IDirectoryInfo RootDirectory + { + get + { + return mockFileDataAccessor.DirectoryInfo.New(Name); + } + } + + /// + public override long TotalFreeSpace + { + get + { + var mockDriveData = GetMockDriveData(); + return mockDriveData.TotalFreeSpace; + } + } + + /// + public override long TotalSize + { + get + { + var mockDriveData = GetMockDriveData(); + return mockDriveData.TotalSize; + } + } + + /// + public override string VolumeLabel + { + get + { + var mockDriveData = GetMockDriveData(); + return mockDriveData.VolumeLabel; + } + set + { + var mockDriveData = GetMockDriveData(); + mockDriveData.VolumeLabel = value; + } + } + + /// + public override string ToString() + { + return Name; + } + + private MockDriveData GetMockDriveData() + { + return mockFileDataAccessor.GetDrive(name) + ?? throw CommonExceptions.FileNotFound(name); + } +} \ No newline at end of file diff --git a/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockDriveInfoFactory.cs b/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockDriveInfoFactory.cs new file mode 100644 index 000000000..488862df2 --- /dev/null +++ b/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockDriveInfoFactory.cs @@ -0,0 +1,102 @@ +using System.Collections.Generic; + +namespace System.IO.Abstractions.TestingHelpers; + +/// +#if FEATURE_SERIALIZABLE +[Serializable] +#endif +public class MockDriveInfoFactory : IDriveInfoFactory +{ + private readonly IMockFileDataAccessor mockFileSystem; + + /// + public MockDriveInfoFactory(IMockFileDataAccessor mockFileSystem) + { + this.mockFileSystem = mockFileSystem ?? throw new ArgumentNullException(nameof(mockFileSystem)); + } + + /// + public IFileSystem FileSystem + => mockFileSystem; + + /// + public IDriveInfo[] GetDrives() + { + var result = new List(); + foreach (string driveLetter in mockFileSystem.AllDrives) + { + try + { + var mockDriveInfo = new MockDriveInfo(mockFileSystem, driveLetter); + result.Add(mockDriveInfo); + } + catch (ArgumentException) + { + // invalid drives should be ignored + } + } + + return result.ToArray(); + } + + /// + public IDriveInfo New(string driveName) + { + var drive = mockFileSystem.Path.GetPathRoot(driveName); + + return new MockDriveInfo(mockFileSystem, drive); + } + + /// + public IDriveInfo Wrap(DriveInfo driveInfo) + { + if (driveInfo == null) + { + return null; + } + + return New(driveInfo.Name); + } + + private string NormalizeDriveName(string driveName) + { + if (driveName.Length == 3 && mockFileSystem.StringOperations.EndsWith(driveName, @":\")) + { + return mockFileSystem.StringOperations.ToUpper(driveName[0]) + @":\"; + } + + if (mockFileSystem.StringOperations.StartsWith(driveName, @"\\")) + { + return null; + } + + return driveName; + } + + private class DriveEqualityComparer : IEqualityComparer + { + private readonly IMockFileDataAccessor mockFileSystem; + + public DriveEqualityComparer(IMockFileDataAccessor mockFileSystem) + { + this.mockFileSystem = mockFileSystem ?? throw new ArgumentNullException(nameof(mockFileSystem)); + } + + public bool Equals(string x, string y) + { + return ReferenceEquals(x, y) || + (HasDrivePrefix(x) && HasDrivePrefix(y) && mockFileSystem.StringOperations.Equals(x[0], y[0])); + } + + private static bool HasDrivePrefix(string x) + { + return x != null && x.Length >= 2 && x[1] == ':'; + } + + public int GetHashCode(string obj) + { + return mockFileSystem.StringOperations.ToUpper(obj).GetHashCode(); + } + } +} \ No newline at end of file diff --git a/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockFile.Async.cs b/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockFile.Async.cs new file mode 100644 index 000000000..b4765c93a --- /dev/null +++ b/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockFile.Async.cs @@ -0,0 +1,171 @@ +#if FEATURE_ASYNC_FILE + +using System.Collections.Generic; +using System.Runtime.CompilerServices; +using System.Text; +using System.Threading; +using System.Threading.Tasks; + +namespace System.IO.Abstractions.TestingHelpers +{ + partial class MockFile + { +#if FEATURE_FILE_SPAN + /// + public override Task AppendAllBytesAsync(string path, byte[] bytes, CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); + AppendAllBytes(path, bytes); + return Task.CompletedTask; + } + + /// + public override Task AppendAllBytesAsync(string path, ReadOnlyMemory bytes, CancellationToken cancellationToken = default) + { + return AppendAllBytesAsync(path, bytes.ToArray(), cancellationToken); + } +#endif + /// + public override Task AppendAllLinesAsync(string path, IEnumerable contents, CancellationToken cancellationToken = default) => + AppendAllLinesAsync(path, contents, MockFileData.DefaultEncoding, cancellationToken); + + /// + public override Task AppendAllLinesAsync(string path, IEnumerable contents, Encoding encoding, CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); + AppendAllLines(path, contents, encoding); + return Task.CompletedTask; + } + + /// + public override Task AppendAllTextAsync(string path, string contents, CancellationToken cancellationToken = default) => + AppendAllTextAsync(path, contents, MockFileData.DefaultEncoding, cancellationToken); + + + /// + public override Task AppendAllTextAsync(string path, string contents, Encoding encoding, CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); + AppendAllText(path, contents, encoding); + return Task.CompletedTask; + } + +#if FEATURE_FILE_SPAN + /// + public override Task AppendAllTextAsync(string path, ReadOnlyMemory contents, CancellationToken cancellationToken = default) + { + return AppendAllTextAsync(path, contents.ToString(), cancellationToken); + } + + /// + public override Task AppendAllTextAsync(string path, ReadOnlyMemory contents, Encoding encoding, + CancellationToken cancellationToken = default) + { + return AppendAllTextAsync(path, contents.ToString(), encoding, cancellationToken); + } +#endif + + /// + public override Task ReadAllBytesAsync(string path, CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); + return Task.FromResult(ReadAllBytes(path)); + } + + /// + public override Task ReadAllLinesAsync(string path, CancellationToken cancellationToken = default) => + ReadAllLinesAsync(path, MockFileData.DefaultEncoding, cancellationToken); + + /// + + public override Task ReadAllLinesAsync(string path, Encoding encoding, CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); + return Task.FromResult(ReadAllLines(path, encoding)); + } + + /// + public override Task ReadAllTextAsync(string path, CancellationToken cancellationToken = default) => + ReadAllTextAsync(path, MockFileData.DefaultEncoding, cancellationToken); + + + /// + public override Task ReadAllTextAsync(string path, Encoding encoding, CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); + return Task.FromResult(ReadAllText(path, encoding)); + } + +#if FEATURE_READ_LINES_ASYNC + /// + public override IAsyncEnumerable ReadLinesAsync(string path, CancellationToken cancellationToken = default) => + ReadLinesAsync(path, MockFileData.DefaultEncoding, cancellationToken); + + /// + public override async IAsyncEnumerable ReadLinesAsync(string path, Encoding encoding, + [EnumeratorCancellation] CancellationToken cancellationToken = default) + { + var lines = await ReadAllLinesAsync(path, encoding, cancellationToken); + foreach (var line in lines) + yield return line; + } +#endif + + /// + public override Task WriteAllBytesAsync(string path, byte[] bytes, CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); + WriteAllBytes(path, bytes); + return Task.CompletedTask; + } + +#if FEATURE_FILE_SPAN + /// + public override Task WriteAllBytesAsync(string path, ReadOnlyMemory bytes, CancellationToken cancellationToken = default) + { + return WriteAllBytesAsync(path, bytes.ToArray(), cancellationToken); + } +#endif + + /// + public override Task WriteAllLinesAsync(string path, IEnumerable contents, CancellationToken cancellationToken = default) => + WriteAllLinesAsync(path, contents, MockFileData.DefaultEncoding, cancellationToken); + + /// + public override Task WriteAllLinesAsync(string path, IEnumerable contents, Encoding encoding, CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); + WriteAllLines(path, contents, encoding); + return Task.CompletedTask; + } + + /// + public override Task WriteAllTextAsync(string path, string contents, CancellationToken cancellationToken = default) => + WriteAllTextAsync(path, contents, MockFileData.DefaultEncoding, cancellationToken); + + /// + public override Task WriteAllTextAsync(string path, string contents, Encoding encoding, CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); + WriteAllText(path, contents, encoding); + return Task.CompletedTask; + } + +#if FEATURE_FILE_SPAN + /// + public override Task WriteAllTextAsync(string path, ReadOnlyMemory contents, CancellationToken cancellationToken = default) + { + return WriteAllTextAsync(path, contents.ToString(), cancellationToken); + } + + /// + public override Task WriteAllTextAsync(string path, ReadOnlyMemory contents, Encoding encoding, + CancellationToken cancellationToken = default) + { + return WriteAllTextAsync(path, contents.ToString(), encoding, cancellationToken); + } +#endif + } +} + +#endif diff --git a/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockFile.cs b/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockFile.cs new file mode 100644 index 000000000..e4d739704 --- /dev/null +++ b/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockFile.cs @@ -0,0 +1,1414 @@ +using System.Collections.Generic; +using System.Globalization; +using System.Linq; +using System.Text; +using Microsoft.Win32.SafeHandles; + +namespace System.IO.Abstractions.TestingHelpers; + +using XFS = MockUnixSupport; + +/// +#if FEATURE_SERIALIZABLE +[Serializable] +#endif +public partial class MockFile : FileBase +{ + private readonly IMockFileDataAccessor mockFileDataAccessor; + + /// + public MockFile(IMockFileDataAccessor mockFileDataAccessor) : base(mockFileDataAccessor?.FileSystem) + { + this.mockFileDataAccessor = mockFileDataAccessor ?? throw new ArgumentNullException(nameof(mockFileDataAccessor)); + } + +#if FEATURE_FILE_SPAN + /// + public override void AppendAllBytes(string path, byte[] bytes) + { + mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); + + if (!mockFileDataAccessor.FileExists(path)) + { + VerifyDirectoryExists(path); + mockFileDataAccessor.AddFile(path, mockFileDataAccessor.AdjustTimes(new MockFileData(bytes), TimeAdjustments.All)); + } + else + { + var file = mockFileDataAccessor.GetFile(path); + file.CheckFileAccess(path, FileAccess.Write); + mockFileDataAccessor.AdjustTimes(file, TimeAdjustments.LastAccessTime | TimeAdjustments.LastWriteTime); + file.Contents = file.Contents.Concat(bytes).ToArray(); + } + } + + /// + public override void AppendAllBytes(string path, ReadOnlySpan bytes) + { + AppendAllBytes(path, bytes.ToArray()); + } +#endif + + /// + public override void AppendAllLines(string path, IEnumerable contents) + { + AppendAllLines(path, contents, MockFileData.DefaultEncoding); + } + + /// + public override void AppendAllLines(string path, IEnumerable contents, Encoding encoding) + { + mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); + VerifyValueIsNotNull(contents, nameof(contents)); + VerifyValueIsNotNull(encoding, nameof(encoding)); + + var concatContents = contents.Aggregate("", (a, b) => a + b + Environment.NewLine); + AppendAllText(path, concatContents, encoding); + } + + /// + public override void AppendAllText(string path, string contents) + { + AppendAllText(path, contents, MockFileData.DefaultEncoding); + } + + /// + public override void AppendAllText(string path, string contents, Encoding encoding) + { + mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); + + if (encoding == null) + { + throw new ArgumentNullException(nameof(encoding)); + } + + if (!mockFileDataAccessor.FileExists(path)) + { + VerifyDirectoryExists(path); + mockFileDataAccessor.AddFile(path, mockFileDataAccessor.AdjustTimes(new MockFileData(contents, encoding), TimeAdjustments.All)); + } + else + { + var file = mockFileDataAccessor.GetFile(path); + file.CheckFileAccess(path, FileAccess.Write); + mockFileDataAccessor.AdjustTimes(file, TimeAdjustments.LastAccessTime | TimeAdjustments.LastWriteTime); + var bytesToAppend = encoding.GetBytes(contents); + file.Contents = file.Contents.Concat(bytesToAppend).ToArray(); + } + } + +#if FEATURE_FILE_SPAN + /// + public override void AppendAllText(string path, ReadOnlySpan contents) + { + AppendAllText(path, contents.ToString()); + } + + /// + public override void AppendAllText(string path, ReadOnlySpan contents, Encoding encoding) + { + AppendAllText(path, contents.ToString(), encoding); + } +#endif + + /// + public override StreamWriter AppendText(string path) + { + mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); + + if (mockFileDataAccessor.FileExists(path)) + { + StreamWriter sw = new StreamWriter(OpenWrite(path)); + sw.BaseStream.Seek(0, SeekOrigin.End); //push the stream pointer at the end for append. + return sw; + } + + return new StreamWriter(Create(path)); + } + + /// + public override void Copy(string sourceFileName, string destFileName) + { + Copy(sourceFileName, destFileName, false); + } + + /// + public override void Copy(string sourceFileName, string destFileName, bool overwrite) + { + if (sourceFileName == null) + { + throw CommonExceptions.FilenameCannotBeNull(nameof(sourceFileName)); + } + + if (destFileName == null) + { + throw CommonExceptions.FilenameCannotBeNull(nameof(destFileName)); + } + + mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(sourceFileName, nameof(sourceFileName)); + mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(destFileName, nameof(destFileName)); + + if (!Exists(sourceFileName)) + { + throw CommonExceptions.FileNotFound(sourceFileName); + } + + VerifyDirectoryExists(destFileName); + + var fileExists = mockFileDataAccessor.FileExists(destFileName); + if (fileExists) + { + if (!overwrite) + { + throw CommonExceptions.FileAlreadyExists(destFileName); + } + + if (string.Equals(sourceFileName, destFileName, StringComparison.OrdinalIgnoreCase) && XFS.IsWindowsPlatform()) + { + throw CommonExceptions.ProcessCannotAccessFileInUse(destFileName); + } + + mockFileDataAccessor.RemoveFile(destFileName); + } + + var sourceFileData = mockFileDataAccessor.GetFile(sourceFileName); + sourceFileData.CheckFileAccess(sourceFileName, FileAccess.Read); + var destFileData = new MockFileData(sourceFileData); + mockFileDataAccessor.AdjustTimes(destFileData, TimeAdjustments.CreationTime | TimeAdjustments.LastAccessTime); + mockFileDataAccessor.AddFile(destFileName, destFileData); + } + + /// + public override FileSystemStream Create(string path) => + Create(path, 4096); + + /// + public override FileSystemStream Create(string path, int bufferSize) => + Create(path, bufferSize, FileOptions.None); + + /// + public override FileSystemStream Create(string path, int bufferSize, FileOptions options) => + CreateInternal(path, FileAccess.ReadWrite, options); + + private FileSystemStream CreateInternal(string path, FileAccess access, FileOptions options) + { + if (path == null) + { + throw new ArgumentNullException(nameof(path), "Path cannot be null."); + } + + mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, nameof(path)); + VerifyDirectoryExists(path); + + var mockFileData = new MockFileData(new byte[0]); + mockFileDataAccessor.AdjustTimes(mockFileData, TimeAdjustments.All); + mockFileDataAccessor.AddFile(path, mockFileData); + return OpenInternal(path, FileMode.Open, access, options); + } + +#if FEATURE_CREATE_SYMBOLIC_LINK + /// + public override IFileSystemInfo CreateSymbolicLink(string path, string pathToTarget) + { + if (path == null) + { + throw CommonExceptions.FilenameCannotBeNull(nameof(path)); + } + + if (pathToTarget == null) + { + throw CommonExceptions.FilenameCannotBeNull(nameof(pathToTarget)); + } + + mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, nameof(path)); + mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(pathToTarget, nameof(pathToTarget)); + + if (Exists(path)) + { + throw CommonExceptions.FileAlreadyExists(nameof(path)); + } + + VerifyDirectoryExists(path); + + var fileExists = mockFileDataAccessor.FileExists(pathToTarget); + if (!fileExists) + { + throw CommonExceptions.FileNotFound(pathToTarget); + } + + var sourceFileData = mockFileDataAccessor.GetFile(pathToTarget); + sourceFileData.CheckFileAccess(pathToTarget, FileAccess.Read); + var destFileData = new MockFileData(new byte[0]); + mockFileDataAccessor.AdjustTimes(destFileData, TimeAdjustments.CreationTime | TimeAdjustments.LastAccessTime); + destFileData.LinkTarget = pathToTarget; + mockFileDataAccessor.AddFile(path, destFileData); + + var mockFileInfo = new MockFileInfo(mockFileDataAccessor, path); + mockFileInfo.Attributes |= FileAttributes.ReparsePoint; + return mockFileInfo; + } +#endif + /// + public override StreamWriter CreateText(string path) + { + return new StreamWriter(Create(path)); + } + + /// + public override void Decrypt(string path) + { + mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); + + new MockFileInfo(mockFileDataAccessor, path).Decrypt(); + } + /// + public override void Delete(string path) + { + mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); + + // We mimic exact behavior of the standard File.Delete() method + // which throws exception only if the folder does not exist, + // but silently returns if deleting a non-existing file in an existing folder. + VerifyDirectoryExists(path); + + var file = mockFileDataAccessor.GetFile(path); + if (file != null && !file.AllowedFileShare.HasFlag(FileShare.Delete)) + { + throw CommonExceptions.ProcessCannotAccessFileInUse(path); + } + + if (file != null && file.IsDirectory) + { + throw new UnauthorizedAccessException($"Access to the path '{path}' is denied."); + } + + mockFileDataAccessor.RemoveFile(path); + } + + /// + public override void Encrypt(string path) + { + mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); + + new MockFileInfo(mockFileDataAccessor, path).Encrypt(); + } + + /// + public override bool Exists(string path) + { + if (path == null) + { + return false; + } + + if (path.Trim() == string.Empty) + { + return false; + } + + //Not handling exceptions here so that mock behaviour is as similar as possible to System.IO.File.Exists (See #810) + try + { + mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, nameof(path)); + + var file = mockFileDataAccessor.GetFile(path); + return file != null && !file.IsDirectory; + } + catch (ArgumentException) { } + catch (NotSupportedException) { } + catch (IOException) { } + catch (UnauthorizedAccessException) { } + + return false; + } + + /// + /// Gets the of the file on the path. + /// + /// The path to the file. + /// The of the file on the path. + /// is empty, contains only white spaces, or contains invalid characters. + /// The specified path, file name, or both exceed the system-defined maximum length. For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters. + /// is in an invalid format. + /// represents a file and is invalid, such as being on an unmapped drive, or the file cannot be found. + /// represents a directory and is invalid, such as being on an unmapped drive, or the directory cannot be found. + /// This file is being used by another process. + /// The caller does not have the required permission. + public override FileAttributes GetAttributes(string path) + { + if (path != null && path.Length == 0) + { + throw CommonExceptions.PathIsNotOfALegalForm(nameof(path)); + } + + mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); + + var possibleFileData = mockFileDataAccessor.GetFile(path); + FileAttributes result; + if (possibleFileData != null) + { + result = possibleFileData.Attributes; + } + else + { + var directoryInfo = mockFileDataAccessor.DirectoryInfo.New(path); + if (directoryInfo.Exists) + { + result = directoryInfo.Attributes; + } + else + { + VerifyDirectoryExists(path); + + throw CommonExceptions.FileNotFound(path); + } + } + + return result; + } + +#if FEATURE_FILE_ATTRIBUTES_VIA_HANDLE + /// + public override FileAttributes GetAttributes(SafeFileHandle fileHandle) + { + throw CommonExceptions.NotImplemented(); + } +#endif + + /// + public override DateTime GetCreationTime(string path) + { + mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); + + return GetTimeFromFile(path, data => data.CreationTime.LocalDateTime, () => MockFileData.DefaultDateTimeOffset.LocalDateTime); + } + +#if FEATURE_FILE_ATTRIBUTES_VIA_HANDLE + /// + public override DateTime GetCreationTime(SafeFileHandle fileHandle) + { + throw CommonExceptions.NotImplemented(); + } +#endif + + /// + public override DateTime GetCreationTimeUtc(string path) + { + mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); + + return GetTimeFromFile(path, data => data.CreationTime.UtcDateTime, () => MockFileData.DefaultDateTimeOffset.UtcDateTime); + } + +#if FEATURE_FILE_ATTRIBUTES_VIA_HANDLE + /// + public override DateTime GetCreationTimeUtc(SafeFileHandle fileHandle) + { + throw CommonExceptions.NotImplemented(); + } +#endif + + /// + public override DateTime GetLastAccessTime(string path) + { + mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); + + return GetTimeFromFile(path, data => data.LastAccessTime.LocalDateTime, () => MockFileData.DefaultDateTimeOffset.LocalDateTime); + } + +#if FEATURE_FILE_ATTRIBUTES_VIA_HANDLE + /// + public override DateTime GetLastAccessTime(SafeFileHandle fileHandle) + { + throw CommonExceptions.NotImplemented(); + } +#endif + + /// + public override DateTime GetLastAccessTimeUtc(string path) + { + mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); + + return GetTimeFromFile(path, data => data.LastAccessTime.UtcDateTime, () => MockFileData.DefaultDateTimeOffset.UtcDateTime); + } + +#if FEATURE_FILE_ATTRIBUTES_VIA_HANDLE + /// + public override DateTime GetLastAccessTimeUtc(SafeFileHandle fileHandle) + { + throw CommonExceptions.NotImplemented(); + } +#endif + + /// + public override DateTime GetLastWriteTime(string path) + { + mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); + + return GetTimeFromFile(path, data => data.LastWriteTime.LocalDateTime, () => MockFileData.DefaultDateTimeOffset.LocalDateTime); + } + +#if FEATURE_FILE_ATTRIBUTES_VIA_HANDLE + /// + public override DateTime GetLastWriteTime(SafeFileHandle fileHandle) + { + throw CommonExceptions.NotImplemented(); + } +#endif + + /// + public override DateTime GetLastWriteTimeUtc(string path) + { + mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); + + return GetTimeFromFile(path, data => data.LastWriteTime.UtcDateTime, () => MockFileData.DefaultDateTimeOffset.UtcDateTime); + } + +#if FEATURE_FILE_ATTRIBUTES_VIA_HANDLE + /// + public override DateTime GetLastWriteTimeUtc(SafeFileHandle fileHandle) + { + throw CommonExceptions.NotImplemented(); + } +#endif + +#if FEATURE_UNIX_FILE_MODE + /// + public override UnixFileMode GetUnixFileMode(string path) + { + mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); + + if (!mockFileDataAccessor.FileExists(path)) + { + throw CommonExceptions.FileNotFound(path); + } + + var mockFileData = mockFileDataAccessor.GetFile(path); + return mockFileData.UnixMode; + } +#endif + +#if FEATURE_FILE_ATTRIBUTES_VIA_HANDLE + /// + public override UnixFileMode GetUnixFileMode(SafeFileHandle fileHandle) + { + throw CommonExceptions.NotImplemented(); + } +#endif + + private DateTime GetTimeFromFile(string path, Func existingFileFunction, Func nonExistingFileFunction) + { + DateTime result; + MockFileData file = mockFileDataAccessor.GetFile(path); + if (file != null) + { + result = existingFileFunction(file); + } + else + { + result = nonExistingFileFunction(); + } + + return result; + } + + /// + public override void Move(string sourceFileName, string destFileName) + { + if (sourceFileName == null) + { + throw CommonExceptions.FilenameCannotBeNull(nameof(sourceFileName)); + } + + if (destFileName == null) + { + throw CommonExceptions.FilenameCannotBeNull(nameof(destFileName)); + } + + mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(sourceFileName, nameof(sourceFileName)); + mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(destFileName, nameof(destFileName)); + + var sourceFile = mockFileDataAccessor.GetFile(sourceFileName); + + if (sourceFile == null) + { + throw CommonExceptions.FileNotFound(sourceFileName); + } + + if (!sourceFile.AllowedFileShare.HasFlag(FileShare.Delete)) + { + throw CommonExceptions.ProcessCannotAccessFileInUse(); + } + + VerifyDirectoryExists(destFileName); + + if (mockFileDataAccessor.GetFile(destFileName) != null) + { + if (mockFileDataAccessor.StringOperations.Equals(destFileName, sourceFileName)) + { + if (XFS.IsWindowsPlatform()) + { + mockFileDataAccessor.RemoveFile(sourceFileName); + mockFileDataAccessor.AddFile(destFileName, mockFileDataAccessor.AdjustTimes(new MockFileData(sourceFile), TimeAdjustments.LastAccessTime), false); + } + return; + } + else + { + throw new IOException("A file can not be created if it already exists."); + } + } + + mockFileDataAccessor.RemoveFile(sourceFileName, false); + mockFileDataAccessor.AddFile(destFileName, mockFileDataAccessor.AdjustTimes(new MockFileData(sourceFile), TimeAdjustments.LastAccessTime), false); + } + +#if FEATURE_FILE_MOVE_WITH_OVERWRITE + /// + public override void Move(string sourceFileName, string destFileName, bool overwrite) + { + if (sourceFileName == null) + { + throw CommonExceptions.FilenameCannotBeNull(nameof(sourceFileName)); + } + + if (destFileName == null) + { + throw CommonExceptions.FilenameCannotBeNull(nameof(destFileName)); + } + + mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(sourceFileName, nameof(sourceFileName)); + mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(destFileName, nameof(destFileName)); + + if (mockFileDataAccessor.GetFile(destFileName) != null) + { + if (destFileName.Equals(sourceFileName)) + { + return; + } + else if (!overwrite) + { + throw new IOException("A file can not be created if it already exists."); + } + } + + + var sourceFile = mockFileDataAccessor.GetFile(sourceFileName); + + if (sourceFile == null) + { + throw CommonExceptions.FileNotFound(sourceFileName); + } + if (!sourceFile.AllowedFileShare.HasFlag(FileShare.Delete)) + { + throw CommonExceptions.ProcessCannotAccessFileInUse(); + } + VerifyDirectoryExists(destFileName); + + mockFileDataAccessor.RemoveFile(sourceFileName); + mockFileDataAccessor.AddFile(destFileName, mockFileDataAccessor.AdjustTimes(new MockFileData(sourceFile), TimeAdjustments.LastAccessTime)); + } +#endif + + /// + public override FileSystemStream Open(string path, FileMode mode) + { + mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); + + return Open(path, mode, mode == FileMode.Append ? FileAccess.Write : FileAccess.ReadWrite, FileShare.None); + } + + /// + public override FileSystemStream Open(string path, FileMode mode, FileAccess access) + { + mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); + + return Open(path, mode, access, FileShare.None); + } + + /// + public override FileSystemStream Open(string path, FileMode mode, FileAccess access, FileShare share) => + OpenInternal(path, mode, access, FileOptions.None); + +#if FEATURE_FILESTREAM_OPTIONS + /// + public override FileSystemStream Open(string path, FileStreamOptions options) + { + return OpenInternal(path, options.Mode, options.Access, options.Options); + } +#endif + + private FileSystemStream OpenInternal( + string path, + FileMode mode, + FileAccess access, + FileOptions options) + { + mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); + + bool exists = mockFileDataAccessor.FileExists(path); + + if (mode == FileMode.CreateNew && exists) + { + throw CommonExceptions.FileAlreadyExists(path); + } + + if ((mode == FileMode.Open || mode == FileMode.Truncate) && !exists) + { + throw CommonExceptions.FileNotFound(path); + } + + if (!exists || mode == FileMode.CreateNew) + { + return CreateInternal(path, access, options); + } + + if (mode == FileMode.Create || mode == FileMode.Truncate) + { + Delete(path); + return CreateInternal(path, access, options); + } + + var mockFileData = mockFileDataAccessor.GetFile(path); + mockFileData.CheckFileAccess(path, access); + var timeAdjustments = TimeAdjustments.LastAccessTime; + if (access.HasFlag(FileAccess.Write)) + { + timeAdjustments |= TimeAdjustments.LastWriteTime; + } + mockFileDataAccessor.AdjustTimes(mockFileData, timeAdjustments); + + return new MockFileStream(mockFileDataAccessor, path, mode, access, FileShare.Read, options); + } + + /// + public override FileSystemStream OpenRead(string path) + { + mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); + + return Open(path, FileMode.Open, FileAccess.Read, FileShare.Read); + } + + /// + public override StreamReader OpenText(string path) + { + mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); + + return new StreamReader(OpenRead(path)); + } + + /// + public override FileSystemStream OpenWrite(string path) => OpenWriteInternal(path, FileOptions.None); + + private FileSystemStream OpenWriteInternal(string path, FileOptions options) + { + mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); + return OpenInternal(path, FileMode.OpenOrCreate, FileAccess.Write, options); + } + + /// + public override byte[] ReadAllBytes(string path) + { + mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); + + if (!mockFileDataAccessor.FileExists(path)) + { + throw CommonExceptions.FileNotFound(path); + } + mockFileDataAccessor.GetFile(path).CheckFileAccess(path, FileAccess.Read); + var fileData = mockFileDataAccessor.GetFile(path); + mockFileDataAccessor.AdjustTimes(fileData, TimeAdjustments.LastAccessTime); + return fileData.Contents.ToArray(); + } + + /// + public override string[] ReadAllLines(string path) + { + mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); + + if (!mockFileDataAccessor.FileExists(path)) + { + throw CommonExceptions.FileNotFound(path); + } + var fileData = mockFileDataAccessor.GetFile(path); + fileData.CheckFileAccess(path, FileAccess.Read); + mockFileDataAccessor.AdjustTimes(fileData, TimeAdjustments.LastAccessTime); + + return fileData + .TextContents + .SplitLines(); + } + + /// + public override string[] ReadAllLines(string path, Encoding encoding) + { + mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); + + if (encoding == null) + { + throw new ArgumentNullException(nameof(encoding)); + } + + if (!mockFileDataAccessor.FileExists(path)) + { + throw CommonExceptions.FileNotFound(path); + } + + var fileData = mockFileDataAccessor.GetFile(path); + fileData.CheckFileAccess(path, FileAccess.Read); + mockFileDataAccessor.AdjustTimes(fileData, TimeAdjustments.LastAccessTime); + + using (var ms = new MemoryStream(fileData.Contents)) + using (var sr = new StreamReader(ms, encoding)) + { + return sr.ReadToEnd().SplitLines(); + } + } + + /// + public override string ReadAllText(string path) + { + return ReadAllText(path, MockFileData.DefaultEncoding); + } + + /// + public override string ReadAllText(string path, Encoding encoding) + { + mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); + + if (!mockFileDataAccessor.FileExists(path)) + { + throw CommonExceptions.FileNotFound(path); + } + + if (encoding == null) + { + throw new ArgumentNullException(nameof(encoding)); + } + + return ReadAllTextInternal(path, encoding); + } + + /// + public override IEnumerable ReadLines(string path) + { + mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); + + return ReadAllLines(path); + } + + /// + public override IEnumerable ReadLines(string path, Encoding encoding) + { + mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); + VerifyValueIsNotNull(encoding, "encoding"); + + return ReadAllLines(path, encoding); + } + + /// + public override void Replace(string sourceFileName, string destinationFileName, string destinationBackupFileName) + { + Replace(sourceFileName, destinationFileName, destinationBackupFileName, false); + } + + /// + public override void Replace(string sourceFileName, string destinationFileName, string destinationBackupFileName, bool ignoreMetadataErrors) + { + if (sourceFileName == null) + { + throw new ArgumentNullException(nameof(sourceFileName)); + } + + if (destinationFileName == null) + { + throw new ArgumentNullException(nameof(destinationFileName)); + } + + if (!mockFileDataAccessor.FileExists(sourceFileName)) + { + throw CommonExceptions.FileNotFound(sourceFileName); + } + + if (!mockFileDataAccessor.FileExists(destinationFileName)) + { + throw CommonExceptions.FileNotFound(destinationFileName); + } + + if (mockFileDataAccessor.StringOperations.Equals(sourceFileName, destinationFileName) && XFS.IsWindowsPlatform()) + { + throw CommonExceptions.ProcessCannotAccessFileInUse(); + } + + if (destinationBackupFileName != null) + { + Copy(destinationFileName, destinationBackupFileName, overwrite: true); + } + + Delete(destinationFileName); + Move(sourceFileName, destinationFileName); + } + +#if FEATURE_CREATE_SYMBOLIC_LINK + /// + public override IFileSystemInfo ResolveLinkTarget(string linkPath, bool returnFinalTarget) + { + var initialContainer = mockFileDataAccessor.GetFile(linkPath); + if (initialContainer.LinkTarget != null) + { + var nextLocation = initialContainer.LinkTarget; + var nextContainer = mockFileDataAccessor.GetFile(nextLocation); + + if (returnFinalTarget) + { + // The maximum number of symbolic links that are followed: + // https://learn.microsoft.com/en-us/dotnet/api/system.io.directory.resolvelinktarget?view=net-6.0#remarks + int maxResolveLinks = XFS.IsWindowsPlatform() ? 63 : 40; + for (int i = 1; i < maxResolveLinks; i++) + { + if (nextContainer.LinkTarget == null) + { + break; + } + nextLocation = nextContainer.LinkTarget; + nextContainer = mockFileDataAccessor.GetFile(nextLocation); + } + + if (nextContainer.LinkTarget != null) + { + throw CommonExceptions.NameCannotBeResolvedByTheSystem(linkPath); + } + } + + if (nextContainer.IsDirectory) + { + return new MockDirectoryInfo(mockFileDataAccessor, nextLocation); + } + else + { + return new MockFileInfo(mockFileDataAccessor, nextLocation); + } + } + throw CommonExceptions.NameCannotBeResolvedByTheSystem(linkPath); + } +#endif + + /// + public override void SetAttributes(string path, FileAttributes fileAttributes) + { + mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); + + var possibleFileData = mockFileDataAccessor.GetFile(path); + if (possibleFileData == null) + { + var directoryInfo = mockFileDataAccessor.DirectoryInfo.New(path); + if (directoryInfo.Exists) + { + directoryInfo.Attributes = fileAttributes; + } + else + { + throw CommonExceptions.FileNotFound(path); + } + } + else + { + mockFileDataAccessor.AdjustTimes(possibleFileData, TimeAdjustments.LastAccessTime); + possibleFileData.Attributes = fileAttributes; + } + } + +#if FEATURE_FILE_ATTRIBUTES_VIA_HANDLE + /// + public override void SetAttributes(SafeFileHandle fileHandle, FileAttributes fileAttributes) + { + throw CommonExceptions.NotImplemented(); + } +#endif + + /// + public override void SetCreationTime(string path, DateTime creationTime) + { + mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); + + mockFileDataAccessor.GetFile(path).CreationTime = new DateTimeOffset(creationTime); + } + +#if FEATURE_FILE_ATTRIBUTES_VIA_HANDLE + /// + public override void SetCreationTime(SafeFileHandle fileHandle, DateTime creationTime) + { + throw CommonExceptions.NotImplemented(); + } +#endif + + /// + public override void SetCreationTimeUtc(string path, DateTime creationTimeUtc) + { + mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); + + mockFileDataAccessor.GetFile(path).CreationTime = new DateTimeOffset(creationTimeUtc, TimeSpan.Zero); + } + +#if FEATURE_FILE_ATTRIBUTES_VIA_HANDLE + /// + public override void SetCreationTimeUtc(SafeFileHandle fileHandle, DateTime creationTimeUtc) + { + throw CommonExceptions.NotImplemented(); + } +#endif + + /// + public override void SetLastAccessTime(string path, DateTime lastAccessTime) + { + mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); + + mockFileDataAccessor.GetFile(path).LastAccessTime = new DateTimeOffset(lastAccessTime); + } + +#if FEATURE_FILE_ATTRIBUTES_VIA_HANDLE + /// + public override void SetLastAccessTime(SafeFileHandle fileHandle, DateTime lastAccessTime) + { + throw CommonExceptions.NotImplemented(); + } +#endif + + /// + public override void SetLastAccessTimeUtc(string path, DateTime lastAccessTimeUtc) + { + mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); + + mockFileDataAccessor.GetFile(path).LastAccessTime = new DateTimeOffset(lastAccessTimeUtc, TimeSpan.Zero); + } + +#if FEATURE_FILE_ATTRIBUTES_VIA_HANDLE + /// + public override void SetLastAccessTimeUtc(SafeFileHandle fileHandle, DateTime lastAccessTimeUtc) + { + throw CommonExceptions.NotImplemented(); + } +#endif + + /// + public override void SetLastWriteTime(string path, DateTime lastWriteTime) + { + mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); + + mockFileDataAccessor.GetFile(path).LastWriteTime = new DateTimeOffset(lastWriteTime); + } + +#if FEATURE_FILE_ATTRIBUTES_VIA_HANDLE + /// + public override void SetLastWriteTime(SafeFileHandle fileHandle, DateTime lastWriteTime) + { + throw CommonExceptions.NotImplemented(); + } +#endif + + /// + public override void SetLastWriteTimeUtc(string path, DateTime lastWriteTimeUtc) + { + mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); + + mockFileDataAccessor.GetFile(path).LastWriteTime = new DateTimeOffset(lastWriteTimeUtc, TimeSpan.Zero); + } + +#if FEATURE_FILE_ATTRIBUTES_VIA_HANDLE + /// + public override void SetLastWriteTimeUtc(SafeFileHandle fileHandle, DateTime lastWriteTimeUtc) + { + throw CommonExceptions.NotImplemented(); + } +#endif + +#if FEATURE_UNIX_FILE_MODE + /// + public override void SetUnixFileMode(string path, UnixFileMode mode) + { + mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); + + if (!mockFileDataAccessor.FileExists(path)) + { + throw CommonExceptions.FileNotFound(path); + } + + var mockFileData = mockFileDataAccessor.GetFile(path); + mockFileData.UnixMode = mode; + } +#endif + +#if FEATURE_FILE_ATTRIBUTES_VIA_HANDLE + /// + public override void SetUnixFileMode(SafeFileHandle fileHandle, UnixFileMode mode) + { + throw CommonExceptions.NotImplemented(); + } +#endif + + /// + /// Creates a new file, writes the specified byte array to the file, and then closes the file. + /// If the target file already exists, it is overwritten. + /// + /// The file to write to. + /// The bytes to write to the file. + /// is a zero-length string, contains only white space, or contains one or more invalid characters as defined by . + /// is or contents is empty. + /// + /// The specified path, file name, or both exceed the system-defined maximum length. + /// For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters. + /// + /// The specified path is invalid (for example, it is on an unmapped drive). + /// An I/O error occurred while opening the file. + /// + /// path specified a file that is read-only. + /// -or- + /// This operation is not supported on the current platform. + /// -or- + /// path specified a directory. + /// -or- + /// The caller does not have the required permission. + /// + /// The file specified in was not found. + /// is in an invalid format. + /// The caller does not have the required permission. + /// + /// Given a byte array and a file path, this method opens the specified file, writes the contents of the byte array to the file, and then closes the file. + /// + public override void WriteAllBytes(string path, byte[] bytes) + { + VerifyValueIsNotNull(bytes, "bytes"); + + mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); + VerifyDirectoryExists(path); + + mockFileDataAccessor.AddFile(path, mockFileDataAccessor.AdjustTimes(new MockFileData(bytes.ToArray()), TimeAdjustments.All)); + } + +#if FEATURE_FILE_SPAN + /// + public override void WriteAllBytes(string path, ReadOnlySpan bytes) + { + WriteAllBytes(path, bytes.ToArray()); + } +#endif + + /// + /// Creates a new file, writes a collection of strings to the file, and then closes the file. + /// + /// The file to write to. + /// The lines to write to the file. + /// is a zero-length string, contains only white space, or contains one or more invalid characters as defined by . + /// Either or is . + /// The specified path is invalid (for example, it is on an unmapped drive). + /// The file specified in was not found. + /// An I/O error occurred while opening the file. + /// + /// The specified path, file name, or both exceed the system-defined maximum length. + /// For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters. + /// + /// is in an invalid format. + /// The caller does not have the required permission. + /// + /// specified a file that is read-only. + /// -or- + /// This operation is not supported on the current platform. + /// -or- + /// specified a directory. + /// -or- + /// The caller does not have the required permission. + /// + /// + /// + /// If the target file already exists, it is overwritten. + /// + /// + /// You can use this method to create the contents for a collection class that takes an in its constructor, such as a , , or a class. + /// + /// + public override void WriteAllLines(string path, IEnumerable contents) + { + mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); + VerifyValueIsNotNull(contents, "contents"); + + WriteAllLines(path, contents, MockFileData.DefaultEncoding); + } + + /// + /// Creates a new file by using the specified encoding, writes a collection of strings to the file, and then closes the file. + /// + /// The file to write to. + /// The lines to write to the file. + /// The character encoding to use. + /// is a zero-length string, contains only white space, or contains one or more invalid characters as defined by . + /// Either , , or is . + /// The specified path is invalid (for example, it is on an unmapped drive). + /// The file specified in was not found. + /// An I/O error occurred while opening the file. + /// + /// The specified path, file name, or both exceed the system-defined maximum length. + /// For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters. + /// + /// is in an invalid format. + /// The caller does not have the required permission. + /// + /// specified a file that is read-only. + /// -or- + /// This operation is not supported on the current platform. + /// -or- + /// specified a directory. + /// -or- + /// The caller does not have the required permission. + /// + /// + /// + /// If the target file already exists, it is overwritten. + /// + /// + /// You can use this method to create a file that contains the following: + /// + /// + /// The results of a LINQ to Objects query on the lines of a file, as obtained by using the ReadLines method. + /// + /// + /// The contents of a collection that implements an of strings. + /// + /// + /// + /// + public override void WriteAllLines(string path, IEnumerable contents, Encoding encoding) + { + mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); + VerifyValueIsNotNull(contents, "contents"); + VerifyValueIsNotNull(encoding, "encoding"); + + var sb = new StringBuilder(); + foreach (var line in contents) + { + sb.AppendLine(line); + } + + WriteAllText(path, sb.ToString(), encoding); + } + + /// + /// Creates a new file, writes the specified string array to the file by using the specified encoding, and then closes the file. + /// + /// The file to write to. + /// The string array to write to the file. + /// is a zero-length string, contains only white space, or contains one or more invalid characters as defined by . + /// Either or is . + /// + /// The specified path, file name, or both exceed the system-defined maximum length. + /// For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters. + /// + /// The specified path is invalid (for example, it is on an unmapped drive). + /// An I/O error occurred while opening the file. + /// + /// specified a file that is read-only. + /// -or- + /// This operation is not supported on the current platform. + /// -or- + /// specified a directory. + /// -or- + /// The caller does not have the required permission. + /// + /// The file specified in was not found. + /// is in an invalid format. + /// The caller does not have the required permission. + /// + /// + /// If the target file already exists, it is overwritten. + /// + /// + /// The default behavior of the WriteAllLines method is to write out data using UTF-8 encoding without a byte order mark (BOM). If it is necessary to include a UTF-8 identifier, such as a byte order mark, at the beginning of a file, use the method overload with encoding. + /// + /// + /// Given a string array and a file path, this method opens the specified file, writes the string array to the file using the specified encoding, + /// and then closes the file. + /// + /// + public override void WriteAllLines(string path, string[] contents) + { + mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); + VerifyValueIsNotNull(contents, "contents"); + + WriteAllLines(path, contents, MockFileData.DefaultEncoding); + } + + /// + /// Creates a new file, writes the specified string array to the file by using the specified encoding, and then closes the file. + /// + /// The file to write to. + /// The string array to write to the file. + /// An object that represents the character encoding applied to the string array. + /// is a zero-length string, contains only white space, or contains one or more invalid characters as defined by . + /// Either or is . + /// + /// The specified path, file name, or both exceed the system-defined maximum length. + /// For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters. + /// + /// The specified path is invalid (for example, it is on an unmapped drive). + /// An I/O error occurred while opening the file. + /// + /// specified a file that is read-only. + /// -or- + /// This operation is not supported on the current platform. + /// -or- + /// specified a directory. + /// -or- + /// The caller does not have the required permission. + /// + /// The file specified in was not found. + /// is in an invalid format. + /// The caller does not have the required permission. + /// + /// + /// If the target file already exists, it is overwritten. + /// + /// + /// Given a string array and a file path, this method opens the specified file, writes the string array to the file using the specified encoding, + /// and then closes the file. + /// + /// + public override void WriteAllLines(string path, string[] contents, Encoding encoding) + { + mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); + VerifyValueIsNotNull(contents, "contents"); + VerifyValueIsNotNull(encoding, "encoding"); + + WriteAllLines(path, new List(contents), encoding); + } + + /// + /// Creates a new file, writes the specified string to the file using the specified encoding, and then closes the file. If the target file already exists, it is overwritten. + /// + /// The file to write to. + /// The string to write to the file. + /// is a zero-length string, contains only white space, or contains one or more invalid characters as defined by . + /// is or contents is empty. + /// + /// The specified path, file name, or both exceed the system-defined maximum length. + /// For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters. + /// + /// The specified path is invalid (for example, it is on an unmapped drive). + /// An I/O error occurred while opening the file. + /// + /// path specified a file that is read-only. + /// -or- + /// This operation is not supported on the current platform. + /// -or- + /// path specified a directory. + /// -or- + /// The caller does not have the required permission. + /// + /// The file specified in was not found. + /// is in an invalid format. + /// The caller does not have the required permission. + /// + /// This method uses UTF-8 encoding without a Byte-Order Mark (BOM), so using the method will return an empty byte array. + /// If it is necessary to include a UTF-8 identifier, such as a byte order mark, at the beginning of a file, use the method overload with encoding. + /// + /// Given a string and a file path, this method opens the specified file, writes the string to the file, and then closes the file. + /// + /// + public override void WriteAllText(string path, string contents) + { + WriteAllText(path, contents, MockFileData.DefaultEncoding); + } + + /// + /// Creates a new file, writes the specified string to the file using the specified encoding, and then closes the file. If the target file already exists, it is overwritten. + /// + /// The file to write to. + /// The string to write to the file. + /// The encoding to apply to the string. + /// is a zero-length string, contains only white space, or contains one or more invalid characters as defined by . + /// is or contents is empty. + /// + /// The specified path, file name, or both exceed the system-defined maximum length. + /// For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters. + /// + /// The specified path is invalid (for example, it is on an unmapped drive). + /// An I/O error occurred while opening the file. + /// + /// path specified a file that is read-only. + /// -or- + /// This operation is not supported on the current platform. + /// -or- + /// path specified a directory. + /// -or- + /// The caller does not have the required permission. + /// + /// The file specified in was not found. + /// is in an invalid format. + /// The caller does not have the required permission. + /// + /// Given a string and a file path, this method opens the specified file, writes the string to the file using the specified encoding, and then closes the file. + /// The file handle is guaranteed to be closed by this method, even if exceptions are raised. + /// + public override void WriteAllText(string path, string contents, Encoding encoding) + { + mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); + VerifyValueIsNotNull(path, "path"); + + if (mockFileDataAccessor.Directory.Exists(path)) + { + throw CommonExceptions.AccessDenied(path); + } + + VerifyDirectoryExists(path); + + MockFileData data = contents == null ? new MockFileData(new byte[0]) : new MockFileData(contents, encoding); + mockFileDataAccessor.AddFile(path, mockFileDataAccessor.AdjustTimes(data, TimeAdjustments.All)); + } + +#if FEATURE_FILE_SPAN + /// + public override void WriteAllText(string path, ReadOnlySpan contents) + { + WriteAllText(path, contents.ToString()); + } + + /// + public override void WriteAllText(string path, ReadOnlySpan contents, Encoding encoding) + { + WriteAllText(path, contents.ToString(), encoding); + } +#endif + + internal static string ReadAllBytes(byte[] contents, Encoding encoding) + { + using (var ms = new MemoryStream(contents)) + using (var sr = new StreamReader(ms, encoding)) + { + return sr.ReadToEnd(); + } + } + + private string ReadAllTextInternal(string path, Encoding encoding) + { + var mockFileData = mockFileDataAccessor.GetFile(path); + mockFileData.CheckFileAccess(path, FileAccess.Read); + mockFileDataAccessor.AdjustTimes(mockFileData, TimeAdjustments.LastAccessTime); + return ReadAllBytes(mockFileData.Contents, encoding); + } + + private void VerifyValueIsNotNull(object value, string parameterName) + { + if (value == null) + { + throw new ArgumentNullException(parameterName, StringResources.Manager.GetString("VALUE_CANNOT_BE_NULL")); + } + } + + private void VerifyDirectoryExists(string path) + { + var pathOps = mockFileDataAccessor.Path; + var dir = pathOps.GetDirectoryName(pathOps.GetFullPath(path)); + + if (!mockFileDataAccessor.Directory.Exists(dir)) + { + throw CommonExceptions.CouldNotFindPartOfPath(path); + } + } +} \ No newline at end of file diff --git a/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockFileData.cs b/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockFileData.cs new file mode 100644 index 000000000..ea15019a1 --- /dev/null +++ b/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockFileData.cs @@ -0,0 +1,245 @@ +using System.Linq; +using System.Runtime.Versioning; +using System.Security.AccessControl; +using System.Text; + +namespace System.IO.Abstractions.TestingHelpers; + +/// +/// The class represents the associated data of a file. +/// +#if FEATURE_SERIALIZABLE +[Serializable] +#endif +public class MockFileData +{ + /// + /// The default encoding. + /// + public static readonly Encoding DefaultEncoding = new UTF8Encoding(false, true); + + /// + /// The null object. It represents the data of a non-existing file or directory. + /// + internal static readonly MockFileData NullObject = new MockFileData(string.Empty) + { + LastWriteTime = new DateTime(1601, 01, 01, 00, 00, 00, DateTimeKind.Utc), + LastAccessTime = new DateTime(1601, 01, 01, 00, 00, 00, DateTimeKind.Utc), + CreationTime = new DateTime(1601, 01, 01, 00, 00, 00, DateTimeKind.Utc), + Attributes = (FileAttributes)(-1), + }; + + /// + /// Gets the default date time offset. + /// E.g. for not existing files. + /// + public static readonly DateTimeOffset DefaultDateTimeOffset = new DateTime(1601, 01, 01, 00, 00, 00, DateTimeKind.Utc); + + /// + /// The access control of the . + /// +#if FEATURE_SERIALIZABLE + [NonSerialized] +#endif + private FileSecurity accessControl; + + /// + /// Gets a value indicating whether the is a directory or not. + /// + public bool IsDirectory { get { return Attributes.HasFlag(FileAttributes.Directory); } } + + /// + /// Initializes a new instance of the class with an empty content. + /// + private MockFileData() + { + var now = DateTime.UtcNow; + LastWriteTime = now; + LastAccessTime = now; + CreationTime = now; + } + + /// + /// Initializes a new instance of the class with the content of using the encoding of . + /// + /// The textual content encoded into bytes with . + public MockFileData(string textContents) + : this(DefaultEncoding.GetBytes(textContents)) + { } + + /// + /// Initializes a new instance of the class with the content of using the encoding of . + /// + /// The textual content. + /// The specific encoding used the encode the text. + /// The constructor respect the BOM of . + public MockFileData(string textContents, Encoding encoding) + : this() + { + Contents = encoding.GetPreamble().Concat(encoding.GetBytes(textContents)).ToArray(); + } + + /// + /// Initializes a new instance of the class with the content of . + /// + /// The actual content. + /// Thrown if is . + public MockFileData(byte[] contents) + : this() + { + Contents = contents ?? throw new ArgumentNullException(nameof(contents)); + } + + + /// + /// Initializes a new instance of the class by copying the given . + /// + /// The template instance. + /// Thrown if is . + public MockFileData(MockFileData template) + { + if (template == null) + { + throw new ArgumentNullException(nameof(template)); + } + + accessControl = template.accessControl; + Attributes = template.Attributes; + Contents = template.Contents.ToArray(); + CreationTime = template.CreationTime; + LastAccessTime = template.LastAccessTime; + LastWriteTime = template.LastWriteTime; +#if FEATURE_FILE_SYSTEM_INFO_LINK_TARGET + LinkTarget = template.LinkTarget; +#endif + } + + /// + /// Gets or sets the byte contents of the . + /// + public byte[] Contents { get; set; } + + /// + /// Gets or sets the file version info of the + /// + public IFileVersionInfo FileVersionInfo { get; set; } + + /// + /// Gets or sets the string contents of the . + /// + /// + /// The setter uses the using this can scramble the actual contents. + /// + public string TextContents + { + get { return MockFile.ReadAllBytes(Contents, DefaultEncoding); } + set { Contents = DefaultEncoding.GetBytes(value); } + } + + /// + /// Gets or sets the date and time the was created. + /// + public DateTimeOffset CreationTime + { + get { return creationTime; } + set { creationTime = value.ToUniversalTime(); } + } + private DateTimeOffset creationTime; + + /// + /// Gets or sets the date and time of the was last accessed to. + /// + public DateTimeOffset LastAccessTime + { + get { return lastAccessTime; } + set { lastAccessTime = value.ToUniversalTime(); } + } + private DateTimeOffset lastAccessTime; + + /// + /// Gets or sets the date and time of the was last written to. + /// + public DateTimeOffset LastWriteTime + { + get { return lastWriteTime; } + set { lastWriteTime = value.ToUniversalTime(); } + } + private DateTimeOffset lastWriteTime; + +#if FEATURE_FILE_SYSTEM_INFO_LINK_TARGET + /// + /// Gets or sets the link target of the . + /// + public string LinkTarget { get; set; } +#endif + + /// + /// Casts a string into . + /// + /// The path of the to be created. + public static implicit operator MockFileData(string s) + { + return new MockFileData(s); + } + + /// + /// Gets or sets the specified of the . + /// + public FileAttributes Attributes { get; set; } = FileAttributes.Normal; + + /// + /// Gets or sets of the . + /// + [SupportedOSPlatform("windows")] + public FileSecurity AccessControl + { + get + { + // FileSecurity's constructor will throw PlatformNotSupportedException on non-Windows platform, so we initialize it in lazy way. + // This let's us use this class as long as we don't use AccessControl property. + return accessControl ?? (accessControl = new FileSecurity()); + } + set { accessControl = value; } + } + + /// + /// Gets or sets the File sharing mode for this file, this allows you to lock a file for reading or writing. + /// + public FileShare AllowedFileShare { get; set; } = FileShare.ReadWrite | FileShare.Delete; + +#if FEATURE_UNIX_FILE_MODE + /// + /// Gets or sets the Unix file mode (permissions) for this file. + /// This allows you to configure the read, write and execute access for user, group and other. + /// + public UnixFileMode UnixMode { get; set; } = UnixFileMode.UserRead | UnixFileMode.GroupRead | + UnixFileMode.OtherRead | UnixFileMode.UserWrite; +#endif + + /// + /// Checks whether the file is accessible for this type of FileAccess. + /// MockFileData can be configured to have FileShare.None, which indicates it is locked by a 'different process'. + /// + /// If the file is 'locked by a different process', an IOException will be thrown. + /// If the file is read-only and is accessed for writing, an UnauthorizedAccessException will be thrown. + /// + /// The path is used in the exception message to match the message in real life situations + /// The access type to check + internal void CheckFileAccess(string path, FileAccess access) + { + if (!AllowedFileShare.HasFlag((FileShare)access)) + { + throw CommonExceptions.ProcessCannotAccessFileInUse(path); + } + + if (Attributes.HasFlag(FileAttributes.ReadOnly) && access.HasFlag(FileAccess.Write)) + { + throw CommonExceptions.AccessDenied(path); + } + } + + internal virtual MockFileData Clone() + { + return new MockFileData(this); + } +} \ No newline at end of file diff --git a/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockFileInfo.cs b/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockFileInfo.cs new file mode 100644 index 000000000..188ea3e0a --- /dev/null +++ b/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockFileInfo.cs @@ -0,0 +1,442 @@ +using System.Runtime.Versioning; +using System.Security.AccessControl; + +namespace System.IO.Abstractions.TestingHelpers; + +/// +#if FEATURE_SERIALIZABLE +[Serializable] +#endif +public class MockFileInfo : FileInfoBase, IFileSystemAclSupport +{ + private readonly IMockFileDataAccessor mockFileSystem; + private string path; + private readonly string originalPath; + private MockFileData cachedMockFileData; + private MockFile mockFile; + private bool refreshOnNextRead; + + /// + public MockFileInfo(IMockFileDataAccessor mockFileSystem, string path) : base(mockFileSystem?.FileSystem) + { + this.mockFileSystem = mockFileSystem ?? throw new ArgumentNullException(nameof(mockFileSystem)); + mockFileSystem.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); + this.originalPath = path; + this.path = mockFileSystem.Path.GetFullPath(path); + this.mockFile = new MockFile(mockFileSystem); + Refresh(); + } + +#if FEATURE_CREATE_SYMBOLIC_LINK + /// + public override void CreateAsSymbolicLink(string pathToTarget) + { + FileSystem.File.CreateSymbolicLink(FullName, pathToTarget); + } +#endif + + /// + public override void Delete() + { + refreshOnNextRead = true; + mockFile.Delete(path); + } + + /// + public override void Refresh() + { + var mockFileData = mockFileSystem.GetFile(path)?.Clone(); + cachedMockFileData = mockFileData ?? MockFileData.NullObject.Clone(); + } + +#if FEATURE_CREATE_SYMBOLIC_LINK + /// + public override IFileSystemInfo ResolveLinkTarget(bool returnFinalTarget) + { + return FileSystem.File.ResolveLinkTarget(FullName, returnFinalTarget); + } +#endif + + /// + public override FileAttributes Attributes + { + get + { + var mockFileData = GetMockFileDataForRead(); + return mockFileData.Attributes; + } + set + { + var mockFileData = GetMockFileDataForWrite(); + mockFileData.Attributes = value & ~FileAttributes.Directory; + } + } + + /// + public override DateTime CreationTime + { + get + { + var mockFileData = GetMockFileDataForRead(); + return mockFileData.CreationTime.LocalDateTime; + } + set + { + var mockFileData = GetMockFileDataForWrite(); + mockFileData.CreationTime = AdjustUnspecifiedKind(value, DateTimeKind.Local); + } + } + + /// + public override DateTime CreationTimeUtc + { + get + { + var mockFileData = GetMockFileDataForRead(); + return mockFileData.CreationTime.UtcDateTime; + } + set + { + var mockFileData = GetMockFileDataForWrite(); + mockFileData.CreationTime = AdjustUnspecifiedKind(value, DateTimeKind.Utc); + } + } + + /// + public override bool Exists + { + get + { + var mockFileData = GetMockFileDataForRead(); + return (int)mockFileData.Attributes != -1 && !mockFileData.IsDirectory; + } + } + + /// + public override string Extension + { + get + { + // System.IO.Path.GetExtension does only string manipulation, + // so it's safe to delegate. + return Path.GetExtension(path); + } + } + + /// + public override string FullName + { + get { return path; } + } + + /// + public override DateTime LastAccessTime + { + get + { + var mockFileData = GetMockFileDataForRead(); + return mockFileData.LastAccessTime.LocalDateTime; + } + set + { + var mockFileData = GetMockFileDataForWrite(); + mockFileData.LastAccessTime = AdjustUnspecifiedKind(value, DateTimeKind.Local); + } + } + + /// + public override DateTime LastAccessTimeUtc + { + get + { + var mockFileData = GetMockFileDataForRead(); + return mockFileData.LastAccessTime.UtcDateTime; + } + set + { + var mockFileData = GetMockFileDataForWrite(); + mockFileData.LastAccessTime = AdjustUnspecifiedKind(value, DateTimeKind.Utc); + } + } + + /// + public override DateTime LastWriteTime + { + get + { + var mockFileData = GetMockFileDataForRead(); + return mockFileData.LastWriteTime.LocalDateTime; + } + set + { + var mockFileData = GetMockFileDataForWrite(); + mockFileData.LastWriteTime = AdjustUnspecifiedKind(value, DateTimeKind.Local); + } + } + + /// + public override DateTime LastWriteTimeUtc + { + get + { + var mockFileData = GetMockFileDataForRead(); + return mockFileData.LastWriteTime.UtcDateTime; + } + set + { + var mockFileData = GetMockFileDataForWrite(); + mockFileData.LastWriteTime = AdjustUnspecifiedKind(value, DateTimeKind.Utc); + } + } + +#if FEATURE_FILE_SYSTEM_INFO_LINK_TARGET + /// + public override string LinkTarget + { + get + { + var mockFileData = GetMockFileDataForRead(); + return mockFileData.LinkTarget; + } + } +#endif + + /// + public override string Name + { + get { return new MockPath(mockFileSystem).GetFileName(path); } + } + + /// + public override StreamWriter AppendText() + { + return new StreamWriter(new MockFileStream(mockFileSystem, FullName, FileMode.Append, FileAccess.Write)); + } + + /// + public override IFileInfo CopyTo(string destFileName) + { + return CopyTo(destFileName, false); + } + + /// + public override IFileInfo CopyTo(string destFileName, bool overwrite) + { + if (destFileName == FullName) + { + return this; + } + mockFile.Copy(FullName, destFileName, overwrite); + return mockFileSystem.FileInfo.New(destFileName); + } + + /// + public override FileSystemStream Create() + { + var result = mockFile.Create(FullName); + refreshOnNextRead = true; + return result; + } + + /// + public override StreamWriter CreateText() + { + var result = mockFile.CreateText(FullName); + refreshOnNextRead = true; + return result; + } + + /// + public override void Decrypt() + { + var mockFileData = GetMockFileDataForWrite(); + mockFileData.Attributes &= ~FileAttributes.Encrypted; + } + + /// + public override void Encrypt() + { + var mockFileData = GetMockFileDataForWrite(); + mockFileData.Attributes |= FileAttributes.Encrypted; + } + + /// + public override void MoveTo(string destFileName) + { + mockFile.Move(path, destFileName); + path = mockFileSystem.Path.GetFullPath(destFileName); + } + +#if FEATURE_FILE_MOVE_WITH_OVERWRITE + /// + public override void MoveTo(string destFileName, bool overwrite) + { + mockFile.Move(path, destFileName, overwrite); + path = mockFileSystem.Path.GetFullPath(destFileName); + } +#endif + + /// + public override FileSystemStream Open(FileMode mode) + { + return mockFile.Open(FullName, mode); + } + + /// + public override FileSystemStream Open(FileMode mode, FileAccess access) + { + return mockFile.Open(FullName, mode, access); + } + + /// + public override FileSystemStream Open(FileMode mode, FileAccess access, FileShare share) + { + return mockFile.Open(FullName, mode, access, share); + } + +#if FEATURE_FILESTREAM_OPTIONS + /// + public override FileSystemStream Open(FileStreamOptions options) + { + return mockFile.Open(FullName, options.Mode, options.Access, options.Share); + } +#endif + + /// + public override FileSystemStream OpenRead() => mockFile.OpenRead(path); + + /// + public override StreamReader OpenText() => mockFile.OpenText(path); + + /// + public override FileSystemStream OpenWrite() => mockFile.OpenWrite(path); + + /// + public override IFileInfo Replace(string destinationFileName, string destinationBackupFileName) + { + return Replace(destinationFileName, destinationBackupFileName, false); + } + + /// + public override IFileInfo Replace(string destinationFileName, string destinationBackupFileName, bool ignoreMetadataErrors) + { + mockFile.Replace(path, destinationFileName, destinationBackupFileName, ignoreMetadataErrors); + return mockFileSystem.FileInfo.New(destinationFileName); + } + + /// + public override IDirectoryInfo Directory + { + get + { + return mockFileSystem.DirectoryInfo.New(DirectoryName); + } + } + + /// + public override string DirectoryName + { + get + { + // System.IO.Path.GetDirectoryName does only string manipulation, + // so it's safe to delegate. + return Path.GetDirectoryName(path); + } + } + + /// + public override bool IsReadOnly + { + get + { + var mockFileData = GetMockFileDataForRead(); + return (mockFileData.Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly; + } + set + { + var mockFileData = GetMockFileDataForWrite(); + if (value) + { + mockFileData.Attributes |= FileAttributes.ReadOnly; + } + else + { + mockFileData.Attributes &= ~FileAttributes.ReadOnly; + } + } + } + + /// + public override long Length + { + get + { + var mockFileData = GetMockFileDataForRead(); + if (mockFileData == null || mockFileData.IsDirectory) + { + throw CommonExceptions.FileNotFound(path); + } + return mockFileData.Contents.Length; + } + } + + /// + public override string ToString() + { + return originalPath; + } + + /// + [SupportedOSPlatform("windows")] + public object GetAccessControl() + { + return GetMockFileData().AccessControl; + } + + /// + [SupportedOSPlatform("windows")] + public object GetAccessControl(IFileSystemAclSupport.AccessControlSections includeSections) + { + return GetMockFileData().AccessControl; + } + + /// + [SupportedOSPlatform("windows")] + public void SetAccessControl(object value) + { + GetMockFileData().AccessControl = value as FileSecurity; + } + + private MockFileData GetMockFileData() + { + return mockFileSystem.GetFile(path) + ?? throw CommonExceptions.FileNotFound(path); + } + + private static DateTime AdjustUnspecifiedKind(DateTime time, DateTimeKind fallbackKind) + { + if (time.Kind == DateTimeKind.Unspecified) + { + return DateTime.SpecifyKind(time, fallbackKind); + } + + return time; + } + + private MockFileData GetMockFileDataForRead() + { + if (refreshOnNextRead) + { + Refresh(); + refreshOnNextRead = false; + } + return cachedMockFileData; + } + + private MockFileData GetMockFileDataForWrite() + { + refreshOnNextRead = true; + return mockFileSystem.GetFile(path) + ?? throw CommonExceptions.FileNotFound(path); + } +} \ No newline at end of file diff --git a/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockFileInfoFactory.cs b/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockFileInfoFactory.cs new file mode 100644 index 000000000..7d72ffa7c --- /dev/null +++ b/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockFileInfoFactory.cs @@ -0,0 +1,37 @@ +namespace System.IO.Abstractions.TestingHelpers; + +/// +#if FEATURE_SERIALIZABLE +[Serializable] +#endif +public class MockFileInfoFactory : IFileInfoFactory +{ + private readonly IMockFileDataAccessor mockFileSystem; + + /// + public MockFileInfoFactory(IMockFileDataAccessor mockFileSystem) + { + this.mockFileSystem = mockFileSystem ?? throw new ArgumentNullException(nameof(mockFileSystem)); + } + + /// + public IFileSystem FileSystem + => mockFileSystem; + + /// + public IFileInfo New(string fileName) + { + return new MockFileInfo(mockFileSystem, fileName); + } + + /// + public IFileInfo Wrap(FileInfo fileInfo) + { + if (fileInfo == null) + { + return null; + } + + return new MockFileInfo(mockFileSystem, fileInfo.FullName); + } +} \ No newline at end of file diff --git a/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockFileStream.cs b/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockFileStream.cs new file mode 100644 index 000000000..c633dd8ef --- /dev/null +++ b/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockFileStream.cs @@ -0,0 +1,348 @@ +using System.Threading.Tasks; +using System.Threading; +using System.Runtime.Versioning; +using System.Security.AccessControl; + +namespace System.IO.Abstractions.TestingHelpers; + +/// +#if FEATURE_SERIALIZABLE +[Serializable] +#endif +public class MockFileStream : FileSystemStream, IFileSystemAclSupport +{ + /// + /// Wrapper around a with no backing store, which + /// is used as a replacement for a . As such + /// it implements the same properties and methods as a . + /// + public new static FileSystemStream Null { get; } = new NullFileSystemStream(); + + private class NullFileSystemStream : FileSystemStream + { + /// + /// Initializes a new instance of . + /// + public NullFileSystemStream() : base(Null, ".", true) + { + + } + } + + private readonly IMockFileDataAccessor mockFileDataAccessor; + private readonly string path; + private readonly Guid guid = Guid.NewGuid(); + private readonly FileAccess access = FileAccess.ReadWrite; + private readonly FileShare share = FileShare.Read; + private readonly FileOptions options; + private readonly MockFileData fileData; + private bool disposed; + + /// + public MockFileStream( + IMockFileDataAccessor mockFileDataAccessor, + string path, + FileMode mode, + FileAccess access = FileAccess.ReadWrite, + FileShare share = FileShare.Read, + FileOptions options = FileOptions.None) + : base(new MemoryStream(), + path == null ? null : Path.GetFullPath(path), + (options & FileOptions.Asynchronous) != 0) + + { + ThrowIfInvalidModeAccess(mode, access); + + this.mockFileDataAccessor = mockFileDataAccessor ?? throw new ArgumentNullException(nameof(mockFileDataAccessor)); + path = mockFileDataAccessor.PathVerifier.FixPath(path); + this.path = path; + this.options = options; + + if (mockFileDataAccessor.FileExists(path)) + { + if (mode.Equals(FileMode.CreateNew)) + { + throw CommonExceptions.FileAlreadyExists(path); + } + + fileData = mockFileDataAccessor.GetFile(path); + fileData.CheckFileAccess(path, access); + + var timeAdjustments = GetTimeAdjustmentsForFileStreamWhenFileExists(mode, access); + mockFileDataAccessor.AdjustTimes(fileData, timeAdjustments); + var existingContents = fileData.Contents; + var keepExistingContents = + existingContents?.Length > 0 && + mode != FileMode.Truncate && mode != FileMode.Create; + if (keepExistingContents) + { + base.Write(existingContents, 0, existingContents.Length); + base.Seek(0, mode == FileMode.Append + ? SeekOrigin.End + : SeekOrigin.Begin); + } + } + else + { + var directoryPath = mockFileDataAccessor.Path.GetDirectoryName(path); + if (!string.IsNullOrEmpty(directoryPath) && !mockFileDataAccessor.Directory.Exists(directoryPath)) + { + throw CommonExceptions.CouldNotFindPartOfPath(path); + } + + if (mode.Equals(FileMode.Open) || mode.Equals(FileMode.Truncate)) + { + throw CommonExceptions.FileNotFound(path); + } + + fileData = new MockFileData(new byte[] { }); + mockFileDataAccessor.AdjustTimes(fileData, + TimeAdjustments.CreationTime | TimeAdjustments.LastAccessTime); + mockFileDataAccessor.AddFile(path, fileData); + } + + mockFileDataAccessor.FileHandles.AddHandle(path, guid, access, share); + this.access = access; + this.share = share; + } + + private static void ThrowIfInvalidModeAccess(FileMode mode, FileAccess access) + { + if (mode == FileMode.Append) + { + if (access == FileAccess.Read) + { + throw CommonExceptions.InvalidAccessCombination(mode, access); + } + + if (access != FileAccess.Write) + { + throw CommonExceptions.AppendAccessOnlyInWriteOnlyMode(); + } + } + + if (!access.HasFlag(FileAccess.Write) && + (mode == FileMode.Truncate || mode == FileMode.CreateNew || + mode == FileMode.Create || mode == FileMode.Append)) + { + throw CommonExceptions.InvalidAccessCombination(mode, access); + } + } + + /// + public override bool CanRead => access.HasFlag(FileAccess.Read); + + /// + public override bool CanWrite => access.HasFlag(FileAccess.Write); + + /// + public override int Read(byte[] buffer, int offset, int count) + { + mockFileDataAccessor.AdjustTimes(fileData, + TimeAdjustments.LastAccessTime); + return base.Read(buffer, offset, count); + } + + /// + protected override void Dispose(bool disposing) + { + if (disposed) + { + return; + } + mockFileDataAccessor.FileHandles.RemoveHandle(path, guid); + InternalFlush(); + base.Dispose(disposing); + OnClose(); + disposed = true; + } + + /// + public override void EndWrite(IAsyncResult asyncResult) + { + if (!CanWrite) + { + throw new NotSupportedException("Stream does not support writing."); + } + base.EndWrite(asyncResult); + } + + /// + public override void SetLength(long value) + { + if (!CanWrite) + { + throw new NotSupportedException("Stream does not support writing."); + } + + base.SetLength(value); + } + + /// + public override void Write(byte[] buffer, int offset, int count) + { + if (!CanWrite) + { + throw new NotSupportedException("Stream does not support writing."); + } + mockFileDataAccessor.AdjustTimes(fileData, + TimeAdjustments.LastAccessTime | TimeAdjustments.LastWriteTime); + base.Write(buffer, offset, count); + } + +#if FEATURE_SPAN + /// + public override void Write(ReadOnlySpan buffer) + { + if (!CanWrite) + { + throw new NotSupportedException("Stream does not support writing."); + } + mockFileDataAccessor.AdjustTimes(fileData, + TimeAdjustments.LastAccessTime | TimeAdjustments.LastWriteTime); + base.Write(buffer); + } +#endif + + /// + public override Task WriteAsync(byte[] buffer, int offset, int count, + CancellationToken cancellationToken) + { + if (!CanWrite) + { + throw new NotSupportedException("Stream does not support writing."); + } + mockFileDataAccessor.AdjustTimes(fileData, + TimeAdjustments.LastAccessTime | TimeAdjustments.LastWriteTime); + return base.WriteAsync(buffer, offset, count, cancellationToken); + } + +#if FEATURE_SPAN + /// + public override ValueTask WriteAsync(ReadOnlyMemory buffer, + CancellationToken cancellationToken = new()) + { + if (!CanWrite) + { + throw new NotSupportedException("Stream does not support writing."); + } + mockFileDataAccessor.AdjustTimes(fileData, + TimeAdjustments.LastAccessTime | TimeAdjustments.LastWriteTime); + return base.WriteAsync(buffer, cancellationToken); + } +#endif + + /// + public override void WriteByte(byte value) + { + if (!CanWrite) + { + throw new NotSupportedException("Stream does not support writing."); + } + mockFileDataAccessor.AdjustTimes(fileData, + TimeAdjustments.LastAccessTime | TimeAdjustments.LastWriteTime); + base.WriteByte(value); + } + + /// + public override void Flush() + { + InternalFlush(); + } + + /// + public override void Flush(bool flushToDisk) + => InternalFlush(); + + /// + public override Task FlushAsync(CancellationToken cancellationToken) + { + InternalFlush(); + return Task.CompletedTask; + } + + /// + [SupportedOSPlatform("windows")] + public object GetAccessControl() + { + return GetMockFileData().AccessControl; + } + + /// + [SupportedOSPlatform("windows")] + public object GetAccessControl(IFileSystemAclSupport.AccessControlSections includeSections) + { + return GetMockFileData().AccessControl; + } + + /// + [SupportedOSPlatform("windows")] + public void SetAccessControl(object value) + { + GetMockFileData().AccessControl = value as FileSecurity; + } + + private MockFileData GetMockFileData() + { + return mockFileDataAccessor.GetFile(path) + ?? throw CommonExceptions.FileNotFound(path); + } + + private void InternalFlush() + { + if (mockFileDataAccessor.FileExists(path)) + { + var mockFileData = mockFileDataAccessor.GetFile(path); + /* reset back to the beginning .. */ + var position = Position; + Seek(0, SeekOrigin.Begin); + /* .. read everything out */ + var data = new byte[Length]; + _ = Read(data, 0, (int)Length); + /* restore to original position */ + Seek(position, SeekOrigin.Begin); + /* .. put it in the mock system */ + mockFileData.Contents = data; + } + } + + private void OnClose() + { + if (options.HasFlag(FileOptions.DeleteOnClose) && mockFileDataAccessor.FileExists(path)) + { + mockFileDataAccessor.RemoveFile(path); + } + + if (options.HasFlag(FileOptions.Encrypted) && mockFileDataAccessor.FileExists(path)) + { +#pragma warning disable CA1416 // Ignore SupportedOSPlatform for testing helper encryption + mockFileDataAccessor.FileInfo.New(path).Encrypt(); +#pragma warning restore CA1416 + } + } + + private TimeAdjustments GetTimeAdjustmentsForFileStreamWhenFileExists(FileMode mode, FileAccess access) + { + switch (mode) + { + case FileMode.Append: + case FileMode.CreateNew: + if (access.HasFlag(FileAccess.Read)) + { + return TimeAdjustments.LastAccessTime; + } + return TimeAdjustments.None; + case FileMode.Create: + case FileMode.Truncate: + if (access.HasFlag(FileAccess.Write)) + { + return TimeAdjustments.LastAccessTime | TimeAdjustments.LastWriteTime; + } + return TimeAdjustments.LastAccessTime; + case FileMode.Open: + case FileMode.OpenOrCreate: + default: + return TimeAdjustments.None; + } + } +} \ No newline at end of file diff --git a/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockFileStreamFactory.cs b/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockFileStreamFactory.cs new file mode 100644 index 000000000..1dc39759c --- /dev/null +++ b/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockFileStreamFactory.cs @@ -0,0 +1,68 @@ +using System.Security.AccessControl; +using Microsoft.Win32.SafeHandles; + +namespace System.IO.Abstractions.TestingHelpers; + +/// +#if FEATURE_SERIALIZABLE +[Serializable] +#endif +public class MockFileStreamFactory : IFileStreamFactory +{ + private readonly IMockFileDataAccessor mockFileSystem; + + /// + public MockFileStreamFactory(IMockFileDataAccessor mockFileSystem) + => this.mockFileSystem = mockFileSystem ?? throw new ArgumentNullException(nameof(mockFileSystem)); + + /// + public IFileSystem FileSystem + => mockFileSystem; + + /// + public FileSystemStream New(SafeFileHandle handle, FileAccess access) + => new MockFileStream(mockFileSystem, handle.ToString(), FileMode.Open, access: access); + + /// + public FileSystemStream New(SafeFileHandle handle, FileAccess access, int bufferSize) + => new MockFileStream(mockFileSystem, handle.ToString(), FileMode.Open, access: access); + + /// + public FileSystemStream New(SafeFileHandle handle, FileAccess access, int bufferSize, bool isAsync) + => new MockFileStream(mockFileSystem, handle.ToString(), FileMode.Open, access: access); + + /// + public FileSystemStream New(string path, FileMode mode) + => new MockFileStream(mockFileSystem, path, mode); + + /// + public FileSystemStream New(string path, FileMode mode, FileAccess access) + => new MockFileStream(mockFileSystem, path, mode, access); + + /// + public FileSystemStream New(string path, FileMode mode, FileAccess access, FileShare share) + => new MockFileStream(mockFileSystem, path, mode, access, share); + + /// + public FileSystemStream New(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize) + => new MockFileStream(mockFileSystem, path, mode, access, share); + + /// + public FileSystemStream New(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, bool useAsync) + => new MockFileStream(mockFileSystem, path, mode, access, share); + + /// + public FileSystemStream New(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, + FileOptions options) + => new MockFileStream(mockFileSystem, path, mode, access, share, options); + +#if FEATURE_FILESTREAM_OPTIONS + /// + public FileSystemStream New(string path, FileStreamOptions options) + => new MockFileStream(mockFileSystem, path, options.Mode, options.Access, options.Share, options.Options); +#endif + + /// + public FileSystemStream Wrap(FileStream fileStream) + => throw new NotSupportedException("You cannot wrap an existing FileStream in the MockFileSystem instance!"); +} \ No newline at end of file diff --git a/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockFileSystem.cs b/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockFileSystem.cs new file mode 100644 index 000000000..fa5c57430 --- /dev/null +++ b/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockFileSystem.cs @@ -0,0 +1,588 @@ +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using System.Runtime.Serialization; + +namespace System.IO.Abstractions.TestingHelpers; + +using XFS = MockUnixSupport; + +/// +#if FEATURE_SERIALIZABLE +[Serializable] +#endif +public class MockFileSystem : FileSystemBase, IMockFileDataAccessor +{ + private const string DEFAULT_CURRENT_DIRECTORY = @"C:\"; + private const string TEMP_DIRECTORY = @"C:\temp\"; + + private readonly IDictionary files; + private readonly IDictionary drives; + private readonly PathVerifier pathVerifier; +#if FEATURE_SERIALIZABLE + [NonSerialized] +#endif + private readonly FileHandles fileHandles = new(); +#if FEATURE_SERIALIZABLE + [NonSerialized] +#endif + private Func dateTimeProvider = defaultDateTimeProvider; + private static Func defaultDateTimeProvider = () => DateTime.UtcNow; + + /// + public MockFileSystem() : this(null) { } + + /// + public MockFileSystem(IDictionary files, string currentDirectory = "") + : this(files, new MockFileSystemOptions + { + CurrentDirectory = currentDirectory, + CreateDefaultTempDir = true + }) { } + + /// + public MockFileSystem(MockFileSystemOptions options) + : this(null, options) { } + + /// + public MockFileSystem(IDictionary files, MockFileSystemOptions options) + { + options ??= new MockFileSystemOptions(); + var currentDirectory = options.CurrentDirectory; + if (string.IsNullOrEmpty(currentDirectory)) + { + currentDirectory = XFS.Path(DEFAULT_CURRENT_DIRECTORY); + } + else if (!System.IO.Path.IsPathRooted(currentDirectory)) + { + throw new ArgumentException("Current directory needs to be rooted.", nameof(currentDirectory)); + } + + var defaultTempDirectory = XFS.Path(TEMP_DIRECTORY); + + StringOperations = new StringOperations(XFS.IsUnixPlatform()); + pathVerifier = new PathVerifier(this); + this.files = new Dictionary(StringOperations.Comparer); + drives = new Dictionary(StringOperations.Comparer); + + Path = new MockPath(this, defaultTempDirectory); + File = new MockFile(this); + Directory = new MockDirectory(this, currentDirectory); + FileInfo = new MockFileInfoFactory(this); + FileVersionInfo = new MockFileVersionInfoFactory(this); + FileStream = new MockFileStreamFactory(this); + DirectoryInfo = new MockDirectoryInfoFactory(this); + DriveInfo = new MockDriveInfoFactory(this); + FileSystemWatcher = new MockFileSystemWatcherFactory(this); + + if (files != null) + { + foreach (var entry in files) + { + AddFile(entry.Key, entry.Value); + } + } + + if (!FileExists(currentDirectory)) + { + AddDirectory(currentDirectory); + } + + if (options.CreateDefaultTempDir && !FileExists(defaultTempDirectory)) + { + AddDirectory(defaultTempDirectory); + } + } + + /// + public StringOperations StringOperations { get; } + /// + public override IFile File { get; } + /// + public override IDirectory Directory { get; } + /// + public override IFileInfoFactory FileInfo { get; } + /// + public override IFileVersionInfoFactory FileVersionInfo { get; } + /// + public override IFileStreamFactory FileStream { get; } + /// + public override IPath Path { get; } + /// + public override IDirectoryInfoFactory DirectoryInfo { get; } + /// + public override IDriveInfoFactory DriveInfo { get; } + /// + public override IFileSystemWatcherFactory FileSystemWatcher { get; } + /// + public IFileSystem FileSystem => this; + /// + public PathVerifier PathVerifier => pathVerifier; + /// + public FileHandles FileHandles => fileHandles; + + /// + /// Replaces the time provider with a mocked instance. This allows to influence the used time in tests. + /// + /// If not set, the default implementation returns . + /// + /// The function that returns the current . + /// + public MockFileSystem MockTime(Func dateTimeProvider) + { + this.dateTimeProvider = dateTimeProvider ?? defaultDateTimeProvider; + return this; + } + + //If C:\foo exists, ensures that trying to save a file to "C:\FOO\file.txt" instead saves it to "C:\foo\file.txt". + private string GetPathWithCorrectDirectoryCapitalization(string fullPath) + { + string[] splitPath = fullPath.Split(Path.DirectorySeparatorChar); + string leftHalf = fullPath; + string rightHalf = ""; + + for (int i = splitPath.Length - 1; i > 1; i--) + { + rightHalf = i == splitPath.Length - 1 ? splitPath[i] : splitPath[i] + Path.DirectorySeparatorChar + rightHalf; + int lastSeparator = leftHalf.LastIndexOf(Path.DirectorySeparatorChar); + leftHalf = lastSeparator > 0 ? leftHalf.Substring(0, lastSeparator) : leftHalf; + + if (DirectoryExistsWithoutFixingPath(leftHalf)) + { + string baseDirectory; + lock (files) + { + baseDirectory = files[leftHalf].Path; + } + + return baseDirectory + Path.DirectorySeparatorChar + rightHalf; + } + } + + return fullPath.TrimSlashes(); + } + + /// + public MockFileData AdjustTimes(MockFileData fileData, TimeAdjustments timeAdjustments) + { + var now = dateTimeProvider(); + if (timeAdjustments.HasFlag(TimeAdjustments.CreationTime)) + { + fileData.CreationTime = now; + } + + if (timeAdjustments.HasFlag(TimeAdjustments.LastAccessTime)) + { + fileData.LastAccessTime = now; + } + + if (timeAdjustments.HasFlag(TimeAdjustments.LastWriteTime)) + { + fileData.LastWriteTime = now; + } + + return fileData; + } + + /// + public MockFileData GetFile(string path) + { + path = pathVerifier.FixPath(path).TrimSlashes(); + return GetFileWithoutFixingPath(path); + } + + /// + public MockDriveData GetDrive(string name) + { + name = PathVerifier.NormalizeDriveName(name); + lock (drives) + { + return drives.TryGetValue(name, out var result) ? result : null; + } + } + + private void SetEntry(string path, MockFileData mockFile) + { + path = GetPathWithCorrectDirectoryCapitalization( + pathVerifier.FixPath(path) + ).TrimSlashes(); + + lock (files) + { + files[path] = new FileSystemEntry { Path = path, Data = mockFile }; + } + + lock (drives) + { + if (PathVerifier.TryNormalizeDriveName(path, out string driveLetter)) + { + if (!drives.ContainsKey(driveLetter)) + { + drives[driveLetter] = new MockDriveData(); + } + } + } + } + + /// + public void AddFile(string path, MockFileData mockFile, bool verifyAccess = true) + { + var fixedPath = GetPathWithCorrectDirectoryCapitalization( + pathVerifier.FixPath(path) + ); + + mockFile ??= new MockFileData(string.Empty); + var file = GetFile(fixedPath); + + if (file != null) + { + var isReadOnly = (file.Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly; + var isHidden = (file.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden; + + if (verifyAccess && (isReadOnly || isHidden)) + { + throw CommonExceptions.AccessDenied(path); + } + file.CheckFileAccess(fixedPath, FileAccess.Write); + mockFile.CreationTime = file.CreationTime; + } + + var directoryPath = Path.GetDirectoryName(fixedPath); + if (directoryPath == null) + { + AddDrive(fixedPath, new MockDriveData()); + } + else if (!DirectoryExistsWithoutFixingPath(directoryPath)) + { + AddDirectory(directoryPath); + } + + mockFile.FileVersionInfo ??= new MockFileVersionInfo(fixedPath); + + SetEntry(fixedPath, mockFile); + } + + /// + /// Add a new file that is empty. + /// + /// A string representing the path of the new file to add. + public void AddEmptyFile(string path) + { + AddFile(path, new MockFileData("")); + } + + /// + /// Add a new file that is empty. + /// + /// An representing the path of the new file to add. + public void AddEmptyFile(IFileInfo path) + { + AddEmptyFile(path.FullName); + path.Refresh(); + } + + /// + /// Add a new, empty directory. + /// + /// An representing the path of the new directory to add. + public void AddDirectory(IDirectoryInfo path) + { + AddDirectory(path.FullName); + path.Refresh(); + } + + /// + /// Add a new file with its contents set to a specified . + /// + /// An representing the path of the new file to add. + /// The data to use for the contents of the new file. + /// Flag indicating if the access conditions should be verified. + public void AddFile(IFileInfo path, MockFileData data, bool verifyAccess = true) + { + AddFile(path.FullName, data, verifyAccess); + path.Refresh(); + } + + /// + /// Gets a file. + /// + /// The path of the file to get. + /// The file. if the file does not exist. + public MockFileData GetFile(IFileInfo path) + { + return GetFile(path.FullName); + } + + /// + public void AddDirectory(string path) + { + var fixedPath = GetPathWithCorrectDirectoryCapitalization( + pathVerifier.FixPath(path) + ); + var separator = Path.DirectorySeparatorChar.ToString(); + + if (FileExists(fixedPath) && FileIsReadOnly(fixedPath)) + { + throw CommonExceptions.AccessDenied(fixedPath); + } + var lastIndex = 0; + var isUnc = + StringOperations.StartsWith(fixedPath, @"\\") || + StringOperations.StartsWith(fixedPath, @"//"); + + if (isUnc) + { + //First, confirm they aren't trying to create '\\server\' + lastIndex = StringOperations.IndexOf(fixedPath, separator, 2); + + if (lastIndex < 0) + { + throw CommonExceptions.InvalidUncPath(nameof(path)); + } + + /* + * Although CreateDirectory(@"\\server\share\") is not going to work in real code, we allow it here for the purposes of setting up test doubles. + * See PR https://github.com/TestableIO/System.IO.Abstractions/pull/90 for conversation + */ + } + + while ((lastIndex = StringOperations.IndexOf(fixedPath, separator, lastIndex + 1)) > -1) + { + var segment = fixedPath.Substring(0, lastIndex + 1); + if (!DirectoryExistsWithoutFixingPath(segment)) + { + SetEntry(segment, new MockDirectoryData()); + } + } + + var s = StringOperations.EndsWith(fixedPath, separator) ? fixedPath : fixedPath + separator; + SetEntry(s, new MockDirectoryData()); + } + + /// + public void AddFileFromEmbeddedResource(string path, Assembly resourceAssembly, string embeddedResourcePath) + { + using (var embeddedResourceStream = resourceAssembly.GetManifestResourceStream(embeddedResourcePath)) + { + if (embeddedResourceStream == null) + { + throw new ArgumentException("Resource not found in assembly", nameof(embeddedResourcePath)); + } + + using (var streamReader = new BinaryReader(embeddedResourceStream)) + { + var fileData = streamReader.ReadBytes((int)embeddedResourceStream.Length); + AddFile(path, new MockFileData(fileData)); + } + } + } + + /// + public void AddFilesFromEmbeddedNamespace(string path, Assembly resourceAssembly, string embeddedResourcePath) + { + var matchingResources = resourceAssembly.GetManifestResourceNames().Where(f => f.StartsWith(embeddedResourcePath)); + foreach (var resource in matchingResources) + { + using (var embeddedResourceStream = resourceAssembly.GetManifestResourceStream(resource)) + using (var streamReader = new BinaryReader(embeddedResourceStream)) + { + var fileName = resource.Substring(embeddedResourcePath.Length + 1); + var fileData = streamReader.ReadBytes((int)embeddedResourceStream.Length); + var filePath = Path.Combine(path, fileName); + AddFile(filePath, new MockFileData(fileData)); + } + } + } + + /// + public void AddDrive(string name, MockDriveData mockDrive) + { + name = PathVerifier.NormalizeDriveName(name); + lock (drives) + { + drives[name] = mockDrive; + } + } + + /// + public void MoveDirectory(string sourcePath, string destPath) + { + sourcePath = pathVerifier.FixPath(sourcePath); + destPath = pathVerifier.FixPath(destPath); + + var sourcePathSequence = sourcePath.Split(new[] { Path.DirectorySeparatorChar }, StringSplitOptions.RemoveEmptyEntries); + + lock (files) + { + var affectedPaths = files.Keys + .Where(p => PathStartsWith(p, sourcePathSequence)) + .ToList(); + + foreach (var path in affectedPaths) + { + var newPath = Path.Combine(destPath, path.Substring(sourcePath.Length).TrimStart(Path.DirectorySeparatorChar)); + var entry = files[path]; + entry.Path = newPath; + files[newPath] = entry; + files.Remove(path); + } + } + + bool PathStartsWith(string path, string[] minMatch) + { + var pathSequence = path.Split(new[] { Path.DirectorySeparatorChar }, StringSplitOptions.RemoveEmptyEntries); + if (pathSequence.Length < minMatch.Length) + { + return false; + } + + for (var i = 0; i < minMatch.Length; i++) + { + if (!StringOperations.Equals(minMatch[i], pathSequence[i])) + { + return false; + } + } + + return true; + } + } + + /// + public void RemoveFile(string path, bool verifyAccess = true) + { + path = pathVerifier.FixPath(path); + + lock (files) + { + if (FileExists(path) && verifyAccess && (FileIsReadOnly(path) || Directory.Exists(path) && AnyFileIsReadOnly(path))) + { + throw CommonExceptions.AccessDenied(path); + } + + files.Remove(path); + } + } + + /// + public bool FileExists(string path) + { + if (string.IsNullOrEmpty(path)) + { + return false; + } + + path = pathVerifier.FixPath(path).TrimSlashes(); + + lock (files) + { + return files.ContainsKey(path); + } + } + + /// + public IEnumerable AllPaths + { + get + { + lock (files) + { + return files.Keys.ToArray(); + } + } + } + + /// + public IEnumerable AllNodes + { + get + { + lock (files) + { + return AllPaths.Where(path => !IsStartOfAnotherPath(path)).ToArray(); + } + } + } + + /// + public IEnumerable AllFiles + { + get + { + lock (files) + { + return files.Where(f => !f.Value.Data.IsDirectory).Select(f => f.Key).ToArray(); + } + } + } + + /// + public IEnumerable AllDirectories + { + get + { + lock (files) + { + return files.Where(f => f.Value.Data.IsDirectory).Select(f => f.Key).ToArray(); + } + } + } + + /// + public IEnumerable AllDrives + { + get + { + lock (drives) + { + return drives.Keys.ToArray(); + } + } + } + + [OnDeserializing] + private void OnDeserializing(StreamingContext c) + { + dateTimeProvider = defaultDateTimeProvider; + } + + private bool AnyFileIsReadOnly(string path) + { + return Directory.GetFiles(path).Any(file => FileIsReadOnly(file)); + } + + private bool IsStartOfAnotherPath(string path) + { + return AllPaths.Any(otherPath => otherPath.StartsWith(path) && otherPath != path); + } + + private MockFileData GetFileWithoutFixingPath(string path) + { + lock (files) + { + return files.TryGetValue(path, out var result) ? result.Data : null; + } + } + + private bool DirectoryExistsWithoutFixingPath(string path) + { + lock (files) + { + return files.TryGetValue(path, out var result) && result.Data.IsDirectory; + } + } + + private bool FileIsReadOnly(string path) + { + return (GetFile(path).Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly; + } + +#if FEATURE_SERIALIZABLE + [Serializable] +#endif + private class FileSystemEntry + { + public string Path { get; set; } + public MockFileData Data { get; set; } + } +} diff --git a/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockFileSystemOptions.cs b/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockFileSystemOptions.cs new file mode 100644 index 000000000..f6f19dbf3 --- /dev/null +++ b/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockFileSystemOptions.cs @@ -0,0 +1,17 @@ +namespace System.IO.Abstractions.TestingHelpers; + +/// +/// Constructor options for +/// +public class MockFileSystemOptions +{ + /// + /// The with which the is initialized. + /// + public string CurrentDirectory { get; init; } = ""; + + /// + /// Flag indicating, if a temporary directory should be created. + /// + public bool CreateDefaultTempDir { get; init; } = true; +} \ No newline at end of file diff --git a/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockFileSystemWatcherFactory.cs b/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockFileSystemWatcherFactory.cs new file mode 100644 index 000000000..ad60ae5d5 --- /dev/null +++ b/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockFileSystemWatcherFactory.cs @@ -0,0 +1,41 @@ +namespace System.IO.Abstractions.TestingHelpers; + +/// +#if FEATURE_SERIALIZABLE +[Serializable] +#endif +public class MockFileSystemWatcherFactory : IFileSystemWatcherFactory +{ + + /// + public MockFileSystemWatcherFactory(MockFileSystem mockFileSystem) + { + FileSystem = mockFileSystem; + } + + /// + public IFileSystem FileSystem { get; } + + /// + public IFileSystemWatcher New() + => throw new NotImplementedException(StringResources.Manager.GetString("FILE_SYSTEM_WATCHER_NOT_IMPLEMENTED_EXCEPTION")); + + /// + public IFileSystemWatcher New(string path) + => throw new NotImplementedException(StringResources.Manager.GetString("FILE_SYSTEM_WATCHER_NOT_IMPLEMENTED_EXCEPTION")); + + /// + public IFileSystemWatcher New(string path, string filter) + => throw new NotImplementedException(StringResources.Manager.GetString("FILE_SYSTEM_WATCHER_NOT_IMPLEMENTED_EXCEPTION")); + + /// + public IFileSystemWatcher Wrap(FileSystemWatcher fileSystemWatcher) + { + if (fileSystemWatcher == null) + { + return null; + } + + throw new NotImplementedException(StringResources.Manager.GetString("FILE_SYSTEM_WATCHER_NOT_IMPLEMENTED_EXCEPTION")); + } +} \ No newline at end of file diff --git a/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockFileVersionInfo.cs b/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockFileVersionInfo.cs new file mode 100644 index 000000000..16f220655 --- /dev/null +++ b/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockFileVersionInfo.cs @@ -0,0 +1,173 @@ +using System.Diagnostics; +using System.Text; + +namespace System.IO.Abstractions.TestingHelpers; + +/// +#if FEATURE_SERIALIZABLE +[Serializable] +#endif +public class MockFileVersionInfo : FileVersionInfoBase +{ + /// + public MockFileVersionInfo( + string fileName, + string fileVersion = null, + string productVersion = null, + string fileDescription = null, + string productName = null, + string companyName = null, + string comments = null, + string internalName = null, + bool isDebug = false, + bool isPatched = false, + bool isPrivateBuild = false, + bool isPreRelease = false, + bool isSpecialBuild = false, + string language = null, + string legalCopyright = null, + string legalTrademarks = null, + string originalFilename = null, + string privateBuild = null, + string specialBuild = null) + { + FileName = fileName; + FileVersion = fileVersion; + ProductVersion = productVersion; + FileDescription = fileDescription; + ProductName = productName; + CompanyName = companyName; + Comments = comments; + InternalName = internalName; + IsDebug = isDebug; + IsPatched = isPatched; + IsPrivateBuild = isPrivateBuild; + IsPreRelease = isPreRelease; + IsSpecialBuild = isSpecialBuild; + Language = language; + LegalCopyright = legalCopyright; + LegalTrademarks = legalTrademarks; + OriginalFilename = originalFilename; + PrivateBuild = privateBuild; + SpecialBuild = specialBuild; + + if (Version.TryParse(fileVersion, out Version version)) + { + FileMajorPart = version.Major; + FileMinorPart = version.Minor; + FileBuildPart = version.Build; + FilePrivatePart = version.Revision; + } + + var parsedProductVersion = ProductVersionParser.Parse(productVersion); + + ProductMajorPart = parsedProductVersion.Major; + ProductMinorPart = parsedProductVersion.Minor; + ProductBuildPart = parsedProductVersion.Build; + ProductPrivatePart = parsedProductVersion.PrivatePart; + } + + /// + public override string FileName { get; } + + /// + public override string FileVersion { get; } + + /// + public override string ProductVersion { get; } + + /// + public override string FileDescription { get; } + + /// + public override string ProductName { get; } + + /// + public override string CompanyName { get; } + + /// + public override string Comments { get; } + + /// + public override string InternalName { get; } + + /// + public override bool IsDebug { get; } + + /// + public override bool IsPatched { get; } + + /// + public override bool IsPrivateBuild { get; } + + /// + public override bool IsPreRelease { get; } + + /// + public override bool IsSpecialBuild { get; } + + /// + public override string Language { get; } + + /// + public override string LegalCopyright { get; } + + /// + public override string LegalTrademarks { get; } + + /// + public override string OriginalFilename { get; } + + /// + public override string PrivateBuild { get; } + + /// + public override string SpecialBuild { get; } + + /// + public override int FileMajorPart { get; } + + /// + public override int FileMinorPart { get; } + + /// + public override int FileBuildPart { get; } + + /// + public override int FilePrivatePart { get; } + + /// + public override int ProductMajorPart { get; } + + /// + public override int ProductMinorPart { get; } + + /// + public override int ProductBuildPart { get; } + + /// + public override int ProductPrivatePart { get; } + + /// + public override string ToString() + { + // An initial capacity of 512 was chosen because it is large enough to cover + // the size of the static strings with enough capacity left over to cover + // average length property values. + var sb = new StringBuilder(512); + sb.Append("File: ").AppendLine(FileName); + sb.Append("InternalName: ").AppendLine(InternalName); + sb.Append("OriginalFilename: ").AppendLine(OriginalFilename); + sb.Append("FileVersion: ").AppendLine(FileVersion); + sb.Append("FileDescription: ").AppendLine(FileDescription); + sb.Append("Product: ").AppendLine(ProductName); + sb.Append("ProductVersion: ").AppendLine(ProductVersion); + sb.Append("Debug: ").AppendLine(IsDebug.ToString()); + sb.Append("Patched: ").AppendLine(IsPatched.ToString()); + sb.Append("PreRelease: ").AppendLine(IsPreRelease.ToString()); + sb.Append("PrivateBuild: ").AppendLine(IsPrivateBuild.ToString()); + sb.Append("SpecialBuild: ").AppendLine(IsSpecialBuild.ToString()); + sb.Append("Language: ").AppendLine(Language); + return sb.ToString(); + } +} \ No newline at end of file diff --git a/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockFileVersionInfoFactory.cs b/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockFileVersionInfoFactory.cs new file mode 100644 index 000000000..69de3f7dd --- /dev/null +++ b/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockFileVersionInfoFactory.cs @@ -0,0 +1,32 @@ +namespace System.IO.Abstractions.TestingHelpers; + +/// +#if FEATURE_SERIALIZABLE +[Serializable] +#endif +public class MockFileVersionInfoFactory : IFileVersionInfoFactory +{ + private readonly IMockFileDataAccessor mockFileSystem; + + /// + public MockFileVersionInfoFactory(IMockFileDataAccessor mockFileSystem) + { + this.mockFileSystem = mockFileSystem ?? throw new ArgumentNullException(nameof(mockFileSystem)); + } + + /// + public IFileSystem FileSystem => mockFileSystem; + + /// + public IFileVersionInfo GetVersionInfo(string fileName) + { + MockFileData mockFileData = mockFileSystem.GetFile(fileName); + + if (mockFileData != null) + { + return mockFileData.FileVersionInfo; + } + + throw CommonExceptions.FileNotFound(fileName); + } +} \ No newline at end of file diff --git a/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockPath.cs b/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockPath.cs new file mode 100644 index 000000000..c1852f9e1 --- /dev/null +++ b/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockPath.cs @@ -0,0 +1,191 @@ +using System.Collections.Generic; +using System.Globalization; +using System.Linq; + +namespace System.IO.Abstractions.TestingHelpers; + +/// +/// PathWrapper calls direct to Path but all this does is string manipulation so we can inherit directly from PathWrapper as no IO is done +/// +#if FEATURE_SERIALIZABLE +[Serializable] +#endif +public class MockPath : PathWrapper +{ + private readonly IMockFileDataAccessor mockFileDataAccessor; + private readonly string defaultTempDirectory; + + /// + public MockPath(IMockFileDataAccessor mockFileDataAccessor) : this(mockFileDataAccessor, string.Empty) { } + + /// + public MockPath(IMockFileDataAccessor mockFileDataAccessor, string defaultTempDirectory) : base(mockFileDataAccessor?.FileSystem) + { + this.mockFileDataAccessor = mockFileDataAccessor ?? throw new ArgumentNullException(nameof(mockFileDataAccessor)); + this.defaultTempDirectory = !string.IsNullOrEmpty(defaultTempDirectory) ? defaultTempDirectory : base.GetTempPath(); + } + +#if FEATURE_PATH_EXISTS + /// + public override bool Exists(string path) + { + return mockFileDataAccessor.FileExists(path); + } +#endif + + /// + public override string GetFullPath(string path) + { + if (path == null) + { + throw new ArgumentNullException(nameof(path), StringResources.Manager.GetString("VALUE_CANNOT_BE_NULL")); + } + + if (string.IsNullOrWhiteSpace(path)) + { + throw CommonExceptions.PathIsNotOfALegalForm(nameof(path)); + } + + path = path.Replace(AltDirectorySeparatorChar, DirectorySeparatorChar); + + bool isUnc = + mockFileDataAccessor.StringOperations.StartsWith(path, @"\\") || + mockFileDataAccessor.StringOperations.StartsWith(path, @"//"); + + string root = GetPathRoot(path); + + bool hasTrailingSlash = path.Length > 1 && path[path.Length - 1] == DirectorySeparatorChar; + + string[] pathSegments; + + if (root.Length == 0) + { + // relative path on the current drive or volume + path = mockFileDataAccessor.Directory.GetCurrentDirectory() + DirectorySeparatorChar + path; + pathSegments = GetSegments(path); + } + else if (isUnc) + { + // unc path + pathSegments = GetSegments(path); + if (pathSegments.Length < 2) + { + throw CommonExceptions.InvalidUncPath(nameof(path)); + } + } + else if (mockFileDataAccessor.StringOperations.Equals(@"\", root) || + mockFileDataAccessor.StringOperations.Equals(@"/", root)) + { + // absolute path on the current drive or volume + pathSegments = GetSegments(GetPathRoot(mockFileDataAccessor.Directory.GetCurrentDirectory()), path); + } + else + { + pathSegments = GetSegments(path); + } + + // unc paths need at least two segments, the others need one segment + var isUnixRooted = mockFileDataAccessor.StringOperations.StartsWith( + mockFileDataAccessor.Directory.GetCurrentDirectory(), + "/"); + + var minPathSegments = isUnc + ? 2 + : isUnixRooted ? 0 : 1; + + var stack = new Stack(); + foreach (var segment in pathSegments) + { + if (mockFileDataAccessor.StringOperations.Equals("..", segment)) + { + // only pop, if afterwards are at least the minimal amount of path segments + if (stack.Count > minPathSegments) + { + stack.Pop(); + } + } + else if (mockFileDataAccessor.StringOperations.Equals(".", segment)) + { + // ignore . + } + else + { + stack.Push(segment); + } + } + + var fullPath = string.Join(string.Format(CultureInfo.InvariantCulture, "{0}", DirectorySeparatorChar), stack.Reverse().ToArray()); + + if (hasTrailingSlash) + { + fullPath += DirectorySeparatorChar; + } + + if (isUnixRooted && !isUnc) + { + fullPath = "/" + fullPath; + } + else if (isUnixRooted) + { + fullPath = @"//" + fullPath; + } + else if (isUnc) + { + fullPath = @"\\" + fullPath; + } + + return fullPath; + } + + private string[] GetSegments(params string[] paths) + { + return paths.SelectMany(path => path.Split(new[] { DirectorySeparatorChar }, StringSplitOptions.RemoveEmptyEntries)).ToArray(); + } + + /// + public override string GetTempFileName() + { + string fileName = mockFileDataAccessor.Path.GetRandomFileName(); + string tempDir = this.GetTempPath(); + + string fullPath = mockFileDataAccessor.Path.Combine(tempDir, fileName); + + mockFileDataAccessor.AddFile(fullPath, new MockFileData(string.Empty)); + + return fullPath; + } + + /// + public override string GetTempPath() => defaultTempDirectory; + +#if FEATURE_ADVANCED_PATH_OPERATIONS + /// + public override string GetRelativePath(string relativeTo, string path) + { + if (relativeTo == null) + { + throw new ArgumentNullException(nameof(relativeTo), StringResources.Manager.GetString("VALUE_CANNOT_BE_NULL")); + } + + if (string.IsNullOrWhiteSpace(relativeTo)) + { + throw CommonExceptions.PathIsNotOfALegalForm(nameof(relativeTo)); + } + + if (path == null) + { + throw new ArgumentNullException(nameof(path), StringResources.Manager.GetString("VALUE_CANNOT_BE_NULL")); + } + + if (path.Length == 0) + { + throw CommonExceptions.PathIsNotOfALegalForm(nameof(path)); + } + + relativeTo = GetFullPath(relativeTo); + path = GetFullPath(path); + + return Path.GetRelativePath(relativeTo, path); + } +#endif +} \ No newline at end of file diff --git a/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockUnixSupport.cs b/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockUnixSupport.cs new file mode 100644 index 000000000..b1a0e54c7 --- /dev/null +++ b/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockUnixSupport.cs @@ -0,0 +1,28 @@ +using System.Text.RegularExpressions; + +namespace System.IO.Abstractions.TestingHelpers; + +/// +/// Provides helper methods for handling paths in a portable way. +/// +public static class MockUnixSupport +{ + private static readonly Regex pathTransform = new Regex(@"^[a-zA-Z]:(?.*)$"); + + /// + /// Normalizes the given path so that it works on all platfoms. + /// + public static string Path(string path) => path != null && IsUnixPlatform() + ? pathTransform.Replace(path, "${path}").Replace(@"\", "/") + : path; + + /// + /// Determines whether the current runtime platform is Unix. + /// + public static bool IsUnixPlatform() => IO.Path.DirectorySeparatorChar == '/'; + + /// + /// Determines whether the current runtime platform is Windows. + /// + public static bool IsWindowsPlatform() => IO.Path.DirectorySeparatorChar == '\\'; +} \ No newline at end of file diff --git a/src/TestableIO.System.IO.Abstractions.TestingHelpers/PathVerifier.cs b/src/TestableIO.System.IO.Abstractions.TestingHelpers/PathVerifier.cs new file mode 100644 index 000000000..45848c605 --- /dev/null +++ b/src/TestableIO.System.IO.Abstractions.TestingHelpers/PathVerifier.cs @@ -0,0 +1,205 @@ +using System; +using System.Linq; + +namespace System.IO.Abstractions.TestingHelpers; + +using XFS = MockUnixSupport; + +/// +/// Provides helper methods for verifying paths. +/// +#if FEATURE_SERIALIZABLE +[Serializable] +#endif +public class PathVerifier +{ + private static readonly char[] AdditionalInvalidPathChars = { '*', '?' }; + private readonly IMockFileDataAccessor _mockFileDataAccessor; + + // Windows supports extended-length paths with a `\\?\` prefix, to work around low path length limits. + // Ref: https://learn.microsoft.com/en-us/windows/win32/fileio/maximum-file-path-limitation?tabs=registry + private const string WINDOWS_EXTENDED_LENGTH_PATH_PREFIX = @"\\?\"; + + /// + /// Creates a new verifier instance. + /// + public PathVerifier(IMockFileDataAccessor mockFileDataAccessor) + { + _mockFileDataAccessor = mockFileDataAccessor ?? throw new ArgumentNullException(nameof(mockFileDataAccessor)); + } + + /// + /// Determines whether the given path is legal. + /// + public void IsLegalAbsoluteOrRelative(string path, string paramName) + { + if (path == null) + { + throw new ArgumentNullException(paramName, StringResources.Manager.GetString("VALUE_CANNOT_BE_NULL")); + } + + if (path == string.Empty) + { + throw new ArgumentException("Empty file name is not legal.", paramName); + } + + if (path.Trim() == string.Empty) + { + throw CommonExceptions.PathIsNotOfALegalForm(paramName); + } + + if (XFS.IsWindowsPlatform() && !IsValidUseOfVolumeSeparatorChar(path)) + { + + throw CommonExceptions.InvalidUseOfVolumeSeparator(); + } + + if (ExtractFileName(path).IndexOfAny(_mockFileDataAccessor.Path.GetInvalidFileNameChars()) > -1) + { + throw CommonExceptions.IllegalCharactersInPath(); + } + + var filePath = ExtractFilePath(path); + + if (HasIllegalCharacters(filePath, checkAdditional: false)) + { + throw CommonExceptions.IllegalCharactersInPath(); + } + } + + private static bool IsValidUseOfVolumeSeparatorChar(string path) + { + if (XFS.IsWindowsPlatform() && path.StartsWith(WINDOWS_EXTENDED_LENGTH_PATH_PREFIX)) + { + // Skip over the `\\?\` prefix if there is one. + path = path.Substring(WINDOWS_EXTENDED_LENGTH_PATH_PREFIX.Length); + } + + var lastVolSepIndex = path.LastIndexOf(Path.VolumeSeparatorChar); + return lastVolSepIndex == -1 || lastVolSepIndex == 1 && char.IsLetter(path[0]); + } + + private string ExtractFileName(string fullFileName) + { + return fullFileName.Split( + _mockFileDataAccessor.Path.DirectorySeparatorChar, + _mockFileDataAccessor.Path.AltDirectorySeparatorChar).Last(); + } + + private string ExtractFilePath(string fullFileName) + { + var extractFilePath = fullFileName.Split( + _mockFileDataAccessor.Path.DirectorySeparatorChar, + _mockFileDataAccessor.Path.AltDirectorySeparatorChar); + return string.Join(_mockFileDataAccessor.Path.DirectorySeparatorChar.ToString(), extractFilePath.Take(extractFilePath.Length - 1)); + } + + /// + /// Determines whether the given path contains illegal characters. + /// + public bool HasIllegalCharacters(string path, bool checkAdditional) + { + if (path == null) + { + throw new ArgumentNullException(nameof(path)); + } + + var invalidPathChars = _mockFileDataAccessor.Path.GetInvalidPathChars(); + + if (checkAdditional) + { + // AdditionalInvalidPathChars includes '?', but this character is allowed in extended-length + // windows path prefixes (`\\?\`). If we're dealing with such a path, check for invalid + // characters after the prefix. + if (XFS.IsWindowsPlatform() && path.StartsWith(WINDOWS_EXTENDED_LENGTH_PATH_PREFIX)) + { + path = path.Substring(WINDOWS_EXTENDED_LENGTH_PATH_PREFIX.Length); + } + + return path.IndexOfAny(invalidPathChars.Concat(AdditionalInvalidPathChars).ToArray()) >= 0; + } + + return path.IndexOfAny(invalidPathChars) >= 0; + } + + /// + /// Throws an excpetion if the given path contains invalid characters. + /// + public void CheckInvalidPathChars(string path, bool checkAdditional = false) + { + if (path == null) + { + throw new ArgumentNullException(nameof(path)); + } + + if (HasIllegalCharacters(path, checkAdditional)) + { + throw CommonExceptions.IllegalCharactersInPath(); + } + } + + /// + /// Determines the normalized drive name used for drive identification. + /// + /// Thrown if the is not a valid drive name. + public string NormalizeDriveName(string name) + { + return TryNormalizeDriveName(name, out var result) + ? result + : throw new ArgumentException( + @"Object must be a root directory (""C:\"") or a drive letter (""C"")."); + } + + /// + /// Tries to determine the normalized drive name used for drive identification. + /// + public bool TryNormalizeDriveName(string name, out string result) + { + if (name == null) + { + throw new ArgumentNullException(nameof(name)); + } + + const string DRIVE_SEPARATOR = @":\"; + + if (name.Length == 1 + || (name.Length == 2 && name[1] == ':') + || (name.Length == 3 && _mockFileDataAccessor.StringOperations.EndsWith(name, DRIVE_SEPARATOR))) + { + name = name[0] + DRIVE_SEPARATOR; + } + else + { + CheckInvalidPathChars(name); + name = _mockFileDataAccessor.Path.GetPathRoot(name); + + if (string.IsNullOrEmpty(name) || _mockFileDataAccessor.StringOperations.StartsWith(name, @"\\")) + { + result = null; + return false; + } + } + + result = name; + return true; + } + + /// + /// Resolves and normalizes a path. + /// + internal string FixPath(string path) + { + if (path == null) + { + throw new ArgumentNullException(nameof(path), StringResources.Manager.GetString("VALUE_CANNOT_BE_NULL")); + } + + var pathSeparatorFixed = path.Replace( + _mockFileDataAccessor.Path.AltDirectorySeparatorChar, + _mockFileDataAccessor.Path.DirectorySeparatorChar + ); + var fullPath = _mockFileDataAccessor.Path.GetFullPath(pathSeparatorFixed); + + return fullPath; + } +} diff --git a/src/TestableIO.System.IO.Abstractions.TestingHelpers/Polyfills/SupportedOSPlatformAttribute.cs b/src/TestableIO.System.IO.Abstractions.TestingHelpers/Polyfills/SupportedOSPlatformAttribute.cs new file mode 100644 index 000000000..ef6635b4f --- /dev/null +++ b/src/TestableIO.System.IO.Abstractions.TestingHelpers/Polyfills/SupportedOSPlatformAttribute.cs @@ -0,0 +1,12 @@ +#if !FEATURE_SUPPORTED_OS_ATTRIBUTE +namespace System.Runtime.Versioning +{ + [AttributeUsage(AttributeTargets.All)] + internal class SupportedOSPlatformAttribute : Attribute + { + public SupportedOSPlatformAttribute(string _) + { + } + } +} +#endif diff --git a/src/TestableIO.System.IO.Abstractions.TestingHelpers/ProductVersionParser.cs b/src/TestableIO.System.IO.Abstractions.TestingHelpers/ProductVersionParser.cs new file mode 100644 index 000000000..8f5d2459c --- /dev/null +++ b/src/TestableIO.System.IO.Abstractions.TestingHelpers/ProductVersionParser.cs @@ -0,0 +1,98 @@ +using System.Reflection; +using System.Text.RegularExpressions; + +namespace System.IO.Abstractions.TestingHelpers; + +/// +/// Provides functionality to parse a product version string into its major, minor, build, and private parts. +/// +internal static class ProductVersionParser +{ + /// + /// Parses a product version string and extracts the numeric values for the major, minor, build, and private parts, + /// mimicking the behavior of the attribute. + /// + /// The product version string to parse. + /// + /// A object containing the parsed major, minor, build, and private parts. + /// If the input is invalid, returns a with all parts set to 0. + /// + /// + /// The method splits the input string into segments separated by dots ('.') and attempts to extract + /// the leading numeric value from each segment. A maximum of 4 segments are processed; if more than + /// 4 segments are present, all segments are ignored. Additionally, if a segment does not contain + /// a valid numeric part at its start or it contains more than just a number, the rest of the segments are ignored. + /// + public static ProductVersion Parse(string productVersion) + { + if (string.IsNullOrWhiteSpace(productVersion)) + { + return new(); + } + + var segments = productVersion.Split('.'); + if (segments.Length > 4) + { + // if more than 4 segments are present, all segments are ignored + return new(); + } + + var regex = new Regex(@"^\d+"); + + int[] parts = new int[4]; + + for (int i = 0; i < segments.Length; i++) + { + var match = regex.Match(segments[i]); + if (match.Success && int.TryParse(match.Value, out int number)) + { + parts[i] = number; + + if (match.Value != segments[i]) + { + // when a segment contains more than a number, the rest of the segments are ignored + break; + } + } + else + { + // when a segment is not valid, the rest of the segments are ignored + break; + } + } + + return new() + { + Major = parts[0], + Minor = parts[1], + Build = parts[2], + PrivatePart = parts[3] + }; + } + + /// + /// Represents a product version with numeric parts for major, minor, build, and private versions. + /// + public class ProductVersion + { + /// + /// Gets the major part of the version number + /// + public int Major { get; init; } + + /// + /// Gets the minor part of the version number + /// + public int Minor { get; init; } + + /// + /// Gets the build part of the version number + /// + public int Build { get; init; } + + /// + /// Gets the private part of the version number + /// + public int PrivatePart { get; init; } + } +} \ No newline at end of file diff --git a/TestingHelpers/Properties/Resources.resx b/src/TestableIO.System.IO.Abstractions.TestingHelpers/Properties/Resources.resx similarity index 78% rename from TestingHelpers/Properties/Resources.resx rename to src/TestableIO.System.IO.Abstractions.TestingHelpers/Properties/Resources.resx index d47ca2bdc..765cccbfe 100644 --- a/TestingHelpers/Properties/Resources.resx +++ b/src/TestableIO.System.IO.Abstractions.TestingHelpers/Properties/Resources.resx @@ -127,7 +127,7 @@ Illegal characters in path. - This test helper hasn't been implemented yet. They are implemented on an as-needed basis. As it seems like you need it, now would be a great time to send us a pull request over at https://github.com/tathamoddie/System.IO.Abstractions. You know, because it's open source and all. + This test helper hasn't been implemented yet. They are implemented on an as-needed basis. As it seems like you need it, now would be a great time to send us a pull request over at https://github.com/TestableIO/System.IO.Abstractions. You know, because it's open source and all. The path is not of a legal form. @@ -141,4 +141,34 @@ File name cannot be null. + + Could not find file '{0}'. + + + MockFileSystem does not have a built-in FileSystemWatcher implementation. You must provide your own mock or implementation of IFileSystemWatcherFactory and assign it to MockFileSystem.FileSystemWatcher. + + + The process cannot access the file because it is being used by another process. + + + The process cannot access the file '{0}' because it is being used by another process. + + + The file '{0}' already exists. + + + Append access can be requested only in write-only mode. + + + Combining FileMode: {0} with FileAccess: {1} is invalid. + + + Cannot create '{0}' because a file or directory with the same name already exists. + + + The name of the file cannot be resolved by the system. : '{0}' + + + '{0}' does not exist or could not be found. + \ No newline at end of file diff --git a/src/TestableIO.System.IO.Abstractions.TestingHelpers/StringExtensions.cs b/src/TestableIO.System.IO.Abstractions.TestingHelpers/StringExtensions.cs new file mode 100644 index 000000000..69db7f553 --- /dev/null +++ b/src/TestableIO.System.IO.Abstractions.TestingHelpers/StringExtensions.cs @@ -0,0 +1,123 @@ +using System.Collections.Generic; +using System.Diagnostics.Contracts; +using System.Linq; +using System.Text; + +namespace System.IO.Abstractions.TestingHelpers; + +using XFS = MockUnixSupport; + +internal static class StringExtensions +{ + [Pure] + public static string[] SplitLines(this string input) + { + var list = new List(); + using (var reader = new StringReader(input)) + { + string str; + while ((str = reader.ReadLine()) != null) + { + list.Add(str); + } + } + + return list.ToArray(); + } + + [Pure] + public static string Replace(this string source, string oldValue, string newValue, StringComparison comparisonType) + { + // from http://stackoverflow.com/a/22565605 with some adaptions + if (string.IsNullOrEmpty(oldValue)) + { + throw new ArgumentNullException(nameof(oldValue)); + } + + if (source.Length == 0) + { + return source; + } + + if (newValue == null) + { + newValue = string.Empty; + } + + var result = new StringBuilder(); + int startingPos = 0; + int nextMatch; + while ((nextMatch = source.IndexOf(oldValue, startingPos, comparisonType)) > -1) + { + result.Append(source, startingPos, nextMatch - startingPos); + result.Append(newValue); + startingPos = nextMatch + oldValue.Length; + } + + result.Append(source, startingPos, source.Length - startingPos); + + return result.ToString(); + } + + [Pure] + public static string TrimSlashes(this string path) + { + if (string.IsNullOrEmpty(path)) + { + return path; + } + + var trimmed = path.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar); + + if (XFS.IsUnixPlatform() + && (path[0] == Path.DirectorySeparatorChar || path[0] == Path.AltDirectorySeparatorChar) + && trimmed == "") + { + return Path.DirectorySeparatorChar.ToString(); + } + + if (XFS.IsWindowsPlatform() + && trimmed.Length == 2 + && char.IsLetter(trimmed[0]) + && trimmed[1] == ':') + { + return trimmed + Path.DirectorySeparatorChar; + } + + return trimmed; + } + + [Pure] + public static string NormalizeSlashes(this string path) + { + path = path.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar); + var sep = Path.DirectorySeparatorChar.ToString(); + var doubleSep = sep + sep; + + var prefixSeps = new string(path.TakeWhile(c => c == Path.DirectorySeparatorChar).ToArray()); + path = path.Substring(prefixSeps.Length); + + // UNC Paths start with double slash but no reason + // to have more than 2 slashes at the start of a path + if (XFS.IsWindowsPlatform() && prefixSeps.Length >= 2) + { + prefixSeps = prefixSeps.Substring(0, 2); + } + else if (prefixSeps.Length > 1) + { + prefixSeps = prefixSeps.Substring(0, 1); + } + + while (true) + { + var newPath = path.Replace(doubleSep, sep); + + if (path == newPath) + { + return prefixSeps + path; + } + + path = newPath; + } + } +} \ No newline at end of file diff --git a/src/TestableIO.System.IO.Abstractions.TestingHelpers/StringOperations.cs b/src/TestableIO.System.IO.Abstractions.TestingHelpers/StringOperations.cs new file mode 100644 index 000000000..9b20386cc --- /dev/null +++ b/src/TestableIO.System.IO.Abstractions.TestingHelpers/StringOperations.cs @@ -0,0 +1,75 @@ +namespace System.IO.Abstractions.TestingHelpers; + +/// +/// Provides operations against path strings dependeing on the case-senstivity of the runtime platform. +/// +#if FEATURE_SERIALIZABLE +[Serializable] +#endif +public class StringOperations +{ + private readonly bool caseSensitive; + private readonly StringComparison comparison; + + /// + /// Creates a new instance. + /// + public StringOperations(bool caseSensitive) + { + this.caseSensitive = caseSensitive; + comparison = caseSensitive ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase; + } + + /// + /// Provides a string comparer. + /// + public StringComparer Comparer => caseSensitive ? StringComparer.Ordinal : StringComparer.OrdinalIgnoreCase; + /// + /// Determines whether the given string starts with the given prefix. + /// + public bool StartsWith(string s, string prefix) => s.StartsWith(prefix, comparison); + /// + /// Determines whether the given string ends with the given suffix. + /// + public bool EndsWith(string s, string suffix) => s.EndsWith(suffix, comparison); + /// + /// Determines whether the given strings are equal. + /// + public bool Equals(string x, string y) => string.Equals(x, y, comparison); + /// + /// Determines whether the given characters are equal. + /// + public bool Equals(char x, char y) => caseSensitive ? x == y : char.ToUpper(x) == char.ToUpper(y); + /// + /// Determines the index of the given substring in the string. + /// + public int IndexOf(string s, string substring) => s.IndexOf(substring, comparison); + /// + /// Determines the index of the given substring in the string. + /// + public int IndexOf(string s, string substring, int startIndex) => s.IndexOf(substring, startIndex, comparison); + /// + /// Determines whether the given string contains the given substring. + /// + public bool Contains(string s, string substring) => s.IndexOf(substring, comparison) >= 0; + /// + /// Replaces a given value by a new value. + /// + public string Replace(string s, string oldValue, string newValue) => s.Replace(oldValue, newValue, comparison); + /// + /// Provides the lower-case representation of the given character. + /// + public char ToLower(char c) => caseSensitive ? c : char.ToLower(c); + /// + /// Provides the upper-case representation of the given character. + /// + public char ToUpper(char c) => caseSensitive ? c : char.ToUpper(c); + /// + /// Provides the lower-case representation of the given string. + /// + public string ToLower(string s) => caseSensitive ? s : s.ToLower(); + /// + /// Provides the upper-case representation of the given string. + /// + public string ToUpper(string s) => caseSensitive ? s : s.ToUpper(); +} \ No newline at end of file diff --git a/src/TestableIO.System.IO.Abstractions.TestingHelpers/StringResources.cs b/src/TestableIO.System.IO.Abstractions.TestingHelpers/StringResources.cs new file mode 100644 index 000000000..60373fd02 --- /dev/null +++ b/src/TestableIO.System.IO.Abstractions.TestingHelpers/StringResources.cs @@ -0,0 +1,11 @@ +using System.Reflection; +using System.Resources; + +namespace System.IO.Abstractions.TestingHelpers; + +internal static class StringResources +{ + public static ResourceManager Manager { get; } = new ResourceManager( + $"{typeof(StringResources).Namespace}.Properties.Resources", + typeof(StringResources).GetTypeInfo().Assembly); +} \ No newline at end of file diff --git a/src/TestableIO.System.IO.Abstractions.TestingHelpers/TestableIO.System.IO.Abstractions.TestingHelpers.csproj b/src/TestableIO.System.IO.Abstractions.TestingHelpers/TestableIO.System.IO.Abstractions.TestingHelpers.csproj new file mode 100644 index 000000000..439bdd6f8 --- /dev/null +++ b/src/TestableIO.System.IO.Abstractions.TestingHelpers/TestableIO.System.IO.Abstractions.TestingHelpers.csproj @@ -0,0 +1,14 @@ + + + + TestableIO.System.IO.Abstractions.TestingHelpers + System.IO.Abstractions.TestingHelpers + A set of pre-built mocks to help when testing file system interactions. + + + + + + + + diff --git a/src/TestableIO.System.IO.Abstractions.TestingHelpers/TimeAdjustments.cs b/src/TestableIO.System.IO.Abstractions.TestingHelpers/TimeAdjustments.cs new file mode 100644 index 000000000..cc7ed1532 --- /dev/null +++ b/src/TestableIO.System.IO.Abstractions.TestingHelpers/TimeAdjustments.cs @@ -0,0 +1,29 @@ +namespace System.IO.Abstractions.TestingHelpers; + +/// +/// Flags indicating which times to adjust for a . +/// +[Flags] +public enum TimeAdjustments +{ + /// + /// Adjusts no times on the + /// + None = 0, + /// + /// Adjusts the + /// + CreationTime = 1 << 0, + /// + /// Adjusts the + /// + LastAccessTime = 1 << 1, + /// + /// Adjusts the + /// + LastWriteTime = 1 << 2, + /// + /// Adjusts all times on the + /// + All = ~0 +} \ No newline at end of file diff --git a/src/TestableIO.System.IO.Abstractions.Wrappers/Converters.cs b/src/TestableIO.System.IO.Abstractions.Wrappers/Converters.cs new file mode 100644 index 000000000..39398177a --- /dev/null +++ b/src/TestableIO.System.IO.Abstractions.Wrappers/Converters.cs @@ -0,0 +1,60 @@ +using System.Collections.Generic; +using System.Globalization; +using System.Linq; + +namespace System.IO.Abstractions; + +internal static class Converters +{ + internal static IEnumerable WrapFileSystemInfos(this IEnumerable input, IFileSystem fileSystem) + => input.Select(info => WrapFileSystemInfo(fileSystem, info)); + + internal static FileSystemInfoBase[] WrapFileSystemInfos(this FileSystemInfo[] input, IFileSystem fileSystem) + => input.Select(info => WrapFileSystemInfo(fileSystem, info)).ToArray(); + + internal static FileSystemInfoBase WrapFileSystemInfo(this FileSystemInfo input, IFileSystem fileSystem) + => WrapFileSystemInfo(fileSystem, input); + + internal static IEnumerable WrapDirectories(this IEnumerable input, IFileSystem fileSystem) + => input.Select(info => WrapDirectoryInfo(fileSystem, info)); + + internal static DirectoryInfoBase[] WrapDirectories(this DirectoryInfo[] input, IFileSystem fileSystem) + => input.Select(info => WrapDirectoryInfo(fileSystem, info)).ToArray(); + + internal static IEnumerable WrapFiles(this IEnumerable input, IFileSystem fileSystem) + => input.Select(info => WrapFileInfo(fileSystem, info)); + + internal static FileInfoBase[] WrapFiles(this FileInfo[] input, IFileSystem fileSystem) + => input.Select(info => WrapFileInfo(fileSystem, info)).ToArray(); + + private static FileSystemInfoBase WrapFileSystemInfo(IFileSystem fileSystem, FileSystemInfo item) + { + if (item is null) + { + return null; + } + + if (item is FileInfo fileInfo) + { + return WrapFileInfo(fileSystem, fileInfo); + } + else if (item is DirectoryInfo directoryInfo) + { + return WrapDirectoryInfo(fileSystem, directoryInfo); + } + else + { + throw new NotImplementedException(string.Format( + CultureInfo.InvariantCulture, + "The type {0} is not recognized by the System.IO.Abstractions library.", + item.GetType().AssemblyQualifiedName + )); + } + } + + private static FileInfoBase WrapFileInfo(IFileSystem fileSystem, FileInfo f) + => f is null ? null : new FileInfoWrapper(fileSystem, f); + + private static DirectoryInfoBase WrapDirectoryInfo(IFileSystem fileSystem, DirectoryInfo d) + => d is null ? null : new DirectoryInfoWrapper(fileSystem, d); +} \ No newline at end of file diff --git a/src/TestableIO.System.IO.Abstractions.Wrappers/DirectoryAclExtensions.cs b/src/TestableIO.System.IO.Abstractions.Wrappers/DirectoryAclExtensions.cs new file mode 100644 index 000000000..248442c63 --- /dev/null +++ b/src/TestableIO.System.IO.Abstractions.Wrappers/DirectoryAclExtensions.cs @@ -0,0 +1,66 @@ +using System.Runtime.Versioning; +using System.Security.AccessControl; + +namespace System.IO.Abstractions; + +/// +/// ACL (access control list) extension methods for . +/// +public static class DirectoryAclExtensions +{ +#if FEATURE_FILE_SYSTEM_ACL_EXTENSIONS + /// +#else + /// +#endif + [SupportedOSPlatform("windows")] + public static void CreateDirectory(this IDirectory directory, + string path, + DirectorySecurity directorySecurity) + { + IDirectoryInfo directoryInfo = directory.FileSystem.DirectoryInfo.New(path); + directoryInfo.Create(directorySecurity); + } + +#if FEATURE_FILE_SYSTEM_ACL_EXTENSIONS + /// +#else + /// +#endif + [SupportedOSPlatform("windows")] + public static DirectorySecurity GetAccessControl( + this IDirectory directory, string path) + { + IDirectoryInfo directoryInfo = directory.FileSystem.DirectoryInfo.New(path); + return directoryInfo.GetAccessControl(); + } + +#if FEATURE_FILE_SYSTEM_ACL_EXTENSIONS + /// +#else + /// +#endif + [SupportedOSPlatform("windows")] + public static DirectorySecurity GetAccessControl( + this IDirectory directory, + string path, + AccessControlSections includeSections) + { + IDirectoryInfo directoryInfo = directory.FileSystem.DirectoryInfo.New(path); + return directoryInfo.GetAccessControl(includeSections); + } + +#if FEATURE_FILE_SYSTEM_ACL_EXTENSIONS + /// +#else + /// +#endif + [SupportedOSPlatform("windows")] + public static void SetAccessControl(this IDirectory directory, + string path, + DirectorySecurity directorySecurity) + { + IDirectoryInfo directoryInfo = directory.FileSystem.DirectoryInfo.New(path); + directoryInfo.SetAccessControl(directorySecurity); + } +} \ No newline at end of file diff --git a/src/TestableIO.System.IO.Abstractions.Wrappers/DirectoryBase.cs b/src/TestableIO.System.IO.Abstractions.Wrappers/DirectoryBase.cs new file mode 100644 index 000000000..c8583b3c7 --- /dev/null +++ b/src/TestableIO.System.IO.Abstractions.Wrappers/DirectoryBase.cs @@ -0,0 +1,196 @@ +using System.Collections.Generic; + +namespace System.IO.Abstractions; + +/// +#if FEATURE_SERIALIZABLE +[Serializable] +#endif +public abstract class DirectoryBase : IDirectory +{ + /// + /// Base class for calling static methods of + /// + protected DirectoryBase(IFileSystem fileSystem) + { + FileSystem = fileSystem; + } + + [Obsolete("This constructor only exists to support mocking libraries.", error: true)] + internal DirectoryBase() { } + + /// + /// Exposes the underlying filesystem implementation. This is useful for implementing extension methods. + /// + public IFileSystem FileSystem { get; } + + /// + public abstract IDirectoryInfo CreateDirectory(string path); + +#if FEATURE_UNIX_FILE_MODE + /// + public abstract IDirectoryInfo CreateDirectory(string path, UnixFileMode unixCreateMode); +#endif + +#if FEATURE_CREATE_SYMBOLIC_LINK + /// + public abstract IFileSystemInfo CreateSymbolicLink(string path, string pathToTarget); +#endif + +#if FEATURE_CREATE_TEMP_SUBDIRECTORY + /// + public abstract IDirectoryInfo CreateTempSubdirectory(string prefix = null); +#endif + /// + public abstract void Delete(string path); + + /// + public abstract void Delete(string path, bool recursive); + + /// + public abstract bool Exists(string path); + + /// + public abstract DateTime GetCreationTime(string path); + + /// + public abstract DateTime GetCreationTimeUtc(string path); + + /// + public abstract string GetCurrentDirectory(); + + /// + public abstract string[] GetDirectories(string path); + + /// + public abstract string[] GetDirectories(string path, string searchPattern); + + /// + public abstract string[] GetDirectories(string path, string searchPattern, SearchOption searchOption); + +#if FEATURE_ENUMERATION_OPTIONS + /// + public abstract string[] GetDirectories(string path, string searchPattern, EnumerationOptions enumerationOptions); +#endif + + /// + public abstract string GetDirectoryRoot(string path); + + /// + public abstract string[] GetFiles(string path); + + /// + public abstract string[] GetFiles(string path, string searchPattern); + + /// + public abstract string[] GetFiles(string path, string searchPattern, SearchOption searchOption); + +#if FEATURE_ENUMERATION_OPTIONS + /// + public abstract string[] GetFiles(string path, string searchPattern, EnumerationOptions enumerationOptions); +#endif + + /// + public abstract string[] GetFileSystemEntries(string path); + + /// + public abstract string[] GetFileSystemEntries(string path, string searchPattern); + + /// + public abstract string[] GetFileSystemEntries(string path, string searchPattern, SearchOption searchOption); + +#if FEATURE_ENUMERATION_OPTIONS + /// + public abstract string[] GetFileSystemEntries(string path, string searchPattern, + EnumerationOptions enumerationOptions); +#endif + + /// + public abstract DateTime GetLastAccessTime(string path); + + /// + public abstract DateTime GetLastAccessTimeUtc(string path); + + /// + public abstract DateTime GetLastWriteTime(string path); + + /// + public abstract DateTime GetLastWriteTimeUtc(string path); + + /// + public abstract string[] GetLogicalDrives(); + + /// + public abstract IDirectoryInfo GetParent(string path); + + /// + public abstract void Move(string sourceDirName, string destDirName); + +#if FEATURE_CREATE_SYMBOLIC_LINK + /// + public abstract IFileSystemInfo ResolveLinkTarget(string linkPath, bool returnFinalTarget); +#endif + + /// + public abstract void SetCreationTime(string path, DateTime creationTime); + + /// + public abstract void SetCreationTimeUtc(string path, DateTime creationTimeUtc); + + /// + public abstract void SetCurrentDirectory(string path); + + /// + public abstract void SetLastAccessTime(string path, DateTime lastAccessTime); + + /// + public abstract void SetLastAccessTimeUtc(string path, DateTime lastAccessTimeUtc); + + /// + public abstract void SetLastWriteTime(string path, DateTime lastWriteTime); + + /// + public abstract void SetLastWriteTimeUtc(string path, DateTime lastWriteTimeUtc); + + /// + public abstract IEnumerable EnumerateDirectories(string path); + + /// + public abstract IEnumerable EnumerateDirectories(string path, string searchPattern); + + /// + public abstract IEnumerable EnumerateDirectories(string path, string searchPattern, SearchOption searchOption); + +#if FEATURE_ENUMERATION_OPTIONS + /// + public abstract IEnumerable EnumerateDirectories(string path, string searchPattern, EnumerationOptions enumerationOptions); +#endif + + /// + public abstract IEnumerable EnumerateFiles(string path); + + /// + public abstract IEnumerable EnumerateFiles(string path, string searchPattern); + + /// + public abstract IEnumerable EnumerateFiles(string path, string searchPattern, SearchOption searchOption); + +#if FEATURE_ENUMERATION_OPTIONS + /// + public abstract IEnumerable EnumerateFiles(string path, string searchPattern, EnumerationOptions enumerationOptions); +#endif + + /// + public abstract IEnumerable EnumerateFileSystemEntries(string path); + + /// + public abstract IEnumerable EnumerateFileSystemEntries(string path, string searchPattern); + + /// + public abstract IEnumerable EnumerateFileSystemEntries(string path, string searchPattern, SearchOption searchOption); + +#if FEATURE_ENUMERATION_OPTIONS + /// + public abstract IEnumerable EnumerateFileSystemEntries(string path, string searchPattern, EnumerationOptions enumerationOptions); +#endif +} \ No newline at end of file diff --git a/src/TestableIO.System.IO.Abstractions.Wrappers/DirectoryInfoAclExtensions.cs b/src/TestableIO.System.IO.Abstractions.Wrappers/DirectoryInfoAclExtensions.cs new file mode 100644 index 000000000..81c38f155 --- /dev/null +++ b/src/TestableIO.System.IO.Abstractions.Wrappers/DirectoryInfoAclExtensions.cs @@ -0,0 +1,86 @@ +using System.Runtime.Versioning; +using System.Security.AccessControl; + +namespace System.IO.Abstractions; + +/// +/// ACL (access control list) extension methods for . +/// +public static class DirectoryInfoAclExtensions +{ +#if FEATURE_FILE_SYSTEM_ACL_EXTENSIONS + /// +#else + /// +#endif + [SupportedOSPlatform("windows")] + public static void Create(this IDirectoryInfo directoryInfo, + DirectorySecurity directorySecurity) + { + IFileSystemAclSupport aclSupport = directoryInfo as IFileSystemAclSupport; + if (aclSupport == null) + { + throw new NotSupportedException("The directory info does not support ACL extensions"); + } + + directoryInfo.Create(); + aclSupport.SetAccessControl(directorySecurity); + } + +#if FEATURE_FILE_SYSTEM_ACL_EXTENSIONS + /// +#else + /// +#endif + [SupportedOSPlatform("windows")] + public static DirectorySecurity GetAccessControl( + this IDirectoryInfo directoryInfo) + { + IFileSystemAclSupport aclSupport = directoryInfo as IFileSystemAclSupport; + var directorySecurity = aclSupport?.GetAccessControl() as DirectorySecurity; + if (aclSupport == null || directorySecurity == null) + { + throw new NotSupportedException("The directory info does not support ACL extensions"); + } + + return directorySecurity; + } + +#if FEATURE_FILE_SYSTEM_ACL_EXTENSIONS + /// +#else + /// +#endif + [SupportedOSPlatform("windows")] + public static DirectorySecurity GetAccessControl( + this IDirectoryInfo directoryInfo, + AccessControlSections includeSections) + { + IFileSystemAclSupport aclSupport = directoryInfo as IFileSystemAclSupport; + var directorySecurity = aclSupport?.GetAccessControl((IFileSystemAclSupport.AccessControlSections) includeSections) as DirectorySecurity; + if (aclSupport == null || directorySecurity == null) + { + throw new NotSupportedException("The directory info does not support ACL extensions"); + } + + return directorySecurity; + } + +#if FEATURE_FILE_SYSTEM_ACL_EXTENSIONS + /// +#else + /// +#endif + [SupportedOSPlatform("windows")] + public static void SetAccessControl(this IDirectoryInfo directoryInfo, + DirectorySecurity directorySecurity) + { + IFileSystemAclSupport aclSupport = directoryInfo as IFileSystemAclSupport; + if (aclSupport == null) + { + throw new NotSupportedException("The directory info does not support ACL extensions"); + } + + aclSupport.SetAccessControl(directorySecurity); + } +} \ No newline at end of file diff --git a/src/TestableIO.System.IO.Abstractions.Wrappers/DirectoryInfoBase.cs b/src/TestableIO.System.IO.Abstractions.Wrappers/DirectoryInfoBase.cs new file mode 100644 index 000000000..59e21cd0d --- /dev/null +++ b/src/TestableIO.System.IO.Abstractions.Wrappers/DirectoryInfoBase.cs @@ -0,0 +1,135 @@ +using System.Collections.Generic; + +namespace System.IO.Abstractions; + +/// +#if FEATURE_SERIALIZABLE +[Serializable] +#endif +public abstract class DirectoryInfoBase : FileSystemInfoBase, IDirectoryInfo +{ + /// + /// Base class for calling methods of + /// + protected DirectoryInfoBase(IFileSystem fileSystem) : base(fileSystem) + { + } + + [Obsolete("This constructor only exists to support mocking libraries.", error: true)] + internal DirectoryInfoBase() { } + + /// + public abstract void Create(); + + /// + public abstract IDirectoryInfo CreateSubdirectory(string path); + + /// + public abstract void Delete(bool recursive); + + /// + public abstract IEnumerable EnumerateDirectories(); + + /// + public abstract IEnumerable EnumerateDirectories(string searchPattern); + + /// + public abstract IEnumerable EnumerateDirectories(string searchPattern, SearchOption searchOption); + +#if FEATURE_ENUMERATION_OPTIONS + /// + public abstract IEnumerable EnumerateDirectories(string searchPattern, EnumerationOptions enumerationOptions); +#endif + + /// + public abstract IEnumerable EnumerateFiles(); + + /// + public abstract IEnumerable EnumerateFiles(string searchPattern); + + /// + public abstract IEnumerable EnumerateFiles(string searchPattern, SearchOption searchOption); + +#if FEATURE_ENUMERATION_OPTIONS + /// + public abstract IEnumerable EnumerateFiles(string searchPattern, EnumerationOptions enumerationOptions); +#endif + + /// + public abstract IEnumerable EnumerateFileSystemInfos(); + + /// + public abstract IEnumerable EnumerateFileSystemInfos(string searchPattern); + + /// + public abstract IEnumerable EnumerateFileSystemInfos(string searchPattern, SearchOption searchOption); + +#if FEATURE_ENUMERATION_OPTIONS + /// + public abstract IEnumerable EnumerateFileSystemInfos(string searchPattern, EnumerationOptions enumerationOptions); +#endif + + /// + public abstract IDirectoryInfo[] GetDirectories(); + + /// + public abstract IDirectoryInfo[] GetDirectories(string searchPattern); + + /// + public abstract IDirectoryInfo[] GetDirectories(string searchPattern, SearchOption searchOption); + +#if FEATURE_ENUMERATION_OPTIONS + /// + public abstract IDirectoryInfo[] GetDirectories(string searchPattern, EnumerationOptions enumerationOptions); +#endif + + /// + public abstract IFileInfo[] GetFiles(); + + /// + public abstract IFileInfo[] GetFiles(string searchPattern); + + /// + public abstract IFileInfo[] GetFiles(string searchPattern, SearchOption searchOption); + + +#if FEATURE_ENUMERATION_OPTIONS + /// + public abstract IFileInfo[] GetFiles(string searchPattern, EnumerationOptions enumerationOptions); +#endif + + /// + public abstract IFileSystemInfo[] GetFileSystemInfos(); + + /// + public abstract IFileSystemInfo[] GetFileSystemInfos(string searchPattern); + + /// + public abstract IFileSystemInfo[] GetFileSystemInfos(string searchPattern, SearchOption searchOption); + +#if FEATURE_ENUMERATION_OPTIONS + /// + public abstract IFileSystemInfo[] GetFileSystemInfos(string searchPattern, EnumerationOptions enumerationOptions); +#endif + + /// + public abstract void MoveTo(string destDirName); + + /// + public abstract IDirectoryInfo Parent { get; } + + /// + public abstract IDirectoryInfo Root { get; } + + /// + /// Implicitly converts a to a . + /// + public static implicit operator DirectoryInfoBase(DirectoryInfo directoryInfo) + { + if (directoryInfo == null) + { + return null; + } + return new DirectoryInfoWrapper(new FileSystem(), directoryInfo); + } +} \ No newline at end of file diff --git a/src/TestableIO.System.IO.Abstractions.Wrappers/DirectoryInfoFactory.cs b/src/TestableIO.System.IO.Abstractions.Wrappers/DirectoryInfoFactory.cs new file mode 100644 index 000000000..78beda1d8 --- /dev/null +++ b/src/TestableIO.System.IO.Abstractions.Wrappers/DirectoryInfoFactory.cs @@ -0,0 +1,38 @@ +namespace System.IO.Abstractions; +#if FEATURE_SERIALIZABLE +[Serializable] +#endif +internal class DirectoryInfoFactory : IDirectoryInfoFactory +{ + private readonly IFileSystem fileSystem; + + /// + /// Base factory class for creating a + /// + public DirectoryInfoFactory(IFileSystem fileSystem) + { + this.fileSystem = fileSystem; + } + + /// + public IFileSystem FileSystem + => fileSystem; + + /// + public IDirectoryInfo New(string path) + { + var realDirectoryInfo = new DirectoryInfo(path); + return new DirectoryInfoWrapper(fileSystem, realDirectoryInfo); + } + + /// + public IDirectoryInfo Wrap(DirectoryInfo directoryInfo) + { + if (directoryInfo == null) + { + return null; + } + + return new DirectoryInfoWrapper(fileSystem, directoryInfo); + } +} \ No newline at end of file diff --git a/src/TestableIO.System.IO.Abstractions.Wrappers/DirectoryInfoWrapper.cs b/src/TestableIO.System.IO.Abstractions.Wrappers/DirectoryInfoWrapper.cs new file mode 100644 index 000000000..6d2554534 --- /dev/null +++ b/src/TestableIO.System.IO.Abstractions.Wrappers/DirectoryInfoWrapper.cs @@ -0,0 +1,367 @@ +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Versioning; +using System.Security.AccessControl; + +namespace System.IO.Abstractions; + +/// +#if FEATURE_SERIALIZABLE +[Serializable] +#endif +public class DirectoryInfoWrapper : DirectoryInfoBase, IFileSystemAclSupport +{ + private readonly DirectoryInfo instance; + + /// + /// Wrapper class for calling methods of + /// + public DirectoryInfoWrapper(IFileSystem fileSystem, DirectoryInfo instance) : base(fileSystem) + { + this.instance = instance ?? throw new ArgumentNullException(nameof(instance)); + } + +#if FEATURE_CREATE_SYMBOLIC_LINK + /// + public override void CreateAsSymbolicLink(string pathToTarget) + { + instance.CreateAsSymbolicLink(pathToTarget); + } +#endif + + /// + public override void Delete() + { + instance.Delete(); + } + + /// + public override void Refresh() + { + instance.Refresh(); + } + +#if FEATURE_CREATE_SYMBOLIC_LINK + /// + public override IFileSystemInfo ResolveLinkTarget(bool returnFinalTarget) + { + return instance.ResolveLinkTarget(returnFinalTarget) + .WrapFileSystemInfo(FileSystem); + } +#endif + + /// + public override FileAttributes Attributes + { + get { return instance.Attributes; } + set { instance.Attributes = value; } + } + + /// + public override DateTime CreationTime + { + get { return instance.CreationTime; } + set { instance.CreationTime = value; } + } + + /// + public override DateTime CreationTimeUtc + { + get { return instance.CreationTimeUtc; } + set { instance.CreationTimeUtc = value; } + } + + /// + public override bool Exists + { + get { return instance.Exists; } + } + + /// + public override string Extension + { + get { return instance.Extension; } + } + + /// + public override string FullName + { + get { return instance.FullName; } + } + + /// + public override DateTime LastAccessTime + { + get { return instance.LastAccessTime; } + set { instance.LastAccessTime = value; } + } + + /// + public override DateTime LastAccessTimeUtc + { + get { return instance.LastAccessTimeUtc; } + set { instance.LastAccessTimeUtc = value; } + } + + /// + public override DateTime LastWriteTime + { + get { return instance.LastWriteTime; } + set { instance.LastWriteTime = value; } + } + + /// + public override DateTime LastWriteTimeUtc + { + get { return instance.LastWriteTimeUtc; } + set { instance.LastWriteTimeUtc = value; } + } + +#if FEATURE_FILE_SYSTEM_INFO_LINK_TARGET + /// + public override string LinkTarget + { + get { return instance.LinkTarget; } + } +#endif + + /// + public override string Name + { + get { return instance.Name; } + } + + /// + public override void Create() + { + instance.Create(); + } + + /// + public override IDirectoryInfo CreateSubdirectory(string path) + { + return new DirectoryInfoWrapper(FileSystem, instance.CreateSubdirectory(path)); + } + + /// + public override void Delete(bool recursive) + { + instance.Delete(recursive); + } + + /// + public override IEnumerable EnumerateDirectories() + { + return instance.EnumerateDirectories().Select(directoryInfo => new DirectoryInfoWrapper(FileSystem, directoryInfo)); + } + + /// + public override IEnumerable EnumerateDirectories(string searchPattern) + { + return instance.EnumerateDirectories(searchPattern).Select(directoryInfo => new DirectoryInfoWrapper(FileSystem, directoryInfo)); + } + + /// + public override IEnumerable EnumerateDirectories(string searchPattern, SearchOption searchOption) + { + return instance.EnumerateDirectories(searchPattern, searchOption).Select(directoryInfo => new DirectoryInfoWrapper(FileSystem, directoryInfo)); + } + +#if FEATURE_ENUMERATION_OPTIONS + /// + public override IEnumerable EnumerateDirectories(string searchPattern, EnumerationOptions enumerationOptions) + { + return instance.EnumerateDirectories(searchPattern, enumerationOptions).Select(directoryInfo => new DirectoryInfoWrapper(FileSystem, directoryInfo)); + } +#endif + + /// + public override IEnumerable EnumerateFiles() + { + return instance.EnumerateFiles().Select(fileInfo => new FileInfoWrapper(FileSystem, fileInfo)); + } + + /// + public override IEnumerable EnumerateFiles(string searchPattern) + { + return instance.EnumerateFiles(searchPattern).Select(fileInfo => new FileInfoWrapper(FileSystem, fileInfo)); + } + + /// + public override IEnumerable EnumerateFiles(string searchPattern, SearchOption searchOption) + { + return instance.EnumerateFiles(searchPattern, searchOption).Select(fileInfo => new FileInfoWrapper(FileSystem, fileInfo)); + } + +#if FEATURE_ENUMERATION_OPTIONS + /// + public override IEnumerable EnumerateFiles(string searchPattern, EnumerationOptions enumerationOptions) + { + return instance.EnumerateFiles(searchPattern, enumerationOptions).Select(fileInfo => new FileInfoWrapper(FileSystem, fileInfo)); + } +#endif + + /// + public override IEnumerable EnumerateFileSystemInfos() + { + return instance.EnumerateFileSystemInfos().WrapFileSystemInfos(FileSystem); + } + + /// + public override IEnumerable EnumerateFileSystemInfos(string searchPattern) + { + return instance.EnumerateFileSystemInfos(searchPattern).WrapFileSystemInfos(FileSystem); + } + + /// + public override IEnumerable EnumerateFileSystemInfos(string searchPattern, SearchOption searchOption) + { + return instance.EnumerateFileSystemInfos(searchPattern, searchOption).WrapFileSystemInfos(FileSystem); + } + +#if FEATURE_ENUMERATION_OPTIONS + /// + public override IEnumerable EnumerateFileSystemInfos(string searchPattern, EnumerationOptions enumerationOptions) + { + return instance.EnumerateFileSystemInfos(searchPattern, enumerationOptions).WrapFileSystemInfos(FileSystem); + } +#endif + + /// + public override IDirectoryInfo[] GetDirectories() + { + return instance.GetDirectories().WrapDirectories(FileSystem); + } + + /// + public override IDirectoryInfo[] GetDirectories(string searchPattern) + { + return instance.GetDirectories(searchPattern).WrapDirectories(FileSystem); + } + + /// + public override IDirectoryInfo[] GetDirectories(string searchPattern, SearchOption searchOption) + { + return instance.GetDirectories(searchPattern, searchOption).WrapDirectories(FileSystem); + } + +#if FEATURE_ENUMERATION_OPTIONS + /// + public override IDirectoryInfo[] GetDirectories(string searchPattern, EnumerationOptions enumerationOptions) + { + return instance.GetDirectories(searchPattern, enumerationOptions).WrapDirectories(FileSystem); + } +#endif + + /// + public override IFileInfo[] GetFiles() + { + return instance.GetFiles().WrapFiles(FileSystem); + } + + /// + public override IFileInfo[] GetFiles(string searchPattern) + { + return instance.GetFiles(searchPattern).WrapFiles(FileSystem); + } + + /// + public override IFileInfo[] GetFiles(string searchPattern, SearchOption searchOption) + { + return instance.GetFiles(searchPattern, searchOption).WrapFiles(FileSystem); + } + +#if FEATURE_ENUMERATION_OPTIONS + /// + public override IFileInfo[] GetFiles(string searchPattern, EnumerationOptions enumerationOptions) + { + return instance.GetFiles(searchPattern, enumerationOptions).WrapFiles(FileSystem); + } +#endif + + /// + public override IFileSystemInfo[] GetFileSystemInfos() + { + return instance.GetFileSystemInfos().WrapFileSystemInfos(FileSystem); + } + + /// + public override IFileSystemInfo[] GetFileSystemInfos(string searchPattern) + { + return instance.GetFileSystemInfos(searchPattern).WrapFileSystemInfos(FileSystem); + } + + /// + public override IFileSystemInfo[] GetFileSystemInfos(string searchPattern, SearchOption searchOption) + { + return instance.GetFileSystemInfos(searchPattern, searchOption).WrapFileSystemInfos(FileSystem); + } + +#if FEATURE_ENUMERATION_OPTIONS + /// + public override IFileSystemInfo[] GetFileSystemInfos(string searchPattern, EnumerationOptions enumerationOptions) + { + return instance.GetFileSystemInfos(searchPattern, enumerationOptions).WrapFileSystemInfos(FileSystem); + } +#endif + + /// + public override void MoveTo(string destDirName) + { + instance.MoveTo(destDirName); + } + + /// + public override IDirectoryInfo Parent + { + get + { + if (instance.Parent == null) + { + return null; + } + else + { + return new DirectoryInfoWrapper(FileSystem, instance.Parent); + } + } + } + + /// + public override IDirectoryInfo Root + => new DirectoryInfoWrapper(FileSystem, instance.Root); + + /// + public override string ToString() + { + return instance.ToString(); + } + + /// + [SupportedOSPlatform("windows")] + public object GetAccessControl() + { + return instance.GetAccessControl(); + } + + /// + [SupportedOSPlatform("windows")] + public object GetAccessControl(IFileSystemAclSupport.AccessControlSections includeSections) + { + return instance.GetAccessControl((AccessControlSections)includeSections); + } + + /// + [SupportedOSPlatform("windows")] + public void SetAccessControl(object value) + { + if (value is DirectorySecurity directorySecurity) + { + this.instance.SetAccessControl(directorySecurity); + } + else + { + throw new ArgumentException("value must be of type `FileSecurity`"); + } + } +} \ No newline at end of file diff --git a/src/TestableIO.System.IO.Abstractions.Wrappers/DirectoryWrapper.cs b/src/TestableIO.System.IO.Abstractions.Wrappers/DirectoryWrapper.cs new file mode 100644 index 000000000..2485366d5 --- /dev/null +++ b/src/TestableIO.System.IO.Abstractions.Wrappers/DirectoryWrapper.cs @@ -0,0 +1,349 @@ +using System.Collections.Generic; +using System.Runtime.Versioning; + +namespace System.IO.Abstractions; + +/// +#if FEATURE_SERIALIZABLE +[Serializable] +#endif +public class DirectoryWrapper : DirectoryBase +{ + /// + public DirectoryWrapper(IFileSystem fileSystem) : base(fileSystem) + { + } + + /// + public override IDirectoryInfo CreateDirectory(string path) + { + var directoryInfo = new DirectoryInfo(path); + directoryInfo.Create(); + return new DirectoryInfoWrapper(FileSystem, directoryInfo); + } + +#if FEATURE_UNIX_FILE_MODE + /// + [UnsupportedOSPlatform("windows")] + public override IDirectoryInfo CreateDirectory(string path, UnixFileMode unixCreateMode) + { + return new DirectoryInfoWrapper(FileSystem, + Directory.CreateDirectory(path, unixCreateMode)); + } +#endif + +#if FEATURE_CREATE_SYMBOLIC_LINK + /// + public override IFileSystemInfo CreateSymbolicLink(string path, string pathToTarget) + { + return Directory.CreateSymbolicLink(path, pathToTarget) + .WrapFileSystemInfo(FileSystem); + } +#endif + +#if FEATURE_CREATE_TEMP_SUBDIRECTORY + /// + public override IDirectoryInfo CreateTempSubdirectory(string prefix = null) + { + return new DirectoryInfoWrapper(FileSystem, + Directory.CreateTempSubdirectory(prefix)); + } +#endif + /// + public override void Delete(string path) + { + Directory.Delete(path); + } + + /// + public override void Delete(string path, bool recursive) + { + Directory.Delete(path, recursive); + } + + /// + public override bool Exists(string path) + { + return Directory.Exists(path); + } + + /// + public override DateTime GetCreationTime(string path) + { + return Directory.GetCreationTime(path); + } + + /// + public override DateTime GetCreationTimeUtc(string path) + { + return Directory.GetCreationTimeUtc(path); + } + + /// + public override string GetCurrentDirectory() + { + return Directory.GetCurrentDirectory(); + } + + /// + public override string[] GetDirectories(string path) + { + return Directory.GetDirectories(path); + } + + /// + public override string[] GetDirectories(string path, string searchPattern) + { + return Directory.GetDirectories(path, searchPattern); + } + + /// + public override string[] GetDirectories(string path, string searchPattern, SearchOption searchOption) + { + return Directory.GetDirectories(path, searchPattern, searchOption); + } + +#if FEATURE_ENUMERATION_OPTIONS + /// + public override string[] GetDirectories(string path, string searchPattern, EnumerationOptions enumerationOptions) + { + return Directory.GetDirectories(path, searchPattern, enumerationOptions); + } +#endif + + /// + public override string GetDirectoryRoot(string path) + { + return Directory.GetDirectoryRoot(path); + } + + /// + public override string[] GetFiles(string path) + { + return Directory.GetFiles(path); + } + + /// + public override string[] GetFiles(string path, string searchPattern) + { + return Directory.GetFiles(path, searchPattern); + } + + /// + public override string[] GetFiles(string path, string searchPattern, SearchOption searchOption) + { + return Directory.GetFiles(path, searchPattern, searchOption); + } + +#if FEATURE_ENUMERATION_OPTIONS + /// + public override string[] GetFiles(string path, string searchPattern, EnumerationOptions enumerationOptions) + { + return Directory.GetFiles(path, searchPattern, enumerationOptions); + } +#endif + + /// + public override string[] GetFileSystemEntries(string path) + { + return Directory.GetFileSystemEntries(path); + } + + /// + public override string[] GetFileSystemEntries(string path, string searchPattern) + { + return Directory.GetFileSystemEntries(path, searchPattern); + } + + /// + public override string[] GetFileSystemEntries(string path, string searchPattern, SearchOption searchOption) + { + return Directory.GetFileSystemEntries(path, searchPattern, searchOption); + } + +#if FEATURE_ENUMERATION_OPTIONS + /// + public override string[] GetFileSystemEntries(string path, string searchPattern, EnumerationOptions enumerationOptions) + { + return Directory.GetFileSystemEntries(path, searchPattern, enumerationOptions); + } +#endif + + /// + public override DateTime GetLastAccessTime(string path) + { + return Directory.GetLastAccessTime(path); + } + + /// + public override DateTime GetLastAccessTimeUtc(string path) + { + return Directory.GetLastAccessTimeUtc(path); + } + + /// + public override DateTime GetLastWriteTime(string path) + { + return Directory.GetLastWriteTime(path); + } + + /// + public override DateTime GetLastWriteTimeUtc(string path) + { + return Directory.GetLastWriteTimeUtc(path); + } + + /// + public override string[] GetLogicalDrives() + { + return Directory.GetLogicalDrives(); + } + + /// + public override IDirectoryInfo GetParent(string path) + { + var parent = Directory.GetParent(path); + + if (parent == null) + { + return null; + } + + return new DirectoryInfoWrapper(FileSystem, parent); + } + + /// + public override void Move(string sourceDirName, string destDirName) + { + Directory.Move(sourceDirName, destDirName); + } + +#if FEATURE_CREATE_SYMBOLIC_LINK + /// + public override IFileSystemInfo ResolveLinkTarget(string linkPath, bool returnFinalTarget) + { + return Directory.ResolveLinkTarget(linkPath, returnFinalTarget) + .WrapFileSystemInfo(FileSystem); + } +#endif + + /// + public override void SetCreationTime(string path, DateTime creationTime) + { + Directory.SetCreationTime(path, creationTime); + } + + /// + public override void SetCreationTimeUtc(string path, DateTime creationTimeUtc) + { + Directory.SetCreationTimeUtc(path, creationTimeUtc); + } + + /// + public override void SetCurrentDirectory(string path) + { + Directory.SetCurrentDirectory(path); + } + + /// + public override void SetLastAccessTime(string path, DateTime lastAccessTime) + { + Directory.SetLastAccessTime(path, lastAccessTime); + } + + /// + public override void SetLastAccessTimeUtc(string path, DateTime lastAccessTimeUtc) + { + Directory.SetLastAccessTimeUtc(path, lastAccessTimeUtc); + } + + /// + public override void SetLastWriteTime(string path, DateTime lastWriteTime) + { + Directory.SetLastWriteTime(path, lastWriteTime); + } + + /// + public override void SetLastWriteTimeUtc(string path, DateTime lastWriteTimeUtc) + { + Directory.SetLastWriteTimeUtc(path, lastWriteTimeUtc); + } + + /// + public override IEnumerable EnumerateDirectories(string path) + { + return Directory.EnumerateDirectories(path); + } + + /// + public override IEnumerable EnumerateDirectories(string path, string searchPattern) + { + return Directory.EnumerateDirectories(path, searchPattern); + } + + /// + public override IEnumerable EnumerateDirectories(string path, string searchPattern, SearchOption searchOption) + { + return Directory.EnumerateDirectories(path, searchPattern, searchOption); + } + +#if FEATURE_ENUMERATION_OPTIONS + /// + public override IEnumerable EnumerateDirectories(string path, string searchPattern, EnumerationOptions enumerationOptions) + { + return Directory.EnumerateDirectories(path, searchPattern, enumerationOptions); + } +#endif + + /// + public override IEnumerable EnumerateFiles(string path) + { + return Directory.EnumerateFiles(path); + } + + /// + public override IEnumerable EnumerateFiles(string path, string searchPattern) + { + return Directory.EnumerateFiles(path, searchPattern); + } + + /// + public override IEnumerable EnumerateFiles(string path, string searchPattern, SearchOption searchOption) + { + return Directory.EnumerateFiles(path, searchPattern, searchOption); + } + +#if FEATURE_ENUMERATION_OPTIONS + /// + public override IEnumerable EnumerateFiles(string path, string searchPattern, EnumerationOptions enumerationOptions) + { + return Directory.EnumerateFiles(path, searchPattern, enumerationOptions); + } +#endif + + /// + public override IEnumerable EnumerateFileSystemEntries(string path) + { + return Directory.EnumerateFileSystemEntries(path); + } + + /// + public override IEnumerable EnumerateFileSystemEntries(string path, string searchPattern) + { + return Directory.EnumerateFileSystemEntries(path, searchPattern); + } + + /// + public override IEnumerable EnumerateFileSystemEntries(string path, string searchPattern, SearchOption searchOption) + { + return Directory.EnumerateFileSystemEntries(path, searchPattern, searchOption); + } + +#if FEATURE_ENUMERATION_OPTIONS + /// + public override IEnumerable EnumerateFileSystemEntries(string path, string searchPattern, EnumerationOptions enumerationOptions) + { + return Directory.EnumerateFileSystemEntries(path, searchPattern, enumerationOptions); + } +#endif +} \ No newline at end of file diff --git a/src/TestableIO.System.IO.Abstractions.Wrappers/DriveInfoBase.cs b/src/TestableIO.System.IO.Abstractions.Wrappers/DriveInfoBase.cs new file mode 100644 index 000000000..ef6629fdd --- /dev/null +++ b/src/TestableIO.System.IO.Abstractions.Wrappers/DriveInfoBase.cs @@ -0,0 +1,64 @@ +namespace System.IO.Abstractions; + +/// +#if FEATURE_SERIALIZABLE +[Serializable] +#endif +public abstract class DriveInfoBase : IDriveInfo +{ + /// + /// Base class for calling methods of + /// + protected DriveInfoBase(IFileSystem fileSystem) + { + FileSystem = fileSystem ?? throw new ArgumentNullException(nameof(fileSystem)); + } + + [Obsolete("This constructor only exists to support mocking libraries.", error: true)] + internal DriveInfoBase() { } + + /// + /// Exposes the underlying filesystem implementation. This is useful for implementing extension methods. + /// + public IFileSystem FileSystem { get; } + + /// + public abstract long AvailableFreeSpace { get; } + + /// + public abstract string DriveFormat { get; } + + /// + public abstract DriveType DriveType { get; } + + /// + public abstract bool IsReady { get; } + + /// + public abstract string Name { get; } + + /// + public abstract IDirectoryInfo RootDirectory { get; } + + /// + public abstract long TotalFreeSpace { get; } + + /// + public abstract long TotalSize { get; } + + /// + public abstract string VolumeLabel { get; set; } + + /// + /// Implicitly converts a to a . + /// + public static implicit operator DriveInfoBase(DriveInfo driveInfo) + { + if (driveInfo == null) + { + return null; + } + + return new DriveInfoWrapper(new FileSystem(), driveInfo); + } +} \ No newline at end of file diff --git a/src/TestableIO.System.IO.Abstractions.Wrappers/DriveInfoFactory.cs b/src/TestableIO.System.IO.Abstractions.Wrappers/DriveInfoFactory.cs new file mode 100644 index 000000000..a9ab7bf80 --- /dev/null +++ b/src/TestableIO.System.IO.Abstractions.Wrappers/DriveInfoFactory.cs @@ -0,0 +1,52 @@ +namespace System.IO.Abstractions; +#if FEATURE_SERIALIZABLE +[Serializable] +#endif +internal class DriveInfoFactory : IDriveInfoFactory +{ + private readonly IFileSystem fileSystem; + + /// + /// Base factory class for creating a + /// + public DriveInfoFactory(IFileSystem fileSystem) + { + this.fileSystem = fileSystem; + } + + /// + public IFileSystem FileSystem + => fileSystem; + + /// + public IDriveInfo[] GetDrives() + { + var driveInfos = DriveInfo.GetDrives(); + var driveInfoWrappers = new DriveInfoBase[driveInfos.Length]; + for (int index = 0; index < driveInfos.Length; index++) + { + var driveInfo = driveInfos[index]; + driveInfoWrappers[index] = new DriveInfoWrapper(fileSystem, driveInfo); + } + + return driveInfoWrappers; + } + + /// + public IDriveInfo New(string driveName) + { + var realDriveInfo = new DriveInfo(driveName); + return new DriveInfoWrapper(fileSystem, realDriveInfo); + } + + /// + public IDriveInfo Wrap(DriveInfo driveInfo) + { + if (driveInfo == null) + { + return null; + } + + return new DriveInfoWrapper(fileSystem, driveInfo); + } +} \ No newline at end of file diff --git a/src/TestableIO.System.IO.Abstractions.Wrappers/DriveInfoWrapper.cs b/src/TestableIO.System.IO.Abstractions.Wrappers/DriveInfoWrapper.cs new file mode 100644 index 000000000..b4f1eb9cd --- /dev/null +++ b/src/TestableIO.System.IO.Abstractions.Wrappers/DriveInfoWrapper.cs @@ -0,0 +1,169 @@ +using System.Runtime.Versioning; + +namespace System.IO.Abstractions; + +/// +/// The wrapper for a . +/// +#if FEATURE_SERIALIZABLE +[Serializable] +#endif +public class DriveInfoWrapper : DriveInfoBase +{ + /// + /// The instance of the real . + /// + private readonly DriveInfo instance; + + /// + /// Initializes a new instance of the class, which acts as a wrapper for a drive info. + /// + /// The underlying IFileSystem. + /// The drive info. + public DriveInfoWrapper(IFileSystem fileSystem, DriveInfo instance) : base(fileSystem) + { + this.instance = instance ?? throw new ArgumentNullException(nameof(instance)); + } + + /// + /// Gets or sets the name of a drive, such as C:\. + /// + /// The name of the drive. + /// + /// This property is the name assigned to the drive, such as C:\ or E:\. + /// + public override string Name + { + get { return instance.Name; } + } + + /// + /// Gets or sets the drive type, such as CD-ROM, removable, network, or fixed. + /// + /// One of the enumeration values that specifies a drive type. + /// + /// The DriveType property indicates whether a drive is one of the following: CDRom, Fixed, Network, NoRootDirectory, Ram, Removable, or Unknown. + /// These values are described in the DriveType enumeration. + /// + public override DriveType DriveType + { + get { return instance.DriveType; } + } + + /// + /// Gets or sets the name of the file system, such as NTFS or FAT32. + /// + /// + /// Use DriveFormat to determine what formatting a drive uses. + /// + /// The name of the file system on the specified drive. + /// Thrown if the access to the drive information is denied. + /// Thrown if the drive does not exist or is not mapped. + /// Thrown if an I/O error occurred (for example, a disk error or a drive was not ready). + public override string DriveFormat + { + get { return instance.DriveFormat; } + } + + /// + /// Gets or sets a value indicating whether a drive is ready. + /// + /// + /// if the drive is ready; if the drive is not ready. + /// + /// + /// IsReady indicates whether a drive is ready. + /// For example, it indicates whether a CD is in a CD drive or whether a removable storage device is ready for read/write operations. + /// If you do not test whether a drive is ready, and it is not ready, querying the drive using will raise an IOException. + /// Do not rely on IsReady to avoid catching exceptions from other members such as TotalSize, TotalFreeSpace, and . + /// Between the time that your code checks IsReady and then accesses one of the other properties (even if the access occurs immediately after the check), + /// a drive may have been disconnected or a disk may have been removed. + /// + public override bool IsReady + { + get { return instance.IsReady; } + } + + /// + /// Gets or sets the amount of available free space on a drive, in bytes. + /// + /// The amount of free space available on the drive, in bytes. + /// + /// This property indicates the amount of free space available on the drive. + /// Note that this number may be different from the TotalFreeSpace number because this property takes into account disk quotas. + /// + /// Thrown if the access to the drive information is denied. + /// Thrown if an I/O error occurred (for example, a disk error or a drive was not ready). + public override long AvailableFreeSpace + { + get { return instance.AvailableFreeSpace; } + } + + /// + /// Gets or sets the total amount of free space available on a drive, in bytes. + /// + /// The total free space available on a drive, in bytes. + /// This property indicates the total amount of free space available on the drive, not just what is available to the current user. + /// Thrown if the access to the drive information is denied. + /// Thrown if the drive does not exist or is not mapped. + /// Thrown if an I/O error occurred (for example, a disk error or a drive was not ready). + public override long TotalFreeSpace + { + get { return instance.TotalFreeSpace; } + } + + /// + /// Gets or sets the total size of storage space on a drive, in bytes. + /// + /// The total size of the drive, in bytes. + /// + /// This property indicates the total size of the drive in bytes, not just what is available to the current user. + /// + /// Thrown if the access to the drive information is denied. + /// Thrown if the drive does not exist or is not mapped. + /// Thrown if an I/O error occurred (for example, a disk error or a drive was not ready). + public override long TotalSize + { + get { return instance.TotalSize; } + } + + /// + /// Gets or sets the root directory of a drive. + /// + /// An object that contains the root directory of the drive. + public override IDirectoryInfo RootDirectory + { + get { return new DirectoryInfoWrapper(FileSystem, instance.RootDirectory); } + } + + /// + /// Gets or sets the volume label of a drive. + /// + /// The volume label. + /// + /// The label length is determined by the operating system. For example, NTFS allows a volume label to be up to 32 characters long. Note that is a valid VolumeLabel. + /// + /// Thrown if an I/O error occurred (for example, a disk error or a drive was not ready). + /// Thrown if the drive does not exist or is not mapped. + /// Thrown if the caller does not have the required permission. + /// + /// Thrown if the volume label is being set on a network or CD-ROM drive + /// -or- + /// Access to the drive information is denied. + /// + public override string VolumeLabel + { + get { return instance.VolumeLabel; } + + [SupportedOSPlatform("windows")] +#pragma warning disable CA1416 + set { instance.VolumeLabel = value; } +#pragma warning restore CA1416 + } + + /// + public override string ToString() + { + return instance.ToString(); + } +} \ No newline at end of file diff --git a/src/TestableIO.System.IO.Abstractions.Wrappers/FileAclExtensions.cs b/src/TestableIO.System.IO.Abstractions.Wrappers/FileAclExtensions.cs new file mode 100644 index 000000000..8a2d4ed0f --- /dev/null +++ b/src/TestableIO.System.IO.Abstractions.Wrappers/FileAclExtensions.cs @@ -0,0 +1,52 @@ +using System.Runtime.Versioning; +using System.Security.AccessControl; + +namespace System.IO.Abstractions; + +/// +/// ACL (access control list) extension methods for . +/// +public static class FileAclExtensions +{ +#if FEATURE_FILE_SYSTEM_ACL_EXTENSIONS + /// +#else + /// +#endif + [SupportedOSPlatform("windows")] + public static FileSecurity GetAccessControl( + this IFile file, string path) + { + IFileInfo fileInfo = file.FileSystem.FileInfo.New(path); + return fileInfo.GetAccessControl(); + } + +#if FEATURE_FILE_SYSTEM_ACL_EXTENSIONS + /// +#else + /// +#endif + [SupportedOSPlatform("windows")] + public static FileSecurity GetAccessControl( + this IFile file, + string path, + AccessControlSections includeSections) + { + IFileInfo fileInfo = file.FileSystem.FileInfo.New(path); + return fileInfo.GetAccessControl(includeSections); + } + +#if FEATURE_FILE_SYSTEM_ACL_EXTENSIONS + /// +#else + /// +#endif + [SupportedOSPlatform("windows")] + public static void SetAccessControl(this IFile file, + string path, + FileSecurity fileSecurity) + { + IFileInfo fileInfo = file.FileSystem.FileInfo.New(path); + fileInfo.SetAccessControl(fileSecurity); + } +} \ No newline at end of file diff --git a/src/TestableIO.System.IO.Abstractions.Wrappers/FileBase.Async.cs b/src/TestableIO.System.IO.Abstractions.Wrappers/FileBase.Async.cs new file mode 100644 index 000000000..edf2f436d --- /dev/null +++ b/src/TestableIO.System.IO.Abstractions.Wrappers/FileBase.Async.cs @@ -0,0 +1,102 @@ +#if FEATURE_ASYNC_FILE + +using System.Collections.Generic; +using System.Text; +using System.Threading; +using System.Threading.Tasks; + +namespace System.IO.Abstractions +{ + partial class FileBase + { +#if FEATURE_FILE_SPAN + /// + public abstract Task AppendAllBytesAsync(string path, byte[] bytes, + CancellationToken cancellationToken = default); + + /// + public abstract Task AppendAllBytesAsync(string path, ReadOnlyMemory bytes, + CancellationToken cancellationToken = default); +#endif + + /// + public abstract Task AppendAllLinesAsync(string path, IEnumerable contents, CancellationToken cancellationToken = default); + + /// + public abstract Task AppendAllLinesAsync(string path, IEnumerable contents, Encoding encoding, CancellationToken cancellationToken = default); + + + /// + public abstract Task AppendAllTextAsync(String path, String contents, CancellationToken cancellationToken = default); + + /// + public abstract Task AppendAllTextAsync(String path, String contents, Encoding encoding, CancellationToken cancellationToken = default); + +#if FEATURE_FILE_SPAN + /// + public abstract Task AppendAllTextAsync(string path, ReadOnlyMemory contents, + CancellationToken cancellationToken = default); + + /// + public abstract Task AppendAllTextAsync(string path, ReadOnlyMemory contents, Encoding encoding, + CancellationToken cancellationToken = default); +#endif + + /// + public abstract Task ReadAllBytesAsync(string path, CancellationToken cancellationToken = default); + /// + public abstract Task ReadAllLinesAsync(string path, CancellationToken cancellationToken = default); + + /// + public abstract Task ReadAllLinesAsync(string path, Encoding encoding, CancellationToken cancellationToken = default); + + /// + public abstract Task ReadAllTextAsync(string path, CancellationToken cancellationToken = default); + + /// + public abstract Task ReadAllTextAsync(string path, Encoding encoding, CancellationToken cancellationToken = default); + +#if FEATURE_READ_LINES_ASYNC + /// + public abstract IAsyncEnumerable ReadLinesAsync(string path, + CancellationToken cancellationToken = default); + + /// + public abstract IAsyncEnumerable ReadLinesAsync(string path, Encoding encoding, + CancellationToken cancellationToken = default); +#endif + + /// + public abstract Task WriteAllBytesAsync(string path, byte[] bytes, CancellationToken cancellationToken = default); + +#if FEATURE_FILE_SPAN + /// + public abstract Task WriteAllBytesAsync(string path, ReadOnlyMemory bytes, + CancellationToken cancellationToken = default); +#endif + + /// + public abstract Task WriteAllLinesAsync(string path, IEnumerable contents, CancellationToken cancellationToken = default); + + /// + public abstract Task WriteAllLinesAsync(string path, IEnumerable contents, Encoding encoding, CancellationToken cancellationToken = default); + + /// + public abstract Task WriteAllTextAsync(string path, string contents, CancellationToken cancellationToken = default); + + /// + public abstract Task WriteAllTextAsync(string path, string contents, Encoding encoding, CancellationToken cancellationToken = default); + +#if FEATURE_FILE_SPAN + /// + public abstract Task WriteAllTextAsync(string path, ReadOnlyMemory contents, + CancellationToken cancellationToken = default); + + /// + public abstract Task WriteAllTextAsync(string path, ReadOnlyMemory contents, Encoding encoding, + CancellationToken cancellationToken = default); +#endif + } +} + +#endif \ No newline at end of file diff --git a/src/TestableIO.System.IO.Abstractions.Wrappers/FileBase.cs b/src/TestableIO.System.IO.Abstractions.Wrappers/FileBase.cs new file mode 100644 index 000000000..bf32b5662 --- /dev/null +++ b/src/TestableIO.System.IO.Abstractions.Wrappers/FileBase.cs @@ -0,0 +1,322 @@ +using System.Collections.Generic; +using System.Text; +using Microsoft.Win32.SafeHandles; + +namespace System.IO.Abstractions; + +/// +#if FEATURE_SERIALIZABLE +[Serializable] +#endif +public abstract partial class FileBase : IFile +{ + /// + /// Base class for calling static methods of + /// + protected FileBase(IFileSystem fileSystem) + { + FileSystem = fileSystem; + } + + [Obsolete("This constructor only exists to support mocking libraries.", error: true)] + internal FileBase() { } + + /// + /// Exposes the underlying filesystem implementation. This is useful for implementing extension methods. + /// + public IFileSystem FileSystem { get; } + +#if FEATURE_FILE_SPAN + /// + public abstract void AppendAllBytes(string path, byte[] bytes); + + /// + public abstract void AppendAllBytes(string path, ReadOnlySpan bytes); +#endif + + /// + public abstract void AppendAllLines(string path, IEnumerable contents); + + /// + public abstract void AppendAllLines(string path, IEnumerable contents, Encoding encoding); + + /// + public abstract void AppendAllText(string path, string contents); + + /// + public abstract void AppendAllText(string path, string contents, Encoding encoding); + +#if FEATURE_FILE_SPAN + /// + public abstract void AppendAllText(string path, ReadOnlySpan contents); + + /// + public abstract void AppendAllText(string path, ReadOnlySpan contents, Encoding encoding); +#endif + + /// + public abstract StreamWriter AppendText(string path); + + /// + public abstract void Copy(string sourceFileName, string destFileName); + + /// + public abstract void Copy(string sourceFileName, string destFileName, bool overwrite); + + /// + public abstract FileSystemStream Create(string path); + + /// + public abstract FileSystemStream Create(string path, int bufferSize); + + /// + public abstract FileSystemStream Create(string path, int bufferSize, FileOptions options); + +#if FEATURE_CREATE_SYMBOLIC_LINK + /// + public abstract IFileSystemInfo CreateSymbolicLink(string path, string pathToTarget); +#endif + /// + public abstract StreamWriter CreateText(string path); + + /// + public abstract void Decrypt(string path); + + /// + public abstract void Delete(string path); + + /// + public abstract void Encrypt(string path); + + /// + public abstract bool Exists(string path); + + /// + public abstract FileAttributes GetAttributes(string path); + +#if FEATURE_FILE_ATTRIBUTES_VIA_HANDLE + /// + public abstract FileAttributes GetAttributes(SafeFileHandle fileHandle); +#endif + + /// + public abstract DateTime GetCreationTime(string path); + +#if FEATURE_FILE_ATTRIBUTES_VIA_HANDLE + /// + public abstract DateTime GetCreationTime(SafeFileHandle fileHandle); +#endif + + /// + public abstract DateTime GetCreationTimeUtc(string path); + +#if FEATURE_FILE_ATTRIBUTES_VIA_HANDLE + /// + public abstract DateTime GetCreationTimeUtc(SafeFileHandle fileHandle); +#endif + + /// + public abstract DateTime GetLastAccessTime(string path); + +#if FEATURE_FILE_ATTRIBUTES_VIA_HANDLE + /// + public abstract DateTime GetLastAccessTime(SafeFileHandle fileHandle); +#endif + + /// + public abstract DateTime GetLastAccessTimeUtc(string path); + +#if FEATURE_FILE_ATTRIBUTES_VIA_HANDLE + /// + public abstract DateTime GetLastAccessTimeUtc(SafeFileHandle fileHandle); +#endif + + /// + public abstract DateTime GetLastWriteTime(string path); + +#if FEATURE_FILE_ATTRIBUTES_VIA_HANDLE + /// + public abstract DateTime GetLastWriteTime(SafeFileHandle fileHandle); +#endif + + /// + public abstract DateTime GetLastWriteTimeUtc(string path); + +#if FEATURE_FILE_ATTRIBUTES_VIA_HANDLE + /// + public abstract DateTime GetLastWriteTimeUtc(SafeFileHandle fileHandle); +#endif + +#if FEATURE_UNIX_FILE_MODE + /// + public abstract UnixFileMode GetUnixFileMode(string path); +#endif + +#if FEATURE_FILE_ATTRIBUTES_VIA_HANDLE + /// + public abstract UnixFileMode GetUnixFileMode(SafeFileHandle fileHandle); +#endif + + /// + public abstract void Move(string sourceFileName, string destFileName); + +#if FEATURE_FILE_MOVE_WITH_OVERWRITE + /// + public abstract void Move(string sourceFileName, string destFileName, bool overwrite); +#endif + + /// + public abstract FileSystemStream Open(string path, FileMode mode); + + /// + public abstract FileSystemStream Open(string path, FileMode mode, FileAccess access); + + /// + public abstract FileSystemStream Open(string path, FileMode mode, FileAccess access, FileShare share); + +#if FEATURE_FILESTREAM_OPTIONS + /// + public abstract FileSystemStream Open(string path, FileStreamOptions options); +#endif + + /// + public abstract FileSystemStream OpenRead(string path); + + /// + public abstract StreamReader OpenText(string path); + + /// + public abstract FileSystemStream OpenWrite(string path); + + /// + public abstract byte[] ReadAllBytes(string path); + + /// + public abstract string[] ReadAllLines(string path); + + /// + public abstract string[] ReadAllLines(string path, Encoding encoding); + + /// + public abstract string ReadAllText(string path); + + /// + public abstract string ReadAllText(string path, Encoding encoding); + + /// + public abstract IEnumerable ReadLines(string path); + + /// + public abstract IEnumerable ReadLines(string path, Encoding encoding); + + /// + public abstract void Replace(string sourceFileName, string destinationFileName, string destinationBackupFileName); + + /// + public abstract void Replace(string sourceFileName, string destinationFileName, string destinationBackupFileName, bool ignoreMetadataErrors); + +#if FEATURE_CREATE_SYMBOLIC_LINK + /// + public abstract IFileSystemInfo ResolveLinkTarget(string linkPath, bool returnFinalTarget); +#endif + + /// + public abstract void SetAttributes(string path, FileAttributes fileAttributes); + +#if FEATURE_FILE_ATTRIBUTES_VIA_HANDLE + /// + public abstract void SetAttributes(SafeFileHandle fileHandle, FileAttributes fileAttributes); +#endif + + /// + public abstract void SetCreationTime(string path, DateTime creationTime); + +#if FEATURE_FILE_ATTRIBUTES_VIA_HANDLE + /// + public abstract void SetCreationTime(SafeFileHandle fileHandle, DateTime creationTime); +#endif + + /// + public abstract void SetCreationTimeUtc(string path, DateTime creationTimeUtc); + +#if FEATURE_FILE_ATTRIBUTES_VIA_HANDLE + /// + public abstract void SetCreationTimeUtc(SafeFileHandle fileHandle, DateTime creationTimeUtc); +#endif + + /// + public abstract void SetLastAccessTime(string path, DateTime lastAccessTime); + +#if FEATURE_FILE_ATTRIBUTES_VIA_HANDLE + /// + public abstract void SetLastAccessTime(SafeFileHandle fileHandle, DateTime lastAccessTime); +#endif + + /// + public abstract void SetLastAccessTimeUtc(string path, DateTime lastAccessTimeUtc); + +#if FEATURE_FILE_ATTRIBUTES_VIA_HANDLE + /// + public abstract void SetLastAccessTimeUtc(SafeFileHandle fileHandle, DateTime lastAccessTimeUtc); +#endif + + /// + public abstract void SetLastWriteTime(string path, DateTime lastWriteTime); + +#if FEATURE_FILE_ATTRIBUTES_VIA_HANDLE + /// + public abstract void SetLastWriteTime(SafeFileHandle fileHandle, DateTime lastWriteTime); +#endif + + /// + public abstract void SetLastWriteTimeUtc(string path, DateTime lastWriteTimeUtc); + +#if FEATURE_FILE_ATTRIBUTES_VIA_HANDLE + /// + public abstract void SetLastWriteTimeUtc(SafeFileHandle fileHandle, DateTime lastWriteTimeUtc); +#endif + +#if FEATURE_UNIX_FILE_MODE + /// + public abstract void SetUnixFileMode(string path, UnixFileMode mode); +#endif + +#if FEATURE_FILE_ATTRIBUTES_VIA_HANDLE + /// + public abstract void SetUnixFileMode(SafeFileHandle fileHandle, UnixFileMode mode); +#endif + + /// + public abstract void WriteAllBytes(string path, byte[] bytes); + +#if FEATURE_FILE_SPAN + /// + public abstract void WriteAllBytes(string path, ReadOnlySpan bytes); +#endif + + /// + public abstract void WriteAllLines(string path, IEnumerable contents); + + /// + public abstract void WriteAllLines(string path, IEnumerable contents, Encoding encoding); + + /// + public abstract void WriteAllLines(string path, string[] contents); + + /// + public abstract void WriteAllLines(string path, string[] contents, Encoding encoding); + + /// + public abstract void WriteAllText(string path, string contents); + + /// + public abstract void WriteAllText(string path, string contents, Encoding encoding); + +#if FEATURE_FILE_SPAN + /// + public abstract void WriteAllText(string path, ReadOnlySpan contents); + + /// + public abstract void WriteAllText(string path, ReadOnlySpan contents, Encoding encoding); +#endif +} \ No newline at end of file diff --git a/src/TestableIO.System.IO.Abstractions.Wrappers/FileInfoAclExtensions.cs b/src/TestableIO.System.IO.Abstractions.Wrappers/FileInfoAclExtensions.cs new file mode 100644 index 000000000..84550e1ce --- /dev/null +++ b/src/TestableIO.System.IO.Abstractions.Wrappers/FileInfoAclExtensions.cs @@ -0,0 +1,67 @@ +using System.Runtime.Versioning; +using System.Security.AccessControl; + +namespace System.IO.Abstractions; + +/// +/// ACL (access control list) extension methods for . +/// +public static class FileInfoAclExtensions +{ +#if FEATURE_FILE_SYSTEM_ACL_EXTENSIONS + /// +#else + /// +#endif + [SupportedOSPlatform("windows")] + public static FileSecurity GetAccessControl( + this IFileInfo fileInfo) + { + IFileSystemAclSupport aclSupport = fileInfo as IFileSystemAclSupport; + var fileSecurity = aclSupport?.GetAccessControl() as FileSecurity; + if (aclSupport == null || fileSecurity == null) + { + throw new NotSupportedException("The file info does not support ACL extensions"); + } + + return fileSecurity; + } + +#if FEATURE_FILE_SYSTEM_ACL_EXTENSIONS + /// +#else + /// +#endif + [SupportedOSPlatform("windows")] + public static FileSecurity GetAccessControl( + this IFileInfo fileInfo, + AccessControlSections includeSections) + { + IFileSystemAclSupport aclSupport = fileInfo as IFileSystemAclSupport; + var fileSecurity = aclSupport?.GetAccessControl((IFileSystemAclSupport.AccessControlSections)includeSections) as FileSecurity; + if (aclSupport == null || fileSecurity == null) + { + throw new NotSupportedException("The file info does not support ACL extensions"); + } + + return fileSecurity; + } + +#if FEATURE_FILE_SYSTEM_ACL_EXTENSIONS + /// +#else + /// +#endif + [SupportedOSPlatform("windows")] + public static void SetAccessControl(this IFileInfo fileInfo, + FileSecurity fileSecurity) + { + IFileSystemAclSupport aclSupport = fileInfo as IFileSystemAclSupport; + if (aclSupport == null) + { + throw new NotSupportedException("The file info does not support ACL extensions"); + } + + aclSupport.SetAccessControl(fileSecurity); + } +} \ No newline at end of file diff --git a/src/TestableIO.System.IO.Abstractions.Wrappers/FileInfoBase.cs b/src/TestableIO.System.IO.Abstractions.Wrappers/FileInfoBase.cs new file mode 100644 index 000000000..6057d3043 --- /dev/null +++ b/src/TestableIO.System.IO.Abstractions.Wrappers/FileInfoBase.cs @@ -0,0 +1,101 @@ +namespace System.IO.Abstractions; + +/// +#if FEATURE_SERIALIZABLE +[Serializable] +#endif +public abstract class FileInfoBase : FileSystemInfoBase, IFileInfo +{ + /// + /// Base class for calling methods of + /// + protected FileInfoBase(IFileSystem fileSystem) : base(fileSystem) + { + } + + [Obsolete("This constructor only exists to support mocking libraries.", error: true)] + internal FileInfoBase() { } + + /// + public abstract StreamWriter AppendText(); + + /// + public abstract IFileInfo CopyTo(string destFileName); + + /// + public abstract IFileInfo CopyTo(string destFileName, bool overwrite); + + /// + public abstract FileSystemStream Create(); + + /// + public abstract StreamWriter CreateText(); + + /// + public abstract void Decrypt(); + + /// + public abstract void Encrypt(); + + /// + public abstract void MoveTo(string destFileName); + +#if FEATURE_FILE_MOVE_WITH_OVERWRITE + /// + public abstract void MoveTo(string destFileName, bool overwrite); +#endif + + /// + public abstract FileSystemStream Open(FileMode mode); + + /// + public abstract FileSystemStream Open(FileMode mode, FileAccess access); + + /// + public abstract FileSystemStream Open(FileMode mode, FileAccess access, FileShare share); + +#if FEATURE_FILESTREAM_OPTIONS + /// + public abstract FileSystemStream Open(FileStreamOptions options); +#endif + + /// + public abstract FileSystemStream OpenRead(); + + /// + public abstract StreamReader OpenText(); + + /// + public abstract FileSystemStream OpenWrite(); + + /// + public abstract IFileInfo Replace(string destinationFileName, string destinationBackupFileName); + + /// + public abstract IFileInfo Replace(string destinationFileName, string destinationBackupFileName, bool ignoreMetadataErrors); + + /// + public abstract IDirectoryInfo Directory { get; } + + /// + public abstract string DirectoryName { get; } + + /// + public abstract bool IsReadOnly { get; set; } + + /// + public abstract long Length { get; } + + /// + /// Implicitly converts a to a . + /// + public static implicit operator FileInfoBase(FileInfo fileInfo) + { + if (fileInfo == null) + { + return null; + } + + return new FileInfoWrapper(new FileSystem(), fileInfo); + } +} \ No newline at end of file diff --git a/src/TestableIO.System.IO.Abstractions.Wrappers/FileInfoFactory.cs b/src/TestableIO.System.IO.Abstractions.Wrappers/FileInfoFactory.cs new file mode 100644 index 000000000..06ad00aa7 --- /dev/null +++ b/src/TestableIO.System.IO.Abstractions.Wrappers/FileInfoFactory.cs @@ -0,0 +1,39 @@ +namespace System.IO.Abstractions; +#if FEATURE_SERIALIZABLE +[Serializable] +#endif +internal class FileInfoFactory : IFileInfoFactory +{ + private readonly IFileSystem fileSystem; + + /// + /// Base factory class for creating a + /// + public FileInfoFactory(IFileSystem fileSystem) + { + this.fileSystem = fileSystem; + } + + /// + public IFileSystem FileSystem + => fileSystem; + + + /// + public IFileInfo New(string fileName) + { + var realFileInfo = new FileInfo(fileName); + return new FileInfoWrapper(fileSystem, realFileInfo); + } + + /// + public IFileInfo Wrap(FileInfo fileInfo) + { + if (fileInfo == null) + { + return null; + } + + return new FileInfoWrapper(fileSystem, fileInfo); + } +} \ No newline at end of file diff --git a/src/TestableIO.System.IO.Abstractions.Wrappers/FileInfoWrapper.cs b/src/TestableIO.System.IO.Abstractions.Wrappers/FileInfoWrapper.cs new file mode 100644 index 000000000..7192055b0 --- /dev/null +++ b/src/TestableIO.System.IO.Abstractions.Wrappers/FileInfoWrapper.cs @@ -0,0 +1,304 @@ +using System.Runtime.Versioning; +using System.Security.AccessControl; + +namespace System.IO.Abstractions; + +/// +#if FEATURE_SERIALIZABLE +[Serializable] +#endif +public class FileInfoWrapper : FileInfoBase, IFileSystemAclSupport +{ + private readonly FileInfo instance; + + /// + /// Wrapper class for calling methods of + /// + public FileInfoWrapper(IFileSystem fileSystem, FileInfo instance) : base(fileSystem) + { + this.instance = instance ?? throw new ArgumentNullException(nameof(instance)); + } + +#if FEATURE_CREATE_SYMBOLIC_LINK + /// + public override void CreateAsSymbolicLink(string pathToTarget) + { + instance.CreateAsSymbolicLink(pathToTarget); + } +#endif + + /// + public override void Delete() + { + instance.Delete(); + } + + /// + public override void Refresh() + { + instance.Refresh(); + } + +#if FEATURE_CREATE_SYMBOLIC_LINK + /// + public override IFileSystemInfo ResolveLinkTarget(bool returnFinalTarget) + { + return instance.ResolveLinkTarget(returnFinalTarget) + .WrapFileSystemInfo(FileSystem); + } +#endif + + /// + public override FileAttributes Attributes + { + get { return instance.Attributes; } + set { instance.Attributes = value; } + } + + /// + public override DateTime CreationTime + { + get { return instance.CreationTime; } + set { instance.CreationTime = value; } + } + + /// + public override DateTime CreationTimeUtc + { + get { return instance.CreationTimeUtc; } + set { instance.CreationTimeUtc = value; } + } + + /// + public override bool Exists + { + get { return instance.Exists; } + } + + /// + public override string Extension + { + get { return instance.Extension; } + } + + /// + public override string FullName + { + get { return instance.FullName; } + } + + /// + public override DateTime LastAccessTime + { + get { return instance.LastAccessTime; } + set { instance.LastAccessTime = value; } + } + + /// + public override DateTime LastAccessTimeUtc + { + get { return instance.LastAccessTimeUtc; } + set { instance.LastAccessTimeUtc = value; } + } + + /// + public override DateTime LastWriteTime + { + get { return instance.LastWriteTime; } + set { instance.LastWriteTime = value; } + } + + /// + public override DateTime LastWriteTimeUtc + { + get { return instance.LastWriteTimeUtc; } + set { instance.LastWriteTimeUtc = value; } + } + +#if FEATURE_FILE_SYSTEM_INFO_LINK_TARGET + /// + public override string LinkTarget + { + get { return instance.LinkTarget; } + } +#endif + + /// + public override string Name + { + get { return instance.Name; } + } + + /// + public override StreamWriter AppendText() + { + return instance.AppendText(); + } + + /// + public override IFileInfo CopyTo(string destFileName) + { + return new FileInfoWrapper(FileSystem, instance.CopyTo(destFileName)); + } + + /// + public override IFileInfo CopyTo(string destFileName, bool overwrite) + { + return new FileInfoWrapper(FileSystem, instance.CopyTo(destFileName, overwrite)); + } + + /// + public override FileSystemStream Create() + { + return new FileStreamWrapper(instance.Create()); + } + + /// + public override StreamWriter CreateText() + { + return instance.CreateText(); + } + + /// + [SupportedOSPlatform("windows")] + public override void Decrypt() + { + instance.Decrypt(); + } + + /// + [SupportedOSPlatform("windows")] + public override void Encrypt() + { + instance.Encrypt(); + } + + /// + public override void MoveTo(string destFileName) + { + instance.MoveTo(destFileName); + } + +#if FEATURE_FILE_MOVE_WITH_OVERWRITE + /// + public override void MoveTo(string destFileName, bool overwrite) + { + instance.MoveTo(destFileName, overwrite); + } +#endif + + /// + public override FileSystemStream Open(FileMode mode) + { + return new FileStreamWrapper(instance.Open(mode)); + } + + /// + public override FileSystemStream Open(FileMode mode, FileAccess access) + { + return new FileStreamWrapper(instance.Open(mode, access)); + } + + /// + public override FileSystemStream Open(FileMode mode, FileAccess access, FileShare share) + { + return new FileStreamWrapper(instance.Open(mode, access, share)); + } + +#if FEATURE_FILESTREAM_OPTIONS + /// + public override FileSystemStream Open(FileStreamOptions options) + { + return new FileStreamWrapper(instance.Open(options)); + } +#endif + + /// + public override FileSystemStream OpenRead() + { + return new FileStreamWrapper(instance.OpenRead()); + } + + /// + public override StreamReader OpenText() + { + return instance.OpenText(); + } + + /// + public override FileSystemStream OpenWrite() + { + return new FileStreamWrapper(instance.OpenWrite()); + } + + /// + public override IFileInfo Replace(string destinationFileName, string destinationBackupFileName) + { + return new FileInfoWrapper(FileSystem, instance.Replace(destinationFileName, destinationBackupFileName)); + } + + /// + public override IFileInfo Replace(string destinationFileName, string destinationBackupFileName, bool ignoreMetadataErrors) + { + return new FileInfoWrapper(FileSystem, instance.Replace(destinationFileName, destinationBackupFileName, ignoreMetadataErrors)); + } + + /// + public override IDirectoryInfo Directory + { + get { return new DirectoryInfoWrapper(FileSystem, instance.Directory); } + } + + /// + public override string DirectoryName + { + get { return instance.DirectoryName; } + } + + /// + public override bool IsReadOnly + { + get { return instance.IsReadOnly; } + set { instance.IsReadOnly = value; } + } + + /// + public override long Length + { + get { return instance.Length; } + } + + /// + public override string ToString() + { + return instance.ToString(); + } + + /// + [SupportedOSPlatform("windows")] + public object GetAccessControl() + { + return instance.GetAccessControl(); + } + + /// + [SupportedOSPlatform("windows")] + public object GetAccessControl(IFileSystemAclSupport.AccessControlSections includeSections) + { + return instance.GetAccessControl((AccessControlSections)includeSections); + } + + /// + [SupportedOSPlatform("windows")] + public void SetAccessControl(object value) + { + if (value is FileSecurity fileSecurity) + { + this.instance.SetAccessControl(fileSecurity); + } + else + { + throw new ArgumentException("value must be of type `FileSecurity`"); + } + } +} \ No newline at end of file diff --git a/src/TestableIO.System.IO.Abstractions.Wrappers/FileStreamAclExtensions.cs b/src/TestableIO.System.IO.Abstractions.Wrappers/FileStreamAclExtensions.cs new file mode 100644 index 000000000..06d126519 --- /dev/null +++ b/src/TestableIO.System.IO.Abstractions.Wrappers/FileStreamAclExtensions.cs @@ -0,0 +1,46 @@ +using System.Runtime.Versioning; +using System.Security.AccessControl; + +namespace System.IO.Abstractions; + +/// +/// ACL (access control list) extension methods for . +/// +public static class FileStreamAclExtensions +{ +#if FEATURE_FILE_SYSTEM_ACL_EXTENSIONS + /// +#else + /// +#endif + [SupportedOSPlatform("windows")] + public static FileSecurity GetAccessControl(this FileSystemStream fileStream) + { + IFileSystemAclSupport aclSupport = fileStream as IFileSystemAclSupport; + var fileSecurity = aclSupport?.GetAccessControl() as FileSecurity; + if (aclSupport == null || fileSecurity == null) + { + throw new NotSupportedException("The file stream does not support ACL extensions"); + } + + return fileSecurity; + } + +#if FEATURE_FILE_SYSTEM_ACL_EXTENSIONS + /// +#else + /// +#endif + [SupportedOSPlatform("windows")] + public static void SetAccessControl(this FileSystemStream fileStream, + FileSecurity fileSecurity) + { + IFileSystemAclSupport aclSupport = fileStream as IFileSystemAclSupport; + if (aclSupport == null) + { + throw new NotSupportedException("The file info does not support ACL extensions"); + } + + aclSupport.SetAccessControl(fileSecurity); + } +} \ No newline at end of file diff --git a/src/TestableIO.System.IO.Abstractions.Wrappers/FileStreamFactory.cs b/src/TestableIO.System.IO.Abstractions.Wrappers/FileStreamFactory.cs new file mode 100644 index 000000000..05599230f --- /dev/null +++ b/src/TestableIO.System.IO.Abstractions.Wrappers/FileStreamFactory.cs @@ -0,0 +1,68 @@ +using Microsoft.Win32.SafeHandles; + +namespace System.IO.Abstractions; +#if FEATURE_SERIALIZABLE +[Serializable] +#endif +internal sealed class FileStreamFactory : IFileStreamFactory +{ + /// + /// Base factory class for creating a + /// + public FileStreamFactory(IFileSystem fileSystem) + { + FileSystem = fileSystem; + } + + /// + public IFileSystem FileSystem { get; } + + /// + public FileSystemStream New(SafeFileHandle handle, FileAccess access) + => new FileStreamWrapper(new FileStream(handle, access)); + + /// + public FileSystemStream New(SafeFileHandle handle, FileAccess access, int bufferSize) + => new FileStreamWrapper(new FileStream(handle, access, bufferSize)); + + /// + public FileSystemStream New(SafeFileHandle handle, FileAccess access, int bufferSize, bool isAsync) + => new FileStreamWrapper(new FileStream(handle, access, bufferSize, isAsync)); + + + /// + public FileSystemStream New(string path, FileMode mode) + => new FileStreamWrapper(new FileStream(path, mode)); + + + /// + public FileSystemStream New(string path, FileMode mode, FileAccess access) + => new FileStreamWrapper(new FileStream(path, mode, access)); + + /// + public FileSystemStream New(string path, FileMode mode, FileAccess access, FileShare share) + => new FileStreamWrapper(new FileStream(path, mode, access, share)); + + /// + public FileSystemStream New(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize) + => new FileStreamWrapper(new FileStream(path, mode, access, share, bufferSize)); + + /// + public FileSystemStream New(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, bool useAsync) + => new FileStreamWrapper(new FileStream(path, mode, access, share, bufferSize, useAsync)); + + /// + public FileSystemStream New(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, + FileOptions options) + => new FileStreamWrapper(new FileStream(path, mode, access, share, bufferSize, options)); + +#if FEATURE_FILESTREAM_OPTIONS + /// + public FileSystemStream New(string path, FileStreamOptions options) + => new FileStreamWrapper(new FileStream(path, options)); +#endif + + /// + public FileSystemStream Wrap(FileStream fileStream) + => new FileStreamWrapper(fileStream); +} \ No newline at end of file diff --git a/src/TestableIO.System.IO.Abstractions.Wrappers/FileStreamWrapper.cs b/src/TestableIO.System.IO.Abstractions.Wrappers/FileStreamWrapper.cs new file mode 100644 index 000000000..074251262 --- /dev/null +++ b/src/TestableIO.System.IO.Abstractions.Wrappers/FileStreamWrapper.cs @@ -0,0 +1,48 @@ +using System.Runtime.Versioning; +using System.Security.AccessControl; + +namespace System.IO.Abstractions; + +internal sealed class FileStreamWrapper : FileSystemStream, IFileSystemAclSupport +{ + private readonly FileStream fileStream; + + public FileStreamWrapper(FileStream fileStream) + : base(fileStream, fileStream.Name, fileStream.IsAsync) + + { + this.fileStream = fileStream; + } + + /// + [SupportedOSPlatform("windows")] + public object GetAccessControl() + { + return fileStream.GetAccessControl(); + } + + /// + [SupportedOSPlatform("windows")] + public object GetAccessControl(IFileSystemAclSupport.AccessControlSections includeSections) + { + throw new NotSupportedException("GetAccessControl with includeSections is not supported for FileStreams"); + } + + /// + [SupportedOSPlatform("windows")] + public void SetAccessControl(object value) + { + if (value is FileSecurity fileSecurity) + { + this.fileStream.SetAccessControl(fileSecurity); + } + else + { + throw new ArgumentException("value must be of type `FileSecurity`"); + } + } + + /// + public override void Flush(bool flushToDisk) + => fileStream.Flush(flushToDisk); +} \ No newline at end of file diff --git a/src/TestableIO.System.IO.Abstractions.Wrappers/FileSystem.cs b/src/TestableIO.System.IO.Abstractions.Wrappers/FileSystem.cs new file mode 100644 index 000000000..816df7ccd --- /dev/null +++ b/src/TestableIO.System.IO.Abstractions.Wrappers/FileSystem.cs @@ -0,0 +1,49 @@ +namespace System.IO.Abstractions; + +/// +#if FEATURE_SERIALIZABLE +[Serializable] +#endif +public class FileSystem : FileSystemBase +{ + /// + public FileSystem() + { + DriveInfo = new DriveInfoFactory(this); + DirectoryInfo = new DirectoryInfoFactory(this); + FileInfo = new FileInfoFactory(this); + FileVersionInfo = new FileVersionInfoFactory(this); + Path = new PathWrapper(this); + File = new FileWrapper(this); + Directory = new DirectoryWrapper(this); + FileStream = new FileStreamFactory(this); + FileSystemWatcher = new FileSystemWatcherFactory(this); + } + + /// + public override IDirectory Directory { get; } + + /// + public override IFile File { get; } + + /// + public override IFileInfoFactory FileInfo { get; } + + /// + public override IFileVersionInfoFactory FileVersionInfo { get; } + + /// + public override IFileStreamFactory FileStream { get; } + + /// + public override IPath Path { get; } + + /// + public override IDirectoryInfoFactory DirectoryInfo { get; } + + /// + public override IDriveInfoFactory DriveInfo { get; } + + /// + public override IFileSystemWatcherFactory FileSystemWatcher { get; } +} \ No newline at end of file diff --git a/src/TestableIO.System.IO.Abstractions.Wrappers/FileSystemBase.cs b/src/TestableIO.System.IO.Abstractions.Wrappers/FileSystemBase.cs new file mode 100644 index 000000000..9a151ccac --- /dev/null +++ b/src/TestableIO.System.IO.Abstractions.Wrappers/FileSystemBase.cs @@ -0,0 +1,35 @@ +namespace System.IO.Abstractions; + +/// +#if FEATURE_SERIALIZABLE +[Serializable] +#endif +public abstract class FileSystemBase : IFileSystem +{ + /// + public abstract IDirectory Directory { get; } + + /// + public abstract IFile File { get; } + + /// + public abstract IFileInfoFactory FileInfo { get; } + + /// + public abstract IFileVersionInfoFactory FileVersionInfo { get; } + + /// + public abstract IFileStreamFactory FileStream { get; } + + /// + public abstract IPath Path { get; } + + /// + public abstract IDirectoryInfoFactory DirectoryInfo { get; } + + /// + public abstract IDriveInfoFactory DriveInfo { get; } + + /// + public abstract IFileSystemWatcherFactory FileSystemWatcher { get; } +} \ No newline at end of file diff --git a/src/TestableIO.System.IO.Abstractions.Wrappers/FileSystemInfoBase.cs b/src/TestableIO.System.IO.Abstractions.Wrappers/FileSystemInfoBase.cs new file mode 100644 index 000000000..7156c1e5d --- /dev/null +++ b/src/TestableIO.System.IO.Abstractions.Wrappers/FileSystemInfoBase.cs @@ -0,0 +1,89 @@ +using System.Runtime.Versioning; + +namespace System.IO.Abstractions; + +/// +#if FEATURE_SERIALIZABLE +[Serializable] +#endif +public abstract class FileSystemInfoBase : IFileSystemInfo +{ + /// + /// Base class for calling methods of + /// + protected FileSystemInfoBase(IFileSystem fileSystem) + { + FileSystem = fileSystem ?? throw new ArgumentNullException(nameof(fileSystem)); + } + + [Obsolete("This constructor only exists to support mocking libraries.", error: true)] + internal FileSystemInfoBase() { } + + /// + /// Exposes the underlying filesystem implementation. This is useful for implementing extension methods. + /// + public IFileSystem FileSystem { get; } + +#if FEATURE_CREATE_SYMBOLIC_LINK + /// + public abstract void CreateAsSymbolicLink(string pathToTarget); +#endif + + /// + public abstract void Delete(); + + /// + public abstract void Refresh(); + +#if FEATURE_CREATE_SYMBOLIC_LINK + /// + public abstract IFileSystemInfo ResolveLinkTarget(bool returnFinalTarget); +#endif + + /// + public abstract FileAttributes Attributes { get; set; } + + /// + public abstract DateTime CreationTime { get; set; } + + /// + public abstract DateTime CreationTimeUtc { get; set; } + + /// + public abstract bool Exists { get; } + + /// + public abstract string Extension { get; } + + /// + public abstract string FullName { get; } + + /// + public abstract DateTime LastAccessTime { get; set; } + + /// + public abstract DateTime LastAccessTimeUtc { get; set; } + + /// + public abstract DateTime LastWriteTime { get; set; } + + /// + public abstract DateTime LastWriteTimeUtc { get; set; } + +#if FEATURE_FILE_SYSTEM_INFO_LINK_TARGET + /// + public abstract string LinkTarget { get; } +#endif + + /// + public abstract string Name { get; } + +#if FEATURE_UNIX_FILE_MODE + /// + public UnixFileMode UnixFileMode + { + get; + [UnsupportedOSPlatform("windows")] set; + } +#endif +} \ No newline at end of file diff --git a/src/TestableIO.System.IO.Abstractions.Wrappers/FileSystemWatcherBase.cs b/src/TestableIO.System.IO.Abstractions.Wrappers/FileSystemWatcherBase.cs new file mode 100644 index 000000000..a51189121 --- /dev/null +++ b/src/TestableIO.System.IO.Abstractions.Wrappers/FileSystemWatcherBase.cs @@ -0,0 +1,145 @@ +using System.ComponentModel; + +namespace System.IO.Abstractions; + +/// +#if FEATURE_SERIALIZABLE +[Serializable] +#endif +public abstract class FileSystemWatcherBase : IFileSystemWatcher +{ + /// + public abstract IFileSystem FileSystem { get; } + + /// + public abstract bool IncludeSubdirectories { get; set; } + + /// + public abstract IContainer Container { get; } + + /// + public abstract bool EnableRaisingEvents { get; set; } + + /// + public abstract string Filter { get; set; } + +#if FEATURE_FILE_SYSTEM_WATCHER_FILTERS + /// + public abstract Collections.ObjectModel.Collection Filters { get; } +#endif + + /// + public abstract int InternalBufferSize { get; set; } + + /// + public abstract NotifyFilters NotifyFilter { get; set; } + + /// + public abstract string Path { get; set; } + + /// + public abstract ISite Site { get; set; } + + /// + public abstract ISynchronizeInvoke SynchronizingObject { get; set; } + + /// + public virtual event FileSystemEventHandler Changed; + + /// + public virtual event FileSystemEventHandler Created; + + /// + public virtual event FileSystemEventHandler Deleted; + + /// + public virtual event ErrorEventHandler Error; + + /// + public virtual event RenamedEventHandler Renamed; + + /// + public abstract void BeginInit(); + + /// + public void Dispose() + { + Dispose(true); + GC.SuppressFinalize(this); + } + + /// + public abstract void EndInit(); + + /// + public abstract IWaitForChangedResult WaitForChanged(WatcherChangeTypes changeType); + + /// + public abstract IWaitForChangedResult WaitForChanged(WatcherChangeTypes changeType, int timeout); + +#if FEATURE_FILE_SYSTEM_WATCHER_WAIT_WITH_TIMESPAN + /// + public abstract IWaitForChangedResult WaitForChanged(WatcherChangeTypes changeType, TimeSpan timeout); +#endif + + /// + /// Implicitly converts a to a . + /// + public static implicit operator FileSystemWatcherBase(FileSystemWatcher watcher) + { + if (watcher == null) + { + return null; + } + + return new FileSystemWatcherWrapper(new FileSystem(), watcher); + } + + /// + /// Callback executed during + /// + public virtual void Dispose(bool disposing) + { + // do nothing + } + + /// + /// Invokes the event. + /// + protected void OnCreated(object sender, FileSystemEventArgs args) + { + Created?.Invoke(sender, args); + } + + /// + /// Invokes the event. + /// + protected void OnChanged(object sender, FileSystemEventArgs args) + { + Changed?.Invoke(sender, args); + } + + /// + /// Invokes the event. + /// + protected void OnDeleted(object sender, FileSystemEventArgs args) + { + Deleted?.Invoke(sender, args); + } + + /// + /// Invokes the event. + /// + protected void OnRenamed(object sender, RenamedEventArgs args) + { + Renamed?.Invoke(sender, args); + } + + /// + /// Invokes the event. + /// + protected void OnError(object sender, ErrorEventArgs args) + { + Error?.Invoke(sender, args); + } +} \ No newline at end of file diff --git a/src/TestableIO.System.IO.Abstractions.Wrappers/FileSystemWatcherFactory.cs b/src/TestableIO.System.IO.Abstractions.Wrappers/FileSystemWatcherFactory.cs new file mode 100644 index 000000000..662483524 --- /dev/null +++ b/src/TestableIO.System.IO.Abstractions.Wrappers/FileSystemWatcherFactory.cs @@ -0,0 +1,42 @@ +namespace System.IO.Abstractions; + +/// +#if FEATURE_SERIALIZABLE +[Serializable] +#endif +public class FileSystemWatcherFactory : IFileSystemWatcherFactory +{ + /// + /// Base factory class for creating a + /// + public FileSystemWatcherFactory(IFileSystem fileSystem) + { + FileSystem = fileSystem; + } + + /// + public IFileSystem FileSystem { get; } + + /// + public IFileSystemWatcher New() + => new FileSystemWatcherWrapper(FileSystem); + + /// + public IFileSystemWatcher New(string path) + => new FileSystemWatcherWrapper(FileSystem, path); + + /// + public IFileSystemWatcher New(string path, string filter) + => new FileSystemWatcherWrapper(FileSystem, path, filter); + + /// + public IFileSystemWatcher Wrap(FileSystemWatcher fileSystemWatcher) + { + if (fileSystemWatcher == null) + { + return null; + } + + return new FileSystemWatcherWrapper(FileSystem, fileSystemWatcher); + } +} \ No newline at end of file diff --git a/src/TestableIO.System.IO.Abstractions.Wrappers/FileSystemWatcherWrapper.cs b/src/TestableIO.System.IO.Abstractions.Wrappers/FileSystemWatcherWrapper.cs new file mode 100644 index 000000000..69af6ae6b --- /dev/null +++ b/src/TestableIO.System.IO.Abstractions.Wrappers/FileSystemWatcherWrapper.cs @@ -0,0 +1,213 @@ +using System.ComponentModel; + +namespace System.IO.Abstractions; + +/// +#if FEATURE_SERIALIZABLE +[Serializable] +#endif +public class FileSystemWatcherWrapper : FileSystemWatcherBase +{ +#if FEATURE_SERIALIZABLE + [NonSerialized] +#endif + private readonly FileSystemWatcher watcher; + + /// + public FileSystemWatcherWrapper(IFileSystem fileSystem) + : this(fileSystem, new FileSystemWatcher()) + { + // do nothing + } + + /// + public FileSystemWatcherWrapper(IFileSystem fileSystem, string path) + : this(fileSystem, new FileSystemWatcher(path)) + { + // do nothing + } + + /// + public FileSystemWatcherWrapper(IFileSystem fileSystem, string path, string filter) + : this(fileSystem, new FileSystemWatcher(path, filter)) + { + // do nothing + } + + /// + public FileSystemWatcherWrapper(IFileSystem fileSystem, FileSystemWatcher watcher) + { + FileSystem = fileSystem; + this.watcher = watcher ?? throw new ArgumentNullException(nameof(watcher)); + this.watcher.Created += OnCreated; + this.watcher.Changed += OnChanged; + this.watcher.Deleted += OnDeleted; + this.watcher.Error += OnError; + this.watcher.Renamed += OnRenamed; + } + + /// + public override IFileSystem FileSystem { get; } + + /// + public override bool IncludeSubdirectories + { + get { return watcher.IncludeSubdirectories; } + set { watcher.IncludeSubdirectories = value; } + } + + /// + public override IContainer Container + => watcher.Container; + + /// + public override bool EnableRaisingEvents + { + get { return watcher.EnableRaisingEvents; } + set { watcher.EnableRaisingEvents = value; } + } + + /// + public override string Filter + { + get { return watcher.Filter; } + set { watcher.Filter = value; } + } + +#if FEATURE_FILE_SYSTEM_WATCHER_FILTERS + /// + public override Collections.ObjectModel.Collection Filters + { + get { return watcher.Filters; } + } +#endif + + /// + public override int InternalBufferSize + { + get { return watcher.InternalBufferSize; } + set { watcher.InternalBufferSize = value; } + } + + /// + public override NotifyFilters NotifyFilter + { + get { return watcher.NotifyFilter; } + set { watcher.NotifyFilter = value; } + } + + /// + public override string Path + { + get { return watcher.Path; } + set { watcher.Path = value; } + } + + /// + public override ISite Site + { + get { return watcher.Site; } + set { watcher.Site = value; } + } + + /// + public override ISynchronizeInvoke SynchronizingObject + { + get { return watcher.SynchronizingObject; } + set { watcher.SynchronizingObject = value; } + } + + /// + public override void BeginInit() + { + watcher.BeginInit(); + } + + /// + public override void Dispose(bool disposing) + { + if (disposing) + { + watcher.Created -= OnCreated; + watcher.Changed -= OnChanged; + watcher.Deleted -= OnDeleted; + watcher.Error -= OnError; + watcher.Renamed -= OnRenamed; + watcher.Dispose(); + } + + base.Dispose(disposing); + } + + /// + public override void EndInit() + { + watcher.EndInit(); + } + + /// + public override IWaitForChangedResult WaitForChanged(WatcherChangeTypes changeType) + { + return new WaitForChangedResultWrapper(watcher.WaitForChanged(changeType)); + } + + /// + public override IWaitForChangedResult WaitForChanged(WatcherChangeTypes changeType, int timeout) + { + return new WaitForChangedResultWrapper(watcher.WaitForChanged(changeType, timeout)); + } + +#if FEATURE_FILE_SYSTEM_WATCHER_WAIT_WITH_TIMESPAN + /// + public override IWaitForChangedResult WaitForChanged(WatcherChangeTypes changeType, TimeSpan timeout) + { + return new WaitForChangedResultWrapper(watcher.WaitForChanged(changeType, timeout)); + } +#endif + + private readonly struct WaitForChangedResultWrapper + : IWaitForChangedResult, IEquatable + { + private readonly WaitForChangedResult instance; + + public WaitForChangedResultWrapper(WaitForChangedResult instance) + { + this.instance = instance; + } + + /// + public WatcherChangeTypes ChangeType + => instance.ChangeType; + + /// + public string Name + => instance.Name; + + /// + public string OldName + => instance.OldName; + + /// + public bool TimedOut + => instance.TimedOut; + + /// + public bool Equals(WaitForChangedResultWrapper other) + { + return instance.Equals(other.instance); + } + + /// + public override bool Equals(object obj) + { + return obj is WaitForChangedResultWrapper other + && Equals(other); + } + + /// + public override int GetHashCode() + { + return instance.GetHashCode(); + } + } +} \ No newline at end of file diff --git a/src/TestableIO.System.IO.Abstractions.Wrappers/FileVersionInfoBase.cs b/src/TestableIO.System.IO.Abstractions.Wrappers/FileVersionInfoBase.cs new file mode 100644 index 000000000..9545833f2 --- /dev/null +++ b/src/TestableIO.System.IO.Abstractions.Wrappers/FileVersionInfoBase.cs @@ -0,0 +1,107 @@ +using System.Diagnostics; + +namespace System.IO.Abstractions; + +/// +#if FEATURE_SERIALIZABLE +[Serializable] +#endif +public abstract class FileVersionInfoBase : IFileVersionInfo +{ + /// + public abstract string Comments { get; } + + /// + public abstract string CompanyName { get; } + + /// + public abstract int FileBuildPart { get; } + + /// + public abstract string FileDescription { get; } + + /// + public abstract int FileMajorPart { get; } + + /// + public abstract int FileMinorPart { get; } + + /// + public abstract string FileName { get; } + + /// + public abstract int FilePrivatePart { get; } + + /// + public abstract string FileVersion { get; } + + /// + public abstract string InternalName { get; } + + /// + public abstract bool IsDebug { get; } + + /// + public abstract bool IsPatched { get; } + + /// + public abstract bool IsPrivateBuild { get; } + + /// + public abstract bool IsPreRelease { get; } + + /// + public abstract bool IsSpecialBuild { get; } + + /// + public abstract string Language { get; } + + /// + public abstract string LegalCopyright { get; } + + /// + public abstract string LegalTrademarks { get; } + + /// + public abstract string OriginalFilename { get; } + + /// + public abstract string PrivateBuild { get; } + + /// + public abstract int ProductBuildPart { get; } + + /// + public abstract int ProductMajorPart { get; } + + /// + public abstract int ProductMinorPart { get; } + + /// + public abstract string ProductName { get; } + + /// + public abstract int ProductPrivatePart { get; } + + /// + public abstract string ProductVersion { get; } + + /// + public abstract string SpecialBuild { get; } + + /// + /// Implicitly converts a to a . + /// + public static implicit operator FileVersionInfoBase(FileVersionInfo fileVersionInfo) + { + if (fileVersionInfo == null) + { + return null; + } + + return new FileVersionInfoWrapper(fileVersionInfo); + } + + /// + public new abstract string ToString(); +} \ No newline at end of file diff --git a/src/TestableIO.System.IO.Abstractions.Wrappers/FileVersionInfoFactory.cs b/src/TestableIO.System.IO.Abstractions.Wrappers/FileVersionInfoFactory.cs new file mode 100644 index 000000000..d9def793e --- /dev/null +++ b/src/TestableIO.System.IO.Abstractions.Wrappers/FileVersionInfoFactory.cs @@ -0,0 +1,27 @@ +namespace System.IO.Abstractions; +#if FEATURE_SERIALIZABLE +[Serializable] +#endif +internal class FileVersionInfoFactory : IFileVersionInfoFactory +{ + private readonly IFileSystem fileSystem; + + /// + /// Base factory class for creating a + /// + public FileVersionInfoFactory(IFileSystem fileSystem) + { + this.fileSystem = fileSystem; + } + + /// + public IFileSystem FileSystem => fileSystem; + + /// + public IFileVersionInfo GetVersionInfo(string fileName) + { + Diagnostics.FileVersionInfo fileVersionInfo = Diagnostics.FileVersionInfo.GetVersionInfo(fileName); + + return new FileVersionInfoWrapper(fileVersionInfo); + } +} \ No newline at end of file diff --git a/src/TestableIO.System.IO.Abstractions.Wrappers/FileVersionInfoWrapper.cs b/src/TestableIO.System.IO.Abstractions.Wrappers/FileVersionInfoWrapper.cs new file mode 100644 index 000000000..4e677f460 --- /dev/null +++ b/src/TestableIO.System.IO.Abstractions.Wrappers/FileVersionInfoWrapper.cs @@ -0,0 +1,186 @@ +using System.Diagnostics; + +namespace System.IO.Abstractions; + +/// +#if FEATURE_SERIALIZABLE +[Serializable] +#endif +public class FileVersionInfoWrapper : FileVersionInfoBase +{ + private readonly FileVersionInfo instance; + + /// + public FileVersionInfoWrapper(FileVersionInfo fileVersionInfo) + { + instance = fileVersionInfo; + } + + /// + public override string Comments + { + get { return instance.Comments; } + } + + /// + public override string CompanyName + { + get { return instance.CompanyName; } + } + + /// + public override int FileBuildPart + { + get { return instance.FileBuildPart; } + } + + /// + public override string FileDescription + { + get { return instance.FileDescription; } + } + + /// + public override int FileMajorPart + { + get { return instance.FileMajorPart; } + } + + /// + public override int FileMinorPart + { + get { return instance.FileMinorPart; } + } + + /// + public override string FileName + { + get { return instance.FileName; } + } + + /// + public override int FilePrivatePart + { + get { return instance.FilePrivatePart; } + } + + /// + public override string FileVersion + { + get { return instance.FileVersion; } + } + + /// + public override string InternalName + { + get { return instance.InternalName; } + } + + /// + public override bool IsDebug + { + get { return instance.IsDebug; } + } + + /// + public override bool IsPatched + { + get { return instance.IsPatched; } + } + + /// + public override bool IsPrivateBuild + { + get { return instance.IsPrivateBuild; } + } + + /// + public override bool IsPreRelease + { + get { return instance.IsPreRelease; } + } + + /// + public override bool IsSpecialBuild + { + get { return instance.IsSpecialBuild; } + } + + /// + public override string Language + { + get { return instance.Language; } + } + + /// + public override string LegalCopyright + { + get { return instance.LegalCopyright; } + } + + /// + public override string LegalTrademarks + { + get { return instance.LegalTrademarks; } + } + + /// + public override string OriginalFilename + { + get { return instance.OriginalFilename; } + } + + /// + public override string PrivateBuild + { + get { return instance.PrivateBuild; } + } + + /// + public override int ProductBuildPart + { + get { return instance.ProductBuildPart; } + } + + /// + public override int ProductMajorPart + { + get { return instance.ProductMajorPart; } + } + + /// + public override int ProductMinorPart + { + get { return instance.ProductMinorPart; } + } + + /// + public override string ProductName + { + get { return instance.ProductName; } + } + + /// + public override int ProductPrivatePart + { + get { return instance.ProductPrivatePart; } + } + + /// + public override string ProductVersion + { + get { return instance.ProductVersion; } + } + + /// + public override string SpecialBuild + { + get { return instance.SpecialBuild; } + } + + /// + public override string ToString() + { + return instance.ToString(); + } +} \ No newline at end of file diff --git a/src/TestableIO.System.IO.Abstractions.Wrappers/FileWrapper.Async.cs b/src/TestableIO.System.IO.Abstractions.Wrappers/FileWrapper.Async.cs new file mode 100644 index 000000000..968312d32 --- /dev/null +++ b/src/TestableIO.System.IO.Abstractions.Wrappers/FileWrapper.Async.cs @@ -0,0 +1,160 @@ +#if FEATURE_ASYNC_FILE + +using System.Collections.Generic; +using System.Text; +using System.Threading.Tasks; +using System.Threading; + +namespace System.IO.Abstractions +{ + partial class FileWrapper + { +#if FEATURE_FILE_SPAN + /// + public override Task AppendAllBytesAsync(string path, byte[] bytes, CancellationToken cancellationToken = default) + { + return File.AppendAllBytesAsync(path, bytes, cancellationToken); + } + + /// + public override Task AppendAllBytesAsync(string path, ReadOnlyMemory bytes, CancellationToken cancellationToken = default) + { + return File.AppendAllBytesAsync(path, bytes, cancellationToken); + } +#endif + /// + public override Task AppendAllLinesAsync(string path, IEnumerable contents, CancellationToken cancellationToken = default) + { + return File.AppendAllLinesAsync(path, contents, cancellationToken); + } + + /// + public override Task AppendAllLinesAsync(string path, IEnumerable contents, Encoding encoding, CancellationToken cancellationToken = default) + { + return File.AppendAllLinesAsync(path, contents, encoding, cancellationToken); + } + + /// + public override Task AppendAllTextAsync(string path, string contents, CancellationToken cancellationToken = default) + { + return File.AppendAllTextAsync(path, contents, cancellationToken); + } + + /// + public override Task AppendAllTextAsync(string path, string contents, Encoding encoding, CancellationToken cancellationToken = default) + { + return File.AppendAllTextAsync(path, contents, encoding, cancellationToken); + } + +#if FEATURE_FILE_SPAN + /// + public override Task AppendAllTextAsync(string path, ReadOnlyMemory contents, CancellationToken cancellationToken = default) + { + return File.AppendAllTextAsync(path, contents, cancellationToken); + } + + /// + public override Task AppendAllTextAsync(string path, ReadOnlyMemory contents, Encoding encoding, + CancellationToken cancellationToken = default) + { + return File.AppendAllTextAsync(path, contents, encoding, cancellationToken); + } +#endif + + /// + public override Task ReadAllBytesAsync(string path, CancellationToken cancellationToken = default) + { + return File.ReadAllBytesAsync(path, cancellationToken); + } + + /// + public override Task ReadAllLinesAsync(string path, CancellationToken cancellationToken = default) + { + return File.ReadAllLinesAsync(path, cancellationToken); + } + + /// + public override Task ReadAllLinesAsync(string path, Encoding encoding, CancellationToken cancellationToken = default) + { + return File.ReadAllLinesAsync(path, encoding, cancellationToken); + } + + /// + public override Task ReadAllTextAsync(string path, CancellationToken cancellationToken = default) + { + return File.ReadAllTextAsync(path, cancellationToken); + } + + /// + public override Task ReadAllTextAsync(string path, Encoding encoding, CancellationToken cancellationToken = default) + { + return File.ReadAllTextAsync(path, encoding, cancellationToken); + } + +#if FEATURE_READ_LINES_ASYNC + /// + public override IAsyncEnumerable ReadLinesAsync(string path, + CancellationToken cancellationToken = default) + => File.ReadLinesAsync(path, cancellationToken); + + /// + public override IAsyncEnumerable ReadLinesAsync(string path, Encoding encoding, + CancellationToken cancellationToken = default) + => File.ReadLinesAsync(path, encoding, cancellationToken); +#endif + + /// + public override Task WriteAllBytesAsync(string path, byte[] bytes, CancellationToken cancellationToken = default) + { + return File.WriteAllBytesAsync(path, bytes, cancellationToken); + } + +#if FEATURE_FILE_SPAN + /// + public override Task WriteAllBytesAsync(string path, ReadOnlyMemory bytes, CancellationToken cancellationToken = default) + { + return File.WriteAllBytesAsync(path, bytes, cancellationToken); + } +#endif + + /// + public override Task WriteAllLinesAsync(string path, IEnumerable contents, CancellationToken cancellationToken = default) + { + return File.WriteAllLinesAsync(path, contents, cancellationToken); + } + + /// + public override Task WriteAllLinesAsync(string path, IEnumerable contents, Encoding encoding, CancellationToken cancellationToken = default) + { + return File.WriteAllLinesAsync(path, contents, encoding, cancellationToken); + } + + /// + public override Task WriteAllTextAsync(string path, string contents, CancellationToken cancellationToken = default) + { + return File.WriteAllTextAsync(path, contents, cancellationToken); + } + + /// + public override Task WriteAllTextAsync(string path, string contents, Encoding encoding, CancellationToken cancellationToken = default) + { + return File.WriteAllTextAsync(path, contents, encoding, cancellationToken); + } + +#if FEATURE_FILE_SPAN + /// + public override Task WriteAllTextAsync(string path, ReadOnlyMemory contents, CancellationToken cancellationToken = default) + { + return File.WriteAllTextAsync(path, contents, cancellationToken); + } + + /// + public override Task WriteAllTextAsync(string path, ReadOnlyMemory contents, Encoding encoding, + CancellationToken cancellationToken = default) + { + return File.WriteAllTextAsync(path, contents, encoding, cancellationToken); + } +#endif + } +} +#endif diff --git a/src/TestableIO.System.IO.Abstractions.Wrappers/FileWrapper.cs b/src/TestableIO.System.IO.Abstractions.Wrappers/FileWrapper.cs new file mode 100644 index 000000000..d240ee059 --- /dev/null +++ b/src/TestableIO.System.IO.Abstractions.Wrappers/FileWrapper.cs @@ -0,0 +1,796 @@ +using System.Collections.Generic; +using System.Runtime.Versioning; +using System.Text; +using Microsoft.Win32.SafeHandles; + +namespace System.IO.Abstractions; + +/// +#if FEATURE_SERIALIZABLE +[Serializable] +#endif +public partial class FileWrapper : FileBase +{ + /// + public FileWrapper(IFileSystem fileSystem) : base(fileSystem) + { + } + +#if FEATURE_FILE_SPAN + /// + public override void AppendAllBytes(string path, byte[] bytes) + { + File.AppendAllBytes(path, bytes); + } + + /// + public override void AppendAllBytes(string path, ReadOnlySpan bytes) + { + File.AppendAllBytes(path, bytes); + } +#endif + + /// + public override void AppendAllLines(string path, IEnumerable contents) + { + File.AppendAllLines(path, contents); + } + + /// + public override void AppendAllLines(string path, IEnumerable contents, Encoding encoding) + { + File.AppendAllLines(path, contents, encoding); + } + + + /// + public override void AppendAllText(string path, string contents) + { + File.AppendAllText(path, contents); + } + + /// + public override void AppendAllText(string path, string contents, Encoding encoding) + { + File.AppendAllText(path, contents, encoding); + } + +#if FEATURE_FILE_SPAN + /// + public override void AppendAllText(string path, ReadOnlySpan contents) + { + File.AppendAllText(path, contents); + } + + /// + public override void AppendAllText(string path, ReadOnlySpan contents, Encoding encoding) + { + File.AppendAllText(path, contents, encoding); + } +#endif + + /// + public override StreamWriter AppendText(string path) + { + return File.AppendText(path); + } + + /// + public override void Copy(string sourceFileName, string destFileName) + { + File.Copy(sourceFileName, destFileName); + } + + /// + public override void Copy(string sourceFileName, string destFileName, bool overwrite) + { + File.Copy(sourceFileName, destFileName, overwrite); + } + + /// + public override FileSystemStream Create(string path) + { + return new FileStreamWrapper(File.Create(path)); + } + + /// + public override FileSystemStream Create(string path, int bufferSize) + { + return new FileStreamWrapper(File.Create(path, bufferSize)); + } + + /// + public override FileSystemStream Create(string path, int bufferSize, FileOptions options) + { + return new FileStreamWrapper(File.Create(path, bufferSize, options)); + } + +#if FEATURE_CREATE_SYMBOLIC_LINK + /// + public override IFileSystemInfo CreateSymbolicLink(string path, string pathToTarget) + { + return File.CreateSymbolicLink(path, pathToTarget) + .WrapFileSystemInfo(FileSystem); + } +#endif + /// + public override StreamWriter CreateText(string path) + { + return File.CreateText(path); + } + + /// + [SupportedOSPlatform("windows")] + public override void Decrypt(string path) + { + File.Decrypt(path); + } + + /// + public override void Delete(string path) + { + File.Delete(path); + } + + /// + [SupportedOSPlatform("windows")] + public override void Encrypt(string path) + { + File.Encrypt(path); + } + + /// + public override bool Exists(string path) + { + return File.Exists(path); + } + + /// + public override FileAttributes GetAttributes(string path) + { + return File.GetAttributes(path); + } + +#if FEATURE_FILE_ATTRIBUTES_VIA_HANDLE + /// + public override FileAttributes GetAttributes(SafeFileHandle fileHandle) + { + return File.GetAttributes(fileHandle); + } +#endif + + /// + public override DateTime GetCreationTime(string path) + { + return File.GetCreationTime(path); + } + +#if FEATURE_FILE_ATTRIBUTES_VIA_HANDLE + /// + public override DateTime GetCreationTime(SafeFileHandle fileHandle) + { + return File.GetCreationTime(fileHandle); + } +#endif + + /// + public override DateTime GetCreationTimeUtc(string path) + { + return File.GetCreationTimeUtc(path); + } + +#if FEATURE_FILE_ATTRIBUTES_VIA_HANDLE + /// + public override DateTime GetCreationTimeUtc(SafeFileHandle fileHandle) + { + return File.GetCreationTimeUtc(fileHandle); + } +#endif + + /// + public override DateTime GetLastAccessTime(string path) + { + return File.GetLastAccessTime(path); + } + +#if FEATURE_FILE_ATTRIBUTES_VIA_HANDLE + /// + public override DateTime GetLastAccessTime(SafeFileHandle fileHandle) + { + return File.GetLastAccessTime(fileHandle); + } +#endif + + /// + public override DateTime GetLastAccessTimeUtc(string path) + { + return File.GetLastAccessTimeUtc(path); + } + +#if FEATURE_FILE_ATTRIBUTES_VIA_HANDLE + /// + public override DateTime GetLastAccessTimeUtc(SafeFileHandle fileHandle) + { + return File.GetLastAccessTimeUtc(fileHandle); + } +#endif + + /// + public override DateTime GetLastWriteTime(string path) + { + return File.GetLastWriteTime(path); + } + +#if FEATURE_FILE_ATTRIBUTES_VIA_HANDLE + /// + public override DateTime GetLastWriteTime(SafeFileHandle fileHandle) + { + return File.GetLastWriteTime(fileHandle); + } +#endif + + /// + public override DateTime GetLastWriteTimeUtc(string path) + { + return File.GetLastWriteTimeUtc(path); + } + +#if FEATURE_FILE_ATTRIBUTES_VIA_HANDLE + /// + public override DateTime GetLastWriteTimeUtc(SafeFileHandle fileHandle) + { + return File.GetLastWriteTimeUtc(fileHandle); + } +#endif + +#if FEATURE_UNIX_FILE_MODE + /// + [UnsupportedOSPlatform("windows")] + public override UnixFileMode GetUnixFileMode(string path) + { + return File.GetUnixFileMode(path); + } +#endif + +#if FEATURE_FILE_ATTRIBUTES_VIA_HANDLE + /// + [UnsupportedOSPlatform("windows")] + public override UnixFileMode GetUnixFileMode(SafeFileHandle fileHandle) + { + return File.GetUnixFileMode(fileHandle); + } +#endif + + /// + public override void Move(string sourceFileName, string destFileName) + { + File.Move(sourceFileName, destFileName); + } + +#if FEATURE_FILE_MOVE_WITH_OVERWRITE + /// + public override void Move(string sourceFileName, string destFileName, bool overwrite) + { + File.Move(sourceFileName, destFileName, overwrite); + } +#endif + + + /// + public override FileSystemStream Open(string path, FileMode mode) + { + return new FileStreamWrapper(File.Open(path, mode)); + } + + /// + public override FileSystemStream Open(string path, FileMode mode, FileAccess access) + { + return new FileStreamWrapper(File.Open(path, mode, access)); + } + + /// + public override FileSystemStream Open(string path, FileMode mode, FileAccess access, FileShare share) + { + return new FileStreamWrapper(File.Open(path, mode, access, share)); + } + +#if FEATURE_FILESTREAM_OPTIONS + /// + public override FileSystemStream Open(string path, FileStreamOptions options) + { + return new FileStreamWrapper(File.Open(path, options)); + } +#endif + + /// + public override FileSystemStream OpenRead(string path) + { + return new FileStreamWrapper(File.OpenRead(path)); + } + + /// + public override StreamReader OpenText(string path) + { + return File.OpenText(path); + } + + /// + public override FileSystemStream OpenWrite(string path) + { + return new FileStreamWrapper(File.OpenWrite(path)); + } + + /// + public override byte[] ReadAllBytes(string path) + { + return File.ReadAllBytes(path); + } + + /// + public override string[] ReadAllLines(string path) + { + return File.ReadAllLines(path); + } + + /// + public override string[] ReadAllLines(string path, Encoding encoding) + { + return File.ReadAllLines(path, encoding); + } + + /// + public override string ReadAllText(string path) + { + return File.ReadAllText(path); + } + + /// + public override string ReadAllText(string path, Encoding encoding) + { + return File.ReadAllText(path, encoding); + } + + /// + public override IEnumerable ReadLines(string path) + { + return File.ReadLines(path); + } + + /// + public override IEnumerable ReadLines(string path, Encoding encoding) + { + return File.ReadLines(path, encoding); + } + + /// + public override void Replace(string sourceFileName, string destinationFileName, string destinationBackupFileName) + { + File.Replace(sourceFileName, destinationFileName, destinationBackupFileName); + } + + /// + public override void Replace(string sourceFileName, string destinationFileName, string destinationBackupFileName, bool ignoreMetadataErrors) + { + File.Replace(sourceFileName, destinationFileName, destinationBackupFileName, ignoreMetadataErrors); + } + +#if FEATURE_CREATE_SYMBOLIC_LINK + /// + public override IFileSystemInfo ResolveLinkTarget(string linkPath, bool returnFinalTarget) + { + return File.ResolveLinkTarget(linkPath, returnFinalTarget) + .WrapFileSystemInfo(FileSystem); + } +#endif + + /// + public override void SetAttributes(string path, FileAttributes fileAttributes) + { + File.SetAttributes(path, fileAttributes); + } + +#if FEATURE_FILE_ATTRIBUTES_VIA_HANDLE + /// + public override void SetAttributes(SafeFileHandle fileHandle, FileAttributes fileAttributes) + { + File.SetAttributes(fileHandle, fileAttributes); + } +#endif + + /// + public override void SetCreationTime(string path, DateTime creationTime) + { + File.SetCreationTime(path, creationTime); + } + +#if FEATURE_FILE_ATTRIBUTES_VIA_HANDLE + /// + public override void SetCreationTime(SafeFileHandle fileHandle, DateTime creationTime) + { + File.SetCreationTime(fileHandle, creationTime); + } +#endif + + /// + public override void SetCreationTimeUtc(string path, DateTime creationTimeUtc) + { + File.SetCreationTimeUtc(path, creationTimeUtc); + } + +#if FEATURE_FILE_ATTRIBUTES_VIA_HANDLE + /// + public override void SetCreationTimeUtc(SafeFileHandle fileHandle, DateTime creationTimeUtc) + { + File.SetCreationTimeUtc(fileHandle, creationTimeUtc); + } +#endif + + /// + public override void SetLastAccessTime(string path, DateTime lastAccessTime) + { + File.SetLastAccessTime(path, lastAccessTime); + } + +#if FEATURE_FILE_ATTRIBUTES_VIA_HANDLE + /// + public override void SetLastAccessTime(SafeFileHandle fileHandle, DateTime lastAccessTime) + { + File.SetLastAccessTime(fileHandle, lastAccessTime); + } +#endif + + /// + public override void SetLastAccessTimeUtc(string path, DateTime lastAccessTimeUtc) + { + File.SetLastAccessTimeUtc(path, lastAccessTimeUtc); + } + +#if FEATURE_FILE_ATTRIBUTES_VIA_HANDLE + /// + public override void SetLastAccessTimeUtc(SafeFileHandle fileHandle, DateTime lastAccessTimeUtc) + { + File.SetLastAccessTimeUtc(fileHandle, lastAccessTimeUtc); + } +#endif + + /// + public override void SetLastWriteTime(string path, DateTime lastWriteTime) + { + File.SetLastWriteTime(path, lastWriteTime); + } + +#if FEATURE_FILE_ATTRIBUTES_VIA_HANDLE + /// + public override void SetLastWriteTime(SafeFileHandle fileHandle, DateTime lastWriteTime) + { + File.SetLastWriteTime(fileHandle, lastWriteTime); + } +#endif + + /// + public override void SetLastWriteTimeUtc(string path, DateTime lastWriteTimeUtc) + { + File.SetLastWriteTimeUtc(path, lastWriteTimeUtc); + } + +#if FEATURE_FILE_ATTRIBUTES_VIA_HANDLE + /// + public override void SetLastWriteTimeUtc(SafeFileHandle fileHandle, DateTime lastWriteTimeUtc) + { + File.SetLastWriteTimeUtc(fileHandle, lastWriteTimeUtc); + } +#endif + +#if FEATURE_UNIX_FILE_MODE + /// + [UnsupportedOSPlatform("windows")] + public override void SetUnixFileMode(string path, UnixFileMode mode) + { + File.SetUnixFileMode(path, mode); + } +#endif + +#if FEATURE_FILE_ATTRIBUTES_VIA_HANDLE + /// + [UnsupportedOSPlatform("windows")] + public override void SetUnixFileMode(SafeFileHandle fileHandle, UnixFileMode mode) + { + File.SetUnixFileMode(fileHandle, mode); + } +#endif + + /// + /// Creates a new file, writes the specified byte array to the file, and then closes the file. + /// If the target file already exists, it is overwritten. + /// + /// The file to write to. + /// The bytes to write to the file. + /// is a zero-length string, contains only white space, or contains one or more invalid characters as defined by . + /// is or contents is empty. + /// + /// The specified path, file name, or both exceed the system-defined maximum length. + /// For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters. + /// + /// The specified path is invalid (for example, it is on an unmapped drive). + /// An I/O error occurred while opening the file. + /// + /// path specified a file that is read-only. + /// -or- + /// This operation is not supported on the current platform. + /// -or- + /// path specified a directory. + /// -or- + /// The caller does not have the required permission. + /// + /// The file specified in was not found. + /// is in an invalid format. + /// The caller does not have the required permission. + /// + /// Given a byte array and a file path, this method opens the specified file, writes the contents of the byte array to the file, and then closes the file. + /// + public override void WriteAllBytes(string path, byte[] bytes) + { + File.WriteAllBytes(path, bytes); + } + +#if FEATURE_FILE_SPAN + /// + public override void WriteAllBytes(string path, ReadOnlySpan bytes) + { + File.WriteAllBytes(path, bytes); + } +#endif + + /// + /// Creates a new file, writes a collection of strings to the file, and then closes the file. + /// + /// The file to write to. + /// The lines to write to the file. + /// is a zero-length string, contains only white space, or contains one or more invalid characters as defined by . + /// Either or is . + /// The specified path is invalid (for example, it is on an unmapped drive). + /// The file specified in was not found. + /// An I/O error occurred while opening the file. + /// + /// The specified path, file name, or both exceed the system-defined maximum length. + /// For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters. + /// + /// is in an invalid format. + /// The caller does not have the required permission. + /// + /// specified a file that is read-only. + /// -or- + /// This operation is not supported on the current platform. + /// -or- + /// specified a directory. + /// -or- + /// The caller does not have the required permission. + /// + /// + /// + /// If the target file already exists, it is overwritten. + /// + /// + /// You can use this method to create the contents for a collection class that takes an in its constructor, such as a , , or a class. + /// + /// + public override void WriteAllLines(string path, IEnumerable contents) + { + File.WriteAllLines(path, contents); + } + + /// + /// Creates a new file by using the specified encoding, writes a collection of strings to the file, and then closes the file. + /// + /// The file to write to. + /// The lines to write to the file. + /// The character encoding to use. + /// is a zero-length string, contains only white space, or contains one or more invalid characters as defined by . + /// Either , , or is . + /// The specified path is invalid (for example, it is on an unmapped drive). + /// The file specified in was not found. + /// An I/O error occurred while opening the file. + /// + /// The specified path, file name, or both exceed the system-defined maximum length. + /// For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters. + /// + /// is in an invalid format. + /// The caller does not have the required permission. + /// + /// specified a file that is read-only. + /// -or- + /// This operation is not supported on the current platform. + /// -or- + /// specified a directory. + /// -or- + /// The caller does not have the required permission. + /// + /// + /// + /// If the target file already exists, it is overwritten. + /// + /// + /// You can use this method to create a file that contains the following: + /// + /// + /// The results of a LINQ to Objects query on the lines of a file, as obtained by using the ReadLines method. + /// + /// + /// The contents of a collection that implements an of strings. + /// + /// + /// + /// + public override void WriteAllLines(string path, IEnumerable contents, Encoding encoding) + { + File.WriteAllLines(path, contents, encoding); + } + + /// + /// Creates a new file, writes the specified string array to the file by using the specified encoding, and then closes the file. + /// + /// The file to write to. + /// The string array to write to the file. + /// is a zero-length string, contains only white space, or contains one or more invalid characters as defined by . + /// Either or is . + /// + /// The specified path, file name, or both exceed the system-defined maximum length. + /// For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters. + /// + /// The specified path is invalid (for example, it is on an unmapped drive). + /// An I/O error occurred while opening the file. + /// + /// specified a file that is read-only. + /// -or- + /// This operation is not supported on the current platform. + /// -or- + /// specified a directory. + /// -or- + /// The caller does not have the required permission. + /// + /// The file specified in was not found. + /// is in an invalid format. + /// The caller does not have the required permission. + /// + /// + /// If the target file already exists, it is overwritten. + /// + /// + /// The default behavior of the WriteAllLines method is to write out data using UTF-8 encoding without a byte order mark (BOM). If it is necessary to include a UTF-8 identifier, such as a byte order mark, at the beginning of a file, use the method overload with encoding. + /// + /// + /// Given a string array and a file path, this method opens the specified file, writes the string array to the file using the specified encoding, + /// and then closes the file. + /// + /// + public override void WriteAllLines(string path, string[] contents) + { + File.WriteAllLines(path, contents); + } + + /// + /// Creates a new file, writes the specified string array to the file by using the specified encoding, and then closes the file. + /// + /// The file to write to. + /// The string array to write to the file. + /// An object that represents the character encoding applied to the string array. + /// is a zero-length string, contains only white space, or contains one or more invalid characters as defined by . + /// Either or is . + /// + /// The specified path, file name, or both exceed the system-defined maximum length. + /// For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters. + /// + /// The specified path is invalid (for example, it is on an unmapped drive). + /// An I/O error occurred while opening the file. + /// + /// specified a file that is read-only. + /// -or- + /// This operation is not supported on the current platform. + /// -or- + /// specified a directory. + /// -or- + /// The caller does not have the required permission. + /// + /// The file specified in was not found. + /// is in an invalid format. + /// The caller does not have the required permission. + /// + /// + /// If the target file already exists, it is overwritten. + /// + /// + /// Given a string array and a file path, this method opens the specified file, writes the string array to the file using the specified encoding, + /// and then closes the file. + /// + /// + public override void WriteAllLines(string path, string[] contents, Encoding encoding) + { + File.WriteAllLines(path, contents, encoding); + } + + /// + /// Creates a new file, writes the specified string to the file using the specified encoding, and then closes the file. If the target file already exists, it is overwritten. + /// + /// The file to write to. + /// The string to write to the file. + /// is a zero-length string, contains only white space, or contains one or more invalid characters as defined by . + /// is or contents is empty. + /// + /// The specified path, file name, or both exceed the system-defined maximum length. + /// For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters. + /// + /// The specified path is invalid (for example, it is on an unmapped drive). + /// An I/O error occurred while opening the file. + /// + /// path specified a file that is read-only. + /// -or- + /// This operation is not supported on the current platform. + /// -or- + /// path specified a directory. + /// -or- + /// The caller does not have the required permission. + /// + /// The file specified in was not found. + /// is in an invalid format. + /// The caller does not have the required permission. + /// + /// This method uses UTF-8 encoding without a Byte-Order Mark (BOM), so using the method will return an empty byte array. + /// If it is necessary to include a UTF-8 identifier, such as a byte order mark, at the beginning of a file, use the method overload with encoding. + /// + /// Given a string and a file path, this method opens the specified file, writes the string to the file, and then closes the file. + /// + /// + public override void WriteAllText(string path, string contents) + { + File.WriteAllText(path, contents); + } + + /// + /// Creates a new file, writes the specified string to the file using the specified encoding, and then closes the file. If the target file already exists, it is overwritten. + /// + /// The file to write to. + /// The string to write to the file. + /// The encoding to apply to the string. + /// is a zero-length string, contains only white space, or contains one or more invalid characters as defined by . + /// is or contents is empty. + /// + /// The specified path, file name, or both exceed the system-defined maximum length. + /// For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters. + /// + /// The specified path is invalid (for example, it is on an unmapped drive). + /// An I/O error occurred while opening the file. + /// + /// path specified a file that is read-only. + /// -or- + /// This operation is not supported on the current platform. + /// -or- + /// path specified a directory. + /// -or- + /// The caller does not have the required permission. + /// + /// The file specified in was not found. + /// is in an invalid format. + /// The caller does not have the required permission. + /// + /// Given a string and a file path, this method opens the specified file, writes the string to the file using the specified encoding, and then closes the file. + /// The file handle is guaranteed to be closed by this method, even if exceptions are raised. + /// + public override void WriteAllText(string path, string contents, Encoding encoding) + { + File.WriteAllText(path, contents, encoding); + } + +#if FEATURE_FILE_SPAN + /// + public override void WriteAllText(string path, ReadOnlySpan contents) + { + File.WriteAllText(path, contents); + } + + /// + public override void WriteAllText(string path, ReadOnlySpan contents, Encoding encoding) + { + File.WriteAllText(path, contents, encoding); + } +#endif +} \ No newline at end of file diff --git a/src/TestableIO.System.IO.Abstractions.Wrappers/PathBase.cs b/src/TestableIO.System.IO.Abstractions.Wrappers/PathBase.cs new file mode 100644 index 000000000..341123b65 --- /dev/null +++ b/src/TestableIO.System.IO.Abstractions.Wrappers/PathBase.cs @@ -0,0 +1,187 @@ +namespace System.IO.Abstractions; + +/// +#if FEATURE_SERIALIZABLE +[Serializable] +#endif +public abstract class PathBase : IPath +{ + /// + /// Base class for calling static methods of + /// + protected PathBase(IFileSystem fileSystem) + { + this.FileSystem = fileSystem; + } + + [Obsolete("This constructor only exists to support mocking libraries.", error: true)] + internal PathBase() { } + + /// + /// Exposes the underlying filesystem implementation. This is useful for implementing extension methods. + /// + public IFileSystem FileSystem { get; } + + /// + public abstract char AltDirectorySeparatorChar { get; } + + /// + public abstract char DirectorySeparatorChar { get; } + + /// + [Obsolete("Please use GetInvalidPathChars or GetInvalidFileNameChars instead.")] + public abstract char[] InvalidPathChars { get; } + + /// + public abstract char PathSeparator { get; } + + /// + public abstract char VolumeSeparatorChar { get; } + + /// + public abstract string ChangeExtension(string path, string extension); + + /// + public abstract string Combine(params string[] paths); + +#if FEATURE_PATH_SPAN + /// + public abstract string Combine(params ReadOnlySpan paths); +#endif + + /// + public abstract string Combine(string path1, string path2); + + /// + public abstract string Combine(string path1, string path2, string path3); + + /// + public abstract string Combine(string path1, string path2, string path3, string path4); + +#if FEATURE_PATH_EXISTS + /// + public abstract bool Exists(string path); +#endif + + /// + public abstract string GetDirectoryName(string path); + + /// + public abstract string GetExtension(string path); + + /// + public abstract string GetFileName(string path); + + /// + public abstract string GetFileNameWithoutExtension(string path); + + /// + public abstract string GetFullPath(string path); + +#if FEATURE_ADVANCED_PATH_OPERATIONS + /// + public abstract string GetFullPath(string path, string basePath); +#endif + + /// + public abstract char[] GetInvalidFileNameChars(); + + /// + public abstract char[] GetInvalidPathChars(); + + /// + public abstract string GetPathRoot(string path); + + /// + public abstract string GetRandomFileName(); + + /// + public abstract string GetTempFileName(); + + /// + public abstract string GetTempPath(); + + /// + public abstract bool HasExtension(string path); + + /// + public abstract bool IsPathRooted(string path); + +#if FEATURE_ADVANCED_PATH_OPERATIONS + /// + public abstract bool IsPathFullyQualified(string path); + + /// + public abstract string GetRelativePath(string relativeTo, string path); +#endif + +#if FEATURE_PATH_JOIN_WITH_SPAN + /// + public abstract string Join(ReadOnlySpan path1, ReadOnlySpan path2); + + /// + public abstract string Join(ReadOnlySpan path1, ReadOnlySpan path2, ReadOnlySpan path3); + +#if FEATURE_PATH_SPAN + /// + public abstract string Join(params ReadOnlySpan paths); +#endif + + /// + public abstract bool TryJoin(ReadOnlySpan path1, ReadOnlySpan path2, ReadOnlySpan path3, Span destination, out int charsWritten); + + /// + public abstract bool TryJoin(ReadOnlySpan path1, ReadOnlySpan path2, Span destination, out int charsWritten); +#endif + +#if FEATURE_ADVANCED_PATH_OPERATIONS + /// + public abstract bool HasExtension(ReadOnlySpan path); + /// + public abstract bool IsPathFullyQualified(ReadOnlySpan path); + /// + public abstract bool IsPathRooted(ReadOnlySpan path); + /// + public abstract ReadOnlySpan GetDirectoryName(ReadOnlySpan path); + /// + public abstract ReadOnlySpan GetExtension(ReadOnlySpan path); + /// + public abstract ReadOnlySpan GetFileName(ReadOnlySpan path); + /// + public abstract ReadOnlySpan GetFileNameWithoutExtension(ReadOnlySpan path); + /// + public abstract ReadOnlySpan GetPathRoot(ReadOnlySpan path); + +#endif +#if FEATURE_PATH_JOIN_WITH_PARAMS + /// + public abstract string Join(params string[] paths); + + /// + public abstract string Join(string path1, string path2); + /// + + public abstract string Join(string path1, string path2, string path3); + +#endif + +#if FEATURE_ENDS_IN_DIRECTORY_SEPARATOR + /// + public abstract bool EndsInDirectorySeparator(ReadOnlySpan path); + /// + public abstract bool EndsInDirectorySeparator(string path); + /// + public abstract ReadOnlySpan TrimEndingDirectorySeparator(ReadOnlySpan path); + + /// + public abstract string TrimEndingDirectorySeparator(string path); +#endif + +#if FEATURE_PATH_JOIN_WITH_FOUR_PATHS + + /// + public abstract string Join(ReadOnlySpan path1, ReadOnlySpan path2, ReadOnlySpan path3, ReadOnlySpan path4); + /// + public abstract string Join(string path1, string path2, string path3, string path4); +#endif +} \ No newline at end of file diff --git a/src/TestableIO.System.IO.Abstractions.Wrappers/PathWrapper.cs b/src/TestableIO.System.IO.Abstractions.Wrappers/PathWrapper.cs new file mode 100644 index 000000000..2c6789210 --- /dev/null +++ b/src/TestableIO.System.IO.Abstractions.Wrappers/PathWrapper.cs @@ -0,0 +1,326 @@ +namespace System.IO.Abstractions; + +/// +#if FEATURE_SERIALIZABLE +[Serializable] +#endif +public class PathWrapper : PathBase +{ + /// + public PathWrapper(IFileSystem fileSystem) : base(fileSystem) + { + } + + /// + public override char AltDirectorySeparatorChar + { + get { return Path.AltDirectorySeparatorChar; } + } + + /// + public override char DirectorySeparatorChar + { + get { return Path.DirectorySeparatorChar; } + } + + /// + [Obsolete("Please use GetInvalidPathChars or GetInvalidFileNameChars instead.")] + public override char[] InvalidPathChars + { + get { return Path.InvalidPathChars; } + } + + /// + public override char PathSeparator + { + get { return Path.PathSeparator; } + } + + /// + public override char VolumeSeparatorChar + { + get { return Path.VolumeSeparatorChar; } + } + + /// + public override string ChangeExtension(string path, string extension) + { + return Path.ChangeExtension(path, extension); + } + + /// + public override string Combine(params string[] paths) + { + return Path.Combine(paths); + } + +#if FEATURE_PATH_SPAN + /// + public override string Combine(params ReadOnlySpan paths) + { + return Path.Combine(paths); + } +#endif + + /// + public override string Combine(string path1, string path2) + { + return Path.Combine(path1, path2); + } + + /// + public override string Combine(string path1, string path2, string path3) + { + return Path.Combine(path1, path2, path3); + } + + /// + public override string Combine(string path1, string path2, string path3, string path4) + { + return Path.Combine(path1, path2, path3, path4); + } + +#if FEATURE_PATH_EXISTS + /// + public override bool Exists(string path) + { + return Path.Exists(path); + } +#endif + + /// + public override string GetDirectoryName(string path) + { + return Path.GetDirectoryName(path); + } + + /// + public override string GetExtension(string path) + { + return Path.GetExtension(path); + } + + /// + public override string GetFileName(string path) + { + return Path.GetFileName(path); + } + + /// + public override string GetFileNameWithoutExtension(string path) + { + return Path.GetFileNameWithoutExtension(path); + } + + /// + public override string GetFullPath(string path) + { + return Path.GetFullPath(path); + } + +# if FEATURE_ADVANCED_PATH_OPERATIONS + /// + public override string GetFullPath(string path, string basePath) + { + return Path.GetFullPath(path, basePath); + } +#endif + + /// + public override char[] GetInvalidFileNameChars() + { + return Path.GetInvalidFileNameChars(); + } + + /// + public override char[] GetInvalidPathChars() + { + return Path.GetInvalidPathChars(); + } + + /// + public override string GetPathRoot(string path) + { + return Path.GetPathRoot(path); + } + + /// + public override string GetRandomFileName() + { + return Path.GetRandomFileName(); + } + + /// + public override string GetTempFileName() + { + return Path.GetTempFileName(); + } + + /// + public override string GetTempPath() + { + return Path.GetTempPath(); + } + + /// + public override bool HasExtension(string path) + { + return Path.HasExtension(path); + } + +#if FEATURE_ADVANCED_PATH_OPERATIONS + /// + public override bool IsPathFullyQualified(string path) + { + return Path.IsPathFullyQualified(path); + } + + /// + public override string GetRelativePath(string relativeTo, string path) + { + return Path.GetRelativePath(relativeTo, path); + } +#endif + +#if FEATURE_PATH_JOIN_WITH_SPAN + /// + public override string Join(ReadOnlySpan path1, ReadOnlySpan path2) => + Path.Join(path1, path2); + + /// + public override string Join(ReadOnlySpan path1, ReadOnlySpan path2, ReadOnlySpan path3) => + Path.Join(path1, path2, path3); + +#if FEATURE_PATH_SPAN + /// + public override string Join(params ReadOnlySpan paths) + { + return Path.Join(paths); + } +#endif + + /// + public override bool TryJoin(ReadOnlySpan path1, ReadOnlySpan path2, Span destination, out int charsWritten) => + Path.TryJoin(path1, path2, destination, out charsWritten); + + /// + public override bool TryJoin(ReadOnlySpan path1, ReadOnlySpan path2, ReadOnlySpan path3, Span destination, out int charsWritten) => + Path.TryJoin(path1, path2, path3, destination, out charsWritten); +#endif + + /// + public override bool IsPathRooted(string path) + { + return Path.IsPathRooted(path); + } + +#if FEATURE_ENDS_IN_DIRECTORY_SEPARATOR + /// + public override bool EndsInDirectorySeparator(ReadOnlySpan path) + { + return Path.EndsInDirectorySeparator(path); + } + + /// + public override bool EndsInDirectorySeparator(string path) + { + return Path.EndsInDirectorySeparator(path); + } + + /// + public override ReadOnlySpan TrimEndingDirectorySeparator(ReadOnlySpan path) + { + return Path.TrimEndingDirectorySeparator(path); + } + + /// + public override string TrimEndingDirectorySeparator(string path) + { + return Path.TrimEndingDirectorySeparator(path); + } +#endif + +#if FEATURE_ADVANCED_PATH_OPERATIONS + /// + public override bool HasExtension(ReadOnlySpan path) + { + return Path.HasExtension(path); + } + + /// + public override bool IsPathFullyQualified(ReadOnlySpan path) + { + return Path.IsPathFullyQualified(path); + } + + /// + public override bool IsPathRooted(ReadOnlySpan path) + { + return Path.IsPathRooted(path); + } + + /// + public override ReadOnlySpan GetDirectoryName(ReadOnlySpan path) + { + return Path.GetDirectoryName(path); + } + + /// + public override ReadOnlySpan GetExtension(ReadOnlySpan path) + { + return Path.GetExtension(path); + } + + /// + public override ReadOnlySpan GetFileName(ReadOnlySpan path) + { + return Path.GetFileName(path); + } + + /// + public override ReadOnlySpan GetFileNameWithoutExtension(ReadOnlySpan path) + { + return Path.GetFileNameWithoutExtension(path); + } + + /// + public override ReadOnlySpan GetPathRoot(ReadOnlySpan path) + { + return Path.GetPathRoot(path); + } +#endif + +#if FEATURE_PATH_JOIN_WITH_FOUR_PATHS + /// + public override string Join(string path1, string path2, string path3, string path4) + { + return Path.Join(path1, path2, path3, path4); + } + + /// + public override string Join(ReadOnlySpan path1, ReadOnlySpan path2, ReadOnlySpan path3, ReadOnlySpan path4) + { + return Path.Join(path1, path2, path3, path4); + } +#endif + +#if FEATURE_PATH_JOIN_WITH_PARAMS + /// + public override string Join(string path1, string path2) + { + return Path.Join(path1, path2); + } + + /// + public override string Join(string path1, string path2, string path3) + { + return Path.Join(path1, path2, path3); + } + + /// + public override string Join(params string[] paths) + { + return Path.Join(paths); + } +#endif +} \ No newline at end of file diff --git a/src/TestableIO.System.IO.Abstractions.Wrappers/Polyfills/SupportedOSPlatformAttribute.cs b/src/TestableIO.System.IO.Abstractions.Wrappers/Polyfills/SupportedOSPlatformAttribute.cs new file mode 100644 index 000000000..ef6635b4f --- /dev/null +++ b/src/TestableIO.System.IO.Abstractions.Wrappers/Polyfills/SupportedOSPlatformAttribute.cs @@ -0,0 +1,12 @@ +#if !FEATURE_SUPPORTED_OS_ATTRIBUTE +namespace System.Runtime.Versioning +{ + [AttributeUsage(AttributeTargets.All)] + internal class SupportedOSPlatformAttribute : Attribute + { + public SupportedOSPlatformAttribute(string _) + { + } + } +} +#endif diff --git a/src/TestableIO.System.IO.Abstractions.Wrappers/TestableIO.System.IO.Abstractions.Wrappers.csproj b/src/TestableIO.System.IO.Abstractions.Wrappers/TestableIO.System.IO.Abstractions.Wrappers.csproj new file mode 100644 index 000000000..91cf86273 --- /dev/null +++ b/src/TestableIO.System.IO.Abstractions.Wrappers/TestableIO.System.IO.Abstractions.Wrappers.csproj @@ -0,0 +1,26 @@ + + + + TestableIO.System.IO.Abstractions.Wrappers + System.IO.Abstractions + A set of abstractions to help make file system interactions testable. + + + + + + + + + + + + <_Parameter1>true + + + + + + + + \ No newline at end of file diff --git a/src/TestableIO.System.IO.Abstractions/AssemblyRedirects.cs b/src/TestableIO.System.IO.Abstractions/AssemblyRedirects.cs new file mode 100644 index 000000000..c9ea21cb2 --- /dev/null +++ b/src/TestableIO.System.IO.Abstractions/AssemblyRedirects.cs @@ -0,0 +1,23 @@ +using System.IO.Abstractions; +using System.Runtime.CompilerServices; + +[assembly: TypeForwardedTo(typeof(FileSystemStream))] +[assembly: TypeForwardedTo(typeof(IDirectory))] +[assembly: TypeForwardedTo(typeof(IDirectoryInfo))] +[assembly: TypeForwardedTo(typeof(IDirectoryInfoFactory))] +[assembly: TypeForwardedTo(typeof(IDriveInfo))] +[assembly: TypeForwardedTo(typeof(IDriveInfoFactory))] +[assembly: TypeForwardedTo(typeof(IFile))] +[assembly: TypeForwardedTo(typeof(IFileInfo))] +[assembly: TypeForwardedTo(typeof(IFileInfoFactory))] +[assembly: TypeForwardedTo(typeof(IFileStreamFactory))] +[assembly: TypeForwardedTo(typeof(IFileSystem))] +[assembly: TypeForwardedTo(typeof(IFileSystemAclSupport))] +[assembly: TypeForwardedTo(typeof(IFileSystemEntity))] +[assembly: TypeForwardedTo(typeof(IFileSystemInfo))] +[assembly: TypeForwardedTo(typeof(IFileSystemWatcher))] +[assembly: TypeForwardedTo(typeof(IFileSystemWatcherFactory))] +[assembly: TypeForwardedTo(typeof(IFileVersionInfo))] +[assembly: TypeForwardedTo(typeof(IFileVersionInfoFactory))] +[assembly: TypeForwardedTo(typeof(IPath))] +[assembly: TypeForwardedTo(typeof(IWaitForChangedResult))] diff --git a/src/TestableIO.System.IO.Abstractions/TestableIO.System.IO.Abstractions.csproj b/src/TestableIO.System.IO.Abstractions/TestableIO.System.IO.Abstractions.csproj new file mode 100644 index 000000000..bc3e9307f --- /dev/null +++ b/src/TestableIO.System.IO.Abstractions/TestableIO.System.IO.Abstractions.csproj @@ -0,0 +1,19 @@ + + + + TestableIO.System.IO.Abstractions + System.IO.Abstractions + A set of abstractions to help make file system interactions testable. + enable + preview + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + diff --git a/tests/Directory.Build.props b/tests/Directory.Build.props new file mode 100644 index 000000000..65e9192f2 --- /dev/null +++ b/tests/Directory.Build.props @@ -0,0 +1,39 @@ + + + + + + net10.0;net9.0;net8.0 + $(TargetFrameworks);net472 + $(NoWarn);S2699 + false + true + + + + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + + + + + + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + + + + + + + + + true + + + diff --git a/tests/TestableIO.System.IO.Abstractions.Api.Tests/ApiAcceptance.cs b/tests/TestableIO.System.IO.Abstractions.Api.Tests/ApiAcceptance.cs new file mode 100644 index 000000000..30c6002d4 --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.Api.Tests/ApiAcceptance.cs @@ -0,0 +1,30 @@ +namespace TestableIO.System.IO.Abstractions.Api.Tests; + +public sealed class ApiAcceptance +{ + /// + /// Execute this test to update the expected public API to the current API surface. + /// + [TestCase] + [Explicit] + public async Task AcceptApiChanges() + { + string[] assemblyNames = + [ + "TestableIO.System.IO.Abstractions.Wrappers", + "TestableIO.System.IO.Abstractions.TestingHelpers", + ]; + + foreach (string assemblyName in assemblyNames) + { + foreach (string framework in Helper.GetTargetFrameworks()) + { + string publicApi = Helper.CreatePublicApi(framework, assemblyName) + .Replace("\n", Environment.NewLine); + Helper.SetExpectedApi(framework, assemblyName, publicApi); + } + } + + await That(assemblyNames).IsNotEmpty(); + } +} diff --git a/tests/TestableIO.System.IO.Abstractions.Api.Tests/ApiApprovalTests.cs b/tests/TestableIO.System.IO.Abstractions.Api.Tests/ApiApprovalTests.cs new file mode 100644 index 000000000..3d9d12b21 --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.Api.Tests/ApiApprovalTests.cs @@ -0,0 +1,44 @@ +using System.Collections.Generic; + +namespace TestableIO.System.IO.Abstractions.Api.Tests; + +/// +/// Whenever a test fails, this means that the public API surface changed. +/// If the change was intentional, execute the test to take over the +/// current public API surface. The changes will become part of the pull request and will be reviewed accordingly. +/// +public sealed class ApiApprovalTests +{ + [TestCaseSource(nameof(TargetFrameworksTheoryData))] + public async Task VerifyPublicApiForWrappers(string framework) + { + const string assemblyName = "TestableIO.System.IO.Abstractions.Wrappers"; + + var publicApi = Helper.CreatePublicApi(framework, assemblyName); + var expectedApi = Helper.GetExpectedApi(framework, assemblyName); + + await That(publicApi).IsEqualTo(expectedApi); + } + + [TestCaseSource(nameof(TargetFrameworksTheoryData))] + public async Task VerifyPublicApiForTestingHelpers(string framework) + { + const string assemblyName = "TestableIO.System.IO.Abstractions.TestingHelpers"; + + var publicApi = Helper.CreatePublicApi(framework, assemblyName); + var expectedApi = Helper.GetExpectedApi(framework, assemblyName); + + await That(publicApi).IsEqualTo(expectedApi); + } + + private static IEnumerable TargetFrameworksTheoryData() + { + List theoryData = new(); + foreach (var targetFramework in Helper.GetTargetFrameworks()) + { + theoryData.Add(targetFramework); + } + + return theoryData; + } +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.Api.Tests/Expected/TestableIO.System.IO.Abstractions.TestingHelpers_net10.0.txt b/tests/TestableIO.System.IO.Abstractions.Api.Tests/Expected/TestableIO.System.IO.Abstractions.TestingHelpers_net10.0.txt new file mode 100644 index 000000000..28283ec09 --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.Api.Tests/Expected/TestableIO.System.IO.Abstractions.TestingHelpers_net10.0.txt @@ -0,0 +1,606 @@ +[assembly: System.Reflection.AssemblyMetadata("RepositoryUrl", "https://github.com/TestableIO/System.IO.Abstractions.git")] +[assembly: System.Runtime.Versioning.TargetFramework(".NETCoreApp,Version=v10.0", FrameworkDisplayName=".NET 10.0")] +public class FileHandles +{ + public FileHandles() { } + public void AddHandle(string path, System.Guid guid, System.IO.FileAccess access, System.IO.FileShare share) { } + public void RemoveHandle(string path, System.Guid guid) { } +} +namespace System.IO.Abstractions.TestingHelpers +{ + public interface IMockFileDataAccessor : System.IO.Abstractions.IFileSystem + { + System.Collections.Generic.IEnumerable AllDirectories { get; } + System.Collections.Generic.IEnumerable AllDrives { get; } + System.Collections.Generic.IEnumerable AllFiles { get; } + System.Collections.Generic.IEnumerable AllPaths { get; } + FileHandles FileHandles { get; } + System.IO.Abstractions.IFileSystem FileSystem { get; } + System.IO.Abstractions.TestingHelpers.PathVerifier PathVerifier { get; } + System.IO.Abstractions.TestingHelpers.StringOperations StringOperations { get; } + void AddDirectory(string path); + void AddDrive(string name, System.IO.Abstractions.TestingHelpers.MockDriveData mockDrive); + void AddFile(string path, System.IO.Abstractions.TestingHelpers.MockFileData mockFile, bool verifyAccess = true); + void AddFileFromEmbeddedResource(string path, System.Reflection.Assembly resourceAssembly, string embeddedResourcePath); + void AddFilesFromEmbeddedNamespace(string path, System.Reflection.Assembly resourceAssembly, string embeddedResourcePath); + System.IO.Abstractions.TestingHelpers.MockFileData AdjustTimes(System.IO.Abstractions.TestingHelpers.MockFileData fileData, System.IO.Abstractions.TestingHelpers.TimeAdjustments timeAdjustments); + bool FileExists(string path); + System.IO.Abstractions.TestingHelpers.MockDriveData GetDrive(string name); + System.IO.Abstractions.TestingHelpers.MockFileData GetFile(string path); + void MoveDirectory(string sourcePath, string destPath); + void RemoveFile(string path, bool verifyAccess = true); + } + [System.Serializable] + public class MockDirectory : System.IO.Abstractions.DirectoryBase + { + public MockDirectory(System.IO.Abstractions.TestingHelpers.IMockFileDataAccessor mockFileDataAccessor, string currentDirectory) { } + public MockDirectory(System.IO.Abstractions.TestingHelpers.IMockFileDataAccessor mockFileDataAccessor, System.IO.Abstractions.FileBase fileBase, string currentDirectory) { } + public override System.IO.Abstractions.IDirectoryInfo CreateDirectory(string path) { } + public override System.IO.Abstractions.IDirectoryInfo CreateDirectory(string path, System.IO.UnixFileMode unixCreateMode) { } + public override System.IO.Abstractions.IFileSystemInfo CreateSymbolicLink(string path, string pathToTarget) { } + public override System.IO.Abstractions.IDirectoryInfo CreateTempSubdirectory(string prefix = null) { } + public override void Delete(string path) { } + public override void Delete(string path, bool recursive) { } + public override System.Collections.Generic.IEnumerable EnumerateDirectories(string path) { } + public override System.Collections.Generic.IEnumerable EnumerateDirectories(string path, string searchPattern) { } + public override System.Collections.Generic.IEnumerable EnumerateDirectories(string path, string searchPattern, System.IO.EnumerationOptions enumerationOptions) { } + public override System.Collections.Generic.IEnumerable EnumerateDirectories(string path, string searchPattern, System.IO.SearchOption searchOption) { } + public override System.Collections.Generic.IEnumerable EnumerateFileSystemEntries(string path) { } + public override System.Collections.Generic.IEnumerable EnumerateFileSystemEntries(string path, string searchPattern) { } + public override System.Collections.Generic.IEnumerable EnumerateFileSystemEntries(string path, string searchPattern, System.IO.EnumerationOptions enumerationOptions) { } + public override System.Collections.Generic.IEnumerable EnumerateFileSystemEntries(string path, string searchPattern, System.IO.SearchOption searchOption) { } + public override System.Collections.Generic.IEnumerable EnumerateFiles(string path) { } + public override System.Collections.Generic.IEnumerable EnumerateFiles(string path, string searchPattern) { } + public override System.Collections.Generic.IEnumerable EnumerateFiles(string path, string searchPattern, System.IO.EnumerationOptions enumerationOptions) { } + public override System.Collections.Generic.IEnumerable EnumerateFiles(string path, string searchPattern, System.IO.SearchOption searchOption) { } + public override bool Exists(string path) { } + public override System.DateTime GetCreationTime(string path) { } + public override System.DateTime GetCreationTimeUtc(string path) { } + public override string GetCurrentDirectory() { } + public override string[] GetDirectories(string path) { } + public override string[] GetDirectories(string path, string searchPattern) { } + public override string[] GetDirectories(string path, string searchPattern, System.IO.EnumerationOptions enumerationOptions) { } + public override string[] GetDirectories(string path, string searchPattern, System.IO.SearchOption searchOption) { } + public override string GetDirectoryRoot(string path) { } + public override string[] GetFileSystemEntries(string path) { } + public override string[] GetFileSystemEntries(string path, string searchPattern) { } + public override string[] GetFileSystemEntries(string path, string searchPattern, System.IO.EnumerationOptions enumerationOptions) { } + public override string[] GetFileSystemEntries(string path, string searchPattern, System.IO.SearchOption searchOption) { } + public override string[] GetFiles(string path) { } + public override string[] GetFiles(string path, string searchPattern) { } + public override string[] GetFiles(string path, string searchPattern, System.IO.EnumerationOptions enumerationOptions) { } + public override string[] GetFiles(string path, string searchPattern, System.IO.SearchOption searchOption) { } + public override System.DateTime GetLastAccessTime(string path) { } + public override System.DateTime GetLastAccessTimeUtc(string path) { } + public override System.DateTime GetLastWriteTime(string path) { } + public override System.DateTime GetLastWriteTimeUtc(string path) { } + public override string[] GetLogicalDrives() { } + public override System.IO.Abstractions.IDirectoryInfo GetParent(string path) { } + public override void Move(string sourceDirName, string destDirName) { } + public override System.IO.Abstractions.IFileSystemInfo ResolveLinkTarget(string linkPath, bool returnFinalTarget) { } + public override void SetCreationTime(string path, System.DateTime creationTime) { } + public override void SetCreationTimeUtc(string path, System.DateTime creationTimeUtc) { } + public override void SetCurrentDirectory(string path) { } + public override void SetLastAccessTime(string path, System.DateTime lastAccessTime) { } + public override void SetLastAccessTimeUtc(string path, System.DateTime lastAccessTimeUtc) { } + public override void SetLastWriteTime(string path, System.DateTime lastWriteTime) { } + public override void SetLastWriteTimeUtc(string path, System.DateTime lastWriteTimeUtc) { } + } + [System.Serializable] + public class MockDirectoryData : System.IO.Abstractions.TestingHelpers.MockFileData + { + public MockDirectoryData() { } + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public new System.Security.AccessControl.DirectorySecurity AccessControl { get; set; } + } + [System.Serializable] + public class MockDirectoryInfo : System.IO.Abstractions.DirectoryInfoBase, System.IO.Abstractions.IFileSystemAclSupport + { + public MockDirectoryInfo(System.IO.Abstractions.TestingHelpers.IMockFileDataAccessor mockFileDataAccessor, string directoryPath) { } + public override System.IO.FileAttributes Attributes { get; set; } + public override System.DateTime CreationTime { get; set; } + public override System.DateTime CreationTimeUtc { get; set; } + public override bool Exists { get; } + public override string Extension { get; } + public override string FullName { get; } + public override System.DateTime LastAccessTime { get; set; } + public override System.DateTime LastAccessTimeUtc { get; set; } + public override System.DateTime LastWriteTime { get; set; } + public override System.DateTime LastWriteTimeUtc { get; set; } + public override string LinkTarget { get; } + public override string Name { get; } + public override System.IO.Abstractions.IDirectoryInfo Parent { get; } + public override System.IO.Abstractions.IDirectoryInfo Root { get; } + public override void Create() { } + public override void CreateAsSymbolicLink(string pathToTarget) { } + public override System.IO.Abstractions.IDirectoryInfo CreateSubdirectory(string path) { } + public override void Delete() { } + public override void Delete(bool recursive) { } + public override System.Collections.Generic.IEnumerable EnumerateDirectories() { } + public override System.Collections.Generic.IEnumerable EnumerateDirectories(string searchPattern) { } + public override System.Collections.Generic.IEnumerable EnumerateDirectories(string searchPattern, System.IO.EnumerationOptions enumerationOptions) { } + public override System.Collections.Generic.IEnumerable EnumerateDirectories(string searchPattern, System.IO.SearchOption searchOption) { } + public override System.Collections.Generic.IEnumerable EnumerateFileSystemInfos() { } + public override System.Collections.Generic.IEnumerable EnumerateFileSystemInfos(string searchPattern) { } + public override System.Collections.Generic.IEnumerable EnumerateFileSystemInfos(string searchPattern, System.IO.EnumerationOptions enumerationOptions) { } + public override System.Collections.Generic.IEnumerable EnumerateFileSystemInfos(string searchPattern, System.IO.SearchOption searchOption) { } + public override System.Collections.Generic.IEnumerable EnumerateFiles() { } + public override System.Collections.Generic.IEnumerable EnumerateFiles(string searchPattern) { } + public override System.Collections.Generic.IEnumerable EnumerateFiles(string searchPattern, System.IO.EnumerationOptions enumerationOptions) { } + public override System.Collections.Generic.IEnumerable EnumerateFiles(string searchPattern, System.IO.SearchOption searchOption) { } + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public object GetAccessControl() { } + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public object GetAccessControl(System.IO.Abstractions.IFileSystemAclSupport.AccessControlSections includeSections) { } + public override System.IO.Abstractions.IDirectoryInfo[] GetDirectories() { } + public override System.IO.Abstractions.IDirectoryInfo[] GetDirectories(string searchPattern) { } + public override System.IO.Abstractions.IDirectoryInfo[] GetDirectories(string searchPattern, System.IO.EnumerationOptions enumerationOptions) { } + public override System.IO.Abstractions.IDirectoryInfo[] GetDirectories(string searchPattern, System.IO.SearchOption searchOption) { } + public override System.IO.Abstractions.IFileSystemInfo[] GetFileSystemInfos() { } + public override System.IO.Abstractions.IFileSystemInfo[] GetFileSystemInfos(string searchPattern) { } + public override System.IO.Abstractions.IFileSystemInfo[] GetFileSystemInfos(string searchPattern, System.IO.EnumerationOptions enumerationOptions) { } + public override System.IO.Abstractions.IFileSystemInfo[] GetFileSystemInfos(string searchPattern, System.IO.SearchOption searchOption) { } + public override System.IO.Abstractions.IFileInfo[] GetFiles() { } + public override System.IO.Abstractions.IFileInfo[] GetFiles(string searchPattern) { } + public override System.IO.Abstractions.IFileInfo[] GetFiles(string searchPattern, System.IO.EnumerationOptions enumerationOptions) { } + public override System.IO.Abstractions.IFileInfo[] GetFiles(string searchPattern, System.IO.SearchOption searchOption) { } + public override void MoveTo(string destDirName) { } + public override void Refresh() { } + public override System.IO.Abstractions.IFileSystemInfo ResolveLinkTarget(bool returnFinalTarget) { } + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public void SetAccessControl(object value) { } + public override string ToString() { } + } + [System.Serializable] + public class MockDirectoryInfoFactory : System.IO.Abstractions.IDirectoryInfoFactory, System.IO.Abstractions.IFileSystemEntity + { + public MockDirectoryInfoFactory(System.IO.Abstractions.TestingHelpers.IMockFileDataAccessor mockFileSystem) { } + public System.IO.Abstractions.IFileSystem FileSystem { get; } + public System.IO.Abstractions.IDirectoryInfo New(string path) { } + public System.IO.Abstractions.IDirectoryInfo Wrap(System.IO.DirectoryInfo directoryInfo) { } + } + [System.Serializable] + public class MockDriveData + { + public MockDriveData() { } + public MockDriveData(System.IO.Abstractions.TestingHelpers.MockDriveData template) { } + public long AvailableFreeSpace { get; set; } + public string DriveFormat { get; set; } + public System.IO.DriveType DriveType { get; set; } + public bool IsReady { get; set; } + public long TotalFreeSpace { get; set; } + public long TotalSize { get; set; } + public string VolumeLabel { get; set; } + } + [System.Serializable] + public class MockDriveInfo : System.IO.Abstractions.DriveInfoBase + { + public MockDriveInfo(System.IO.Abstractions.TestingHelpers.IMockFileDataAccessor mockFileDataAccessor, string name) { } + public override long AvailableFreeSpace { get; } + public override string DriveFormat { get; } + public override System.IO.DriveType DriveType { get; } + public override bool IsReady { get; } + public override string Name { get; } + public override System.IO.Abstractions.IDirectoryInfo RootDirectory { get; } + public override long TotalFreeSpace { get; } + public override long TotalSize { get; } + public override string VolumeLabel { get; set; } + public override string ToString() { } + } + [System.Serializable] + public class MockDriveInfoFactory : System.IO.Abstractions.IDriveInfoFactory, System.IO.Abstractions.IFileSystemEntity + { + public MockDriveInfoFactory(System.IO.Abstractions.TestingHelpers.IMockFileDataAccessor mockFileSystem) { } + public System.IO.Abstractions.IFileSystem FileSystem { get; } + public System.IO.Abstractions.IDriveInfo[] GetDrives() { } + public System.IO.Abstractions.IDriveInfo New(string driveName) { } + public System.IO.Abstractions.IDriveInfo Wrap(System.IO.DriveInfo driveInfo) { } + } + [System.Serializable] + public class MockFile : System.IO.Abstractions.FileBase + { + public MockFile(System.IO.Abstractions.TestingHelpers.IMockFileDataAccessor mockFileDataAccessor) { } + public override void AppendAllBytes(string path, System.ReadOnlySpan bytes) { } + public override void AppendAllBytes(string path, byte[] bytes) { } + public override System.Threading.Tasks.Task AppendAllBytesAsync(string path, System.ReadOnlyMemory bytes, System.Threading.CancellationToken cancellationToken = default) { } + public override System.Threading.Tasks.Task AppendAllBytesAsync(string path, byte[] bytes, System.Threading.CancellationToken cancellationToken = default) { } + public override void AppendAllLines(string path, System.Collections.Generic.IEnumerable contents) { } + public override void AppendAllLines(string path, System.Collections.Generic.IEnumerable contents, System.Text.Encoding encoding) { } + public override System.Threading.Tasks.Task AppendAllLinesAsync(string path, System.Collections.Generic.IEnumerable contents, System.Threading.CancellationToken cancellationToken = default) { } + public override System.Threading.Tasks.Task AppendAllLinesAsync(string path, System.Collections.Generic.IEnumerable contents, System.Text.Encoding encoding, System.Threading.CancellationToken cancellationToken = default) { } + public override void AppendAllText(string path, System.ReadOnlySpan contents) { } + public override void AppendAllText(string path, string contents) { } + public override void AppendAllText(string path, System.ReadOnlySpan contents, System.Text.Encoding encoding) { } + public override void AppendAllText(string path, string contents, System.Text.Encoding encoding) { } + public override System.Threading.Tasks.Task AppendAllTextAsync(string path, System.ReadOnlyMemory contents, System.Threading.CancellationToken cancellationToken = default) { } + public override System.Threading.Tasks.Task AppendAllTextAsync(string path, string contents, System.Threading.CancellationToken cancellationToken = default) { } + public override System.Threading.Tasks.Task AppendAllTextAsync(string path, System.ReadOnlyMemory contents, System.Text.Encoding encoding, System.Threading.CancellationToken cancellationToken = default) { } + public override System.Threading.Tasks.Task AppendAllTextAsync(string path, string contents, System.Text.Encoding encoding, System.Threading.CancellationToken cancellationToken = default) { } + public override System.IO.StreamWriter AppendText(string path) { } + public override void Copy(string sourceFileName, string destFileName) { } + public override void Copy(string sourceFileName, string destFileName, bool overwrite) { } + public override System.IO.Abstractions.FileSystemStream Create(string path) { } + public override System.IO.Abstractions.FileSystemStream Create(string path, int bufferSize) { } + public override System.IO.Abstractions.FileSystemStream Create(string path, int bufferSize, System.IO.FileOptions options) { } + public override System.IO.Abstractions.IFileSystemInfo CreateSymbolicLink(string path, string pathToTarget) { } + public override System.IO.StreamWriter CreateText(string path) { } + public override void Decrypt(string path) { } + public override void Delete(string path) { } + public override void Encrypt(string path) { } + public override bool Exists(string path) { } + public override System.IO.FileAttributes GetAttributes(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle) { } + public override System.IO.FileAttributes GetAttributes(string path) { } + public override System.DateTime GetCreationTime(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle) { } + public override System.DateTime GetCreationTime(string path) { } + public override System.DateTime GetCreationTimeUtc(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle) { } + public override System.DateTime GetCreationTimeUtc(string path) { } + public override System.DateTime GetLastAccessTime(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle) { } + public override System.DateTime GetLastAccessTime(string path) { } + public override System.DateTime GetLastAccessTimeUtc(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle) { } + public override System.DateTime GetLastAccessTimeUtc(string path) { } + public override System.DateTime GetLastWriteTime(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle) { } + public override System.DateTime GetLastWriteTime(string path) { } + public override System.DateTime GetLastWriteTimeUtc(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle) { } + public override System.DateTime GetLastWriteTimeUtc(string path) { } + public override System.IO.UnixFileMode GetUnixFileMode(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle) { } + public override System.IO.UnixFileMode GetUnixFileMode(string path) { } + public override void Move(string sourceFileName, string destFileName) { } + public override void Move(string sourceFileName, string destFileName, bool overwrite) { } + public override System.IO.Abstractions.FileSystemStream Open(string path, System.IO.FileMode mode) { } + public override System.IO.Abstractions.FileSystemStream Open(string path, System.IO.FileStreamOptions options) { } + public override System.IO.Abstractions.FileSystemStream Open(string path, System.IO.FileMode mode, System.IO.FileAccess access) { } + public override System.IO.Abstractions.FileSystemStream Open(string path, System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share) { } + public override System.IO.Abstractions.FileSystemStream OpenRead(string path) { } + public override System.IO.StreamReader OpenText(string path) { } + public override System.IO.Abstractions.FileSystemStream OpenWrite(string path) { } + public override byte[] ReadAllBytes(string path) { } + public override System.Threading.Tasks.Task ReadAllBytesAsync(string path, System.Threading.CancellationToken cancellationToken = default) { } + public override string[] ReadAllLines(string path) { } + public override string[] ReadAllLines(string path, System.Text.Encoding encoding) { } + public override System.Threading.Tasks.Task ReadAllLinesAsync(string path, System.Threading.CancellationToken cancellationToken = default) { } + public override System.Threading.Tasks.Task ReadAllLinesAsync(string path, System.Text.Encoding encoding, System.Threading.CancellationToken cancellationToken = default) { } + public override string ReadAllText(string path) { } + public override string ReadAllText(string path, System.Text.Encoding encoding) { } + public override System.Threading.Tasks.Task ReadAllTextAsync(string path, System.Threading.CancellationToken cancellationToken = default) { } + public override System.Threading.Tasks.Task ReadAllTextAsync(string path, System.Text.Encoding encoding, System.Threading.CancellationToken cancellationToken = default) { } + public override System.Collections.Generic.IEnumerable ReadLines(string path) { } + public override System.Collections.Generic.IEnumerable ReadLines(string path, System.Text.Encoding encoding) { } + public override System.Collections.Generic.IAsyncEnumerable ReadLinesAsync(string path, System.Threading.CancellationToken cancellationToken = default) { } + [System.Runtime.CompilerServices.AsyncIteratorStateMachine(typeof(System.IO.Abstractions.TestingHelpers.MockFile.d__14))] + public override System.Collections.Generic.IAsyncEnumerable ReadLinesAsync(string path, System.Text.Encoding encoding, [System.Runtime.CompilerServices.EnumeratorCancellation] System.Threading.CancellationToken cancellationToken = default) { } + public override void Replace(string sourceFileName, string destinationFileName, string destinationBackupFileName) { } + public override void Replace(string sourceFileName, string destinationFileName, string destinationBackupFileName, bool ignoreMetadataErrors) { } + public override System.IO.Abstractions.IFileSystemInfo ResolveLinkTarget(string linkPath, bool returnFinalTarget) { } + public override void SetAttributes(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle, System.IO.FileAttributes fileAttributes) { } + public override void SetAttributes(string path, System.IO.FileAttributes fileAttributes) { } + public override void SetCreationTime(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle, System.DateTime creationTime) { } + public override void SetCreationTime(string path, System.DateTime creationTime) { } + public override void SetCreationTimeUtc(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle, System.DateTime creationTimeUtc) { } + public override void SetCreationTimeUtc(string path, System.DateTime creationTimeUtc) { } + public override void SetLastAccessTime(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle, System.DateTime lastAccessTime) { } + public override void SetLastAccessTime(string path, System.DateTime lastAccessTime) { } + public override void SetLastAccessTimeUtc(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle, System.DateTime lastAccessTimeUtc) { } + public override void SetLastAccessTimeUtc(string path, System.DateTime lastAccessTimeUtc) { } + public override void SetLastWriteTime(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle, System.DateTime lastWriteTime) { } + public override void SetLastWriteTime(string path, System.DateTime lastWriteTime) { } + public override void SetLastWriteTimeUtc(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle, System.DateTime lastWriteTimeUtc) { } + public override void SetLastWriteTimeUtc(string path, System.DateTime lastWriteTimeUtc) { } + public override void SetUnixFileMode(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle, System.IO.UnixFileMode mode) { } + public override void SetUnixFileMode(string path, System.IO.UnixFileMode mode) { } + public override void WriteAllBytes(string path, System.ReadOnlySpan bytes) { } + public override void WriteAllBytes(string path, byte[] bytes) { } + public override System.Threading.Tasks.Task WriteAllBytesAsync(string path, System.ReadOnlyMemory bytes, System.Threading.CancellationToken cancellationToken = default) { } + public override System.Threading.Tasks.Task WriteAllBytesAsync(string path, byte[] bytes, System.Threading.CancellationToken cancellationToken = default) { } + public override void WriteAllLines(string path, System.Collections.Generic.IEnumerable contents) { } + public override void WriteAllLines(string path, string[] contents) { } + public override void WriteAllLines(string path, System.Collections.Generic.IEnumerable contents, System.Text.Encoding encoding) { } + public override void WriteAllLines(string path, string[] contents, System.Text.Encoding encoding) { } + public override System.Threading.Tasks.Task WriteAllLinesAsync(string path, System.Collections.Generic.IEnumerable contents, System.Threading.CancellationToken cancellationToken = default) { } + public override System.Threading.Tasks.Task WriteAllLinesAsync(string path, System.Collections.Generic.IEnumerable contents, System.Text.Encoding encoding, System.Threading.CancellationToken cancellationToken = default) { } + public override void WriteAllText(string path, System.ReadOnlySpan contents) { } + public override void WriteAllText(string path, string contents) { } + public override void WriteAllText(string path, System.ReadOnlySpan contents, System.Text.Encoding encoding) { } + public override void WriteAllText(string path, string contents, System.Text.Encoding encoding) { } + public override System.Threading.Tasks.Task WriteAllTextAsync(string path, System.ReadOnlyMemory contents, System.Threading.CancellationToken cancellationToken = default) { } + public override System.Threading.Tasks.Task WriteAllTextAsync(string path, string contents, System.Threading.CancellationToken cancellationToken = default) { } + public override System.Threading.Tasks.Task WriteAllTextAsync(string path, System.ReadOnlyMemory contents, System.Text.Encoding encoding, System.Threading.CancellationToken cancellationToken = default) { } + public override System.Threading.Tasks.Task WriteAllTextAsync(string path, string contents, System.Text.Encoding encoding, System.Threading.CancellationToken cancellationToken = default) { } + } + [System.Serializable] + public class MockFileData + { + public static readonly System.DateTimeOffset DefaultDateTimeOffset; + public static readonly System.Text.Encoding DefaultEncoding; + public MockFileData(System.IO.Abstractions.TestingHelpers.MockFileData template) { } + public MockFileData(byte[] contents) { } + public MockFileData(string textContents) { } + public MockFileData(string textContents, System.Text.Encoding encoding) { } + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public System.Security.AccessControl.FileSecurity AccessControl { get; set; } + public System.IO.FileShare AllowedFileShare { get; set; } + public System.IO.FileAttributes Attributes { get; set; } + public byte[] Contents { get; set; } + public System.DateTimeOffset CreationTime { get; set; } + public System.IO.Abstractions.IFileVersionInfo FileVersionInfo { get; set; } + public bool IsDirectory { get; } + public System.DateTimeOffset LastAccessTime { get; set; } + public System.DateTimeOffset LastWriteTime { get; set; } + public string LinkTarget { get; set; } + public string TextContents { get; set; } + public System.IO.UnixFileMode UnixMode { get; set; } + public static System.IO.Abstractions.TestingHelpers.MockFileData op_Implicit(string s) { } + } + [System.Serializable] + public class MockFileInfo : System.IO.Abstractions.FileInfoBase, System.IO.Abstractions.IFileSystemAclSupport + { + public MockFileInfo(System.IO.Abstractions.TestingHelpers.IMockFileDataAccessor mockFileSystem, string path) { } + public override System.IO.FileAttributes Attributes { get; set; } + public override System.DateTime CreationTime { get; set; } + public override System.DateTime CreationTimeUtc { get; set; } + public override System.IO.Abstractions.IDirectoryInfo Directory { get; } + public override string DirectoryName { get; } + public override bool Exists { get; } + public override string Extension { get; } + public override string FullName { get; } + public override bool IsReadOnly { get; set; } + public override System.DateTime LastAccessTime { get; set; } + public override System.DateTime LastAccessTimeUtc { get; set; } + public override System.DateTime LastWriteTime { get; set; } + public override System.DateTime LastWriteTimeUtc { get; set; } + public override long Length { get; } + public override string LinkTarget { get; } + public override string Name { get; } + public override System.IO.StreamWriter AppendText() { } + public override System.IO.Abstractions.IFileInfo CopyTo(string destFileName) { } + public override System.IO.Abstractions.IFileInfo CopyTo(string destFileName, bool overwrite) { } + public override System.IO.Abstractions.FileSystemStream Create() { } + public override void CreateAsSymbolicLink(string pathToTarget) { } + public override System.IO.StreamWriter CreateText() { } + public override void Decrypt() { } + public override void Delete() { } + public override void Encrypt() { } + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public object GetAccessControl() { } + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public object GetAccessControl(System.IO.Abstractions.IFileSystemAclSupport.AccessControlSections includeSections) { } + public override void MoveTo(string destFileName) { } + public override void MoveTo(string destFileName, bool overwrite) { } + public override System.IO.Abstractions.FileSystemStream Open(System.IO.FileMode mode) { } + public override System.IO.Abstractions.FileSystemStream Open(System.IO.FileStreamOptions options) { } + public override System.IO.Abstractions.FileSystemStream Open(System.IO.FileMode mode, System.IO.FileAccess access) { } + public override System.IO.Abstractions.FileSystemStream Open(System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share) { } + public override System.IO.Abstractions.FileSystemStream OpenRead() { } + public override System.IO.StreamReader OpenText() { } + public override System.IO.Abstractions.FileSystemStream OpenWrite() { } + public override void Refresh() { } + public override System.IO.Abstractions.IFileInfo Replace(string destinationFileName, string destinationBackupFileName) { } + public override System.IO.Abstractions.IFileInfo Replace(string destinationFileName, string destinationBackupFileName, bool ignoreMetadataErrors) { } + public override System.IO.Abstractions.IFileSystemInfo ResolveLinkTarget(bool returnFinalTarget) { } + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public void SetAccessControl(object value) { } + public override string ToString() { } + } + [System.Serializable] + public class MockFileInfoFactory : System.IO.Abstractions.IFileInfoFactory, System.IO.Abstractions.IFileSystemEntity + { + public MockFileInfoFactory(System.IO.Abstractions.TestingHelpers.IMockFileDataAccessor mockFileSystem) { } + public System.IO.Abstractions.IFileSystem FileSystem { get; } + public System.IO.Abstractions.IFileInfo New(string fileName) { } + public System.IO.Abstractions.IFileInfo Wrap(System.IO.FileInfo fileInfo) { } + } + [System.Serializable] + public class MockFileStream : System.IO.Abstractions.FileSystemStream, System.IO.Abstractions.IFileSystemAclSupport + { + public MockFileStream(System.IO.Abstractions.TestingHelpers.IMockFileDataAccessor mockFileDataAccessor, string path, System.IO.FileMode mode, System.IO.FileAccess access = 3, System.IO.FileShare share = 1, System.IO.FileOptions options = 0) { } + public override bool CanRead { get; } + public override bool CanWrite { get; } + public static System.IO.Abstractions.FileSystemStream Null { get; } + protected override void Dispose(bool disposing) { } + public override void EndWrite(System.IAsyncResult asyncResult) { } + public override void Flush() { } + public override void Flush(bool flushToDisk) { } + public override System.Threading.Tasks.Task FlushAsync(System.Threading.CancellationToken cancellationToken) { } + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public object GetAccessControl() { } + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public object GetAccessControl(System.IO.Abstractions.IFileSystemAclSupport.AccessControlSections includeSections) { } + public override int Read(byte[] buffer, int offset, int count) { } + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public void SetAccessControl(object value) { } + public override void SetLength(long value) { } + public override void Write(System.ReadOnlySpan buffer) { } + public override void Write(byte[] buffer, int offset, int count) { } + public override System.Threading.Tasks.ValueTask WriteAsync(System.ReadOnlyMemory buffer, System.Threading.CancellationToken cancellationToken = default) { } + public override System.Threading.Tasks.Task WriteAsync(byte[] buffer, int offset, int count, System.Threading.CancellationToken cancellationToken) { } + public override void WriteByte(byte value) { } + } + [System.Serializable] + public class MockFileStreamFactory : System.IO.Abstractions.IFileStreamFactory, System.IO.Abstractions.IFileSystemEntity + { + public MockFileStreamFactory(System.IO.Abstractions.TestingHelpers.IMockFileDataAccessor mockFileSystem) { } + public System.IO.Abstractions.IFileSystem FileSystem { get; } + public System.IO.Abstractions.FileSystemStream New(Microsoft.Win32.SafeHandles.SafeFileHandle handle, System.IO.FileAccess access) { } + public System.IO.Abstractions.FileSystemStream New(string path, System.IO.FileMode mode) { } + public System.IO.Abstractions.FileSystemStream New(string path, System.IO.FileStreamOptions options) { } + public System.IO.Abstractions.FileSystemStream New(Microsoft.Win32.SafeHandles.SafeFileHandle handle, System.IO.FileAccess access, int bufferSize) { } + public System.IO.Abstractions.FileSystemStream New(string path, System.IO.FileMode mode, System.IO.FileAccess access) { } + public System.IO.Abstractions.FileSystemStream New(Microsoft.Win32.SafeHandles.SafeFileHandle handle, System.IO.FileAccess access, int bufferSize, bool isAsync) { } + public System.IO.Abstractions.FileSystemStream New(string path, System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share) { } + public System.IO.Abstractions.FileSystemStream New(string path, System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share, int bufferSize) { } + public System.IO.Abstractions.FileSystemStream New(string path, System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share, int bufferSize, System.IO.FileOptions options) { } + public System.IO.Abstractions.FileSystemStream New(string path, System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share, int bufferSize, bool useAsync) { } + public System.IO.Abstractions.FileSystemStream Wrap(System.IO.FileStream fileStream) { } + } + [System.Serializable] + public class MockFileSystem : System.IO.Abstractions.FileSystemBase, System.IO.Abstractions.IFileSystem, System.IO.Abstractions.TestingHelpers.IMockFileDataAccessor + { + public MockFileSystem() { } + public MockFileSystem(System.IO.Abstractions.TestingHelpers.MockFileSystemOptions options) { } + public MockFileSystem(System.Collections.Generic.IDictionary files, System.IO.Abstractions.TestingHelpers.MockFileSystemOptions options) { } + public MockFileSystem(System.Collections.Generic.IDictionary files, string currentDirectory = "") { } + public System.Collections.Generic.IEnumerable AllDirectories { get; } + public System.Collections.Generic.IEnumerable AllDrives { get; } + public System.Collections.Generic.IEnumerable AllFiles { get; } + public System.Collections.Generic.IEnumerable AllNodes { get; } + public System.Collections.Generic.IEnumerable AllPaths { get; } + public override System.IO.Abstractions.IDirectory Directory { get; } + public override System.IO.Abstractions.IDirectoryInfoFactory DirectoryInfo { get; } + public override System.IO.Abstractions.IDriveInfoFactory DriveInfo { get; } + public override System.IO.Abstractions.IFile File { get; } + public FileHandles FileHandles { get; } + public override System.IO.Abstractions.IFileInfoFactory FileInfo { get; } + public override System.IO.Abstractions.IFileStreamFactory FileStream { get; } + public System.IO.Abstractions.IFileSystem FileSystem { get; } + public override System.IO.Abstractions.IFileSystemWatcherFactory FileSystemWatcher { get; } + public override System.IO.Abstractions.IFileVersionInfoFactory FileVersionInfo { get; } + public override System.IO.Abstractions.IPath Path { get; } + public System.IO.Abstractions.TestingHelpers.PathVerifier PathVerifier { get; } + public System.IO.Abstractions.TestingHelpers.StringOperations StringOperations { get; } + public void AddDirectory(System.IO.Abstractions.IDirectoryInfo path) { } + public void AddDirectory(string path) { } + public void AddDrive(string name, System.IO.Abstractions.TestingHelpers.MockDriveData mockDrive) { } + public void AddEmptyFile(System.IO.Abstractions.IFileInfo path) { } + public void AddEmptyFile(string path) { } + public void AddFile(System.IO.Abstractions.IFileInfo path, System.IO.Abstractions.TestingHelpers.MockFileData data, bool verifyAccess = true) { } + public void AddFile(string path, System.IO.Abstractions.TestingHelpers.MockFileData mockFile, bool verifyAccess = true) { } + public void AddFileFromEmbeddedResource(string path, System.Reflection.Assembly resourceAssembly, string embeddedResourcePath) { } + public void AddFilesFromEmbeddedNamespace(string path, System.Reflection.Assembly resourceAssembly, string embeddedResourcePath) { } + public System.IO.Abstractions.TestingHelpers.MockFileData AdjustTimes(System.IO.Abstractions.TestingHelpers.MockFileData fileData, System.IO.Abstractions.TestingHelpers.TimeAdjustments timeAdjustments) { } + public bool FileExists(string path) { } + public System.IO.Abstractions.TestingHelpers.MockDriveData GetDrive(string name) { } + public System.IO.Abstractions.TestingHelpers.MockFileData GetFile(System.IO.Abstractions.IFileInfo path) { } + public System.IO.Abstractions.TestingHelpers.MockFileData GetFile(string path) { } + public System.IO.Abstractions.TestingHelpers.MockFileSystem MockTime(System.Func dateTimeProvider) { } + public void MoveDirectory(string sourcePath, string destPath) { } + public void RemoveFile(string path, bool verifyAccess = true) { } + } + public class MockFileSystemOptions + { + public MockFileSystemOptions() { } + public bool CreateDefaultTempDir { get; init; } + public string CurrentDirectory { get; init; } + } + [System.Serializable] + public class MockFileSystemWatcherFactory : System.IO.Abstractions.IFileSystemEntity, System.IO.Abstractions.IFileSystemWatcherFactory + { + public MockFileSystemWatcherFactory(System.IO.Abstractions.TestingHelpers.MockFileSystem mockFileSystem) { } + public System.IO.Abstractions.IFileSystem FileSystem { get; } + public System.IO.Abstractions.IFileSystemWatcher New() { } + public System.IO.Abstractions.IFileSystemWatcher New(string path) { } + public System.IO.Abstractions.IFileSystemWatcher New(string path, string filter) { } + public System.IO.Abstractions.IFileSystemWatcher Wrap(System.IO.FileSystemWatcher fileSystemWatcher) { } + } + [System.Serializable] + public class MockFileVersionInfo : System.IO.Abstractions.FileVersionInfoBase + { + public MockFileVersionInfo( + string fileName, + string fileVersion = null, + string productVersion = null, + string fileDescription = null, + string productName = null, + string companyName = null, + string comments = null, + string internalName = null, + bool isDebug = false, + bool isPatched = false, + bool isPrivateBuild = false, + bool isPreRelease = false, + bool isSpecialBuild = false, + string language = null, + string legalCopyright = null, + string legalTrademarks = null, + string originalFilename = null, + string privateBuild = null, + string specialBuild = null) { } + public override string Comments { get; } + public override string CompanyName { get; } + public override int FileBuildPart { get; } + public override string FileDescription { get; } + public override int FileMajorPart { get; } + public override int FileMinorPart { get; } + public override string FileName { get; } + public override int FilePrivatePart { get; } + public override string FileVersion { get; } + public override string InternalName { get; } + public override bool IsDebug { get; } + public override bool IsPatched { get; } + public override bool IsPreRelease { get; } + public override bool IsPrivateBuild { get; } + public override bool IsSpecialBuild { get; } + public override string Language { get; } + public override string LegalCopyright { get; } + public override string LegalTrademarks { get; } + public override string OriginalFilename { get; } + public override string PrivateBuild { get; } + public override int ProductBuildPart { get; } + public override int ProductMajorPart { get; } + public override int ProductMinorPart { get; } + public override string ProductName { get; } + public override int ProductPrivatePart { get; } + public override string ProductVersion { get; } + public override string SpecialBuild { get; } + public override string ToString() { } + } + [System.Serializable] + public class MockFileVersionInfoFactory : System.IO.Abstractions.IFileSystemEntity, System.IO.Abstractions.IFileVersionInfoFactory + { + public MockFileVersionInfoFactory(System.IO.Abstractions.TestingHelpers.IMockFileDataAccessor mockFileSystem) { } + public System.IO.Abstractions.IFileSystem FileSystem { get; } + public System.IO.Abstractions.IFileVersionInfo GetVersionInfo(string fileName) { } + } + [System.Serializable] + public class MockPath : System.IO.Abstractions.PathWrapper + { + public MockPath(System.IO.Abstractions.TestingHelpers.IMockFileDataAccessor mockFileDataAccessor) { } + public MockPath(System.IO.Abstractions.TestingHelpers.IMockFileDataAccessor mockFileDataAccessor, string defaultTempDirectory) { } + public override bool Exists(string path) { } + public override string GetFullPath(string path) { } + public override string GetRelativePath(string relativeTo, string path) { } + public override string GetTempFileName() { } + public override string GetTempPath() { } + } + public static class MockUnixSupport + { + public static bool IsUnixPlatform() { } + public static bool IsWindowsPlatform() { } + public static string Path(string path) { } + } + [System.Serializable] + public class PathVerifier + { + public PathVerifier(System.IO.Abstractions.TestingHelpers.IMockFileDataAccessor mockFileDataAccessor) { } + public void CheckInvalidPathChars(string path, bool checkAdditional = false) { } + public bool HasIllegalCharacters(string path, bool checkAdditional) { } + public void IsLegalAbsoluteOrRelative(string path, string paramName) { } + public string NormalizeDriveName(string name) { } + public bool TryNormalizeDriveName(string name, out string result) { } + } + [System.Serializable] + public class StringOperations + { + public StringOperations(bool caseSensitive) { } + public System.StringComparer Comparer { get; } + public bool Contains(string s, string substring) { } + public bool EndsWith(string s, string suffix) { } + public bool Equals(char x, char y) { } + public bool Equals(string x, string y) { } + public int IndexOf(string s, string substring) { } + public int IndexOf(string s, string substring, int startIndex) { } + public string Replace(string s, string oldValue, string newValue) { } + public bool StartsWith(string s, string prefix) { } + public char ToLower(char c) { } + public string ToLower(string s) { } + public char ToUpper(char c) { } + public string ToUpper(string s) { } + } + [System.Flags] + public enum TimeAdjustments + { + None = 0, + CreationTime = 1, + LastAccessTime = 2, + LastWriteTime = 4, + All = -1, + } +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.Api.Tests/Expected/TestableIO.System.IO.Abstractions.TestingHelpers_net472.txt b/tests/TestableIO.System.IO.Abstractions.Api.Tests/Expected/TestableIO.System.IO.Abstractions.TestingHelpers_net472.txt new file mode 100644 index 000000000..bce734d4f --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.Api.Tests/Expected/TestableIO.System.IO.Abstractions.TestingHelpers_net472.txt @@ -0,0 +1,511 @@ +[assembly: System.Reflection.AssemblyMetadata("RepositoryUrl", "https://github.com/TestableIO/System.IO.Abstractions.git")] +[assembly: System.Runtime.Versioning.TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName=".NET Framework 4.7.2")] +public class FileHandles +{ + public FileHandles() { } + public void AddHandle(string path, System.Guid guid, System.IO.FileAccess access, System.IO.FileShare share) { } + public void RemoveHandle(string path, System.Guid guid) { } +} +namespace System.IO.Abstractions.TestingHelpers +{ + public interface IMockFileDataAccessor : System.IO.Abstractions.IFileSystem + { + System.Collections.Generic.IEnumerable AllDirectories { get; } + System.Collections.Generic.IEnumerable AllDrives { get; } + System.Collections.Generic.IEnumerable AllFiles { get; } + System.Collections.Generic.IEnumerable AllPaths { get; } + FileHandles FileHandles { get; } + System.IO.Abstractions.IFileSystem FileSystem { get; } + System.IO.Abstractions.TestingHelpers.PathVerifier PathVerifier { get; } + System.IO.Abstractions.TestingHelpers.StringOperations StringOperations { get; } + void AddDirectory(string path); + void AddDrive(string name, System.IO.Abstractions.TestingHelpers.MockDriveData mockDrive); + void AddFile(string path, System.IO.Abstractions.TestingHelpers.MockFileData mockFile, bool verifyAccess = true); + void AddFileFromEmbeddedResource(string path, System.Reflection.Assembly resourceAssembly, string embeddedResourcePath); + void AddFilesFromEmbeddedNamespace(string path, System.Reflection.Assembly resourceAssembly, string embeddedResourcePath); + System.IO.Abstractions.TestingHelpers.MockFileData AdjustTimes(System.IO.Abstractions.TestingHelpers.MockFileData fileData, System.IO.Abstractions.TestingHelpers.TimeAdjustments timeAdjustments); + bool FileExists(string path); + System.IO.Abstractions.TestingHelpers.MockDriveData GetDrive(string name); + System.IO.Abstractions.TestingHelpers.MockFileData GetFile(string path); + void MoveDirectory(string sourcePath, string destPath); + void RemoveFile(string path, bool verifyAccess = true); + } + [System.Serializable] + public class MockDirectory : System.IO.Abstractions.DirectoryBase + { + public MockDirectory(System.IO.Abstractions.TestingHelpers.IMockFileDataAccessor mockFileDataAccessor, string currentDirectory) { } + public MockDirectory(System.IO.Abstractions.TestingHelpers.IMockFileDataAccessor mockFileDataAccessor, System.IO.Abstractions.FileBase fileBase, string currentDirectory) { } + public override System.IO.Abstractions.IDirectoryInfo CreateDirectory(string path) { } + public override void Delete(string path) { } + public override void Delete(string path, bool recursive) { } + public override System.Collections.Generic.IEnumerable EnumerateDirectories(string path) { } + public override System.Collections.Generic.IEnumerable EnumerateDirectories(string path, string searchPattern) { } + public override System.Collections.Generic.IEnumerable EnumerateDirectories(string path, string searchPattern, System.IO.SearchOption searchOption) { } + public override System.Collections.Generic.IEnumerable EnumerateFileSystemEntries(string path) { } + public override System.Collections.Generic.IEnumerable EnumerateFileSystemEntries(string path, string searchPattern) { } + public override System.Collections.Generic.IEnumerable EnumerateFileSystemEntries(string path, string searchPattern, System.IO.SearchOption searchOption) { } + public override System.Collections.Generic.IEnumerable EnumerateFiles(string path) { } + public override System.Collections.Generic.IEnumerable EnumerateFiles(string path, string searchPattern) { } + public override System.Collections.Generic.IEnumerable EnumerateFiles(string path, string searchPattern, System.IO.SearchOption searchOption) { } + public override bool Exists(string path) { } + public override System.DateTime GetCreationTime(string path) { } + public override System.DateTime GetCreationTimeUtc(string path) { } + public override string GetCurrentDirectory() { } + public override string[] GetDirectories(string path) { } + public override string[] GetDirectories(string path, string searchPattern) { } + public override string[] GetDirectories(string path, string searchPattern, System.IO.SearchOption searchOption) { } + public override string GetDirectoryRoot(string path) { } + public override string[] GetFileSystemEntries(string path) { } + public override string[] GetFileSystemEntries(string path, string searchPattern) { } + public override string[] GetFileSystemEntries(string path, string searchPattern, System.IO.SearchOption searchOption) { } + public override string[] GetFiles(string path) { } + public override string[] GetFiles(string path, string searchPattern) { } + public override string[] GetFiles(string path, string searchPattern, System.IO.SearchOption searchOption) { } + public override System.DateTime GetLastAccessTime(string path) { } + public override System.DateTime GetLastAccessTimeUtc(string path) { } + public override System.DateTime GetLastWriteTime(string path) { } + public override System.DateTime GetLastWriteTimeUtc(string path) { } + public override string[] GetLogicalDrives() { } + public override System.IO.Abstractions.IDirectoryInfo GetParent(string path) { } + public override void Move(string sourceDirName, string destDirName) { } + public override void SetCreationTime(string path, System.DateTime creationTime) { } + public override void SetCreationTimeUtc(string path, System.DateTime creationTimeUtc) { } + public override void SetCurrentDirectory(string path) { } + public override void SetLastAccessTime(string path, System.DateTime lastAccessTime) { } + public override void SetLastAccessTimeUtc(string path, System.DateTime lastAccessTimeUtc) { } + public override void SetLastWriteTime(string path, System.DateTime lastWriteTime) { } + public override void SetLastWriteTimeUtc(string path, System.DateTime lastWriteTimeUtc) { } + } + [System.Serializable] + public class MockDirectoryData : System.IO.Abstractions.TestingHelpers.MockFileData + { + public MockDirectoryData() { } + public new System.Security.AccessControl.DirectorySecurity AccessControl { get; set; } + } + [System.Serializable] + public class MockDirectoryInfo : System.IO.Abstractions.DirectoryInfoBase, System.IO.Abstractions.IFileSystemAclSupport + { + public MockDirectoryInfo(System.IO.Abstractions.TestingHelpers.IMockFileDataAccessor mockFileDataAccessor, string directoryPath) { } + public override System.IO.FileAttributes Attributes { get; set; } + public override System.DateTime CreationTime { get; set; } + public override System.DateTime CreationTimeUtc { get; set; } + public override bool Exists { get; } + public override string Extension { get; } + public override string FullName { get; } + public override System.DateTime LastAccessTime { get; set; } + public override System.DateTime LastAccessTimeUtc { get; set; } + public override System.DateTime LastWriteTime { get; set; } + public override System.DateTime LastWriteTimeUtc { get; set; } + public override string Name { get; } + public override System.IO.Abstractions.IDirectoryInfo Parent { get; } + public override System.IO.Abstractions.IDirectoryInfo Root { get; } + public override void Create() { } + public override System.IO.Abstractions.IDirectoryInfo CreateSubdirectory(string path) { } + public override void Delete() { } + public override void Delete(bool recursive) { } + public override System.Collections.Generic.IEnumerable EnumerateDirectories() { } + public override System.Collections.Generic.IEnumerable EnumerateDirectories(string searchPattern) { } + public override System.Collections.Generic.IEnumerable EnumerateDirectories(string searchPattern, System.IO.SearchOption searchOption) { } + public override System.Collections.Generic.IEnumerable EnumerateFileSystemInfos() { } + public override System.Collections.Generic.IEnumerable EnumerateFileSystemInfos(string searchPattern) { } + public override System.Collections.Generic.IEnumerable EnumerateFileSystemInfos(string searchPattern, System.IO.SearchOption searchOption) { } + public override System.Collections.Generic.IEnumerable EnumerateFiles() { } + public override System.Collections.Generic.IEnumerable EnumerateFiles(string searchPattern) { } + public override System.Collections.Generic.IEnumerable EnumerateFiles(string searchPattern, System.IO.SearchOption searchOption) { } + public object GetAccessControl() { } + public object GetAccessControl(System.IO.Abstractions.IFileSystemAclSupport.AccessControlSections includeSections) { } + public override System.IO.Abstractions.IDirectoryInfo[] GetDirectories() { } + public override System.IO.Abstractions.IDirectoryInfo[] GetDirectories(string searchPattern) { } + public override System.IO.Abstractions.IDirectoryInfo[] GetDirectories(string searchPattern, System.IO.SearchOption searchOption) { } + public override System.IO.Abstractions.IFileSystemInfo[] GetFileSystemInfos() { } + public override System.IO.Abstractions.IFileSystemInfo[] GetFileSystemInfos(string searchPattern) { } + public override System.IO.Abstractions.IFileSystemInfo[] GetFileSystemInfos(string searchPattern, System.IO.SearchOption searchOption) { } + public override System.IO.Abstractions.IFileInfo[] GetFiles() { } + public override System.IO.Abstractions.IFileInfo[] GetFiles(string searchPattern) { } + public override System.IO.Abstractions.IFileInfo[] GetFiles(string searchPattern, System.IO.SearchOption searchOption) { } + public override void MoveTo(string destDirName) { } + public override void Refresh() { } + public void SetAccessControl(object value) { } + public override string ToString() { } + } + [System.Serializable] + public class MockDirectoryInfoFactory : System.IO.Abstractions.IDirectoryInfoFactory, System.IO.Abstractions.IFileSystemEntity + { + public MockDirectoryInfoFactory(System.IO.Abstractions.TestingHelpers.IMockFileDataAccessor mockFileSystem) { } + public System.IO.Abstractions.IFileSystem FileSystem { get; } + public System.IO.Abstractions.IDirectoryInfo New(string path) { } + public System.IO.Abstractions.IDirectoryInfo Wrap(System.IO.DirectoryInfo directoryInfo) { } + } + [System.Serializable] + public class MockDriveData + { + public MockDriveData() { } + public MockDriveData(System.IO.Abstractions.TestingHelpers.MockDriveData template) { } + public long AvailableFreeSpace { get; set; } + public string DriveFormat { get; set; } + public System.IO.DriveType DriveType { get; set; } + public bool IsReady { get; set; } + public long TotalFreeSpace { get; set; } + public long TotalSize { get; set; } + public string VolumeLabel { get; set; } + } + [System.Serializable] + public class MockDriveInfo : System.IO.Abstractions.DriveInfoBase + { + public MockDriveInfo(System.IO.Abstractions.TestingHelpers.IMockFileDataAccessor mockFileDataAccessor, string name) { } + public override long AvailableFreeSpace { get; } + public override string DriveFormat { get; } + public override System.IO.DriveType DriveType { get; } + public override bool IsReady { get; } + public override string Name { get; } + public override System.IO.Abstractions.IDirectoryInfo RootDirectory { get; } + public override long TotalFreeSpace { get; } + public override long TotalSize { get; } + public override string VolumeLabel { get; set; } + public override string ToString() { } + } + [System.Serializable] + public class MockDriveInfoFactory : System.IO.Abstractions.IDriveInfoFactory, System.IO.Abstractions.IFileSystemEntity + { + public MockDriveInfoFactory(System.IO.Abstractions.TestingHelpers.IMockFileDataAccessor mockFileSystem) { } + public System.IO.Abstractions.IFileSystem FileSystem { get; } + public System.IO.Abstractions.IDriveInfo[] GetDrives() { } + public System.IO.Abstractions.IDriveInfo New(string driveName) { } + public System.IO.Abstractions.IDriveInfo Wrap(System.IO.DriveInfo driveInfo) { } + } + [System.Serializable] + public class MockFile : System.IO.Abstractions.FileBase + { + public MockFile(System.IO.Abstractions.TestingHelpers.IMockFileDataAccessor mockFileDataAccessor) { } + public override void AppendAllLines(string path, System.Collections.Generic.IEnumerable contents) { } + public override void AppendAllLines(string path, System.Collections.Generic.IEnumerable contents, System.Text.Encoding encoding) { } + public override void AppendAllText(string path, string contents) { } + public override void AppendAllText(string path, string contents, System.Text.Encoding encoding) { } + public override System.IO.StreamWriter AppendText(string path) { } + public override void Copy(string sourceFileName, string destFileName) { } + public override void Copy(string sourceFileName, string destFileName, bool overwrite) { } + public override System.IO.Abstractions.FileSystemStream Create(string path) { } + public override System.IO.Abstractions.FileSystemStream Create(string path, int bufferSize) { } + public override System.IO.Abstractions.FileSystemStream Create(string path, int bufferSize, System.IO.FileOptions options) { } + public override System.IO.StreamWriter CreateText(string path) { } + public override void Decrypt(string path) { } + public override void Delete(string path) { } + public override void Encrypt(string path) { } + public override bool Exists(string path) { } + public override System.IO.FileAttributes GetAttributes(string path) { } + public override System.DateTime GetCreationTime(string path) { } + public override System.DateTime GetCreationTimeUtc(string path) { } + public override System.DateTime GetLastAccessTime(string path) { } + public override System.DateTime GetLastAccessTimeUtc(string path) { } + public override System.DateTime GetLastWriteTime(string path) { } + public override System.DateTime GetLastWriteTimeUtc(string path) { } + public override void Move(string sourceFileName, string destFileName) { } + public override System.IO.Abstractions.FileSystemStream Open(string path, System.IO.FileMode mode) { } + public override System.IO.Abstractions.FileSystemStream Open(string path, System.IO.FileMode mode, System.IO.FileAccess access) { } + public override System.IO.Abstractions.FileSystemStream Open(string path, System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share) { } + public override System.IO.Abstractions.FileSystemStream OpenRead(string path) { } + public override System.IO.StreamReader OpenText(string path) { } + public override System.IO.Abstractions.FileSystemStream OpenWrite(string path) { } + public override byte[] ReadAllBytes(string path) { } + public override string[] ReadAllLines(string path) { } + public override string[] ReadAllLines(string path, System.Text.Encoding encoding) { } + public override string ReadAllText(string path) { } + public override string ReadAllText(string path, System.Text.Encoding encoding) { } + public override System.Collections.Generic.IEnumerable ReadLines(string path) { } + public override System.Collections.Generic.IEnumerable ReadLines(string path, System.Text.Encoding encoding) { } + public override void Replace(string sourceFileName, string destinationFileName, string destinationBackupFileName) { } + public override void Replace(string sourceFileName, string destinationFileName, string destinationBackupFileName, bool ignoreMetadataErrors) { } + public override void SetAttributes(string path, System.IO.FileAttributes fileAttributes) { } + public override void SetCreationTime(string path, System.DateTime creationTime) { } + public override void SetCreationTimeUtc(string path, System.DateTime creationTimeUtc) { } + public override void SetLastAccessTime(string path, System.DateTime lastAccessTime) { } + public override void SetLastAccessTimeUtc(string path, System.DateTime lastAccessTimeUtc) { } + public override void SetLastWriteTime(string path, System.DateTime lastWriteTime) { } + public override void SetLastWriteTimeUtc(string path, System.DateTime lastWriteTimeUtc) { } + public override void WriteAllBytes(string path, byte[] bytes) { } + public override void WriteAllLines(string path, System.Collections.Generic.IEnumerable contents) { } + public override void WriteAllLines(string path, string[] contents) { } + public override void WriteAllLines(string path, System.Collections.Generic.IEnumerable contents, System.Text.Encoding encoding) { } + public override void WriteAllLines(string path, string[] contents, System.Text.Encoding encoding) { } + public override void WriteAllText(string path, string contents) { } + public override void WriteAllText(string path, string contents, System.Text.Encoding encoding) { } + } + [System.Serializable] + public class MockFileData + { + public static readonly System.DateTimeOffset DefaultDateTimeOffset; + public static readonly System.Text.Encoding DefaultEncoding; + public MockFileData(System.IO.Abstractions.TestingHelpers.MockFileData template) { } + public MockFileData(byte[] contents) { } + public MockFileData(string textContents) { } + public MockFileData(string textContents, System.Text.Encoding encoding) { } + public System.Security.AccessControl.FileSecurity AccessControl { get; set; } + public System.IO.FileShare AllowedFileShare { get; set; } + public System.IO.FileAttributes Attributes { get; set; } + public byte[] Contents { get; set; } + public System.DateTimeOffset CreationTime { get; set; } + public System.IO.Abstractions.IFileVersionInfo FileVersionInfo { get; set; } + public bool IsDirectory { get; } + public System.DateTimeOffset LastAccessTime { get; set; } + public System.DateTimeOffset LastWriteTime { get; set; } + public string TextContents { get; set; } + public static System.IO.Abstractions.TestingHelpers.MockFileData op_Implicit(string s) { } + } + [System.Serializable] + public class MockFileInfo : System.IO.Abstractions.FileInfoBase, System.IO.Abstractions.IFileSystemAclSupport + { + public MockFileInfo(System.IO.Abstractions.TestingHelpers.IMockFileDataAccessor mockFileSystem, string path) { } + public override System.IO.FileAttributes Attributes { get; set; } + public override System.DateTime CreationTime { get; set; } + public override System.DateTime CreationTimeUtc { get; set; } + public override System.IO.Abstractions.IDirectoryInfo Directory { get; } + public override string DirectoryName { get; } + public override bool Exists { get; } + public override string Extension { get; } + public override string FullName { get; } + public override bool IsReadOnly { get; set; } + public override System.DateTime LastAccessTime { get; set; } + public override System.DateTime LastAccessTimeUtc { get; set; } + public override System.DateTime LastWriteTime { get; set; } + public override System.DateTime LastWriteTimeUtc { get; set; } + public override long Length { get; } + public override string Name { get; } + public override System.IO.StreamWriter AppendText() { } + public override System.IO.Abstractions.IFileInfo CopyTo(string destFileName) { } + public override System.IO.Abstractions.IFileInfo CopyTo(string destFileName, bool overwrite) { } + public override System.IO.Abstractions.FileSystemStream Create() { } + public override System.IO.StreamWriter CreateText() { } + public override void Decrypt() { } + public override void Delete() { } + public override void Encrypt() { } + public object GetAccessControl() { } + public object GetAccessControl(System.IO.Abstractions.IFileSystemAclSupport.AccessControlSections includeSections) { } + public override void MoveTo(string destFileName) { } + public override System.IO.Abstractions.FileSystemStream Open(System.IO.FileMode mode) { } + public override System.IO.Abstractions.FileSystemStream Open(System.IO.FileMode mode, System.IO.FileAccess access) { } + public override System.IO.Abstractions.FileSystemStream Open(System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share) { } + public override System.IO.Abstractions.FileSystemStream OpenRead() { } + public override System.IO.StreamReader OpenText() { } + public override System.IO.Abstractions.FileSystemStream OpenWrite() { } + public override void Refresh() { } + public override System.IO.Abstractions.IFileInfo Replace(string destinationFileName, string destinationBackupFileName) { } + public override System.IO.Abstractions.IFileInfo Replace(string destinationFileName, string destinationBackupFileName, bool ignoreMetadataErrors) { } + public void SetAccessControl(object value) { } + public override string ToString() { } + } + [System.Serializable] + public class MockFileInfoFactory : System.IO.Abstractions.IFileInfoFactory, System.IO.Abstractions.IFileSystemEntity + { + public MockFileInfoFactory(System.IO.Abstractions.TestingHelpers.IMockFileDataAccessor mockFileSystem) { } + public System.IO.Abstractions.IFileSystem FileSystem { get; } + public System.IO.Abstractions.IFileInfo New(string fileName) { } + public System.IO.Abstractions.IFileInfo Wrap(System.IO.FileInfo fileInfo) { } + } + [System.Serializable] + public class MockFileStream : System.IO.Abstractions.FileSystemStream, System.IO.Abstractions.IFileSystemAclSupport + { + public MockFileStream(System.IO.Abstractions.TestingHelpers.IMockFileDataAccessor mockFileDataAccessor, string path, System.IO.FileMode mode, System.IO.FileAccess access = 3, System.IO.FileShare share = 1, System.IO.FileOptions options = 0) { } + public override bool CanRead { get; } + public override bool CanWrite { get; } + public static System.IO.Abstractions.FileSystemStream Null { get; } + protected override void Dispose(bool disposing) { } + public override void EndWrite(System.IAsyncResult asyncResult) { } + public override void Flush() { } + public override void Flush(bool flushToDisk) { } + public override System.Threading.Tasks.Task FlushAsync(System.Threading.CancellationToken cancellationToken) { } + public object GetAccessControl() { } + public object GetAccessControl(System.IO.Abstractions.IFileSystemAclSupport.AccessControlSections includeSections) { } + public override int Read(byte[] buffer, int offset, int count) { } + public void SetAccessControl(object value) { } + public override void SetLength(long value) { } + public override void Write(byte[] buffer, int offset, int count) { } + public override System.Threading.Tasks.Task WriteAsync(byte[] buffer, int offset, int count, System.Threading.CancellationToken cancellationToken) { } + public override void WriteByte(byte value) { } + } + [System.Serializable] + public class MockFileStreamFactory : System.IO.Abstractions.IFileStreamFactory, System.IO.Abstractions.IFileSystemEntity + { + public MockFileStreamFactory(System.IO.Abstractions.TestingHelpers.IMockFileDataAccessor mockFileSystem) { } + public System.IO.Abstractions.IFileSystem FileSystem { get; } + public System.IO.Abstractions.FileSystemStream New(Microsoft.Win32.SafeHandles.SafeFileHandle handle, System.IO.FileAccess access) { } + public System.IO.Abstractions.FileSystemStream New(string path, System.IO.FileMode mode) { } + public System.IO.Abstractions.FileSystemStream New(Microsoft.Win32.SafeHandles.SafeFileHandle handle, System.IO.FileAccess access, int bufferSize) { } + public System.IO.Abstractions.FileSystemStream New(string path, System.IO.FileMode mode, System.IO.FileAccess access) { } + public System.IO.Abstractions.FileSystemStream New(Microsoft.Win32.SafeHandles.SafeFileHandle handle, System.IO.FileAccess access, int bufferSize, bool isAsync) { } + public System.IO.Abstractions.FileSystemStream New(string path, System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share) { } + public System.IO.Abstractions.FileSystemStream New(string path, System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share, int bufferSize) { } + public System.IO.Abstractions.FileSystemStream New(string path, System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share, int bufferSize, System.IO.FileOptions options) { } + public System.IO.Abstractions.FileSystemStream New(string path, System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share, int bufferSize, bool useAsync) { } + public System.IO.Abstractions.FileSystemStream Wrap(System.IO.FileStream fileStream) { } + } + [System.Serializable] + public class MockFileSystem : System.IO.Abstractions.FileSystemBase, System.IO.Abstractions.IFileSystem, System.IO.Abstractions.TestingHelpers.IMockFileDataAccessor + { + public MockFileSystem() { } + public MockFileSystem(System.IO.Abstractions.TestingHelpers.MockFileSystemOptions options) { } + public MockFileSystem(System.Collections.Generic.IDictionary files, System.IO.Abstractions.TestingHelpers.MockFileSystemOptions options) { } + public MockFileSystem(System.Collections.Generic.IDictionary files, string currentDirectory = "") { } + public System.Collections.Generic.IEnumerable AllDirectories { get; } + public System.Collections.Generic.IEnumerable AllDrives { get; } + public System.Collections.Generic.IEnumerable AllFiles { get; } + public System.Collections.Generic.IEnumerable AllNodes { get; } + public System.Collections.Generic.IEnumerable AllPaths { get; } + public override System.IO.Abstractions.IDirectory Directory { get; } + public override System.IO.Abstractions.IDirectoryInfoFactory DirectoryInfo { get; } + public override System.IO.Abstractions.IDriveInfoFactory DriveInfo { get; } + public override System.IO.Abstractions.IFile File { get; } + public FileHandles FileHandles { get; } + public override System.IO.Abstractions.IFileInfoFactory FileInfo { get; } + public override System.IO.Abstractions.IFileStreamFactory FileStream { get; } + public System.IO.Abstractions.IFileSystem FileSystem { get; } + public override System.IO.Abstractions.IFileSystemWatcherFactory FileSystemWatcher { get; } + public override System.IO.Abstractions.IFileVersionInfoFactory FileVersionInfo { get; } + public override System.IO.Abstractions.IPath Path { get; } + public System.IO.Abstractions.TestingHelpers.PathVerifier PathVerifier { get; } + public System.IO.Abstractions.TestingHelpers.StringOperations StringOperations { get; } + public void AddDirectory(System.IO.Abstractions.IDirectoryInfo path) { } + public void AddDirectory(string path) { } + public void AddDrive(string name, System.IO.Abstractions.TestingHelpers.MockDriveData mockDrive) { } + public void AddEmptyFile(System.IO.Abstractions.IFileInfo path) { } + public void AddEmptyFile(string path) { } + public void AddFile(System.IO.Abstractions.IFileInfo path, System.IO.Abstractions.TestingHelpers.MockFileData data, bool verifyAccess = true) { } + public void AddFile(string path, System.IO.Abstractions.TestingHelpers.MockFileData mockFile, bool verifyAccess = true) { } + public void AddFileFromEmbeddedResource(string path, System.Reflection.Assembly resourceAssembly, string embeddedResourcePath) { } + public void AddFilesFromEmbeddedNamespace(string path, System.Reflection.Assembly resourceAssembly, string embeddedResourcePath) { } + public System.IO.Abstractions.TestingHelpers.MockFileData AdjustTimes(System.IO.Abstractions.TestingHelpers.MockFileData fileData, System.IO.Abstractions.TestingHelpers.TimeAdjustments timeAdjustments) { } + public bool FileExists(string path) { } + public System.IO.Abstractions.TestingHelpers.MockDriveData GetDrive(string name) { } + public System.IO.Abstractions.TestingHelpers.MockFileData GetFile(System.IO.Abstractions.IFileInfo path) { } + public System.IO.Abstractions.TestingHelpers.MockFileData GetFile(string path) { } + public System.IO.Abstractions.TestingHelpers.MockFileSystem MockTime(System.Func dateTimeProvider) { } + public void MoveDirectory(string sourcePath, string destPath) { } + public void RemoveFile(string path, bool verifyAccess = true) { } + } + public class MockFileSystemOptions + { + public MockFileSystemOptions() { } + public bool CreateDefaultTempDir { get; init; } + public string CurrentDirectory { get; init; } + } + [System.Serializable] + public class MockFileSystemWatcherFactory : System.IO.Abstractions.IFileSystemEntity, System.IO.Abstractions.IFileSystemWatcherFactory + { + public MockFileSystemWatcherFactory(System.IO.Abstractions.TestingHelpers.MockFileSystem mockFileSystem) { } + public System.IO.Abstractions.IFileSystem FileSystem { get; } + public System.IO.Abstractions.IFileSystemWatcher New() { } + public System.IO.Abstractions.IFileSystemWatcher New(string path) { } + public System.IO.Abstractions.IFileSystemWatcher New(string path, string filter) { } + public System.IO.Abstractions.IFileSystemWatcher Wrap(System.IO.FileSystemWatcher fileSystemWatcher) { } + } + [System.Serializable] + public class MockFileVersionInfo : System.IO.Abstractions.FileVersionInfoBase + { + public MockFileVersionInfo( + string fileName, + string fileVersion = null, + string productVersion = null, + string fileDescription = null, + string productName = null, + string companyName = null, + string comments = null, + string internalName = null, + bool isDebug = false, + bool isPatched = false, + bool isPrivateBuild = false, + bool isPreRelease = false, + bool isSpecialBuild = false, + string language = null, + string legalCopyright = null, + string legalTrademarks = null, + string originalFilename = null, + string privateBuild = null, + string specialBuild = null) { } + public override string Comments { get; } + public override string CompanyName { get; } + public override int FileBuildPart { get; } + public override string FileDescription { get; } + public override int FileMajorPart { get; } + public override int FileMinorPart { get; } + public override string FileName { get; } + public override int FilePrivatePart { get; } + public override string FileVersion { get; } + public override string InternalName { get; } + public override bool IsDebug { get; } + public override bool IsPatched { get; } + public override bool IsPreRelease { get; } + public override bool IsPrivateBuild { get; } + public override bool IsSpecialBuild { get; } + public override string Language { get; } + public override string LegalCopyright { get; } + public override string LegalTrademarks { get; } + public override string OriginalFilename { get; } + public override string PrivateBuild { get; } + public override int ProductBuildPart { get; } + public override int ProductMajorPart { get; } + public override int ProductMinorPart { get; } + public override string ProductName { get; } + public override int ProductPrivatePart { get; } + public override string ProductVersion { get; } + public override string SpecialBuild { get; } + public override string ToString() { } + } + [System.Serializable] + public class MockFileVersionInfoFactory : System.IO.Abstractions.IFileSystemEntity, System.IO.Abstractions.IFileVersionInfoFactory + { + public MockFileVersionInfoFactory(System.IO.Abstractions.TestingHelpers.IMockFileDataAccessor mockFileSystem) { } + public System.IO.Abstractions.IFileSystem FileSystem { get; } + public System.IO.Abstractions.IFileVersionInfo GetVersionInfo(string fileName) { } + } + [System.Serializable] + public class MockPath : System.IO.Abstractions.PathWrapper + { + public MockPath(System.IO.Abstractions.TestingHelpers.IMockFileDataAccessor mockFileDataAccessor) { } + public MockPath(System.IO.Abstractions.TestingHelpers.IMockFileDataAccessor mockFileDataAccessor, string defaultTempDirectory) { } + public override string GetFullPath(string path) { } + public override string GetTempFileName() { } + public override string GetTempPath() { } + } + public static class MockUnixSupport + { + public static bool IsUnixPlatform() { } + public static bool IsWindowsPlatform() { } + public static string Path(string path) { } + } + [System.Serializable] + public class PathVerifier + { + public PathVerifier(System.IO.Abstractions.TestingHelpers.IMockFileDataAccessor mockFileDataAccessor) { } + public void CheckInvalidPathChars(string path, bool checkAdditional = false) { } + public bool HasIllegalCharacters(string path, bool checkAdditional) { } + public void IsLegalAbsoluteOrRelative(string path, string paramName) { } + public string NormalizeDriveName(string name) { } + public bool TryNormalizeDriveName(string name, out string result) { } + } + [System.Serializable] + public class StringOperations + { + public StringOperations(bool caseSensitive) { } + public System.StringComparer Comparer { get; } + public bool Contains(string s, string substring) { } + public bool EndsWith(string s, string suffix) { } + public bool Equals(char x, char y) { } + public bool Equals(string x, string y) { } + public int IndexOf(string s, string substring) { } + public int IndexOf(string s, string substring, int startIndex) { } + public string Replace(string s, string oldValue, string newValue) { } + public bool StartsWith(string s, string prefix) { } + public char ToLower(char c) { } + public string ToLower(string s) { } + public char ToUpper(char c) { } + public string ToUpper(string s) { } + } + [System.Flags] + public enum TimeAdjustments + { + None = 0, + CreationTime = 1, + LastAccessTime = 2, + LastWriteTime = 4, + All = -1, + } +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.Api.Tests/Expected/TestableIO.System.IO.Abstractions.TestingHelpers_net6.0.txt b/tests/TestableIO.System.IO.Abstractions.Api.Tests/Expected/TestableIO.System.IO.Abstractions.TestingHelpers_net6.0.txt new file mode 100644 index 000000000..7fa0eecba --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.Api.Tests/Expected/TestableIO.System.IO.Abstractions.TestingHelpers_net6.0.txt @@ -0,0 +1,567 @@ +[assembly: System.Reflection.AssemblyMetadata("RepositoryUrl", "https://github.com/TestableIO/System.IO.Abstractions.git")] +[assembly: System.Runtime.Versioning.TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName=".NET 6.0")] +public class FileHandles +{ + public FileHandles() { } + public void AddHandle(string path, System.Guid guid, System.IO.FileAccess access, System.IO.FileShare share) { } + public void RemoveHandle(string path, System.Guid guid) { } +} +namespace System.IO.Abstractions.TestingHelpers +{ + public interface IMockFileDataAccessor : System.IO.Abstractions.IFileSystem + { + System.Collections.Generic.IEnumerable AllDirectories { get; } + System.Collections.Generic.IEnumerable AllDrives { get; } + System.Collections.Generic.IEnumerable AllFiles { get; } + System.Collections.Generic.IEnumerable AllPaths { get; } + FileHandles FileHandles { get; } + System.IO.Abstractions.IFileSystem FileSystem { get; } + System.IO.Abstractions.TestingHelpers.PathVerifier PathVerifier { get; } + System.IO.Abstractions.TestingHelpers.StringOperations StringOperations { get; } + void AddDirectory(string path); + void AddDrive(string name, System.IO.Abstractions.TestingHelpers.MockDriveData mockDrive); + void AddFile(string path, System.IO.Abstractions.TestingHelpers.MockFileData mockFile, bool verifyAccess = true); + void AddFileFromEmbeddedResource(string path, System.Reflection.Assembly resourceAssembly, string embeddedResourcePath); + void AddFilesFromEmbeddedNamespace(string path, System.Reflection.Assembly resourceAssembly, string embeddedResourcePath); + System.IO.Abstractions.TestingHelpers.MockFileData AdjustTimes(System.IO.Abstractions.TestingHelpers.MockFileData fileData, System.IO.Abstractions.TestingHelpers.TimeAdjustments timeAdjustments); + bool FileExists(string path); + System.IO.Abstractions.TestingHelpers.MockDriveData GetDrive(string name); + System.IO.Abstractions.TestingHelpers.MockFileData GetFile(string path); + void MoveDirectory(string sourcePath, string destPath); + void RemoveFile(string path, bool verifyAccess = true); + } + [System.Serializable] + public class MockDirectory : System.IO.Abstractions.DirectoryBase + { + public MockDirectory(System.IO.Abstractions.TestingHelpers.IMockFileDataAccessor mockFileDataAccessor, string currentDirectory) { } + public MockDirectory(System.IO.Abstractions.TestingHelpers.IMockFileDataAccessor mockFileDataAccessor, System.IO.Abstractions.FileBase fileBase, string currentDirectory) { } + public override System.IO.Abstractions.IDirectoryInfo CreateDirectory(string path) { } + public override System.IO.Abstractions.IFileSystemInfo CreateSymbolicLink(string path, string pathToTarget) { } + public override void Delete(string path) { } + public override void Delete(string path, bool recursive) { } + public override System.Collections.Generic.IEnumerable EnumerateDirectories(string path) { } + public override System.Collections.Generic.IEnumerable EnumerateDirectories(string path, string searchPattern) { } + public override System.Collections.Generic.IEnumerable EnumerateDirectories(string path, string searchPattern, System.IO.EnumerationOptions enumerationOptions) { } + public override System.Collections.Generic.IEnumerable EnumerateDirectories(string path, string searchPattern, System.IO.SearchOption searchOption) { } + public override System.Collections.Generic.IEnumerable EnumerateFileSystemEntries(string path) { } + public override System.Collections.Generic.IEnumerable EnumerateFileSystemEntries(string path, string searchPattern) { } + public override System.Collections.Generic.IEnumerable EnumerateFileSystemEntries(string path, string searchPattern, System.IO.EnumerationOptions enumerationOptions) { } + public override System.Collections.Generic.IEnumerable EnumerateFileSystemEntries(string path, string searchPattern, System.IO.SearchOption searchOption) { } + public override System.Collections.Generic.IEnumerable EnumerateFiles(string path) { } + public override System.Collections.Generic.IEnumerable EnumerateFiles(string path, string searchPattern) { } + public override System.Collections.Generic.IEnumerable EnumerateFiles(string path, string searchPattern, System.IO.EnumerationOptions enumerationOptions) { } + public override System.Collections.Generic.IEnumerable EnumerateFiles(string path, string searchPattern, System.IO.SearchOption searchOption) { } + public override bool Exists(string path) { } + public override System.DateTime GetCreationTime(string path) { } + public override System.DateTime GetCreationTimeUtc(string path) { } + public override string GetCurrentDirectory() { } + public override string[] GetDirectories(string path) { } + public override string[] GetDirectories(string path, string searchPattern) { } + public override string[] GetDirectories(string path, string searchPattern, System.IO.EnumerationOptions enumerationOptions) { } + public override string[] GetDirectories(string path, string searchPattern, System.IO.SearchOption searchOption) { } + public override string GetDirectoryRoot(string path) { } + public override string[] GetFileSystemEntries(string path) { } + public override string[] GetFileSystemEntries(string path, string searchPattern) { } + public override string[] GetFileSystemEntries(string path, string searchPattern, System.IO.EnumerationOptions enumerationOptions) { } + public override string[] GetFileSystemEntries(string path, string searchPattern, System.IO.SearchOption searchOption) { } + public override string[] GetFiles(string path) { } + public override string[] GetFiles(string path, string searchPattern) { } + public override string[] GetFiles(string path, string searchPattern, System.IO.EnumerationOptions enumerationOptions) { } + public override string[] GetFiles(string path, string searchPattern, System.IO.SearchOption searchOption) { } + public override System.DateTime GetLastAccessTime(string path) { } + public override System.DateTime GetLastAccessTimeUtc(string path) { } + public override System.DateTime GetLastWriteTime(string path) { } + public override System.DateTime GetLastWriteTimeUtc(string path) { } + public override string[] GetLogicalDrives() { } + public override System.IO.Abstractions.IDirectoryInfo GetParent(string path) { } + public override void Move(string sourceDirName, string destDirName) { } + public override System.IO.Abstractions.IFileSystemInfo ResolveLinkTarget(string linkPath, bool returnFinalTarget) { } + public override void SetCreationTime(string path, System.DateTime creationTime) { } + public override void SetCreationTimeUtc(string path, System.DateTime creationTimeUtc) { } + public override void SetCurrentDirectory(string path) { } + public override void SetLastAccessTime(string path, System.DateTime lastAccessTime) { } + public override void SetLastAccessTimeUtc(string path, System.DateTime lastAccessTimeUtc) { } + public override void SetLastWriteTime(string path, System.DateTime lastWriteTime) { } + public override void SetLastWriteTimeUtc(string path, System.DateTime lastWriteTimeUtc) { } + } + [System.Serializable] + public class MockDirectoryData : System.IO.Abstractions.TestingHelpers.MockFileData + { + public MockDirectoryData() { } + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public new System.Security.AccessControl.DirectorySecurity AccessControl { get; set; } + } + [System.Serializable] + public class MockDirectoryInfo : System.IO.Abstractions.DirectoryInfoBase, System.IO.Abstractions.IFileSystemAclSupport + { + public MockDirectoryInfo(System.IO.Abstractions.TestingHelpers.IMockFileDataAccessor mockFileDataAccessor, string directoryPath) { } + public override System.IO.FileAttributes Attributes { get; set; } + public override System.DateTime CreationTime { get; set; } + public override System.DateTime CreationTimeUtc { get; set; } + public override bool Exists { get; } + public override string Extension { get; } + public override string FullName { get; } + public override System.DateTime LastAccessTime { get; set; } + public override System.DateTime LastAccessTimeUtc { get; set; } + public override System.DateTime LastWriteTime { get; set; } + public override System.DateTime LastWriteTimeUtc { get; set; } + public override string LinkTarget { get; } + public override string Name { get; } + public override System.IO.Abstractions.IDirectoryInfo Parent { get; } + public override System.IO.Abstractions.IDirectoryInfo Root { get; } + public override void Create() { } + public override void CreateAsSymbolicLink(string pathToTarget) { } + public override System.IO.Abstractions.IDirectoryInfo CreateSubdirectory(string path) { } + public override void Delete() { } + public override void Delete(bool recursive) { } + public override System.Collections.Generic.IEnumerable EnumerateDirectories() { } + public override System.Collections.Generic.IEnumerable EnumerateDirectories(string searchPattern) { } + public override System.Collections.Generic.IEnumerable EnumerateDirectories(string searchPattern, System.IO.EnumerationOptions enumerationOptions) { } + public override System.Collections.Generic.IEnumerable EnumerateDirectories(string searchPattern, System.IO.SearchOption searchOption) { } + public override System.Collections.Generic.IEnumerable EnumerateFileSystemInfos() { } + public override System.Collections.Generic.IEnumerable EnumerateFileSystemInfos(string searchPattern) { } + public override System.Collections.Generic.IEnumerable EnumerateFileSystemInfos(string searchPattern, System.IO.EnumerationOptions enumerationOptions) { } + public override System.Collections.Generic.IEnumerable EnumerateFileSystemInfos(string searchPattern, System.IO.SearchOption searchOption) { } + public override System.Collections.Generic.IEnumerable EnumerateFiles() { } + public override System.Collections.Generic.IEnumerable EnumerateFiles(string searchPattern) { } + public override System.Collections.Generic.IEnumerable EnumerateFiles(string searchPattern, System.IO.EnumerationOptions enumerationOptions) { } + public override System.Collections.Generic.IEnumerable EnumerateFiles(string searchPattern, System.IO.SearchOption searchOption) { } + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public object GetAccessControl() { } + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public object GetAccessControl(System.IO.Abstractions.IFileSystemAclSupport.AccessControlSections includeSections) { } + public override System.IO.Abstractions.IDirectoryInfo[] GetDirectories() { } + public override System.IO.Abstractions.IDirectoryInfo[] GetDirectories(string searchPattern) { } + public override System.IO.Abstractions.IDirectoryInfo[] GetDirectories(string searchPattern, System.IO.EnumerationOptions enumerationOptions) { } + public override System.IO.Abstractions.IDirectoryInfo[] GetDirectories(string searchPattern, System.IO.SearchOption searchOption) { } + public override System.IO.Abstractions.IFileSystemInfo[] GetFileSystemInfos() { } + public override System.IO.Abstractions.IFileSystemInfo[] GetFileSystemInfos(string searchPattern) { } + public override System.IO.Abstractions.IFileSystemInfo[] GetFileSystemInfos(string searchPattern, System.IO.EnumerationOptions enumerationOptions) { } + public override System.IO.Abstractions.IFileSystemInfo[] GetFileSystemInfos(string searchPattern, System.IO.SearchOption searchOption) { } + public override System.IO.Abstractions.IFileInfo[] GetFiles() { } + public override System.IO.Abstractions.IFileInfo[] GetFiles(string searchPattern) { } + public override System.IO.Abstractions.IFileInfo[] GetFiles(string searchPattern, System.IO.EnumerationOptions enumerationOptions) { } + public override System.IO.Abstractions.IFileInfo[] GetFiles(string searchPattern, System.IO.SearchOption searchOption) { } + public override void MoveTo(string destDirName) { } + public override void Refresh() { } + public override System.IO.Abstractions.IFileSystemInfo ResolveLinkTarget(bool returnFinalTarget) { } + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public void SetAccessControl(object value) { } + public override string ToString() { } + } + [System.Serializable] + public class MockDirectoryInfoFactory : System.IO.Abstractions.IDirectoryInfoFactory, System.IO.Abstractions.IFileSystemEntity + { + public MockDirectoryInfoFactory(System.IO.Abstractions.TestingHelpers.IMockFileDataAccessor mockFileSystem) { } + public System.IO.Abstractions.IFileSystem FileSystem { get; } + public System.IO.Abstractions.IDirectoryInfo New(string path) { } + public System.IO.Abstractions.IDirectoryInfo Wrap(System.IO.DirectoryInfo directoryInfo) { } + } + [System.Serializable] + public class MockDriveData + { + public MockDriveData() { } + public MockDriveData(System.IO.Abstractions.TestingHelpers.MockDriveData template) { } + public long AvailableFreeSpace { get; set; } + public string DriveFormat { get; set; } + public System.IO.DriveType DriveType { get; set; } + public bool IsReady { get; set; } + public long TotalFreeSpace { get; set; } + public long TotalSize { get; set; } + public string VolumeLabel { get; set; } + } + [System.Serializable] + public class MockDriveInfo : System.IO.Abstractions.DriveInfoBase + { + public MockDriveInfo(System.IO.Abstractions.TestingHelpers.IMockFileDataAccessor mockFileDataAccessor, string name) { } + public override long AvailableFreeSpace { get; } + public override string DriveFormat { get; } + public override System.IO.DriveType DriveType { get; } + public override bool IsReady { get; } + public override string Name { get; } + public override System.IO.Abstractions.IDirectoryInfo RootDirectory { get; } + public override long TotalFreeSpace { get; } + public override long TotalSize { get; } + public override string VolumeLabel { get; set; } + public override string ToString() { } + } + [System.Serializable] + public class MockDriveInfoFactory : System.IO.Abstractions.IDriveInfoFactory, System.IO.Abstractions.IFileSystemEntity + { + public MockDriveInfoFactory(System.IO.Abstractions.TestingHelpers.IMockFileDataAccessor mockFileSystem) { } + public System.IO.Abstractions.IFileSystem FileSystem { get; } + public System.IO.Abstractions.IDriveInfo[] GetDrives() { } + public System.IO.Abstractions.IDriveInfo New(string driveName) { } + public System.IO.Abstractions.IDriveInfo Wrap(System.IO.DriveInfo driveInfo) { } + } + [System.Serializable] + public class MockFile : System.IO.Abstractions.FileBase + { + public MockFile(System.IO.Abstractions.TestingHelpers.IMockFileDataAccessor mockFileDataAccessor) { } + public override void AppendAllLines(string path, System.Collections.Generic.IEnumerable contents) { } + public override void AppendAllLines(string path, System.Collections.Generic.IEnumerable contents, System.Text.Encoding encoding) { } + public override System.Threading.Tasks.Task AppendAllLinesAsync(string path, System.Collections.Generic.IEnumerable contents, System.Threading.CancellationToken cancellationToken = default) { } + public override System.Threading.Tasks.Task AppendAllLinesAsync(string path, System.Collections.Generic.IEnumerable contents, System.Text.Encoding encoding, System.Threading.CancellationToken cancellationToken = default) { } + public override void AppendAllText(string path, string contents) { } + public override void AppendAllText(string path, string contents, System.Text.Encoding encoding) { } + public override System.Threading.Tasks.Task AppendAllTextAsync(string path, string contents, System.Threading.CancellationToken cancellationToken = default) { } + public override System.Threading.Tasks.Task AppendAllTextAsync(string path, string contents, System.Text.Encoding encoding, System.Threading.CancellationToken cancellationToken = default) { } + public override System.IO.StreamWriter AppendText(string path) { } + public override void Copy(string sourceFileName, string destFileName) { } + public override void Copy(string sourceFileName, string destFileName, bool overwrite) { } + public override System.IO.Abstractions.FileSystemStream Create(string path) { } + public override System.IO.Abstractions.FileSystemStream Create(string path, int bufferSize) { } + public override System.IO.Abstractions.FileSystemStream Create(string path, int bufferSize, System.IO.FileOptions options) { } + public override System.IO.Abstractions.IFileSystemInfo CreateSymbolicLink(string path, string pathToTarget) { } + public override System.IO.StreamWriter CreateText(string path) { } + public override void Decrypt(string path) { } + public override void Delete(string path) { } + public override void Encrypt(string path) { } + public override bool Exists(string path) { } + public override System.IO.FileAttributes GetAttributes(string path) { } + public override System.DateTime GetCreationTime(string path) { } + public override System.DateTime GetCreationTimeUtc(string path) { } + public override System.DateTime GetLastAccessTime(string path) { } + public override System.DateTime GetLastAccessTimeUtc(string path) { } + public override System.DateTime GetLastWriteTime(string path) { } + public override System.DateTime GetLastWriteTimeUtc(string path) { } + public override void Move(string sourceFileName, string destFileName) { } + public override void Move(string sourceFileName, string destFileName, bool overwrite) { } + public override System.IO.Abstractions.FileSystemStream Open(string path, System.IO.FileMode mode) { } + public override System.IO.Abstractions.FileSystemStream Open(string path, System.IO.FileStreamOptions options) { } + public override System.IO.Abstractions.FileSystemStream Open(string path, System.IO.FileMode mode, System.IO.FileAccess access) { } + public override System.IO.Abstractions.FileSystemStream Open(string path, System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share) { } + public override System.IO.Abstractions.FileSystemStream OpenRead(string path) { } + public override System.IO.StreamReader OpenText(string path) { } + public override System.IO.Abstractions.FileSystemStream OpenWrite(string path) { } + public override byte[] ReadAllBytes(string path) { } + public override System.Threading.Tasks.Task ReadAllBytesAsync(string path, System.Threading.CancellationToken cancellationToken = default) { } + public override string[] ReadAllLines(string path) { } + public override string[] ReadAllLines(string path, System.Text.Encoding encoding) { } + public override System.Threading.Tasks.Task ReadAllLinesAsync(string path, System.Threading.CancellationToken cancellationToken = default) { } + public override System.Threading.Tasks.Task ReadAllLinesAsync(string path, System.Text.Encoding encoding, System.Threading.CancellationToken cancellationToken = default) { } + public override string ReadAllText(string path) { } + public override string ReadAllText(string path, System.Text.Encoding encoding) { } + public override System.Threading.Tasks.Task ReadAllTextAsync(string path, System.Threading.CancellationToken cancellationToken = default) { } + public override System.Threading.Tasks.Task ReadAllTextAsync(string path, System.Text.Encoding encoding, System.Threading.CancellationToken cancellationToken = default) { } + public override System.Collections.Generic.IEnumerable ReadLines(string path) { } + public override System.Collections.Generic.IEnumerable ReadLines(string path, System.Text.Encoding encoding) { } + public override void Replace(string sourceFileName, string destinationFileName, string destinationBackupFileName) { } + public override void Replace(string sourceFileName, string destinationFileName, string destinationBackupFileName, bool ignoreMetadataErrors) { } + public override System.IO.Abstractions.IFileSystemInfo ResolveLinkTarget(string linkPath, bool returnFinalTarget) { } + public override void SetAttributes(string path, System.IO.FileAttributes fileAttributes) { } + public override void SetCreationTime(string path, System.DateTime creationTime) { } + public override void SetCreationTimeUtc(string path, System.DateTime creationTimeUtc) { } + public override void SetLastAccessTime(string path, System.DateTime lastAccessTime) { } + public override void SetLastAccessTimeUtc(string path, System.DateTime lastAccessTimeUtc) { } + public override void SetLastWriteTime(string path, System.DateTime lastWriteTime) { } + public override void SetLastWriteTimeUtc(string path, System.DateTime lastWriteTimeUtc) { } + public override void WriteAllBytes(string path, byte[] bytes) { } + public override System.Threading.Tasks.Task WriteAllBytesAsync(string path, byte[] bytes, System.Threading.CancellationToken cancellationToken = default) { } + public override void WriteAllLines(string path, System.Collections.Generic.IEnumerable contents) { } + public override void WriteAllLines(string path, string[] contents) { } + public override void WriteAllLines(string path, System.Collections.Generic.IEnumerable contents, System.Text.Encoding encoding) { } + public override void WriteAllLines(string path, string[] contents, System.Text.Encoding encoding) { } + public override System.Threading.Tasks.Task WriteAllLinesAsync(string path, System.Collections.Generic.IEnumerable contents, System.Threading.CancellationToken cancellationToken = default) { } + public override System.Threading.Tasks.Task WriteAllLinesAsync(string path, System.Collections.Generic.IEnumerable contents, System.Text.Encoding encoding, System.Threading.CancellationToken cancellationToken = default) { } + public override void WriteAllText(string path, string contents) { } + public override void WriteAllText(string path, string contents, System.Text.Encoding encoding) { } + public override System.Threading.Tasks.Task WriteAllTextAsync(string path, string contents, System.Threading.CancellationToken cancellationToken = default) { } + public override System.Threading.Tasks.Task WriteAllTextAsync(string path, string contents, System.Text.Encoding encoding, System.Threading.CancellationToken cancellationToken = default) { } + } + [System.Serializable] + public class MockFileData + { + public static readonly System.DateTimeOffset DefaultDateTimeOffset; + public static readonly System.Text.Encoding DefaultEncoding; + public MockFileData(System.IO.Abstractions.TestingHelpers.MockFileData template) { } + public MockFileData(byte[] contents) { } + public MockFileData(string textContents) { } + public MockFileData(string textContents, System.Text.Encoding encoding) { } + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public System.Security.AccessControl.FileSecurity AccessControl { get; set; } + public System.IO.FileShare AllowedFileShare { get; set; } + public System.IO.FileAttributes Attributes { get; set; } + public byte[] Contents { get; set; } + public System.DateTimeOffset CreationTime { get; set; } + public System.IO.Abstractions.IFileVersionInfo FileVersionInfo { get; set; } + public bool IsDirectory { get; } + public System.DateTimeOffset LastAccessTime { get; set; } + public System.DateTimeOffset LastWriteTime { get; set; } + public string LinkTarget { get; set; } + public string TextContents { get; set; } + public static System.IO.Abstractions.TestingHelpers.MockFileData op_Implicit(string s) { } + } + [System.Serializable] + public class MockFileInfo : System.IO.Abstractions.FileInfoBase, System.IO.Abstractions.IFileSystemAclSupport + { + public MockFileInfo(System.IO.Abstractions.TestingHelpers.IMockFileDataAccessor mockFileSystem, string path) { } + public override System.IO.FileAttributes Attributes { get; set; } + public override System.DateTime CreationTime { get; set; } + public override System.DateTime CreationTimeUtc { get; set; } + public override System.IO.Abstractions.IDirectoryInfo Directory { get; } + public override string DirectoryName { get; } + public override bool Exists { get; } + public override string Extension { get; } + public override string FullName { get; } + public override bool IsReadOnly { get; set; } + public override System.DateTime LastAccessTime { get; set; } + public override System.DateTime LastAccessTimeUtc { get; set; } + public override System.DateTime LastWriteTime { get; set; } + public override System.DateTime LastWriteTimeUtc { get; set; } + public override long Length { get; } + public override string LinkTarget { get; } + public override string Name { get; } + public override System.IO.StreamWriter AppendText() { } + public override System.IO.Abstractions.IFileInfo CopyTo(string destFileName) { } + public override System.IO.Abstractions.IFileInfo CopyTo(string destFileName, bool overwrite) { } + public override System.IO.Abstractions.FileSystemStream Create() { } + public override void CreateAsSymbolicLink(string pathToTarget) { } + public override System.IO.StreamWriter CreateText() { } + public override void Decrypt() { } + public override void Delete() { } + public override void Encrypt() { } + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public object GetAccessControl() { } + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public object GetAccessControl(System.IO.Abstractions.IFileSystemAclSupport.AccessControlSections includeSections) { } + public override void MoveTo(string destFileName) { } + public override void MoveTo(string destFileName, bool overwrite) { } + public override System.IO.Abstractions.FileSystemStream Open(System.IO.FileMode mode) { } + public override System.IO.Abstractions.FileSystemStream Open(System.IO.FileStreamOptions options) { } + public override System.IO.Abstractions.FileSystemStream Open(System.IO.FileMode mode, System.IO.FileAccess access) { } + public override System.IO.Abstractions.FileSystemStream Open(System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share) { } + public override System.IO.Abstractions.FileSystemStream OpenRead() { } + public override System.IO.StreamReader OpenText() { } + public override System.IO.Abstractions.FileSystemStream OpenWrite() { } + public override void Refresh() { } + public override System.IO.Abstractions.IFileInfo Replace(string destinationFileName, string destinationBackupFileName) { } + public override System.IO.Abstractions.IFileInfo Replace(string destinationFileName, string destinationBackupFileName, bool ignoreMetadataErrors) { } + public override System.IO.Abstractions.IFileSystemInfo ResolveLinkTarget(bool returnFinalTarget) { } + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public void SetAccessControl(object value) { } + public override string ToString() { } + } + [System.Serializable] + public class MockFileInfoFactory : System.IO.Abstractions.IFileInfoFactory, System.IO.Abstractions.IFileSystemEntity + { + public MockFileInfoFactory(System.IO.Abstractions.TestingHelpers.IMockFileDataAccessor mockFileSystem) { } + public System.IO.Abstractions.IFileSystem FileSystem { get; } + public System.IO.Abstractions.IFileInfo New(string fileName) { } + public System.IO.Abstractions.IFileInfo Wrap(System.IO.FileInfo fileInfo) { } + } + [System.Serializable] + public class MockFileStream : System.IO.Abstractions.FileSystemStream, System.IO.Abstractions.IFileSystemAclSupport + { + public MockFileStream(System.IO.Abstractions.TestingHelpers.IMockFileDataAccessor mockFileDataAccessor, string path, System.IO.FileMode mode, System.IO.FileAccess access = 3, System.IO.FileShare share = 1, System.IO.FileOptions options = 0) { } + public override bool CanRead { get; } + public override bool CanWrite { get; } + public static System.IO.Abstractions.FileSystemStream Null { get; } + protected override void Dispose(bool disposing) { } + public override void EndWrite(System.IAsyncResult asyncResult) { } + public override void Flush() { } + public override void Flush(bool flushToDisk) { } + public override System.Threading.Tasks.Task FlushAsync(System.Threading.CancellationToken cancellationToken) { } + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public object GetAccessControl() { } + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public object GetAccessControl(System.IO.Abstractions.IFileSystemAclSupport.AccessControlSections includeSections) { } + public override int Read(byte[] buffer, int offset, int count) { } + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public void SetAccessControl(object value) { } + public override void SetLength(long value) { } + public override void Write(System.ReadOnlySpan buffer) { } + public override void Write(byte[] buffer, int offset, int count) { } + public override System.Threading.Tasks.ValueTask WriteAsync(System.ReadOnlyMemory buffer, System.Threading.CancellationToken cancellationToken = default) { } + public override System.Threading.Tasks.Task WriteAsync(byte[] buffer, int offset, int count, System.Threading.CancellationToken cancellationToken) { } + public override void WriteByte(byte value) { } + } + [System.Serializable] + public class MockFileStreamFactory : System.IO.Abstractions.IFileStreamFactory, System.IO.Abstractions.IFileSystemEntity + { + public MockFileStreamFactory(System.IO.Abstractions.TestingHelpers.IMockFileDataAccessor mockFileSystem) { } + public System.IO.Abstractions.IFileSystem FileSystem { get; } + public System.IO.Abstractions.FileSystemStream New(Microsoft.Win32.SafeHandles.SafeFileHandle handle, System.IO.FileAccess access) { } + public System.IO.Abstractions.FileSystemStream New(string path, System.IO.FileMode mode) { } + public System.IO.Abstractions.FileSystemStream New(string path, System.IO.FileStreamOptions options) { } + public System.IO.Abstractions.FileSystemStream New(Microsoft.Win32.SafeHandles.SafeFileHandle handle, System.IO.FileAccess access, int bufferSize) { } + public System.IO.Abstractions.FileSystemStream New(string path, System.IO.FileMode mode, System.IO.FileAccess access) { } + public System.IO.Abstractions.FileSystemStream New(Microsoft.Win32.SafeHandles.SafeFileHandle handle, System.IO.FileAccess access, int bufferSize, bool isAsync) { } + public System.IO.Abstractions.FileSystemStream New(string path, System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share) { } + public System.IO.Abstractions.FileSystemStream New(string path, System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share, int bufferSize) { } + public System.IO.Abstractions.FileSystemStream New(string path, System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share, int bufferSize, System.IO.FileOptions options) { } + public System.IO.Abstractions.FileSystemStream New(string path, System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share, int bufferSize, bool useAsync) { } + public System.IO.Abstractions.FileSystemStream Wrap(System.IO.FileStream fileStream) { } + } + [System.Serializable] + public class MockFileSystem : System.IO.Abstractions.FileSystemBase, System.IO.Abstractions.IFileSystem, System.IO.Abstractions.TestingHelpers.IMockFileDataAccessor + { + public MockFileSystem() { } + public MockFileSystem(System.IO.Abstractions.TestingHelpers.MockFileSystemOptions options) { } + public MockFileSystem(System.Collections.Generic.IDictionary files, System.IO.Abstractions.TestingHelpers.MockFileSystemOptions options) { } + public MockFileSystem(System.Collections.Generic.IDictionary files, string currentDirectory = "") { } + public System.Collections.Generic.IEnumerable AllDirectories { get; } + public System.Collections.Generic.IEnumerable AllDrives { get; } + public System.Collections.Generic.IEnumerable AllFiles { get; } + public System.Collections.Generic.IEnumerable AllNodes { get; } + public System.Collections.Generic.IEnumerable AllPaths { get; } + public override System.IO.Abstractions.IDirectory Directory { get; } + public override System.IO.Abstractions.IDirectoryInfoFactory DirectoryInfo { get; } + public override System.IO.Abstractions.IDriveInfoFactory DriveInfo { get; } + public override System.IO.Abstractions.IFile File { get; } + public FileHandles FileHandles { get; } + public override System.IO.Abstractions.IFileInfoFactory FileInfo { get; } + public override System.IO.Abstractions.IFileStreamFactory FileStream { get; } + public System.IO.Abstractions.IFileSystem FileSystem { get; } + public override System.IO.Abstractions.IFileSystemWatcherFactory FileSystemWatcher { get; } + public override System.IO.Abstractions.IFileVersionInfoFactory FileVersionInfo { get; } + public override System.IO.Abstractions.IPath Path { get; } + public System.IO.Abstractions.TestingHelpers.PathVerifier PathVerifier { get; } + public System.IO.Abstractions.TestingHelpers.StringOperations StringOperations { get; } + public void AddDirectory(System.IO.Abstractions.IDirectoryInfo path) { } + public void AddDirectory(string path) { } + public void AddDrive(string name, System.IO.Abstractions.TestingHelpers.MockDriveData mockDrive) { } + public void AddEmptyFile(System.IO.Abstractions.IFileInfo path) { } + public void AddEmptyFile(string path) { } + public void AddFile(System.IO.Abstractions.IFileInfo path, System.IO.Abstractions.TestingHelpers.MockFileData data, bool verifyAccess = true) { } + public void AddFile(string path, System.IO.Abstractions.TestingHelpers.MockFileData mockFile, bool verifyAccess = true) { } + public void AddFileFromEmbeddedResource(string path, System.Reflection.Assembly resourceAssembly, string embeddedResourcePath) { } + public void AddFilesFromEmbeddedNamespace(string path, System.Reflection.Assembly resourceAssembly, string embeddedResourcePath) { } + public System.IO.Abstractions.TestingHelpers.MockFileData AdjustTimes(System.IO.Abstractions.TestingHelpers.MockFileData fileData, System.IO.Abstractions.TestingHelpers.TimeAdjustments timeAdjustments) { } + public bool FileExists(string path) { } + public System.IO.Abstractions.TestingHelpers.MockDriveData GetDrive(string name) { } + public System.IO.Abstractions.TestingHelpers.MockFileData GetFile(System.IO.Abstractions.IFileInfo path) { } + public System.IO.Abstractions.TestingHelpers.MockFileData GetFile(string path) { } + public System.IO.Abstractions.TestingHelpers.MockFileSystem MockTime(System.Func dateTimeProvider) { } + public void MoveDirectory(string sourcePath, string destPath) { } + public void RemoveFile(string path, bool verifyAccess = true) { } + } + public class MockFileSystemOptions + { + public MockFileSystemOptions() { } + public bool CreateDefaultTempDir { get; init; } + public string CurrentDirectory { get; init; } + } + [System.Serializable] + public class MockFileSystemWatcherFactory : System.IO.Abstractions.IFileSystemEntity, System.IO.Abstractions.IFileSystemWatcherFactory + { + public MockFileSystemWatcherFactory(System.IO.Abstractions.TestingHelpers.MockFileSystem mockFileSystem) { } + public System.IO.Abstractions.IFileSystem FileSystem { get; } + public System.IO.Abstractions.IFileSystemWatcher New() { } + public System.IO.Abstractions.IFileSystemWatcher New(string path) { } + public System.IO.Abstractions.IFileSystemWatcher New(string path, string filter) { } + public System.IO.Abstractions.IFileSystemWatcher Wrap(System.IO.FileSystemWatcher fileSystemWatcher) { } + } + [System.Serializable] + public class MockFileVersionInfo : System.IO.Abstractions.FileVersionInfoBase + { + public MockFileVersionInfo( + string fileName, + string fileVersion = null, + string productVersion = null, + string fileDescription = null, + string productName = null, + string companyName = null, + string comments = null, + string internalName = null, + bool isDebug = false, + bool isPatched = false, + bool isPrivateBuild = false, + bool isPreRelease = false, + bool isSpecialBuild = false, + string language = null, + string legalCopyright = null, + string legalTrademarks = null, + string originalFilename = null, + string privateBuild = null, + string specialBuild = null) { } + public override string Comments { get; } + public override string CompanyName { get; } + public override int FileBuildPart { get; } + public override string FileDescription { get; } + public override int FileMajorPart { get; } + public override int FileMinorPart { get; } + public override string FileName { get; } + public override int FilePrivatePart { get; } + public override string FileVersion { get; } + public override string InternalName { get; } + public override bool IsDebug { get; } + public override bool IsPatched { get; } + public override bool IsPreRelease { get; } + public override bool IsPrivateBuild { get; } + public override bool IsSpecialBuild { get; } + public override string Language { get; } + public override string LegalCopyright { get; } + public override string LegalTrademarks { get; } + public override string OriginalFilename { get; } + public override string PrivateBuild { get; } + public override int ProductBuildPart { get; } + public override int ProductMajorPart { get; } + public override int ProductMinorPart { get; } + public override string ProductName { get; } + public override int ProductPrivatePart { get; } + public override string ProductVersion { get; } + public override string SpecialBuild { get; } + public override string ToString() { } + } + [System.Serializable] + public class MockFileVersionInfoFactory : System.IO.Abstractions.IFileSystemEntity, System.IO.Abstractions.IFileVersionInfoFactory + { + public MockFileVersionInfoFactory(System.IO.Abstractions.TestingHelpers.IMockFileDataAccessor mockFileSystem) { } + public System.IO.Abstractions.IFileSystem FileSystem { get; } + public System.IO.Abstractions.IFileVersionInfo GetVersionInfo(string fileName) { } + } + [System.Serializable] + public class MockPath : System.IO.Abstractions.PathWrapper + { + public MockPath(System.IO.Abstractions.TestingHelpers.IMockFileDataAccessor mockFileDataAccessor) { } + public MockPath(System.IO.Abstractions.TestingHelpers.IMockFileDataAccessor mockFileDataAccessor, string defaultTempDirectory) { } + public override string GetFullPath(string path) { } + public override string GetRelativePath(string relativeTo, string path) { } + public override string GetTempFileName() { } + public override string GetTempPath() { } + } + public static class MockUnixSupport + { + public static bool IsUnixPlatform() { } + public static bool IsWindowsPlatform() { } + public static string Path(string path) { } + } + [System.Serializable] + public class PathVerifier + { + public PathVerifier(System.IO.Abstractions.TestingHelpers.IMockFileDataAccessor mockFileDataAccessor) { } + public void CheckInvalidPathChars(string path, bool checkAdditional = false) { } + public bool HasIllegalCharacters(string path, bool checkAdditional) { } + public void IsLegalAbsoluteOrRelative(string path, string paramName) { } + public string NormalizeDriveName(string name) { } + public bool TryNormalizeDriveName(string name, out string result) { } + } + [System.Serializable] + public class StringOperations + { + public StringOperations(bool caseSensitive) { } + public System.StringComparer Comparer { get; } + public bool Contains(string s, string substring) { } + public bool EndsWith(string s, string suffix) { } + public bool Equals(char x, char y) { } + public bool Equals(string x, string y) { } + public int IndexOf(string s, string substring) { } + public int IndexOf(string s, string substring, int startIndex) { } + public string Replace(string s, string oldValue, string newValue) { } + public bool StartsWith(string s, string prefix) { } + public char ToLower(char c) { } + public string ToLower(string s) { } + public char ToUpper(char c) { } + public string ToUpper(string s) { } + } + [System.Flags] + public enum TimeAdjustments + { + None = 0, + CreationTime = 1, + LastAccessTime = 2, + LastWriteTime = 4, + All = -1, + } +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.Api.Tests/Expected/TestableIO.System.IO.Abstractions.TestingHelpers_net8.0.txt b/tests/TestableIO.System.IO.Abstractions.Api.Tests/Expected/TestableIO.System.IO.Abstractions.TestingHelpers_net8.0.txt new file mode 100644 index 000000000..e898230a1 --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.Api.Tests/Expected/TestableIO.System.IO.Abstractions.TestingHelpers_net8.0.txt @@ -0,0 +1,592 @@ +[assembly: System.Reflection.AssemblyMetadata("RepositoryUrl", "https://github.com/TestableIO/System.IO.Abstractions.git")] +[assembly: System.Runtime.Versioning.TargetFramework(".NETCoreApp,Version=v8.0", FrameworkDisplayName=".NET 8.0")] +public class FileHandles +{ + public FileHandles() { } + public void AddHandle(string path, System.Guid guid, System.IO.FileAccess access, System.IO.FileShare share) { } + public void RemoveHandle(string path, System.Guid guid) { } +} +namespace System.IO.Abstractions.TestingHelpers +{ + public interface IMockFileDataAccessor : System.IO.Abstractions.IFileSystem + { + System.Collections.Generic.IEnumerable AllDirectories { get; } + System.Collections.Generic.IEnumerable AllDrives { get; } + System.Collections.Generic.IEnumerable AllFiles { get; } + System.Collections.Generic.IEnumerable AllPaths { get; } + FileHandles FileHandles { get; } + System.IO.Abstractions.IFileSystem FileSystem { get; } + System.IO.Abstractions.TestingHelpers.PathVerifier PathVerifier { get; } + System.IO.Abstractions.TestingHelpers.StringOperations StringOperations { get; } + void AddDirectory(string path); + void AddDrive(string name, System.IO.Abstractions.TestingHelpers.MockDriveData mockDrive); + void AddFile(string path, System.IO.Abstractions.TestingHelpers.MockFileData mockFile, bool verifyAccess = true); + void AddFileFromEmbeddedResource(string path, System.Reflection.Assembly resourceAssembly, string embeddedResourcePath); + void AddFilesFromEmbeddedNamespace(string path, System.Reflection.Assembly resourceAssembly, string embeddedResourcePath); + System.IO.Abstractions.TestingHelpers.MockFileData AdjustTimes(System.IO.Abstractions.TestingHelpers.MockFileData fileData, System.IO.Abstractions.TestingHelpers.TimeAdjustments timeAdjustments); + bool FileExists(string path); + System.IO.Abstractions.TestingHelpers.MockDriveData GetDrive(string name); + System.IO.Abstractions.TestingHelpers.MockFileData GetFile(string path); + void MoveDirectory(string sourcePath, string destPath); + void RemoveFile(string path, bool verifyAccess = true); + } + [System.Serializable] + public class MockDirectory : System.IO.Abstractions.DirectoryBase + { + public MockDirectory(System.IO.Abstractions.TestingHelpers.IMockFileDataAccessor mockFileDataAccessor, string currentDirectory) { } + public MockDirectory(System.IO.Abstractions.TestingHelpers.IMockFileDataAccessor mockFileDataAccessor, System.IO.Abstractions.FileBase fileBase, string currentDirectory) { } + public override System.IO.Abstractions.IDirectoryInfo CreateDirectory(string path) { } + public override System.IO.Abstractions.IDirectoryInfo CreateDirectory(string path, System.IO.UnixFileMode unixCreateMode) { } + public override System.IO.Abstractions.IFileSystemInfo CreateSymbolicLink(string path, string pathToTarget) { } + public override System.IO.Abstractions.IDirectoryInfo CreateTempSubdirectory(string prefix = null) { } + public override void Delete(string path) { } + public override void Delete(string path, bool recursive) { } + public override System.Collections.Generic.IEnumerable EnumerateDirectories(string path) { } + public override System.Collections.Generic.IEnumerable EnumerateDirectories(string path, string searchPattern) { } + public override System.Collections.Generic.IEnumerable EnumerateDirectories(string path, string searchPattern, System.IO.EnumerationOptions enumerationOptions) { } + public override System.Collections.Generic.IEnumerable EnumerateDirectories(string path, string searchPattern, System.IO.SearchOption searchOption) { } + public override System.Collections.Generic.IEnumerable EnumerateFileSystemEntries(string path) { } + public override System.Collections.Generic.IEnumerable EnumerateFileSystemEntries(string path, string searchPattern) { } + public override System.Collections.Generic.IEnumerable EnumerateFileSystemEntries(string path, string searchPattern, System.IO.EnumerationOptions enumerationOptions) { } + public override System.Collections.Generic.IEnumerable EnumerateFileSystemEntries(string path, string searchPattern, System.IO.SearchOption searchOption) { } + public override System.Collections.Generic.IEnumerable EnumerateFiles(string path) { } + public override System.Collections.Generic.IEnumerable EnumerateFiles(string path, string searchPattern) { } + public override System.Collections.Generic.IEnumerable EnumerateFiles(string path, string searchPattern, System.IO.EnumerationOptions enumerationOptions) { } + public override System.Collections.Generic.IEnumerable EnumerateFiles(string path, string searchPattern, System.IO.SearchOption searchOption) { } + public override bool Exists(string path) { } + public override System.DateTime GetCreationTime(string path) { } + public override System.DateTime GetCreationTimeUtc(string path) { } + public override string GetCurrentDirectory() { } + public override string[] GetDirectories(string path) { } + public override string[] GetDirectories(string path, string searchPattern) { } + public override string[] GetDirectories(string path, string searchPattern, System.IO.EnumerationOptions enumerationOptions) { } + public override string[] GetDirectories(string path, string searchPattern, System.IO.SearchOption searchOption) { } + public override string GetDirectoryRoot(string path) { } + public override string[] GetFileSystemEntries(string path) { } + public override string[] GetFileSystemEntries(string path, string searchPattern) { } + public override string[] GetFileSystemEntries(string path, string searchPattern, System.IO.EnumerationOptions enumerationOptions) { } + public override string[] GetFileSystemEntries(string path, string searchPattern, System.IO.SearchOption searchOption) { } + public override string[] GetFiles(string path) { } + public override string[] GetFiles(string path, string searchPattern) { } + public override string[] GetFiles(string path, string searchPattern, System.IO.EnumerationOptions enumerationOptions) { } + public override string[] GetFiles(string path, string searchPattern, System.IO.SearchOption searchOption) { } + public override System.DateTime GetLastAccessTime(string path) { } + public override System.DateTime GetLastAccessTimeUtc(string path) { } + public override System.DateTime GetLastWriteTime(string path) { } + public override System.DateTime GetLastWriteTimeUtc(string path) { } + public override string[] GetLogicalDrives() { } + public override System.IO.Abstractions.IDirectoryInfo GetParent(string path) { } + public override void Move(string sourceDirName, string destDirName) { } + public override System.IO.Abstractions.IFileSystemInfo ResolveLinkTarget(string linkPath, bool returnFinalTarget) { } + public override void SetCreationTime(string path, System.DateTime creationTime) { } + public override void SetCreationTimeUtc(string path, System.DateTime creationTimeUtc) { } + public override void SetCurrentDirectory(string path) { } + public override void SetLastAccessTime(string path, System.DateTime lastAccessTime) { } + public override void SetLastAccessTimeUtc(string path, System.DateTime lastAccessTimeUtc) { } + public override void SetLastWriteTime(string path, System.DateTime lastWriteTime) { } + public override void SetLastWriteTimeUtc(string path, System.DateTime lastWriteTimeUtc) { } + } + [System.Serializable] + public class MockDirectoryData : System.IO.Abstractions.TestingHelpers.MockFileData + { + public MockDirectoryData() { } + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public new System.Security.AccessControl.DirectorySecurity AccessControl { get; set; } + } + [System.Serializable] + public class MockDirectoryInfo : System.IO.Abstractions.DirectoryInfoBase, System.IO.Abstractions.IFileSystemAclSupport + { + public MockDirectoryInfo(System.IO.Abstractions.TestingHelpers.IMockFileDataAccessor mockFileDataAccessor, string directoryPath) { } + public override System.IO.FileAttributes Attributes { get; set; } + public override System.DateTime CreationTime { get; set; } + public override System.DateTime CreationTimeUtc { get; set; } + public override bool Exists { get; } + public override string Extension { get; } + public override string FullName { get; } + public override System.DateTime LastAccessTime { get; set; } + public override System.DateTime LastAccessTimeUtc { get; set; } + public override System.DateTime LastWriteTime { get; set; } + public override System.DateTime LastWriteTimeUtc { get; set; } + public override string LinkTarget { get; } + public override string Name { get; } + public override System.IO.Abstractions.IDirectoryInfo Parent { get; } + public override System.IO.Abstractions.IDirectoryInfo Root { get; } + public override void Create() { } + public override void CreateAsSymbolicLink(string pathToTarget) { } + public override System.IO.Abstractions.IDirectoryInfo CreateSubdirectory(string path) { } + public override void Delete() { } + public override void Delete(bool recursive) { } + public override System.Collections.Generic.IEnumerable EnumerateDirectories() { } + public override System.Collections.Generic.IEnumerable EnumerateDirectories(string searchPattern) { } + public override System.Collections.Generic.IEnumerable EnumerateDirectories(string searchPattern, System.IO.EnumerationOptions enumerationOptions) { } + public override System.Collections.Generic.IEnumerable EnumerateDirectories(string searchPattern, System.IO.SearchOption searchOption) { } + public override System.Collections.Generic.IEnumerable EnumerateFileSystemInfos() { } + public override System.Collections.Generic.IEnumerable EnumerateFileSystemInfos(string searchPattern) { } + public override System.Collections.Generic.IEnumerable EnumerateFileSystemInfos(string searchPattern, System.IO.EnumerationOptions enumerationOptions) { } + public override System.Collections.Generic.IEnumerable EnumerateFileSystemInfos(string searchPattern, System.IO.SearchOption searchOption) { } + public override System.Collections.Generic.IEnumerable EnumerateFiles() { } + public override System.Collections.Generic.IEnumerable EnumerateFiles(string searchPattern) { } + public override System.Collections.Generic.IEnumerable EnumerateFiles(string searchPattern, System.IO.EnumerationOptions enumerationOptions) { } + public override System.Collections.Generic.IEnumerable EnumerateFiles(string searchPattern, System.IO.SearchOption searchOption) { } + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public object GetAccessControl() { } + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public object GetAccessControl(System.IO.Abstractions.IFileSystemAclSupport.AccessControlSections includeSections) { } + public override System.IO.Abstractions.IDirectoryInfo[] GetDirectories() { } + public override System.IO.Abstractions.IDirectoryInfo[] GetDirectories(string searchPattern) { } + public override System.IO.Abstractions.IDirectoryInfo[] GetDirectories(string searchPattern, System.IO.EnumerationOptions enumerationOptions) { } + public override System.IO.Abstractions.IDirectoryInfo[] GetDirectories(string searchPattern, System.IO.SearchOption searchOption) { } + public override System.IO.Abstractions.IFileSystemInfo[] GetFileSystemInfos() { } + public override System.IO.Abstractions.IFileSystemInfo[] GetFileSystemInfos(string searchPattern) { } + public override System.IO.Abstractions.IFileSystemInfo[] GetFileSystemInfos(string searchPattern, System.IO.EnumerationOptions enumerationOptions) { } + public override System.IO.Abstractions.IFileSystemInfo[] GetFileSystemInfos(string searchPattern, System.IO.SearchOption searchOption) { } + public override System.IO.Abstractions.IFileInfo[] GetFiles() { } + public override System.IO.Abstractions.IFileInfo[] GetFiles(string searchPattern) { } + public override System.IO.Abstractions.IFileInfo[] GetFiles(string searchPattern, System.IO.EnumerationOptions enumerationOptions) { } + public override System.IO.Abstractions.IFileInfo[] GetFiles(string searchPattern, System.IO.SearchOption searchOption) { } + public override void MoveTo(string destDirName) { } + public override void Refresh() { } + public override System.IO.Abstractions.IFileSystemInfo ResolveLinkTarget(bool returnFinalTarget) { } + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public void SetAccessControl(object value) { } + public override string ToString() { } + } + [System.Serializable] + public class MockDirectoryInfoFactory : System.IO.Abstractions.IDirectoryInfoFactory, System.IO.Abstractions.IFileSystemEntity + { + public MockDirectoryInfoFactory(System.IO.Abstractions.TestingHelpers.IMockFileDataAccessor mockFileSystem) { } + public System.IO.Abstractions.IFileSystem FileSystem { get; } + public System.IO.Abstractions.IDirectoryInfo New(string path) { } + public System.IO.Abstractions.IDirectoryInfo Wrap(System.IO.DirectoryInfo directoryInfo) { } + } + [System.Serializable] + public class MockDriveData + { + public MockDriveData() { } + public MockDriveData(System.IO.Abstractions.TestingHelpers.MockDriveData template) { } + public long AvailableFreeSpace { get; set; } + public string DriveFormat { get; set; } + public System.IO.DriveType DriveType { get; set; } + public bool IsReady { get; set; } + public long TotalFreeSpace { get; set; } + public long TotalSize { get; set; } + public string VolumeLabel { get; set; } + } + [System.Serializable] + public class MockDriveInfo : System.IO.Abstractions.DriveInfoBase + { + public MockDriveInfo(System.IO.Abstractions.TestingHelpers.IMockFileDataAccessor mockFileDataAccessor, string name) { } + public override long AvailableFreeSpace { get; } + public override string DriveFormat { get; } + public override System.IO.DriveType DriveType { get; } + public override bool IsReady { get; } + public override string Name { get; } + public override System.IO.Abstractions.IDirectoryInfo RootDirectory { get; } + public override long TotalFreeSpace { get; } + public override long TotalSize { get; } + public override string VolumeLabel { get; set; } + public override string ToString() { } + } + [System.Serializable] + public class MockDriveInfoFactory : System.IO.Abstractions.IDriveInfoFactory, System.IO.Abstractions.IFileSystemEntity + { + public MockDriveInfoFactory(System.IO.Abstractions.TestingHelpers.IMockFileDataAccessor mockFileSystem) { } + public System.IO.Abstractions.IFileSystem FileSystem { get; } + public System.IO.Abstractions.IDriveInfo[] GetDrives() { } + public System.IO.Abstractions.IDriveInfo New(string driveName) { } + public System.IO.Abstractions.IDriveInfo Wrap(System.IO.DriveInfo driveInfo) { } + } + [System.Serializable] + public class MockFile : System.IO.Abstractions.FileBase + { + public MockFile(System.IO.Abstractions.TestingHelpers.IMockFileDataAccessor mockFileDataAccessor) { } + public override void AppendAllLines(string path, System.Collections.Generic.IEnumerable contents) { } + public override void AppendAllLines(string path, System.Collections.Generic.IEnumerable contents, System.Text.Encoding encoding) { } + public override System.Threading.Tasks.Task AppendAllLinesAsync(string path, System.Collections.Generic.IEnumerable contents, System.Threading.CancellationToken cancellationToken = default) { } + public override System.Threading.Tasks.Task AppendAllLinesAsync(string path, System.Collections.Generic.IEnumerable contents, System.Text.Encoding encoding, System.Threading.CancellationToken cancellationToken = default) { } + public override void AppendAllText(string path, string contents) { } + public override void AppendAllText(string path, string contents, System.Text.Encoding encoding) { } + public override System.Threading.Tasks.Task AppendAllTextAsync(string path, string contents, System.Threading.CancellationToken cancellationToken = default) { } + public override System.Threading.Tasks.Task AppendAllTextAsync(string path, string contents, System.Text.Encoding encoding, System.Threading.CancellationToken cancellationToken = default) { } + public override System.IO.StreamWriter AppendText(string path) { } + public override void Copy(string sourceFileName, string destFileName) { } + public override void Copy(string sourceFileName, string destFileName, bool overwrite) { } + public override System.IO.Abstractions.FileSystemStream Create(string path) { } + public override System.IO.Abstractions.FileSystemStream Create(string path, int bufferSize) { } + public override System.IO.Abstractions.FileSystemStream Create(string path, int bufferSize, System.IO.FileOptions options) { } + public override System.IO.Abstractions.IFileSystemInfo CreateSymbolicLink(string path, string pathToTarget) { } + public override System.IO.StreamWriter CreateText(string path) { } + public override void Decrypt(string path) { } + public override void Delete(string path) { } + public override void Encrypt(string path) { } + public override bool Exists(string path) { } + public override System.IO.FileAttributes GetAttributes(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle) { } + public override System.IO.FileAttributes GetAttributes(string path) { } + public override System.DateTime GetCreationTime(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle) { } + public override System.DateTime GetCreationTime(string path) { } + public override System.DateTime GetCreationTimeUtc(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle) { } + public override System.DateTime GetCreationTimeUtc(string path) { } + public override System.DateTime GetLastAccessTime(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle) { } + public override System.DateTime GetLastAccessTime(string path) { } + public override System.DateTime GetLastAccessTimeUtc(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle) { } + public override System.DateTime GetLastAccessTimeUtc(string path) { } + public override System.DateTime GetLastWriteTime(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle) { } + public override System.DateTime GetLastWriteTime(string path) { } + public override System.DateTime GetLastWriteTimeUtc(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle) { } + public override System.DateTime GetLastWriteTimeUtc(string path) { } + public override System.IO.UnixFileMode GetUnixFileMode(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle) { } + public override System.IO.UnixFileMode GetUnixFileMode(string path) { } + public override void Move(string sourceFileName, string destFileName) { } + public override void Move(string sourceFileName, string destFileName, bool overwrite) { } + public override System.IO.Abstractions.FileSystemStream Open(string path, System.IO.FileMode mode) { } + public override System.IO.Abstractions.FileSystemStream Open(string path, System.IO.FileStreamOptions options) { } + public override System.IO.Abstractions.FileSystemStream Open(string path, System.IO.FileMode mode, System.IO.FileAccess access) { } + public override System.IO.Abstractions.FileSystemStream Open(string path, System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share) { } + public override System.IO.Abstractions.FileSystemStream OpenRead(string path) { } + public override System.IO.StreamReader OpenText(string path) { } + public override System.IO.Abstractions.FileSystemStream OpenWrite(string path) { } + public override byte[] ReadAllBytes(string path) { } + public override System.Threading.Tasks.Task ReadAllBytesAsync(string path, System.Threading.CancellationToken cancellationToken = default) { } + public override string[] ReadAllLines(string path) { } + public override string[] ReadAllLines(string path, System.Text.Encoding encoding) { } + public override System.Threading.Tasks.Task ReadAllLinesAsync(string path, System.Threading.CancellationToken cancellationToken = default) { } + public override System.Threading.Tasks.Task ReadAllLinesAsync(string path, System.Text.Encoding encoding, System.Threading.CancellationToken cancellationToken = default) { } + public override string ReadAllText(string path) { } + public override string ReadAllText(string path, System.Text.Encoding encoding) { } + public override System.Threading.Tasks.Task ReadAllTextAsync(string path, System.Threading.CancellationToken cancellationToken = default) { } + public override System.Threading.Tasks.Task ReadAllTextAsync(string path, System.Text.Encoding encoding, System.Threading.CancellationToken cancellationToken = default) { } + public override System.Collections.Generic.IEnumerable ReadLines(string path) { } + public override System.Collections.Generic.IEnumerable ReadLines(string path, System.Text.Encoding encoding) { } + public override System.Collections.Generic.IAsyncEnumerable ReadLinesAsync(string path, System.Threading.CancellationToken cancellationToken = default) { } + [System.Runtime.CompilerServices.AsyncIteratorStateMachine(typeof(System.IO.Abstractions.TestingHelpers.MockFile.d__10))] + public override System.Collections.Generic.IAsyncEnumerable ReadLinesAsync(string path, System.Text.Encoding encoding, [System.Runtime.CompilerServices.EnumeratorCancellation] System.Threading.CancellationToken cancellationToken = default) { } + public override void Replace(string sourceFileName, string destinationFileName, string destinationBackupFileName) { } + public override void Replace(string sourceFileName, string destinationFileName, string destinationBackupFileName, bool ignoreMetadataErrors) { } + public override System.IO.Abstractions.IFileSystemInfo ResolveLinkTarget(string linkPath, bool returnFinalTarget) { } + public override void SetAttributes(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle, System.IO.FileAttributes fileAttributes) { } + public override void SetAttributes(string path, System.IO.FileAttributes fileAttributes) { } + public override void SetCreationTime(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle, System.DateTime creationTime) { } + public override void SetCreationTime(string path, System.DateTime creationTime) { } + public override void SetCreationTimeUtc(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle, System.DateTime creationTimeUtc) { } + public override void SetCreationTimeUtc(string path, System.DateTime creationTimeUtc) { } + public override void SetLastAccessTime(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle, System.DateTime lastAccessTime) { } + public override void SetLastAccessTime(string path, System.DateTime lastAccessTime) { } + public override void SetLastAccessTimeUtc(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle, System.DateTime lastAccessTimeUtc) { } + public override void SetLastAccessTimeUtc(string path, System.DateTime lastAccessTimeUtc) { } + public override void SetLastWriteTime(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle, System.DateTime lastWriteTime) { } + public override void SetLastWriteTime(string path, System.DateTime lastWriteTime) { } + public override void SetLastWriteTimeUtc(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle, System.DateTime lastWriteTimeUtc) { } + public override void SetLastWriteTimeUtc(string path, System.DateTime lastWriteTimeUtc) { } + public override void SetUnixFileMode(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle, System.IO.UnixFileMode mode) { } + public override void SetUnixFileMode(string path, System.IO.UnixFileMode mode) { } + public override void WriteAllBytes(string path, byte[] bytes) { } + public override System.Threading.Tasks.Task WriteAllBytesAsync(string path, byte[] bytes, System.Threading.CancellationToken cancellationToken = default) { } + public override void WriteAllLines(string path, System.Collections.Generic.IEnumerable contents) { } + public override void WriteAllLines(string path, string[] contents) { } + public override void WriteAllLines(string path, System.Collections.Generic.IEnumerable contents, System.Text.Encoding encoding) { } + public override void WriteAllLines(string path, string[] contents, System.Text.Encoding encoding) { } + public override System.Threading.Tasks.Task WriteAllLinesAsync(string path, System.Collections.Generic.IEnumerable contents, System.Threading.CancellationToken cancellationToken = default) { } + public override System.Threading.Tasks.Task WriteAllLinesAsync(string path, System.Collections.Generic.IEnumerable contents, System.Text.Encoding encoding, System.Threading.CancellationToken cancellationToken = default) { } + public override void WriteAllText(string path, string contents) { } + public override void WriteAllText(string path, string contents, System.Text.Encoding encoding) { } + public override System.Threading.Tasks.Task WriteAllTextAsync(string path, string contents, System.Threading.CancellationToken cancellationToken = default) { } + public override System.Threading.Tasks.Task WriteAllTextAsync(string path, string contents, System.Text.Encoding encoding, System.Threading.CancellationToken cancellationToken = default) { } + } + [System.Serializable] + public class MockFileData + { + public static readonly System.DateTimeOffset DefaultDateTimeOffset; + public static readonly System.Text.Encoding DefaultEncoding; + public MockFileData(System.IO.Abstractions.TestingHelpers.MockFileData template) { } + public MockFileData(byte[] contents) { } + public MockFileData(string textContents) { } + public MockFileData(string textContents, System.Text.Encoding encoding) { } + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public System.Security.AccessControl.FileSecurity AccessControl { get; set; } + public System.IO.FileShare AllowedFileShare { get; set; } + public System.IO.FileAttributes Attributes { get; set; } + public byte[] Contents { get; set; } + public System.DateTimeOffset CreationTime { get; set; } + public System.IO.Abstractions.IFileVersionInfo FileVersionInfo { get; set; } + public bool IsDirectory { get; } + public System.DateTimeOffset LastAccessTime { get; set; } + public System.DateTimeOffset LastWriteTime { get; set; } + public string LinkTarget { get; set; } + public string TextContents { get; set; } + public System.IO.UnixFileMode UnixMode { get; set; } + public static System.IO.Abstractions.TestingHelpers.MockFileData op_Implicit(string s) { } + } + [System.Serializable] + public class MockFileInfo : System.IO.Abstractions.FileInfoBase, System.IO.Abstractions.IFileSystemAclSupport + { + public MockFileInfo(System.IO.Abstractions.TestingHelpers.IMockFileDataAccessor mockFileSystem, string path) { } + public override System.IO.FileAttributes Attributes { get; set; } + public override System.DateTime CreationTime { get; set; } + public override System.DateTime CreationTimeUtc { get; set; } + public override System.IO.Abstractions.IDirectoryInfo Directory { get; } + public override string DirectoryName { get; } + public override bool Exists { get; } + public override string Extension { get; } + public override string FullName { get; } + public override bool IsReadOnly { get; set; } + public override System.DateTime LastAccessTime { get; set; } + public override System.DateTime LastAccessTimeUtc { get; set; } + public override System.DateTime LastWriteTime { get; set; } + public override System.DateTime LastWriteTimeUtc { get; set; } + public override long Length { get; } + public override string LinkTarget { get; } + public override string Name { get; } + public override System.IO.StreamWriter AppendText() { } + public override System.IO.Abstractions.IFileInfo CopyTo(string destFileName) { } + public override System.IO.Abstractions.IFileInfo CopyTo(string destFileName, bool overwrite) { } + public override System.IO.Abstractions.FileSystemStream Create() { } + public override void CreateAsSymbolicLink(string pathToTarget) { } + public override System.IO.StreamWriter CreateText() { } + public override void Decrypt() { } + public override void Delete() { } + public override void Encrypt() { } + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public object GetAccessControl() { } + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public object GetAccessControl(System.IO.Abstractions.IFileSystemAclSupport.AccessControlSections includeSections) { } + public override void MoveTo(string destFileName) { } + public override void MoveTo(string destFileName, bool overwrite) { } + public override System.IO.Abstractions.FileSystemStream Open(System.IO.FileMode mode) { } + public override System.IO.Abstractions.FileSystemStream Open(System.IO.FileStreamOptions options) { } + public override System.IO.Abstractions.FileSystemStream Open(System.IO.FileMode mode, System.IO.FileAccess access) { } + public override System.IO.Abstractions.FileSystemStream Open(System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share) { } + public override System.IO.Abstractions.FileSystemStream OpenRead() { } + public override System.IO.StreamReader OpenText() { } + public override System.IO.Abstractions.FileSystemStream OpenWrite() { } + public override void Refresh() { } + public override System.IO.Abstractions.IFileInfo Replace(string destinationFileName, string destinationBackupFileName) { } + public override System.IO.Abstractions.IFileInfo Replace(string destinationFileName, string destinationBackupFileName, bool ignoreMetadataErrors) { } + public override System.IO.Abstractions.IFileSystemInfo ResolveLinkTarget(bool returnFinalTarget) { } + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public void SetAccessControl(object value) { } + public override string ToString() { } + } + [System.Serializable] + public class MockFileInfoFactory : System.IO.Abstractions.IFileInfoFactory, System.IO.Abstractions.IFileSystemEntity + { + public MockFileInfoFactory(System.IO.Abstractions.TestingHelpers.IMockFileDataAccessor mockFileSystem) { } + public System.IO.Abstractions.IFileSystem FileSystem { get; } + public System.IO.Abstractions.IFileInfo New(string fileName) { } + public System.IO.Abstractions.IFileInfo Wrap(System.IO.FileInfo fileInfo) { } + } + [System.Serializable] + public class MockFileStream : System.IO.Abstractions.FileSystemStream, System.IO.Abstractions.IFileSystemAclSupport + { + public MockFileStream(System.IO.Abstractions.TestingHelpers.IMockFileDataAccessor mockFileDataAccessor, string path, System.IO.FileMode mode, System.IO.FileAccess access = 3, System.IO.FileShare share = 1, System.IO.FileOptions options = 0) { } + public override bool CanRead { get; } + public override bool CanWrite { get; } + public static System.IO.Abstractions.FileSystemStream Null { get; } + protected override void Dispose(bool disposing) { } + public override void EndWrite(System.IAsyncResult asyncResult) { } + public override void Flush() { } + public override void Flush(bool flushToDisk) { } + public override System.Threading.Tasks.Task FlushAsync(System.Threading.CancellationToken cancellationToken) { } + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public object GetAccessControl() { } + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public object GetAccessControl(System.IO.Abstractions.IFileSystemAclSupport.AccessControlSections includeSections) { } + public override int Read(byte[] buffer, int offset, int count) { } + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public void SetAccessControl(object value) { } + public override void SetLength(long value) { } + public override void Write(System.ReadOnlySpan buffer) { } + public override void Write(byte[] buffer, int offset, int count) { } + public override System.Threading.Tasks.ValueTask WriteAsync(System.ReadOnlyMemory buffer, System.Threading.CancellationToken cancellationToken = default) { } + public override System.Threading.Tasks.Task WriteAsync(byte[] buffer, int offset, int count, System.Threading.CancellationToken cancellationToken) { } + public override void WriteByte(byte value) { } + } + [System.Serializable] + public class MockFileStreamFactory : System.IO.Abstractions.IFileStreamFactory, System.IO.Abstractions.IFileSystemEntity + { + public MockFileStreamFactory(System.IO.Abstractions.TestingHelpers.IMockFileDataAccessor mockFileSystem) { } + public System.IO.Abstractions.IFileSystem FileSystem { get; } + public System.IO.Abstractions.FileSystemStream New(Microsoft.Win32.SafeHandles.SafeFileHandle handle, System.IO.FileAccess access) { } + public System.IO.Abstractions.FileSystemStream New(string path, System.IO.FileMode mode) { } + public System.IO.Abstractions.FileSystemStream New(string path, System.IO.FileStreamOptions options) { } + public System.IO.Abstractions.FileSystemStream New(Microsoft.Win32.SafeHandles.SafeFileHandle handle, System.IO.FileAccess access, int bufferSize) { } + public System.IO.Abstractions.FileSystemStream New(string path, System.IO.FileMode mode, System.IO.FileAccess access) { } + public System.IO.Abstractions.FileSystemStream New(Microsoft.Win32.SafeHandles.SafeFileHandle handle, System.IO.FileAccess access, int bufferSize, bool isAsync) { } + public System.IO.Abstractions.FileSystemStream New(string path, System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share) { } + public System.IO.Abstractions.FileSystemStream New(string path, System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share, int bufferSize) { } + public System.IO.Abstractions.FileSystemStream New(string path, System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share, int bufferSize, System.IO.FileOptions options) { } + public System.IO.Abstractions.FileSystemStream New(string path, System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share, int bufferSize, bool useAsync) { } + public System.IO.Abstractions.FileSystemStream Wrap(System.IO.FileStream fileStream) { } + } + [System.Serializable] + public class MockFileSystem : System.IO.Abstractions.FileSystemBase, System.IO.Abstractions.IFileSystem, System.IO.Abstractions.TestingHelpers.IMockFileDataAccessor + { + public MockFileSystem() { } + public MockFileSystem(System.IO.Abstractions.TestingHelpers.MockFileSystemOptions options) { } + public MockFileSystem(System.Collections.Generic.IDictionary files, System.IO.Abstractions.TestingHelpers.MockFileSystemOptions options) { } + public MockFileSystem(System.Collections.Generic.IDictionary files, string currentDirectory = "") { } + public System.Collections.Generic.IEnumerable AllDirectories { get; } + public System.Collections.Generic.IEnumerable AllDrives { get; } + public System.Collections.Generic.IEnumerable AllFiles { get; } + public System.Collections.Generic.IEnumerable AllNodes { get; } + public System.Collections.Generic.IEnumerable AllPaths { get; } + public override System.IO.Abstractions.IDirectory Directory { get; } + public override System.IO.Abstractions.IDirectoryInfoFactory DirectoryInfo { get; } + public override System.IO.Abstractions.IDriveInfoFactory DriveInfo { get; } + public override System.IO.Abstractions.IFile File { get; } + public FileHandles FileHandles { get; } + public override System.IO.Abstractions.IFileInfoFactory FileInfo { get; } + public override System.IO.Abstractions.IFileStreamFactory FileStream { get; } + public System.IO.Abstractions.IFileSystem FileSystem { get; } + public override System.IO.Abstractions.IFileSystemWatcherFactory FileSystemWatcher { get; } + public override System.IO.Abstractions.IFileVersionInfoFactory FileVersionInfo { get; } + public override System.IO.Abstractions.IPath Path { get; } + public System.IO.Abstractions.TestingHelpers.PathVerifier PathVerifier { get; } + public System.IO.Abstractions.TestingHelpers.StringOperations StringOperations { get; } + public void AddDirectory(System.IO.Abstractions.IDirectoryInfo path) { } + public void AddDirectory(string path) { } + public void AddDrive(string name, System.IO.Abstractions.TestingHelpers.MockDriveData mockDrive) { } + public void AddEmptyFile(System.IO.Abstractions.IFileInfo path) { } + public void AddEmptyFile(string path) { } + public void AddFile(System.IO.Abstractions.IFileInfo path, System.IO.Abstractions.TestingHelpers.MockFileData data, bool verifyAccess = true) { } + public void AddFile(string path, System.IO.Abstractions.TestingHelpers.MockFileData mockFile, bool verifyAccess = true) { } + public void AddFileFromEmbeddedResource(string path, System.Reflection.Assembly resourceAssembly, string embeddedResourcePath) { } + public void AddFilesFromEmbeddedNamespace(string path, System.Reflection.Assembly resourceAssembly, string embeddedResourcePath) { } + public System.IO.Abstractions.TestingHelpers.MockFileData AdjustTimes(System.IO.Abstractions.TestingHelpers.MockFileData fileData, System.IO.Abstractions.TestingHelpers.TimeAdjustments timeAdjustments) { } + public bool FileExists(string path) { } + public System.IO.Abstractions.TestingHelpers.MockDriveData GetDrive(string name) { } + public System.IO.Abstractions.TestingHelpers.MockFileData GetFile(System.IO.Abstractions.IFileInfo path) { } + public System.IO.Abstractions.TestingHelpers.MockFileData GetFile(string path) { } + public System.IO.Abstractions.TestingHelpers.MockFileSystem MockTime(System.Func dateTimeProvider) { } + public void MoveDirectory(string sourcePath, string destPath) { } + public void RemoveFile(string path, bool verifyAccess = true) { } + } + public class MockFileSystemOptions + { + public MockFileSystemOptions() { } + public bool CreateDefaultTempDir { get; init; } + public string CurrentDirectory { get; init; } + } + [System.Serializable] + public class MockFileSystemWatcherFactory : System.IO.Abstractions.IFileSystemEntity, System.IO.Abstractions.IFileSystemWatcherFactory + { + public MockFileSystemWatcherFactory(System.IO.Abstractions.TestingHelpers.MockFileSystem mockFileSystem) { } + public System.IO.Abstractions.IFileSystem FileSystem { get; } + public System.IO.Abstractions.IFileSystemWatcher New() { } + public System.IO.Abstractions.IFileSystemWatcher New(string path) { } + public System.IO.Abstractions.IFileSystemWatcher New(string path, string filter) { } + public System.IO.Abstractions.IFileSystemWatcher Wrap(System.IO.FileSystemWatcher fileSystemWatcher) { } + } + [System.Serializable] + public class MockFileVersionInfo : System.IO.Abstractions.FileVersionInfoBase + { + public MockFileVersionInfo( + string fileName, + string fileVersion = null, + string productVersion = null, + string fileDescription = null, + string productName = null, + string companyName = null, + string comments = null, + string internalName = null, + bool isDebug = false, + bool isPatched = false, + bool isPrivateBuild = false, + bool isPreRelease = false, + bool isSpecialBuild = false, + string language = null, + string legalCopyright = null, + string legalTrademarks = null, + string originalFilename = null, + string privateBuild = null, + string specialBuild = null) { } + public override string Comments { get; } + public override string CompanyName { get; } + public override int FileBuildPart { get; } + public override string FileDescription { get; } + public override int FileMajorPart { get; } + public override int FileMinorPart { get; } + public override string FileName { get; } + public override int FilePrivatePart { get; } + public override string FileVersion { get; } + public override string InternalName { get; } + public override bool IsDebug { get; } + public override bool IsPatched { get; } + public override bool IsPreRelease { get; } + public override bool IsPrivateBuild { get; } + public override bool IsSpecialBuild { get; } + public override string Language { get; } + public override string LegalCopyright { get; } + public override string LegalTrademarks { get; } + public override string OriginalFilename { get; } + public override string PrivateBuild { get; } + public override int ProductBuildPart { get; } + public override int ProductMajorPart { get; } + public override int ProductMinorPart { get; } + public override string ProductName { get; } + public override int ProductPrivatePart { get; } + public override string ProductVersion { get; } + public override string SpecialBuild { get; } + public override string ToString() { } + } + [System.Serializable] + public class MockFileVersionInfoFactory : System.IO.Abstractions.IFileSystemEntity, System.IO.Abstractions.IFileVersionInfoFactory + { + public MockFileVersionInfoFactory(System.IO.Abstractions.TestingHelpers.IMockFileDataAccessor mockFileSystem) { } + public System.IO.Abstractions.IFileSystem FileSystem { get; } + public System.IO.Abstractions.IFileVersionInfo GetVersionInfo(string fileName) { } + } + [System.Serializable] + public class MockPath : System.IO.Abstractions.PathWrapper + { + public MockPath(System.IO.Abstractions.TestingHelpers.IMockFileDataAccessor mockFileDataAccessor) { } + public MockPath(System.IO.Abstractions.TestingHelpers.IMockFileDataAccessor mockFileDataAccessor, string defaultTempDirectory) { } + public override bool Exists(string path) { } + public override string GetFullPath(string path) { } + public override string GetRelativePath(string relativeTo, string path) { } + public override string GetTempFileName() { } + public override string GetTempPath() { } + } + public static class MockUnixSupport + { + public static bool IsUnixPlatform() { } + public static bool IsWindowsPlatform() { } + public static string Path(string path) { } + } + [System.Serializable] + public class PathVerifier + { + public PathVerifier(System.IO.Abstractions.TestingHelpers.IMockFileDataAccessor mockFileDataAccessor) { } + public void CheckInvalidPathChars(string path, bool checkAdditional = false) { } + public bool HasIllegalCharacters(string path, bool checkAdditional) { } + public void IsLegalAbsoluteOrRelative(string path, string paramName) { } + public string NormalizeDriveName(string name) { } + public bool TryNormalizeDriveName(string name, out string result) { } + } + [System.Serializable] + public class StringOperations + { + public StringOperations(bool caseSensitive) { } + public System.StringComparer Comparer { get; } + public bool Contains(string s, string substring) { } + public bool EndsWith(string s, string suffix) { } + public bool Equals(char x, char y) { } + public bool Equals(string x, string y) { } + public int IndexOf(string s, string substring) { } + public int IndexOf(string s, string substring, int startIndex) { } + public string Replace(string s, string oldValue, string newValue) { } + public bool StartsWith(string s, string prefix) { } + public char ToLower(char c) { } + public string ToLower(string s) { } + public char ToUpper(char c) { } + public string ToUpper(string s) { } + } + [System.Flags] + public enum TimeAdjustments + { + None = 0, + CreationTime = 1, + LastAccessTime = 2, + LastWriteTime = 4, + All = -1, + } +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.Api.Tests/Expected/TestableIO.System.IO.Abstractions.TestingHelpers_net9.0.txt b/tests/TestableIO.System.IO.Abstractions.Api.Tests/Expected/TestableIO.System.IO.Abstractions.TestingHelpers_net9.0.txt new file mode 100644 index 000000000..dea869d1f --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.Api.Tests/Expected/TestableIO.System.IO.Abstractions.TestingHelpers_net9.0.txt @@ -0,0 +1,606 @@ +[assembly: System.Reflection.AssemblyMetadata("RepositoryUrl", "https://github.com/TestableIO/System.IO.Abstractions.git")] +[assembly: System.Runtime.Versioning.TargetFramework(".NETCoreApp,Version=v9.0", FrameworkDisplayName=".NET 9.0")] +public class FileHandles +{ + public FileHandles() { } + public void AddHandle(string path, System.Guid guid, System.IO.FileAccess access, System.IO.FileShare share) { } + public void RemoveHandle(string path, System.Guid guid) { } +} +namespace System.IO.Abstractions.TestingHelpers +{ + public interface IMockFileDataAccessor : System.IO.Abstractions.IFileSystem + { + System.Collections.Generic.IEnumerable AllDirectories { get; } + System.Collections.Generic.IEnumerable AllDrives { get; } + System.Collections.Generic.IEnumerable AllFiles { get; } + System.Collections.Generic.IEnumerable AllPaths { get; } + FileHandles FileHandles { get; } + System.IO.Abstractions.IFileSystem FileSystem { get; } + System.IO.Abstractions.TestingHelpers.PathVerifier PathVerifier { get; } + System.IO.Abstractions.TestingHelpers.StringOperations StringOperations { get; } + void AddDirectory(string path); + void AddDrive(string name, System.IO.Abstractions.TestingHelpers.MockDriveData mockDrive); + void AddFile(string path, System.IO.Abstractions.TestingHelpers.MockFileData mockFile, bool verifyAccess = true); + void AddFileFromEmbeddedResource(string path, System.Reflection.Assembly resourceAssembly, string embeddedResourcePath); + void AddFilesFromEmbeddedNamespace(string path, System.Reflection.Assembly resourceAssembly, string embeddedResourcePath); + System.IO.Abstractions.TestingHelpers.MockFileData AdjustTimes(System.IO.Abstractions.TestingHelpers.MockFileData fileData, System.IO.Abstractions.TestingHelpers.TimeAdjustments timeAdjustments); + bool FileExists(string path); + System.IO.Abstractions.TestingHelpers.MockDriveData GetDrive(string name); + System.IO.Abstractions.TestingHelpers.MockFileData GetFile(string path); + void MoveDirectory(string sourcePath, string destPath); + void RemoveFile(string path, bool verifyAccess = true); + } + [System.Serializable] + public class MockDirectory : System.IO.Abstractions.DirectoryBase + { + public MockDirectory(System.IO.Abstractions.TestingHelpers.IMockFileDataAccessor mockFileDataAccessor, string currentDirectory) { } + public MockDirectory(System.IO.Abstractions.TestingHelpers.IMockFileDataAccessor mockFileDataAccessor, System.IO.Abstractions.FileBase fileBase, string currentDirectory) { } + public override System.IO.Abstractions.IDirectoryInfo CreateDirectory(string path) { } + public override System.IO.Abstractions.IDirectoryInfo CreateDirectory(string path, System.IO.UnixFileMode unixCreateMode) { } + public override System.IO.Abstractions.IFileSystemInfo CreateSymbolicLink(string path, string pathToTarget) { } + public override System.IO.Abstractions.IDirectoryInfo CreateTempSubdirectory(string prefix = null) { } + public override void Delete(string path) { } + public override void Delete(string path, bool recursive) { } + public override System.Collections.Generic.IEnumerable EnumerateDirectories(string path) { } + public override System.Collections.Generic.IEnumerable EnumerateDirectories(string path, string searchPattern) { } + public override System.Collections.Generic.IEnumerable EnumerateDirectories(string path, string searchPattern, System.IO.EnumerationOptions enumerationOptions) { } + public override System.Collections.Generic.IEnumerable EnumerateDirectories(string path, string searchPattern, System.IO.SearchOption searchOption) { } + public override System.Collections.Generic.IEnumerable EnumerateFileSystemEntries(string path) { } + public override System.Collections.Generic.IEnumerable EnumerateFileSystemEntries(string path, string searchPattern) { } + public override System.Collections.Generic.IEnumerable EnumerateFileSystemEntries(string path, string searchPattern, System.IO.EnumerationOptions enumerationOptions) { } + public override System.Collections.Generic.IEnumerable EnumerateFileSystemEntries(string path, string searchPattern, System.IO.SearchOption searchOption) { } + public override System.Collections.Generic.IEnumerable EnumerateFiles(string path) { } + public override System.Collections.Generic.IEnumerable EnumerateFiles(string path, string searchPattern) { } + public override System.Collections.Generic.IEnumerable EnumerateFiles(string path, string searchPattern, System.IO.EnumerationOptions enumerationOptions) { } + public override System.Collections.Generic.IEnumerable EnumerateFiles(string path, string searchPattern, System.IO.SearchOption searchOption) { } + public override bool Exists(string path) { } + public override System.DateTime GetCreationTime(string path) { } + public override System.DateTime GetCreationTimeUtc(string path) { } + public override string GetCurrentDirectory() { } + public override string[] GetDirectories(string path) { } + public override string[] GetDirectories(string path, string searchPattern) { } + public override string[] GetDirectories(string path, string searchPattern, System.IO.EnumerationOptions enumerationOptions) { } + public override string[] GetDirectories(string path, string searchPattern, System.IO.SearchOption searchOption) { } + public override string GetDirectoryRoot(string path) { } + public override string[] GetFileSystemEntries(string path) { } + public override string[] GetFileSystemEntries(string path, string searchPattern) { } + public override string[] GetFileSystemEntries(string path, string searchPattern, System.IO.EnumerationOptions enumerationOptions) { } + public override string[] GetFileSystemEntries(string path, string searchPattern, System.IO.SearchOption searchOption) { } + public override string[] GetFiles(string path) { } + public override string[] GetFiles(string path, string searchPattern) { } + public override string[] GetFiles(string path, string searchPattern, System.IO.EnumerationOptions enumerationOptions) { } + public override string[] GetFiles(string path, string searchPattern, System.IO.SearchOption searchOption) { } + public override System.DateTime GetLastAccessTime(string path) { } + public override System.DateTime GetLastAccessTimeUtc(string path) { } + public override System.DateTime GetLastWriteTime(string path) { } + public override System.DateTime GetLastWriteTimeUtc(string path) { } + public override string[] GetLogicalDrives() { } + public override System.IO.Abstractions.IDirectoryInfo GetParent(string path) { } + public override void Move(string sourceDirName, string destDirName) { } + public override System.IO.Abstractions.IFileSystemInfo ResolveLinkTarget(string linkPath, bool returnFinalTarget) { } + public override void SetCreationTime(string path, System.DateTime creationTime) { } + public override void SetCreationTimeUtc(string path, System.DateTime creationTimeUtc) { } + public override void SetCurrentDirectory(string path) { } + public override void SetLastAccessTime(string path, System.DateTime lastAccessTime) { } + public override void SetLastAccessTimeUtc(string path, System.DateTime lastAccessTimeUtc) { } + public override void SetLastWriteTime(string path, System.DateTime lastWriteTime) { } + public override void SetLastWriteTimeUtc(string path, System.DateTime lastWriteTimeUtc) { } + } + [System.Serializable] + public class MockDirectoryData : System.IO.Abstractions.TestingHelpers.MockFileData + { + public MockDirectoryData() { } + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public new System.Security.AccessControl.DirectorySecurity AccessControl { get; set; } + } + [System.Serializable] + public class MockDirectoryInfo : System.IO.Abstractions.DirectoryInfoBase, System.IO.Abstractions.IFileSystemAclSupport + { + public MockDirectoryInfo(System.IO.Abstractions.TestingHelpers.IMockFileDataAccessor mockFileDataAccessor, string directoryPath) { } + public override System.IO.FileAttributes Attributes { get; set; } + public override System.DateTime CreationTime { get; set; } + public override System.DateTime CreationTimeUtc { get; set; } + public override bool Exists { get; } + public override string Extension { get; } + public override string FullName { get; } + public override System.DateTime LastAccessTime { get; set; } + public override System.DateTime LastAccessTimeUtc { get; set; } + public override System.DateTime LastWriteTime { get; set; } + public override System.DateTime LastWriteTimeUtc { get; set; } + public override string LinkTarget { get; } + public override string Name { get; } + public override System.IO.Abstractions.IDirectoryInfo Parent { get; } + public override System.IO.Abstractions.IDirectoryInfo Root { get; } + public override void Create() { } + public override void CreateAsSymbolicLink(string pathToTarget) { } + public override System.IO.Abstractions.IDirectoryInfo CreateSubdirectory(string path) { } + public override void Delete() { } + public override void Delete(bool recursive) { } + public override System.Collections.Generic.IEnumerable EnumerateDirectories() { } + public override System.Collections.Generic.IEnumerable EnumerateDirectories(string searchPattern) { } + public override System.Collections.Generic.IEnumerable EnumerateDirectories(string searchPattern, System.IO.EnumerationOptions enumerationOptions) { } + public override System.Collections.Generic.IEnumerable EnumerateDirectories(string searchPattern, System.IO.SearchOption searchOption) { } + public override System.Collections.Generic.IEnumerable EnumerateFileSystemInfos() { } + public override System.Collections.Generic.IEnumerable EnumerateFileSystemInfos(string searchPattern) { } + public override System.Collections.Generic.IEnumerable EnumerateFileSystemInfos(string searchPattern, System.IO.EnumerationOptions enumerationOptions) { } + public override System.Collections.Generic.IEnumerable EnumerateFileSystemInfos(string searchPattern, System.IO.SearchOption searchOption) { } + public override System.Collections.Generic.IEnumerable EnumerateFiles() { } + public override System.Collections.Generic.IEnumerable EnumerateFiles(string searchPattern) { } + public override System.Collections.Generic.IEnumerable EnumerateFiles(string searchPattern, System.IO.EnumerationOptions enumerationOptions) { } + public override System.Collections.Generic.IEnumerable EnumerateFiles(string searchPattern, System.IO.SearchOption searchOption) { } + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public object GetAccessControl() { } + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public object GetAccessControl(System.IO.Abstractions.IFileSystemAclSupport.AccessControlSections includeSections) { } + public override System.IO.Abstractions.IDirectoryInfo[] GetDirectories() { } + public override System.IO.Abstractions.IDirectoryInfo[] GetDirectories(string searchPattern) { } + public override System.IO.Abstractions.IDirectoryInfo[] GetDirectories(string searchPattern, System.IO.EnumerationOptions enumerationOptions) { } + public override System.IO.Abstractions.IDirectoryInfo[] GetDirectories(string searchPattern, System.IO.SearchOption searchOption) { } + public override System.IO.Abstractions.IFileSystemInfo[] GetFileSystemInfos() { } + public override System.IO.Abstractions.IFileSystemInfo[] GetFileSystemInfos(string searchPattern) { } + public override System.IO.Abstractions.IFileSystemInfo[] GetFileSystemInfos(string searchPattern, System.IO.EnumerationOptions enumerationOptions) { } + public override System.IO.Abstractions.IFileSystemInfo[] GetFileSystemInfos(string searchPattern, System.IO.SearchOption searchOption) { } + public override System.IO.Abstractions.IFileInfo[] GetFiles() { } + public override System.IO.Abstractions.IFileInfo[] GetFiles(string searchPattern) { } + public override System.IO.Abstractions.IFileInfo[] GetFiles(string searchPattern, System.IO.EnumerationOptions enumerationOptions) { } + public override System.IO.Abstractions.IFileInfo[] GetFiles(string searchPattern, System.IO.SearchOption searchOption) { } + public override void MoveTo(string destDirName) { } + public override void Refresh() { } + public override System.IO.Abstractions.IFileSystemInfo ResolveLinkTarget(bool returnFinalTarget) { } + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public void SetAccessControl(object value) { } + public override string ToString() { } + } + [System.Serializable] + public class MockDirectoryInfoFactory : System.IO.Abstractions.IDirectoryInfoFactory, System.IO.Abstractions.IFileSystemEntity + { + public MockDirectoryInfoFactory(System.IO.Abstractions.TestingHelpers.IMockFileDataAccessor mockFileSystem) { } + public System.IO.Abstractions.IFileSystem FileSystem { get; } + public System.IO.Abstractions.IDirectoryInfo New(string path) { } + public System.IO.Abstractions.IDirectoryInfo Wrap(System.IO.DirectoryInfo directoryInfo) { } + } + [System.Serializable] + public class MockDriveData + { + public MockDriveData() { } + public MockDriveData(System.IO.Abstractions.TestingHelpers.MockDriveData template) { } + public long AvailableFreeSpace { get; set; } + public string DriveFormat { get; set; } + public System.IO.DriveType DriveType { get; set; } + public bool IsReady { get; set; } + public long TotalFreeSpace { get; set; } + public long TotalSize { get; set; } + public string VolumeLabel { get; set; } + } + [System.Serializable] + public class MockDriveInfo : System.IO.Abstractions.DriveInfoBase + { + public MockDriveInfo(System.IO.Abstractions.TestingHelpers.IMockFileDataAccessor mockFileDataAccessor, string name) { } + public override long AvailableFreeSpace { get; } + public override string DriveFormat { get; } + public override System.IO.DriveType DriveType { get; } + public override bool IsReady { get; } + public override string Name { get; } + public override System.IO.Abstractions.IDirectoryInfo RootDirectory { get; } + public override long TotalFreeSpace { get; } + public override long TotalSize { get; } + public override string VolumeLabel { get; set; } + public override string ToString() { } + } + [System.Serializable] + public class MockDriveInfoFactory : System.IO.Abstractions.IDriveInfoFactory, System.IO.Abstractions.IFileSystemEntity + { + public MockDriveInfoFactory(System.IO.Abstractions.TestingHelpers.IMockFileDataAccessor mockFileSystem) { } + public System.IO.Abstractions.IFileSystem FileSystem { get; } + public System.IO.Abstractions.IDriveInfo[] GetDrives() { } + public System.IO.Abstractions.IDriveInfo New(string driveName) { } + public System.IO.Abstractions.IDriveInfo Wrap(System.IO.DriveInfo driveInfo) { } + } + [System.Serializable] + public class MockFile : System.IO.Abstractions.FileBase + { + public MockFile(System.IO.Abstractions.TestingHelpers.IMockFileDataAccessor mockFileDataAccessor) { } + public override void AppendAllBytes(string path, System.ReadOnlySpan bytes) { } + public override void AppendAllBytes(string path, byte[] bytes) { } + public override System.Threading.Tasks.Task AppendAllBytesAsync(string path, System.ReadOnlyMemory bytes, System.Threading.CancellationToken cancellationToken = default) { } + public override System.Threading.Tasks.Task AppendAllBytesAsync(string path, byte[] bytes, System.Threading.CancellationToken cancellationToken = default) { } + public override void AppendAllLines(string path, System.Collections.Generic.IEnumerable contents) { } + public override void AppendAllLines(string path, System.Collections.Generic.IEnumerable contents, System.Text.Encoding encoding) { } + public override System.Threading.Tasks.Task AppendAllLinesAsync(string path, System.Collections.Generic.IEnumerable contents, System.Threading.CancellationToken cancellationToken = default) { } + public override System.Threading.Tasks.Task AppendAllLinesAsync(string path, System.Collections.Generic.IEnumerable contents, System.Text.Encoding encoding, System.Threading.CancellationToken cancellationToken = default) { } + public override void AppendAllText(string path, System.ReadOnlySpan contents) { } + public override void AppendAllText(string path, string contents) { } + public override void AppendAllText(string path, System.ReadOnlySpan contents, System.Text.Encoding encoding) { } + public override void AppendAllText(string path, string contents, System.Text.Encoding encoding) { } + public override System.Threading.Tasks.Task AppendAllTextAsync(string path, System.ReadOnlyMemory contents, System.Threading.CancellationToken cancellationToken = default) { } + public override System.Threading.Tasks.Task AppendAllTextAsync(string path, string contents, System.Threading.CancellationToken cancellationToken = default) { } + public override System.Threading.Tasks.Task AppendAllTextAsync(string path, System.ReadOnlyMemory contents, System.Text.Encoding encoding, System.Threading.CancellationToken cancellationToken = default) { } + public override System.Threading.Tasks.Task AppendAllTextAsync(string path, string contents, System.Text.Encoding encoding, System.Threading.CancellationToken cancellationToken = default) { } + public override System.IO.StreamWriter AppendText(string path) { } + public override void Copy(string sourceFileName, string destFileName) { } + public override void Copy(string sourceFileName, string destFileName, bool overwrite) { } + public override System.IO.Abstractions.FileSystemStream Create(string path) { } + public override System.IO.Abstractions.FileSystemStream Create(string path, int bufferSize) { } + public override System.IO.Abstractions.FileSystemStream Create(string path, int bufferSize, System.IO.FileOptions options) { } + public override System.IO.Abstractions.IFileSystemInfo CreateSymbolicLink(string path, string pathToTarget) { } + public override System.IO.StreamWriter CreateText(string path) { } + public override void Decrypt(string path) { } + public override void Delete(string path) { } + public override void Encrypt(string path) { } + public override bool Exists(string path) { } + public override System.IO.FileAttributes GetAttributes(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle) { } + public override System.IO.FileAttributes GetAttributes(string path) { } + public override System.DateTime GetCreationTime(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle) { } + public override System.DateTime GetCreationTime(string path) { } + public override System.DateTime GetCreationTimeUtc(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle) { } + public override System.DateTime GetCreationTimeUtc(string path) { } + public override System.DateTime GetLastAccessTime(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle) { } + public override System.DateTime GetLastAccessTime(string path) { } + public override System.DateTime GetLastAccessTimeUtc(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle) { } + public override System.DateTime GetLastAccessTimeUtc(string path) { } + public override System.DateTime GetLastWriteTime(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle) { } + public override System.DateTime GetLastWriteTime(string path) { } + public override System.DateTime GetLastWriteTimeUtc(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle) { } + public override System.DateTime GetLastWriteTimeUtc(string path) { } + public override System.IO.UnixFileMode GetUnixFileMode(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle) { } + public override System.IO.UnixFileMode GetUnixFileMode(string path) { } + public override void Move(string sourceFileName, string destFileName) { } + public override void Move(string sourceFileName, string destFileName, bool overwrite) { } + public override System.IO.Abstractions.FileSystemStream Open(string path, System.IO.FileMode mode) { } + public override System.IO.Abstractions.FileSystemStream Open(string path, System.IO.FileStreamOptions options) { } + public override System.IO.Abstractions.FileSystemStream Open(string path, System.IO.FileMode mode, System.IO.FileAccess access) { } + public override System.IO.Abstractions.FileSystemStream Open(string path, System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share) { } + public override System.IO.Abstractions.FileSystemStream OpenRead(string path) { } + public override System.IO.StreamReader OpenText(string path) { } + public override System.IO.Abstractions.FileSystemStream OpenWrite(string path) { } + public override byte[] ReadAllBytes(string path) { } + public override System.Threading.Tasks.Task ReadAllBytesAsync(string path, System.Threading.CancellationToken cancellationToken = default) { } + public override string[] ReadAllLines(string path) { } + public override string[] ReadAllLines(string path, System.Text.Encoding encoding) { } + public override System.Threading.Tasks.Task ReadAllLinesAsync(string path, System.Threading.CancellationToken cancellationToken = default) { } + public override System.Threading.Tasks.Task ReadAllLinesAsync(string path, System.Text.Encoding encoding, System.Threading.CancellationToken cancellationToken = default) { } + public override string ReadAllText(string path) { } + public override string ReadAllText(string path, System.Text.Encoding encoding) { } + public override System.Threading.Tasks.Task ReadAllTextAsync(string path, System.Threading.CancellationToken cancellationToken = default) { } + public override System.Threading.Tasks.Task ReadAllTextAsync(string path, System.Text.Encoding encoding, System.Threading.CancellationToken cancellationToken = default) { } + public override System.Collections.Generic.IEnumerable ReadLines(string path) { } + public override System.Collections.Generic.IEnumerable ReadLines(string path, System.Text.Encoding encoding) { } + public override System.Collections.Generic.IAsyncEnumerable ReadLinesAsync(string path, System.Threading.CancellationToken cancellationToken = default) { } + [System.Runtime.CompilerServices.AsyncIteratorStateMachine(typeof(System.IO.Abstractions.TestingHelpers.MockFile.d__14))] + public override System.Collections.Generic.IAsyncEnumerable ReadLinesAsync(string path, System.Text.Encoding encoding, [System.Runtime.CompilerServices.EnumeratorCancellation] System.Threading.CancellationToken cancellationToken = default) { } + public override void Replace(string sourceFileName, string destinationFileName, string destinationBackupFileName) { } + public override void Replace(string sourceFileName, string destinationFileName, string destinationBackupFileName, bool ignoreMetadataErrors) { } + public override System.IO.Abstractions.IFileSystemInfo ResolveLinkTarget(string linkPath, bool returnFinalTarget) { } + public override void SetAttributes(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle, System.IO.FileAttributes fileAttributes) { } + public override void SetAttributes(string path, System.IO.FileAttributes fileAttributes) { } + public override void SetCreationTime(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle, System.DateTime creationTime) { } + public override void SetCreationTime(string path, System.DateTime creationTime) { } + public override void SetCreationTimeUtc(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle, System.DateTime creationTimeUtc) { } + public override void SetCreationTimeUtc(string path, System.DateTime creationTimeUtc) { } + public override void SetLastAccessTime(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle, System.DateTime lastAccessTime) { } + public override void SetLastAccessTime(string path, System.DateTime lastAccessTime) { } + public override void SetLastAccessTimeUtc(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle, System.DateTime lastAccessTimeUtc) { } + public override void SetLastAccessTimeUtc(string path, System.DateTime lastAccessTimeUtc) { } + public override void SetLastWriteTime(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle, System.DateTime lastWriteTime) { } + public override void SetLastWriteTime(string path, System.DateTime lastWriteTime) { } + public override void SetLastWriteTimeUtc(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle, System.DateTime lastWriteTimeUtc) { } + public override void SetLastWriteTimeUtc(string path, System.DateTime lastWriteTimeUtc) { } + public override void SetUnixFileMode(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle, System.IO.UnixFileMode mode) { } + public override void SetUnixFileMode(string path, System.IO.UnixFileMode mode) { } + public override void WriteAllBytes(string path, System.ReadOnlySpan bytes) { } + public override void WriteAllBytes(string path, byte[] bytes) { } + public override System.Threading.Tasks.Task WriteAllBytesAsync(string path, System.ReadOnlyMemory bytes, System.Threading.CancellationToken cancellationToken = default) { } + public override System.Threading.Tasks.Task WriteAllBytesAsync(string path, byte[] bytes, System.Threading.CancellationToken cancellationToken = default) { } + public override void WriteAllLines(string path, System.Collections.Generic.IEnumerable contents) { } + public override void WriteAllLines(string path, string[] contents) { } + public override void WriteAllLines(string path, System.Collections.Generic.IEnumerable contents, System.Text.Encoding encoding) { } + public override void WriteAllLines(string path, string[] contents, System.Text.Encoding encoding) { } + public override System.Threading.Tasks.Task WriteAllLinesAsync(string path, System.Collections.Generic.IEnumerable contents, System.Threading.CancellationToken cancellationToken = default) { } + public override System.Threading.Tasks.Task WriteAllLinesAsync(string path, System.Collections.Generic.IEnumerable contents, System.Text.Encoding encoding, System.Threading.CancellationToken cancellationToken = default) { } + public override void WriteAllText(string path, System.ReadOnlySpan contents) { } + public override void WriteAllText(string path, string contents) { } + public override void WriteAllText(string path, System.ReadOnlySpan contents, System.Text.Encoding encoding) { } + public override void WriteAllText(string path, string contents, System.Text.Encoding encoding) { } + public override System.Threading.Tasks.Task WriteAllTextAsync(string path, System.ReadOnlyMemory contents, System.Threading.CancellationToken cancellationToken = default) { } + public override System.Threading.Tasks.Task WriteAllTextAsync(string path, string contents, System.Threading.CancellationToken cancellationToken = default) { } + public override System.Threading.Tasks.Task WriteAllTextAsync(string path, System.ReadOnlyMemory contents, System.Text.Encoding encoding, System.Threading.CancellationToken cancellationToken = default) { } + public override System.Threading.Tasks.Task WriteAllTextAsync(string path, string contents, System.Text.Encoding encoding, System.Threading.CancellationToken cancellationToken = default) { } + } + [System.Serializable] + public class MockFileData + { + public static readonly System.DateTimeOffset DefaultDateTimeOffset; + public static readonly System.Text.Encoding DefaultEncoding; + public MockFileData(System.IO.Abstractions.TestingHelpers.MockFileData template) { } + public MockFileData(byte[] contents) { } + public MockFileData(string textContents) { } + public MockFileData(string textContents, System.Text.Encoding encoding) { } + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public System.Security.AccessControl.FileSecurity AccessControl { get; set; } + public System.IO.FileShare AllowedFileShare { get; set; } + public System.IO.FileAttributes Attributes { get; set; } + public byte[] Contents { get; set; } + public System.DateTimeOffset CreationTime { get; set; } + public System.IO.Abstractions.IFileVersionInfo FileVersionInfo { get; set; } + public bool IsDirectory { get; } + public System.DateTimeOffset LastAccessTime { get; set; } + public System.DateTimeOffset LastWriteTime { get; set; } + public string LinkTarget { get; set; } + public string TextContents { get; set; } + public System.IO.UnixFileMode UnixMode { get; set; } + public static System.IO.Abstractions.TestingHelpers.MockFileData op_Implicit(string s) { } + } + [System.Serializable] + public class MockFileInfo : System.IO.Abstractions.FileInfoBase, System.IO.Abstractions.IFileSystemAclSupport + { + public MockFileInfo(System.IO.Abstractions.TestingHelpers.IMockFileDataAccessor mockFileSystem, string path) { } + public override System.IO.FileAttributes Attributes { get; set; } + public override System.DateTime CreationTime { get; set; } + public override System.DateTime CreationTimeUtc { get; set; } + public override System.IO.Abstractions.IDirectoryInfo Directory { get; } + public override string DirectoryName { get; } + public override bool Exists { get; } + public override string Extension { get; } + public override string FullName { get; } + public override bool IsReadOnly { get; set; } + public override System.DateTime LastAccessTime { get; set; } + public override System.DateTime LastAccessTimeUtc { get; set; } + public override System.DateTime LastWriteTime { get; set; } + public override System.DateTime LastWriteTimeUtc { get; set; } + public override long Length { get; } + public override string LinkTarget { get; } + public override string Name { get; } + public override System.IO.StreamWriter AppendText() { } + public override System.IO.Abstractions.IFileInfo CopyTo(string destFileName) { } + public override System.IO.Abstractions.IFileInfo CopyTo(string destFileName, bool overwrite) { } + public override System.IO.Abstractions.FileSystemStream Create() { } + public override void CreateAsSymbolicLink(string pathToTarget) { } + public override System.IO.StreamWriter CreateText() { } + public override void Decrypt() { } + public override void Delete() { } + public override void Encrypt() { } + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public object GetAccessControl() { } + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public object GetAccessControl(System.IO.Abstractions.IFileSystemAclSupport.AccessControlSections includeSections) { } + public override void MoveTo(string destFileName) { } + public override void MoveTo(string destFileName, bool overwrite) { } + public override System.IO.Abstractions.FileSystemStream Open(System.IO.FileMode mode) { } + public override System.IO.Abstractions.FileSystemStream Open(System.IO.FileStreamOptions options) { } + public override System.IO.Abstractions.FileSystemStream Open(System.IO.FileMode mode, System.IO.FileAccess access) { } + public override System.IO.Abstractions.FileSystemStream Open(System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share) { } + public override System.IO.Abstractions.FileSystemStream OpenRead() { } + public override System.IO.StreamReader OpenText() { } + public override System.IO.Abstractions.FileSystemStream OpenWrite() { } + public override void Refresh() { } + public override System.IO.Abstractions.IFileInfo Replace(string destinationFileName, string destinationBackupFileName) { } + public override System.IO.Abstractions.IFileInfo Replace(string destinationFileName, string destinationBackupFileName, bool ignoreMetadataErrors) { } + public override System.IO.Abstractions.IFileSystemInfo ResolveLinkTarget(bool returnFinalTarget) { } + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public void SetAccessControl(object value) { } + public override string ToString() { } + } + [System.Serializable] + public class MockFileInfoFactory : System.IO.Abstractions.IFileInfoFactory, System.IO.Abstractions.IFileSystemEntity + { + public MockFileInfoFactory(System.IO.Abstractions.TestingHelpers.IMockFileDataAccessor mockFileSystem) { } + public System.IO.Abstractions.IFileSystem FileSystem { get; } + public System.IO.Abstractions.IFileInfo New(string fileName) { } + public System.IO.Abstractions.IFileInfo Wrap(System.IO.FileInfo fileInfo) { } + } + [System.Serializable] + public class MockFileStream : System.IO.Abstractions.FileSystemStream, System.IO.Abstractions.IFileSystemAclSupport + { + public MockFileStream(System.IO.Abstractions.TestingHelpers.IMockFileDataAccessor mockFileDataAccessor, string path, System.IO.FileMode mode, System.IO.FileAccess access = 3, System.IO.FileShare share = 1, System.IO.FileOptions options = 0) { } + public override bool CanRead { get; } + public override bool CanWrite { get; } + public static System.IO.Abstractions.FileSystemStream Null { get; } + protected override void Dispose(bool disposing) { } + public override void EndWrite(System.IAsyncResult asyncResult) { } + public override void Flush() { } + public override void Flush(bool flushToDisk) { } + public override System.Threading.Tasks.Task FlushAsync(System.Threading.CancellationToken cancellationToken) { } + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public object GetAccessControl() { } + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public object GetAccessControl(System.IO.Abstractions.IFileSystemAclSupport.AccessControlSections includeSections) { } + public override int Read(byte[] buffer, int offset, int count) { } + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public void SetAccessControl(object value) { } + public override void SetLength(long value) { } + public override void Write(System.ReadOnlySpan buffer) { } + public override void Write(byte[] buffer, int offset, int count) { } + public override System.Threading.Tasks.ValueTask WriteAsync(System.ReadOnlyMemory buffer, System.Threading.CancellationToken cancellationToken = default) { } + public override System.Threading.Tasks.Task WriteAsync(byte[] buffer, int offset, int count, System.Threading.CancellationToken cancellationToken) { } + public override void WriteByte(byte value) { } + } + [System.Serializable] + public class MockFileStreamFactory : System.IO.Abstractions.IFileStreamFactory, System.IO.Abstractions.IFileSystemEntity + { + public MockFileStreamFactory(System.IO.Abstractions.TestingHelpers.IMockFileDataAccessor mockFileSystem) { } + public System.IO.Abstractions.IFileSystem FileSystem { get; } + public System.IO.Abstractions.FileSystemStream New(Microsoft.Win32.SafeHandles.SafeFileHandle handle, System.IO.FileAccess access) { } + public System.IO.Abstractions.FileSystemStream New(string path, System.IO.FileMode mode) { } + public System.IO.Abstractions.FileSystemStream New(string path, System.IO.FileStreamOptions options) { } + public System.IO.Abstractions.FileSystemStream New(Microsoft.Win32.SafeHandles.SafeFileHandle handle, System.IO.FileAccess access, int bufferSize) { } + public System.IO.Abstractions.FileSystemStream New(string path, System.IO.FileMode mode, System.IO.FileAccess access) { } + public System.IO.Abstractions.FileSystemStream New(Microsoft.Win32.SafeHandles.SafeFileHandle handle, System.IO.FileAccess access, int bufferSize, bool isAsync) { } + public System.IO.Abstractions.FileSystemStream New(string path, System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share) { } + public System.IO.Abstractions.FileSystemStream New(string path, System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share, int bufferSize) { } + public System.IO.Abstractions.FileSystemStream New(string path, System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share, int bufferSize, System.IO.FileOptions options) { } + public System.IO.Abstractions.FileSystemStream New(string path, System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share, int bufferSize, bool useAsync) { } + public System.IO.Abstractions.FileSystemStream Wrap(System.IO.FileStream fileStream) { } + } + [System.Serializable] + public class MockFileSystem : System.IO.Abstractions.FileSystemBase, System.IO.Abstractions.IFileSystem, System.IO.Abstractions.TestingHelpers.IMockFileDataAccessor + { + public MockFileSystem() { } + public MockFileSystem(System.IO.Abstractions.TestingHelpers.MockFileSystemOptions options) { } + public MockFileSystem(System.Collections.Generic.IDictionary files, System.IO.Abstractions.TestingHelpers.MockFileSystemOptions options) { } + public MockFileSystem(System.Collections.Generic.IDictionary files, string currentDirectory = "") { } + public System.Collections.Generic.IEnumerable AllDirectories { get; } + public System.Collections.Generic.IEnumerable AllDrives { get; } + public System.Collections.Generic.IEnumerable AllFiles { get; } + public System.Collections.Generic.IEnumerable AllNodes { get; } + public System.Collections.Generic.IEnumerable AllPaths { get; } + public override System.IO.Abstractions.IDirectory Directory { get; } + public override System.IO.Abstractions.IDirectoryInfoFactory DirectoryInfo { get; } + public override System.IO.Abstractions.IDriveInfoFactory DriveInfo { get; } + public override System.IO.Abstractions.IFile File { get; } + public FileHandles FileHandles { get; } + public override System.IO.Abstractions.IFileInfoFactory FileInfo { get; } + public override System.IO.Abstractions.IFileStreamFactory FileStream { get; } + public System.IO.Abstractions.IFileSystem FileSystem { get; } + public override System.IO.Abstractions.IFileSystemWatcherFactory FileSystemWatcher { get; } + public override System.IO.Abstractions.IFileVersionInfoFactory FileVersionInfo { get; } + public override System.IO.Abstractions.IPath Path { get; } + public System.IO.Abstractions.TestingHelpers.PathVerifier PathVerifier { get; } + public System.IO.Abstractions.TestingHelpers.StringOperations StringOperations { get; } + public void AddDirectory(System.IO.Abstractions.IDirectoryInfo path) { } + public void AddDirectory(string path) { } + public void AddDrive(string name, System.IO.Abstractions.TestingHelpers.MockDriveData mockDrive) { } + public void AddEmptyFile(System.IO.Abstractions.IFileInfo path) { } + public void AddEmptyFile(string path) { } + public void AddFile(System.IO.Abstractions.IFileInfo path, System.IO.Abstractions.TestingHelpers.MockFileData data, bool verifyAccess = true) { } + public void AddFile(string path, System.IO.Abstractions.TestingHelpers.MockFileData mockFile, bool verifyAccess = true) { } + public void AddFileFromEmbeddedResource(string path, System.Reflection.Assembly resourceAssembly, string embeddedResourcePath) { } + public void AddFilesFromEmbeddedNamespace(string path, System.Reflection.Assembly resourceAssembly, string embeddedResourcePath) { } + public System.IO.Abstractions.TestingHelpers.MockFileData AdjustTimes(System.IO.Abstractions.TestingHelpers.MockFileData fileData, System.IO.Abstractions.TestingHelpers.TimeAdjustments timeAdjustments) { } + public bool FileExists(string path) { } + public System.IO.Abstractions.TestingHelpers.MockDriveData GetDrive(string name) { } + public System.IO.Abstractions.TestingHelpers.MockFileData GetFile(System.IO.Abstractions.IFileInfo path) { } + public System.IO.Abstractions.TestingHelpers.MockFileData GetFile(string path) { } + public System.IO.Abstractions.TestingHelpers.MockFileSystem MockTime(System.Func dateTimeProvider) { } + public void MoveDirectory(string sourcePath, string destPath) { } + public void RemoveFile(string path, bool verifyAccess = true) { } + } + public class MockFileSystemOptions + { + public MockFileSystemOptions() { } + public bool CreateDefaultTempDir { get; init; } + public string CurrentDirectory { get; init; } + } + [System.Serializable] + public class MockFileSystemWatcherFactory : System.IO.Abstractions.IFileSystemEntity, System.IO.Abstractions.IFileSystemWatcherFactory + { + public MockFileSystemWatcherFactory(System.IO.Abstractions.TestingHelpers.MockFileSystem mockFileSystem) { } + public System.IO.Abstractions.IFileSystem FileSystem { get; } + public System.IO.Abstractions.IFileSystemWatcher New() { } + public System.IO.Abstractions.IFileSystemWatcher New(string path) { } + public System.IO.Abstractions.IFileSystemWatcher New(string path, string filter) { } + public System.IO.Abstractions.IFileSystemWatcher Wrap(System.IO.FileSystemWatcher fileSystemWatcher) { } + } + [System.Serializable] + public class MockFileVersionInfo : System.IO.Abstractions.FileVersionInfoBase + { + public MockFileVersionInfo( + string fileName, + string fileVersion = null, + string productVersion = null, + string fileDescription = null, + string productName = null, + string companyName = null, + string comments = null, + string internalName = null, + bool isDebug = false, + bool isPatched = false, + bool isPrivateBuild = false, + bool isPreRelease = false, + bool isSpecialBuild = false, + string language = null, + string legalCopyright = null, + string legalTrademarks = null, + string originalFilename = null, + string privateBuild = null, + string specialBuild = null) { } + public override string Comments { get; } + public override string CompanyName { get; } + public override int FileBuildPart { get; } + public override string FileDescription { get; } + public override int FileMajorPart { get; } + public override int FileMinorPart { get; } + public override string FileName { get; } + public override int FilePrivatePart { get; } + public override string FileVersion { get; } + public override string InternalName { get; } + public override bool IsDebug { get; } + public override bool IsPatched { get; } + public override bool IsPreRelease { get; } + public override bool IsPrivateBuild { get; } + public override bool IsSpecialBuild { get; } + public override string Language { get; } + public override string LegalCopyright { get; } + public override string LegalTrademarks { get; } + public override string OriginalFilename { get; } + public override string PrivateBuild { get; } + public override int ProductBuildPart { get; } + public override int ProductMajorPart { get; } + public override int ProductMinorPart { get; } + public override string ProductName { get; } + public override int ProductPrivatePart { get; } + public override string ProductVersion { get; } + public override string SpecialBuild { get; } + public override string ToString() { } + } + [System.Serializable] + public class MockFileVersionInfoFactory : System.IO.Abstractions.IFileSystemEntity, System.IO.Abstractions.IFileVersionInfoFactory + { + public MockFileVersionInfoFactory(System.IO.Abstractions.TestingHelpers.IMockFileDataAccessor mockFileSystem) { } + public System.IO.Abstractions.IFileSystem FileSystem { get; } + public System.IO.Abstractions.IFileVersionInfo GetVersionInfo(string fileName) { } + } + [System.Serializable] + public class MockPath : System.IO.Abstractions.PathWrapper + { + public MockPath(System.IO.Abstractions.TestingHelpers.IMockFileDataAccessor mockFileDataAccessor) { } + public MockPath(System.IO.Abstractions.TestingHelpers.IMockFileDataAccessor mockFileDataAccessor, string defaultTempDirectory) { } + public override bool Exists(string path) { } + public override string GetFullPath(string path) { } + public override string GetRelativePath(string relativeTo, string path) { } + public override string GetTempFileName() { } + public override string GetTempPath() { } + } + public static class MockUnixSupport + { + public static bool IsUnixPlatform() { } + public static bool IsWindowsPlatform() { } + public static string Path(string path) { } + } + [System.Serializable] + public class PathVerifier + { + public PathVerifier(System.IO.Abstractions.TestingHelpers.IMockFileDataAccessor mockFileDataAccessor) { } + public void CheckInvalidPathChars(string path, bool checkAdditional = false) { } + public bool HasIllegalCharacters(string path, bool checkAdditional) { } + public void IsLegalAbsoluteOrRelative(string path, string paramName) { } + public string NormalizeDriveName(string name) { } + public bool TryNormalizeDriveName(string name, out string result) { } + } + [System.Serializable] + public class StringOperations + { + public StringOperations(bool caseSensitive) { } + public System.StringComparer Comparer { get; } + public bool Contains(string s, string substring) { } + public bool EndsWith(string s, string suffix) { } + public bool Equals(char x, char y) { } + public bool Equals(string x, string y) { } + public int IndexOf(string s, string substring) { } + public int IndexOf(string s, string substring, int startIndex) { } + public string Replace(string s, string oldValue, string newValue) { } + public bool StartsWith(string s, string prefix) { } + public char ToLower(char c) { } + public string ToLower(string s) { } + public char ToUpper(char c) { } + public string ToUpper(string s) { } + } + [System.Flags] + public enum TimeAdjustments + { + None = 0, + CreationTime = 1, + LastAccessTime = 2, + LastWriteTime = 4, + All = -1, + } +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.Api.Tests/Expected/TestableIO.System.IO.Abstractions.TestingHelpers_netstandard2.0.txt b/tests/TestableIO.System.IO.Abstractions.Api.Tests/Expected/TestableIO.System.IO.Abstractions.TestingHelpers_netstandard2.0.txt new file mode 100644 index 000000000..fd8f7e4fc --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.Api.Tests/Expected/TestableIO.System.IO.Abstractions.TestingHelpers_netstandard2.0.txt @@ -0,0 +1,511 @@ +[assembly: System.Reflection.AssemblyMetadata("RepositoryUrl", "https://github.com/TestableIO/System.IO.Abstractions.git")] +[assembly: System.Runtime.Versioning.TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName=".NET Standard 2.0")] +public class FileHandles +{ + public FileHandles() { } + public void AddHandle(string path, System.Guid guid, System.IO.FileAccess access, System.IO.FileShare share) { } + public void RemoveHandle(string path, System.Guid guid) { } +} +namespace System.IO.Abstractions.TestingHelpers +{ + public interface IMockFileDataAccessor : System.IO.Abstractions.IFileSystem + { + System.Collections.Generic.IEnumerable AllDirectories { get; } + System.Collections.Generic.IEnumerable AllDrives { get; } + System.Collections.Generic.IEnumerable AllFiles { get; } + System.Collections.Generic.IEnumerable AllPaths { get; } + FileHandles FileHandles { get; } + System.IO.Abstractions.IFileSystem FileSystem { get; } + System.IO.Abstractions.TestingHelpers.PathVerifier PathVerifier { get; } + System.IO.Abstractions.TestingHelpers.StringOperations StringOperations { get; } + void AddDirectory(string path); + void AddDrive(string name, System.IO.Abstractions.TestingHelpers.MockDriveData mockDrive); + void AddFile(string path, System.IO.Abstractions.TestingHelpers.MockFileData mockFile, bool verifyAccess = true); + void AddFileFromEmbeddedResource(string path, System.Reflection.Assembly resourceAssembly, string embeddedResourcePath); + void AddFilesFromEmbeddedNamespace(string path, System.Reflection.Assembly resourceAssembly, string embeddedResourcePath); + System.IO.Abstractions.TestingHelpers.MockFileData AdjustTimes(System.IO.Abstractions.TestingHelpers.MockFileData fileData, System.IO.Abstractions.TestingHelpers.TimeAdjustments timeAdjustments); + bool FileExists(string path); + System.IO.Abstractions.TestingHelpers.MockDriveData GetDrive(string name); + System.IO.Abstractions.TestingHelpers.MockFileData GetFile(string path); + void MoveDirectory(string sourcePath, string destPath); + void RemoveFile(string path, bool verifyAccess = true); + } + [System.Serializable] + public class MockDirectory : System.IO.Abstractions.DirectoryBase + { + public MockDirectory(System.IO.Abstractions.TestingHelpers.IMockFileDataAccessor mockFileDataAccessor, string currentDirectory) { } + public MockDirectory(System.IO.Abstractions.TestingHelpers.IMockFileDataAccessor mockFileDataAccessor, System.IO.Abstractions.FileBase fileBase, string currentDirectory) { } + public override System.IO.Abstractions.IDirectoryInfo CreateDirectory(string path) { } + public override void Delete(string path) { } + public override void Delete(string path, bool recursive) { } + public override System.Collections.Generic.IEnumerable EnumerateDirectories(string path) { } + public override System.Collections.Generic.IEnumerable EnumerateDirectories(string path, string searchPattern) { } + public override System.Collections.Generic.IEnumerable EnumerateDirectories(string path, string searchPattern, System.IO.SearchOption searchOption) { } + public override System.Collections.Generic.IEnumerable EnumerateFileSystemEntries(string path) { } + public override System.Collections.Generic.IEnumerable EnumerateFileSystemEntries(string path, string searchPattern) { } + public override System.Collections.Generic.IEnumerable EnumerateFileSystemEntries(string path, string searchPattern, System.IO.SearchOption searchOption) { } + public override System.Collections.Generic.IEnumerable EnumerateFiles(string path) { } + public override System.Collections.Generic.IEnumerable EnumerateFiles(string path, string searchPattern) { } + public override System.Collections.Generic.IEnumerable EnumerateFiles(string path, string searchPattern, System.IO.SearchOption searchOption) { } + public override bool Exists(string path) { } + public override System.DateTime GetCreationTime(string path) { } + public override System.DateTime GetCreationTimeUtc(string path) { } + public override string GetCurrentDirectory() { } + public override string[] GetDirectories(string path) { } + public override string[] GetDirectories(string path, string searchPattern) { } + public override string[] GetDirectories(string path, string searchPattern, System.IO.SearchOption searchOption) { } + public override string GetDirectoryRoot(string path) { } + public override string[] GetFileSystemEntries(string path) { } + public override string[] GetFileSystemEntries(string path, string searchPattern) { } + public override string[] GetFileSystemEntries(string path, string searchPattern, System.IO.SearchOption searchOption) { } + public override string[] GetFiles(string path) { } + public override string[] GetFiles(string path, string searchPattern) { } + public override string[] GetFiles(string path, string searchPattern, System.IO.SearchOption searchOption) { } + public override System.DateTime GetLastAccessTime(string path) { } + public override System.DateTime GetLastAccessTimeUtc(string path) { } + public override System.DateTime GetLastWriteTime(string path) { } + public override System.DateTime GetLastWriteTimeUtc(string path) { } + public override string[] GetLogicalDrives() { } + public override System.IO.Abstractions.IDirectoryInfo GetParent(string path) { } + public override void Move(string sourceDirName, string destDirName) { } + public override void SetCreationTime(string path, System.DateTime creationTime) { } + public override void SetCreationTimeUtc(string path, System.DateTime creationTimeUtc) { } + public override void SetCurrentDirectory(string path) { } + public override void SetLastAccessTime(string path, System.DateTime lastAccessTime) { } + public override void SetLastAccessTimeUtc(string path, System.DateTime lastAccessTimeUtc) { } + public override void SetLastWriteTime(string path, System.DateTime lastWriteTime) { } + public override void SetLastWriteTimeUtc(string path, System.DateTime lastWriteTimeUtc) { } + } + [System.Serializable] + public class MockDirectoryData : System.IO.Abstractions.TestingHelpers.MockFileData + { + public MockDirectoryData() { } + public new System.Security.AccessControl.DirectorySecurity AccessControl { get; set; } + } + [System.Serializable] + public class MockDirectoryInfo : System.IO.Abstractions.DirectoryInfoBase, System.IO.Abstractions.IFileSystemAclSupport + { + public MockDirectoryInfo(System.IO.Abstractions.TestingHelpers.IMockFileDataAccessor mockFileDataAccessor, string directoryPath) { } + public override System.IO.FileAttributes Attributes { get; set; } + public override System.DateTime CreationTime { get; set; } + public override System.DateTime CreationTimeUtc { get; set; } + public override bool Exists { get; } + public override string Extension { get; } + public override string FullName { get; } + public override System.DateTime LastAccessTime { get; set; } + public override System.DateTime LastAccessTimeUtc { get; set; } + public override System.DateTime LastWriteTime { get; set; } + public override System.DateTime LastWriteTimeUtc { get; set; } + public override string Name { get; } + public override System.IO.Abstractions.IDirectoryInfo Parent { get; } + public override System.IO.Abstractions.IDirectoryInfo Root { get; } + public override void Create() { } + public override System.IO.Abstractions.IDirectoryInfo CreateSubdirectory(string path) { } + public override void Delete() { } + public override void Delete(bool recursive) { } + public override System.Collections.Generic.IEnumerable EnumerateDirectories() { } + public override System.Collections.Generic.IEnumerable EnumerateDirectories(string searchPattern) { } + public override System.Collections.Generic.IEnumerable EnumerateDirectories(string searchPattern, System.IO.SearchOption searchOption) { } + public override System.Collections.Generic.IEnumerable EnumerateFileSystemInfos() { } + public override System.Collections.Generic.IEnumerable EnumerateFileSystemInfos(string searchPattern) { } + public override System.Collections.Generic.IEnumerable EnumerateFileSystemInfos(string searchPattern, System.IO.SearchOption searchOption) { } + public override System.Collections.Generic.IEnumerable EnumerateFiles() { } + public override System.Collections.Generic.IEnumerable EnumerateFiles(string searchPattern) { } + public override System.Collections.Generic.IEnumerable EnumerateFiles(string searchPattern, System.IO.SearchOption searchOption) { } + public object GetAccessControl() { } + public object GetAccessControl(System.IO.Abstractions.IFileSystemAclSupport.AccessControlSections includeSections) { } + public override System.IO.Abstractions.IDirectoryInfo[] GetDirectories() { } + public override System.IO.Abstractions.IDirectoryInfo[] GetDirectories(string searchPattern) { } + public override System.IO.Abstractions.IDirectoryInfo[] GetDirectories(string searchPattern, System.IO.SearchOption searchOption) { } + public override System.IO.Abstractions.IFileSystemInfo[] GetFileSystemInfos() { } + public override System.IO.Abstractions.IFileSystemInfo[] GetFileSystemInfos(string searchPattern) { } + public override System.IO.Abstractions.IFileSystemInfo[] GetFileSystemInfos(string searchPattern, System.IO.SearchOption searchOption) { } + public override System.IO.Abstractions.IFileInfo[] GetFiles() { } + public override System.IO.Abstractions.IFileInfo[] GetFiles(string searchPattern) { } + public override System.IO.Abstractions.IFileInfo[] GetFiles(string searchPattern, System.IO.SearchOption searchOption) { } + public override void MoveTo(string destDirName) { } + public override void Refresh() { } + public void SetAccessControl(object value) { } + public override string ToString() { } + } + [System.Serializable] + public class MockDirectoryInfoFactory : System.IO.Abstractions.IDirectoryInfoFactory, System.IO.Abstractions.IFileSystemEntity + { + public MockDirectoryInfoFactory(System.IO.Abstractions.TestingHelpers.IMockFileDataAccessor mockFileSystem) { } + public System.IO.Abstractions.IFileSystem FileSystem { get; } + public System.IO.Abstractions.IDirectoryInfo New(string path) { } + public System.IO.Abstractions.IDirectoryInfo Wrap(System.IO.DirectoryInfo directoryInfo) { } + } + [System.Serializable] + public class MockDriveData + { + public MockDriveData() { } + public MockDriveData(System.IO.Abstractions.TestingHelpers.MockDriveData template) { } + public long AvailableFreeSpace { get; set; } + public string DriveFormat { get; set; } + public System.IO.DriveType DriveType { get; set; } + public bool IsReady { get; set; } + public long TotalFreeSpace { get; set; } + public long TotalSize { get; set; } + public string VolumeLabel { get; set; } + } + [System.Serializable] + public class MockDriveInfo : System.IO.Abstractions.DriveInfoBase + { + public MockDriveInfo(System.IO.Abstractions.TestingHelpers.IMockFileDataAccessor mockFileDataAccessor, string name) { } + public override long AvailableFreeSpace { get; } + public override string DriveFormat { get; } + public override System.IO.DriveType DriveType { get; } + public override bool IsReady { get; } + public override string Name { get; } + public override System.IO.Abstractions.IDirectoryInfo RootDirectory { get; } + public override long TotalFreeSpace { get; } + public override long TotalSize { get; } + public override string VolumeLabel { get; set; } + public override string ToString() { } + } + [System.Serializable] + public class MockDriveInfoFactory : System.IO.Abstractions.IDriveInfoFactory, System.IO.Abstractions.IFileSystemEntity + { + public MockDriveInfoFactory(System.IO.Abstractions.TestingHelpers.IMockFileDataAccessor mockFileSystem) { } + public System.IO.Abstractions.IFileSystem FileSystem { get; } + public System.IO.Abstractions.IDriveInfo[] GetDrives() { } + public System.IO.Abstractions.IDriveInfo New(string driveName) { } + public System.IO.Abstractions.IDriveInfo Wrap(System.IO.DriveInfo driveInfo) { } + } + [System.Serializable] + public class MockFile : System.IO.Abstractions.FileBase + { + public MockFile(System.IO.Abstractions.TestingHelpers.IMockFileDataAccessor mockFileDataAccessor) { } + public override void AppendAllLines(string path, System.Collections.Generic.IEnumerable contents) { } + public override void AppendAllLines(string path, System.Collections.Generic.IEnumerable contents, System.Text.Encoding encoding) { } + public override void AppendAllText(string path, string contents) { } + public override void AppendAllText(string path, string contents, System.Text.Encoding encoding) { } + public override System.IO.StreamWriter AppendText(string path) { } + public override void Copy(string sourceFileName, string destFileName) { } + public override void Copy(string sourceFileName, string destFileName, bool overwrite) { } + public override System.IO.Abstractions.FileSystemStream Create(string path) { } + public override System.IO.Abstractions.FileSystemStream Create(string path, int bufferSize) { } + public override System.IO.Abstractions.FileSystemStream Create(string path, int bufferSize, System.IO.FileOptions options) { } + public override System.IO.StreamWriter CreateText(string path) { } + public override void Decrypt(string path) { } + public override void Delete(string path) { } + public override void Encrypt(string path) { } + public override bool Exists(string path) { } + public override System.IO.FileAttributes GetAttributes(string path) { } + public override System.DateTime GetCreationTime(string path) { } + public override System.DateTime GetCreationTimeUtc(string path) { } + public override System.DateTime GetLastAccessTime(string path) { } + public override System.DateTime GetLastAccessTimeUtc(string path) { } + public override System.DateTime GetLastWriteTime(string path) { } + public override System.DateTime GetLastWriteTimeUtc(string path) { } + public override void Move(string sourceFileName, string destFileName) { } + public override System.IO.Abstractions.FileSystemStream Open(string path, System.IO.FileMode mode) { } + public override System.IO.Abstractions.FileSystemStream Open(string path, System.IO.FileMode mode, System.IO.FileAccess access) { } + public override System.IO.Abstractions.FileSystemStream Open(string path, System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share) { } + public override System.IO.Abstractions.FileSystemStream OpenRead(string path) { } + public override System.IO.StreamReader OpenText(string path) { } + public override System.IO.Abstractions.FileSystemStream OpenWrite(string path) { } + public override byte[] ReadAllBytes(string path) { } + public override string[] ReadAllLines(string path) { } + public override string[] ReadAllLines(string path, System.Text.Encoding encoding) { } + public override string ReadAllText(string path) { } + public override string ReadAllText(string path, System.Text.Encoding encoding) { } + public override System.Collections.Generic.IEnumerable ReadLines(string path) { } + public override System.Collections.Generic.IEnumerable ReadLines(string path, System.Text.Encoding encoding) { } + public override void Replace(string sourceFileName, string destinationFileName, string destinationBackupFileName) { } + public override void Replace(string sourceFileName, string destinationFileName, string destinationBackupFileName, bool ignoreMetadataErrors) { } + public override void SetAttributes(string path, System.IO.FileAttributes fileAttributes) { } + public override void SetCreationTime(string path, System.DateTime creationTime) { } + public override void SetCreationTimeUtc(string path, System.DateTime creationTimeUtc) { } + public override void SetLastAccessTime(string path, System.DateTime lastAccessTime) { } + public override void SetLastAccessTimeUtc(string path, System.DateTime lastAccessTimeUtc) { } + public override void SetLastWriteTime(string path, System.DateTime lastWriteTime) { } + public override void SetLastWriteTimeUtc(string path, System.DateTime lastWriteTimeUtc) { } + public override void WriteAllBytes(string path, byte[] bytes) { } + public override void WriteAllLines(string path, System.Collections.Generic.IEnumerable contents) { } + public override void WriteAllLines(string path, string[] contents) { } + public override void WriteAllLines(string path, System.Collections.Generic.IEnumerable contents, System.Text.Encoding encoding) { } + public override void WriteAllLines(string path, string[] contents, System.Text.Encoding encoding) { } + public override void WriteAllText(string path, string contents) { } + public override void WriteAllText(string path, string contents, System.Text.Encoding encoding) { } + } + [System.Serializable] + public class MockFileData + { + public static readonly System.DateTimeOffset DefaultDateTimeOffset; + public static readonly System.Text.Encoding DefaultEncoding; + public MockFileData(System.IO.Abstractions.TestingHelpers.MockFileData template) { } + public MockFileData(byte[] contents) { } + public MockFileData(string textContents) { } + public MockFileData(string textContents, System.Text.Encoding encoding) { } + public System.Security.AccessControl.FileSecurity AccessControl { get; set; } + public System.IO.FileShare AllowedFileShare { get; set; } + public System.IO.FileAttributes Attributes { get; set; } + public byte[] Contents { get; set; } + public System.DateTimeOffset CreationTime { get; set; } + public System.IO.Abstractions.IFileVersionInfo FileVersionInfo { get; set; } + public bool IsDirectory { get; } + public System.DateTimeOffset LastAccessTime { get; set; } + public System.DateTimeOffset LastWriteTime { get; set; } + public string TextContents { get; set; } + public static System.IO.Abstractions.TestingHelpers.MockFileData op_Implicit(string s) { } + } + [System.Serializable] + public class MockFileInfo : System.IO.Abstractions.FileInfoBase, System.IO.Abstractions.IFileSystemAclSupport + { + public MockFileInfo(System.IO.Abstractions.TestingHelpers.IMockFileDataAccessor mockFileSystem, string path) { } + public override System.IO.FileAttributes Attributes { get; set; } + public override System.DateTime CreationTime { get; set; } + public override System.DateTime CreationTimeUtc { get; set; } + public override System.IO.Abstractions.IDirectoryInfo Directory { get; } + public override string DirectoryName { get; } + public override bool Exists { get; } + public override string Extension { get; } + public override string FullName { get; } + public override bool IsReadOnly { get; set; } + public override System.DateTime LastAccessTime { get; set; } + public override System.DateTime LastAccessTimeUtc { get; set; } + public override System.DateTime LastWriteTime { get; set; } + public override System.DateTime LastWriteTimeUtc { get; set; } + public override long Length { get; } + public override string Name { get; } + public override System.IO.StreamWriter AppendText() { } + public override System.IO.Abstractions.IFileInfo CopyTo(string destFileName) { } + public override System.IO.Abstractions.IFileInfo CopyTo(string destFileName, bool overwrite) { } + public override System.IO.Abstractions.FileSystemStream Create() { } + public override System.IO.StreamWriter CreateText() { } + public override void Decrypt() { } + public override void Delete() { } + public override void Encrypt() { } + public object GetAccessControl() { } + public object GetAccessControl(System.IO.Abstractions.IFileSystemAclSupport.AccessControlSections includeSections) { } + public override void MoveTo(string destFileName) { } + public override System.IO.Abstractions.FileSystemStream Open(System.IO.FileMode mode) { } + public override System.IO.Abstractions.FileSystemStream Open(System.IO.FileMode mode, System.IO.FileAccess access) { } + public override System.IO.Abstractions.FileSystemStream Open(System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share) { } + public override System.IO.Abstractions.FileSystemStream OpenRead() { } + public override System.IO.StreamReader OpenText() { } + public override System.IO.Abstractions.FileSystemStream OpenWrite() { } + public override void Refresh() { } + public override System.IO.Abstractions.IFileInfo Replace(string destinationFileName, string destinationBackupFileName) { } + public override System.IO.Abstractions.IFileInfo Replace(string destinationFileName, string destinationBackupFileName, bool ignoreMetadataErrors) { } + public void SetAccessControl(object value) { } + public override string ToString() { } + } + [System.Serializable] + public class MockFileInfoFactory : System.IO.Abstractions.IFileInfoFactory, System.IO.Abstractions.IFileSystemEntity + { + public MockFileInfoFactory(System.IO.Abstractions.TestingHelpers.IMockFileDataAccessor mockFileSystem) { } + public System.IO.Abstractions.IFileSystem FileSystem { get; } + public System.IO.Abstractions.IFileInfo New(string fileName) { } + public System.IO.Abstractions.IFileInfo Wrap(System.IO.FileInfo fileInfo) { } + } + [System.Serializable] + public class MockFileStream : System.IO.Abstractions.FileSystemStream, System.IO.Abstractions.IFileSystemAclSupport + { + public MockFileStream(System.IO.Abstractions.TestingHelpers.IMockFileDataAccessor mockFileDataAccessor, string path, System.IO.FileMode mode, System.IO.FileAccess access = 3, System.IO.FileShare share = 1, System.IO.FileOptions options = 0) { } + public override bool CanRead { get; } + public override bool CanWrite { get; } + public static System.IO.Abstractions.FileSystemStream Null { get; } + protected override void Dispose(bool disposing) { } + public override void EndWrite(System.IAsyncResult asyncResult) { } + public override void Flush() { } + public override void Flush(bool flushToDisk) { } + public override System.Threading.Tasks.Task FlushAsync(System.Threading.CancellationToken cancellationToken) { } + public object GetAccessControl() { } + public object GetAccessControl(System.IO.Abstractions.IFileSystemAclSupport.AccessControlSections includeSections) { } + public override int Read(byte[] buffer, int offset, int count) { } + public void SetAccessControl(object value) { } + public override void SetLength(long value) { } + public override void Write(byte[] buffer, int offset, int count) { } + public override System.Threading.Tasks.Task WriteAsync(byte[] buffer, int offset, int count, System.Threading.CancellationToken cancellationToken) { } + public override void WriteByte(byte value) { } + } + [System.Serializable] + public class MockFileStreamFactory : System.IO.Abstractions.IFileStreamFactory, System.IO.Abstractions.IFileSystemEntity + { + public MockFileStreamFactory(System.IO.Abstractions.TestingHelpers.IMockFileDataAccessor mockFileSystem) { } + public System.IO.Abstractions.IFileSystem FileSystem { get; } + public System.IO.Abstractions.FileSystemStream New(Microsoft.Win32.SafeHandles.SafeFileHandle handle, System.IO.FileAccess access) { } + public System.IO.Abstractions.FileSystemStream New(string path, System.IO.FileMode mode) { } + public System.IO.Abstractions.FileSystemStream New(Microsoft.Win32.SafeHandles.SafeFileHandle handle, System.IO.FileAccess access, int bufferSize) { } + public System.IO.Abstractions.FileSystemStream New(string path, System.IO.FileMode mode, System.IO.FileAccess access) { } + public System.IO.Abstractions.FileSystemStream New(Microsoft.Win32.SafeHandles.SafeFileHandle handle, System.IO.FileAccess access, int bufferSize, bool isAsync) { } + public System.IO.Abstractions.FileSystemStream New(string path, System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share) { } + public System.IO.Abstractions.FileSystemStream New(string path, System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share, int bufferSize) { } + public System.IO.Abstractions.FileSystemStream New(string path, System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share, int bufferSize, System.IO.FileOptions options) { } + public System.IO.Abstractions.FileSystemStream New(string path, System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share, int bufferSize, bool useAsync) { } + public System.IO.Abstractions.FileSystemStream Wrap(System.IO.FileStream fileStream) { } + } + [System.Serializable] + public class MockFileSystem : System.IO.Abstractions.FileSystemBase, System.IO.Abstractions.IFileSystem, System.IO.Abstractions.TestingHelpers.IMockFileDataAccessor + { + public MockFileSystem() { } + public MockFileSystem(System.IO.Abstractions.TestingHelpers.MockFileSystemOptions options) { } + public MockFileSystem(System.Collections.Generic.IDictionary files, System.IO.Abstractions.TestingHelpers.MockFileSystemOptions options) { } + public MockFileSystem(System.Collections.Generic.IDictionary files, string currentDirectory = "") { } + public System.Collections.Generic.IEnumerable AllDirectories { get; } + public System.Collections.Generic.IEnumerable AllDrives { get; } + public System.Collections.Generic.IEnumerable AllFiles { get; } + public System.Collections.Generic.IEnumerable AllNodes { get; } + public System.Collections.Generic.IEnumerable AllPaths { get; } + public override System.IO.Abstractions.IDirectory Directory { get; } + public override System.IO.Abstractions.IDirectoryInfoFactory DirectoryInfo { get; } + public override System.IO.Abstractions.IDriveInfoFactory DriveInfo { get; } + public override System.IO.Abstractions.IFile File { get; } + public FileHandles FileHandles { get; } + public override System.IO.Abstractions.IFileInfoFactory FileInfo { get; } + public override System.IO.Abstractions.IFileStreamFactory FileStream { get; } + public System.IO.Abstractions.IFileSystem FileSystem { get; } + public override System.IO.Abstractions.IFileSystemWatcherFactory FileSystemWatcher { get; } + public override System.IO.Abstractions.IFileVersionInfoFactory FileVersionInfo { get; } + public override System.IO.Abstractions.IPath Path { get; } + public System.IO.Abstractions.TestingHelpers.PathVerifier PathVerifier { get; } + public System.IO.Abstractions.TestingHelpers.StringOperations StringOperations { get; } + public void AddDirectory(System.IO.Abstractions.IDirectoryInfo path) { } + public void AddDirectory(string path) { } + public void AddDrive(string name, System.IO.Abstractions.TestingHelpers.MockDriveData mockDrive) { } + public void AddEmptyFile(System.IO.Abstractions.IFileInfo path) { } + public void AddEmptyFile(string path) { } + public void AddFile(System.IO.Abstractions.IFileInfo path, System.IO.Abstractions.TestingHelpers.MockFileData data, bool verifyAccess = true) { } + public void AddFile(string path, System.IO.Abstractions.TestingHelpers.MockFileData mockFile, bool verifyAccess = true) { } + public void AddFileFromEmbeddedResource(string path, System.Reflection.Assembly resourceAssembly, string embeddedResourcePath) { } + public void AddFilesFromEmbeddedNamespace(string path, System.Reflection.Assembly resourceAssembly, string embeddedResourcePath) { } + public System.IO.Abstractions.TestingHelpers.MockFileData AdjustTimes(System.IO.Abstractions.TestingHelpers.MockFileData fileData, System.IO.Abstractions.TestingHelpers.TimeAdjustments timeAdjustments) { } + public bool FileExists(string path) { } + public System.IO.Abstractions.TestingHelpers.MockDriveData GetDrive(string name) { } + public System.IO.Abstractions.TestingHelpers.MockFileData GetFile(System.IO.Abstractions.IFileInfo path) { } + public System.IO.Abstractions.TestingHelpers.MockFileData GetFile(string path) { } + public System.IO.Abstractions.TestingHelpers.MockFileSystem MockTime(System.Func dateTimeProvider) { } + public void MoveDirectory(string sourcePath, string destPath) { } + public void RemoveFile(string path, bool verifyAccess = true) { } + } + public class MockFileSystemOptions + { + public MockFileSystemOptions() { } + public bool CreateDefaultTempDir { get; init; } + public string CurrentDirectory { get; init; } + } + [System.Serializable] + public class MockFileSystemWatcherFactory : System.IO.Abstractions.IFileSystemEntity, System.IO.Abstractions.IFileSystemWatcherFactory + { + public MockFileSystemWatcherFactory(System.IO.Abstractions.TestingHelpers.MockFileSystem mockFileSystem) { } + public System.IO.Abstractions.IFileSystem FileSystem { get; } + public System.IO.Abstractions.IFileSystemWatcher New() { } + public System.IO.Abstractions.IFileSystemWatcher New(string path) { } + public System.IO.Abstractions.IFileSystemWatcher New(string path, string filter) { } + public System.IO.Abstractions.IFileSystemWatcher Wrap(System.IO.FileSystemWatcher fileSystemWatcher) { } + } + [System.Serializable] + public class MockFileVersionInfo : System.IO.Abstractions.FileVersionInfoBase + { + public MockFileVersionInfo( + string fileName, + string fileVersion = null, + string productVersion = null, + string fileDescription = null, + string productName = null, + string companyName = null, + string comments = null, + string internalName = null, + bool isDebug = false, + bool isPatched = false, + bool isPrivateBuild = false, + bool isPreRelease = false, + bool isSpecialBuild = false, + string language = null, + string legalCopyright = null, + string legalTrademarks = null, + string originalFilename = null, + string privateBuild = null, + string specialBuild = null) { } + public override string Comments { get; } + public override string CompanyName { get; } + public override int FileBuildPart { get; } + public override string FileDescription { get; } + public override int FileMajorPart { get; } + public override int FileMinorPart { get; } + public override string FileName { get; } + public override int FilePrivatePart { get; } + public override string FileVersion { get; } + public override string InternalName { get; } + public override bool IsDebug { get; } + public override bool IsPatched { get; } + public override bool IsPreRelease { get; } + public override bool IsPrivateBuild { get; } + public override bool IsSpecialBuild { get; } + public override string Language { get; } + public override string LegalCopyright { get; } + public override string LegalTrademarks { get; } + public override string OriginalFilename { get; } + public override string PrivateBuild { get; } + public override int ProductBuildPart { get; } + public override int ProductMajorPart { get; } + public override int ProductMinorPart { get; } + public override string ProductName { get; } + public override int ProductPrivatePart { get; } + public override string ProductVersion { get; } + public override string SpecialBuild { get; } + public override string ToString() { } + } + [System.Serializable] + public class MockFileVersionInfoFactory : System.IO.Abstractions.IFileSystemEntity, System.IO.Abstractions.IFileVersionInfoFactory + { + public MockFileVersionInfoFactory(System.IO.Abstractions.TestingHelpers.IMockFileDataAccessor mockFileSystem) { } + public System.IO.Abstractions.IFileSystem FileSystem { get; } + public System.IO.Abstractions.IFileVersionInfo GetVersionInfo(string fileName) { } + } + [System.Serializable] + public class MockPath : System.IO.Abstractions.PathWrapper + { + public MockPath(System.IO.Abstractions.TestingHelpers.IMockFileDataAccessor mockFileDataAccessor) { } + public MockPath(System.IO.Abstractions.TestingHelpers.IMockFileDataAccessor mockFileDataAccessor, string defaultTempDirectory) { } + public override string GetFullPath(string path) { } + public override string GetTempFileName() { } + public override string GetTempPath() { } + } + public static class MockUnixSupport + { + public static bool IsUnixPlatform() { } + public static bool IsWindowsPlatform() { } + public static string Path(string path) { } + } + [System.Serializable] + public class PathVerifier + { + public PathVerifier(System.IO.Abstractions.TestingHelpers.IMockFileDataAccessor mockFileDataAccessor) { } + public void CheckInvalidPathChars(string path, bool checkAdditional = false) { } + public bool HasIllegalCharacters(string path, bool checkAdditional) { } + public void IsLegalAbsoluteOrRelative(string path, string paramName) { } + public string NormalizeDriveName(string name) { } + public bool TryNormalizeDriveName(string name, out string result) { } + } + [System.Serializable] + public class StringOperations + { + public StringOperations(bool caseSensitive) { } + public System.StringComparer Comparer { get; } + public bool Contains(string s, string substring) { } + public bool EndsWith(string s, string suffix) { } + public bool Equals(char x, char y) { } + public bool Equals(string x, string y) { } + public int IndexOf(string s, string substring) { } + public int IndexOf(string s, string substring, int startIndex) { } + public string Replace(string s, string oldValue, string newValue) { } + public bool StartsWith(string s, string prefix) { } + public char ToLower(char c) { } + public string ToLower(string s) { } + public char ToUpper(char c) { } + public string ToUpper(string s) { } + } + [System.Flags] + public enum TimeAdjustments + { + None = 0, + CreationTime = 1, + LastAccessTime = 2, + LastWriteTime = 4, + All = -1, + } +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.Api.Tests/Expected/TestableIO.System.IO.Abstractions.TestingHelpers_netstandard2.1.txt b/tests/TestableIO.System.IO.Abstractions.Api.Tests/Expected/TestableIO.System.IO.Abstractions.TestingHelpers_netstandard2.1.txt new file mode 100644 index 000000000..0bf9bd3e7 --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.Api.Tests/Expected/TestableIO.System.IO.Abstractions.TestingHelpers_netstandard2.1.txt @@ -0,0 +1,540 @@ +[assembly: System.Reflection.AssemblyMetadata("RepositoryUrl", "https://github.com/TestableIO/System.IO.Abstractions.git")] +[assembly: System.Runtime.Versioning.TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName=".NET Standard 2.1")] +public class FileHandles +{ + public FileHandles() { } + public void AddHandle(string path, System.Guid guid, System.IO.FileAccess access, System.IO.FileShare share) { } + public void RemoveHandle(string path, System.Guid guid) { } +} +namespace System.IO.Abstractions.TestingHelpers +{ + public interface IMockFileDataAccessor : System.IO.Abstractions.IFileSystem + { + System.Collections.Generic.IEnumerable AllDirectories { get; } + System.Collections.Generic.IEnumerable AllDrives { get; } + System.Collections.Generic.IEnumerable AllFiles { get; } + System.Collections.Generic.IEnumerable AllPaths { get; } + FileHandles FileHandles { get; } + System.IO.Abstractions.IFileSystem FileSystem { get; } + System.IO.Abstractions.TestingHelpers.PathVerifier PathVerifier { get; } + System.IO.Abstractions.TestingHelpers.StringOperations StringOperations { get; } + void AddDirectory(string path); + void AddDrive(string name, System.IO.Abstractions.TestingHelpers.MockDriveData mockDrive); + void AddFile(string path, System.IO.Abstractions.TestingHelpers.MockFileData mockFile, bool verifyAccess = true); + void AddFileFromEmbeddedResource(string path, System.Reflection.Assembly resourceAssembly, string embeddedResourcePath); + void AddFilesFromEmbeddedNamespace(string path, System.Reflection.Assembly resourceAssembly, string embeddedResourcePath); + System.IO.Abstractions.TestingHelpers.MockFileData AdjustTimes(System.IO.Abstractions.TestingHelpers.MockFileData fileData, System.IO.Abstractions.TestingHelpers.TimeAdjustments timeAdjustments); + bool FileExists(string path); + System.IO.Abstractions.TestingHelpers.MockDriveData GetDrive(string name); + System.IO.Abstractions.TestingHelpers.MockFileData GetFile(string path); + void MoveDirectory(string sourcePath, string destPath); + void RemoveFile(string path, bool verifyAccess = true); + } + [System.Serializable] + public class MockDirectory : System.IO.Abstractions.DirectoryBase + { + public MockDirectory(System.IO.Abstractions.TestingHelpers.IMockFileDataAccessor mockFileDataAccessor, string currentDirectory) { } + public MockDirectory(System.IO.Abstractions.TestingHelpers.IMockFileDataAccessor mockFileDataAccessor, System.IO.Abstractions.FileBase fileBase, string currentDirectory) { } + public override System.IO.Abstractions.IDirectoryInfo CreateDirectory(string path) { } + public override void Delete(string path) { } + public override void Delete(string path, bool recursive) { } + public override System.Collections.Generic.IEnumerable EnumerateDirectories(string path) { } + public override System.Collections.Generic.IEnumerable EnumerateDirectories(string path, string searchPattern) { } + public override System.Collections.Generic.IEnumerable EnumerateDirectories(string path, string searchPattern, System.IO.EnumerationOptions enumerationOptions) { } + public override System.Collections.Generic.IEnumerable EnumerateDirectories(string path, string searchPattern, System.IO.SearchOption searchOption) { } + public override System.Collections.Generic.IEnumerable EnumerateFileSystemEntries(string path) { } + public override System.Collections.Generic.IEnumerable EnumerateFileSystemEntries(string path, string searchPattern) { } + public override System.Collections.Generic.IEnumerable EnumerateFileSystemEntries(string path, string searchPattern, System.IO.EnumerationOptions enumerationOptions) { } + public override System.Collections.Generic.IEnumerable EnumerateFileSystemEntries(string path, string searchPattern, System.IO.SearchOption searchOption) { } + public override System.Collections.Generic.IEnumerable EnumerateFiles(string path) { } + public override System.Collections.Generic.IEnumerable EnumerateFiles(string path, string searchPattern) { } + public override System.Collections.Generic.IEnumerable EnumerateFiles(string path, string searchPattern, System.IO.EnumerationOptions enumerationOptions) { } + public override System.Collections.Generic.IEnumerable EnumerateFiles(string path, string searchPattern, System.IO.SearchOption searchOption) { } + public override bool Exists(string path) { } + public override System.DateTime GetCreationTime(string path) { } + public override System.DateTime GetCreationTimeUtc(string path) { } + public override string GetCurrentDirectory() { } + public override string[] GetDirectories(string path) { } + public override string[] GetDirectories(string path, string searchPattern) { } + public override string[] GetDirectories(string path, string searchPattern, System.IO.EnumerationOptions enumerationOptions) { } + public override string[] GetDirectories(string path, string searchPattern, System.IO.SearchOption searchOption) { } + public override string GetDirectoryRoot(string path) { } + public override string[] GetFileSystemEntries(string path) { } + public override string[] GetFileSystemEntries(string path, string searchPattern) { } + public override string[] GetFileSystemEntries(string path, string searchPattern, System.IO.EnumerationOptions enumerationOptions) { } + public override string[] GetFileSystemEntries(string path, string searchPattern, System.IO.SearchOption searchOption) { } + public override string[] GetFiles(string path) { } + public override string[] GetFiles(string path, string searchPattern) { } + public override string[] GetFiles(string path, string searchPattern, System.IO.EnumerationOptions enumerationOptions) { } + public override string[] GetFiles(string path, string searchPattern, System.IO.SearchOption searchOption) { } + public override System.DateTime GetLastAccessTime(string path) { } + public override System.DateTime GetLastAccessTimeUtc(string path) { } + public override System.DateTime GetLastWriteTime(string path) { } + public override System.DateTime GetLastWriteTimeUtc(string path) { } + public override string[] GetLogicalDrives() { } + public override System.IO.Abstractions.IDirectoryInfo GetParent(string path) { } + public override void Move(string sourceDirName, string destDirName) { } + public override void SetCreationTime(string path, System.DateTime creationTime) { } + public override void SetCreationTimeUtc(string path, System.DateTime creationTimeUtc) { } + public override void SetCurrentDirectory(string path) { } + public override void SetLastAccessTime(string path, System.DateTime lastAccessTime) { } + public override void SetLastAccessTimeUtc(string path, System.DateTime lastAccessTimeUtc) { } + public override void SetLastWriteTime(string path, System.DateTime lastWriteTime) { } + public override void SetLastWriteTimeUtc(string path, System.DateTime lastWriteTimeUtc) { } + } + [System.Serializable] + public class MockDirectoryData : System.IO.Abstractions.TestingHelpers.MockFileData + { + public MockDirectoryData() { } + public new System.Security.AccessControl.DirectorySecurity AccessControl { get; set; } + } + [System.Serializable] + public class MockDirectoryInfo : System.IO.Abstractions.DirectoryInfoBase, System.IO.Abstractions.IFileSystemAclSupport + { + public MockDirectoryInfo(System.IO.Abstractions.TestingHelpers.IMockFileDataAccessor mockFileDataAccessor, string directoryPath) { } + public override System.IO.FileAttributes Attributes { get; set; } + public override System.DateTime CreationTime { get; set; } + public override System.DateTime CreationTimeUtc { get; set; } + public override bool Exists { get; } + public override string Extension { get; } + public override string FullName { get; } + public override System.DateTime LastAccessTime { get; set; } + public override System.DateTime LastAccessTimeUtc { get; set; } + public override System.DateTime LastWriteTime { get; set; } + public override System.DateTime LastWriteTimeUtc { get; set; } + public override string Name { get; } + public override System.IO.Abstractions.IDirectoryInfo Parent { get; } + public override System.IO.Abstractions.IDirectoryInfo Root { get; } + public override void Create() { } + public override System.IO.Abstractions.IDirectoryInfo CreateSubdirectory(string path) { } + public override void Delete() { } + public override void Delete(bool recursive) { } + public override System.Collections.Generic.IEnumerable EnumerateDirectories() { } + public override System.Collections.Generic.IEnumerable EnumerateDirectories(string searchPattern) { } + public override System.Collections.Generic.IEnumerable EnumerateDirectories(string searchPattern, System.IO.EnumerationOptions enumerationOptions) { } + public override System.Collections.Generic.IEnumerable EnumerateDirectories(string searchPattern, System.IO.SearchOption searchOption) { } + public override System.Collections.Generic.IEnumerable EnumerateFileSystemInfos() { } + public override System.Collections.Generic.IEnumerable EnumerateFileSystemInfos(string searchPattern) { } + public override System.Collections.Generic.IEnumerable EnumerateFileSystemInfos(string searchPattern, System.IO.EnumerationOptions enumerationOptions) { } + public override System.Collections.Generic.IEnumerable EnumerateFileSystemInfos(string searchPattern, System.IO.SearchOption searchOption) { } + public override System.Collections.Generic.IEnumerable EnumerateFiles() { } + public override System.Collections.Generic.IEnumerable EnumerateFiles(string searchPattern) { } + public override System.Collections.Generic.IEnumerable EnumerateFiles(string searchPattern, System.IO.EnumerationOptions enumerationOptions) { } + public override System.Collections.Generic.IEnumerable EnumerateFiles(string searchPattern, System.IO.SearchOption searchOption) { } + public object GetAccessControl() { } + public object GetAccessControl(System.IO.Abstractions.IFileSystemAclSupport.AccessControlSections includeSections) { } + public override System.IO.Abstractions.IDirectoryInfo[] GetDirectories() { } + public override System.IO.Abstractions.IDirectoryInfo[] GetDirectories(string searchPattern) { } + public override System.IO.Abstractions.IDirectoryInfo[] GetDirectories(string searchPattern, System.IO.EnumerationOptions enumerationOptions) { } + public override System.IO.Abstractions.IDirectoryInfo[] GetDirectories(string searchPattern, System.IO.SearchOption searchOption) { } + public override System.IO.Abstractions.IFileSystemInfo[] GetFileSystemInfos() { } + public override System.IO.Abstractions.IFileSystemInfo[] GetFileSystemInfos(string searchPattern) { } + public override System.IO.Abstractions.IFileSystemInfo[] GetFileSystemInfos(string searchPattern, System.IO.EnumerationOptions enumerationOptions) { } + public override System.IO.Abstractions.IFileSystemInfo[] GetFileSystemInfos(string searchPattern, System.IO.SearchOption searchOption) { } + public override System.IO.Abstractions.IFileInfo[] GetFiles() { } + public override System.IO.Abstractions.IFileInfo[] GetFiles(string searchPattern) { } + public override System.IO.Abstractions.IFileInfo[] GetFiles(string searchPattern, System.IO.EnumerationOptions enumerationOptions) { } + public override System.IO.Abstractions.IFileInfo[] GetFiles(string searchPattern, System.IO.SearchOption searchOption) { } + public override void MoveTo(string destDirName) { } + public override void Refresh() { } + public void SetAccessControl(object value) { } + public override string ToString() { } + } + [System.Serializable] + public class MockDirectoryInfoFactory : System.IO.Abstractions.IDirectoryInfoFactory, System.IO.Abstractions.IFileSystemEntity + { + public MockDirectoryInfoFactory(System.IO.Abstractions.TestingHelpers.IMockFileDataAccessor mockFileSystem) { } + public System.IO.Abstractions.IFileSystem FileSystem { get; } + public System.IO.Abstractions.IDirectoryInfo New(string path) { } + public System.IO.Abstractions.IDirectoryInfo Wrap(System.IO.DirectoryInfo directoryInfo) { } + } + [System.Serializable] + public class MockDriveData + { + public MockDriveData() { } + public MockDriveData(System.IO.Abstractions.TestingHelpers.MockDriveData template) { } + public long AvailableFreeSpace { get; set; } + public string DriveFormat { get; set; } + public System.IO.DriveType DriveType { get; set; } + public bool IsReady { get; set; } + public long TotalFreeSpace { get; set; } + public long TotalSize { get; set; } + public string VolumeLabel { get; set; } + } + [System.Serializable] + public class MockDriveInfo : System.IO.Abstractions.DriveInfoBase + { + public MockDriveInfo(System.IO.Abstractions.TestingHelpers.IMockFileDataAccessor mockFileDataAccessor, string name) { } + public override long AvailableFreeSpace { get; } + public override string DriveFormat { get; } + public override System.IO.DriveType DriveType { get; } + public override bool IsReady { get; } + public override string Name { get; } + public override System.IO.Abstractions.IDirectoryInfo RootDirectory { get; } + public override long TotalFreeSpace { get; } + public override long TotalSize { get; } + public override string VolumeLabel { get; set; } + public override string ToString() { } + } + [System.Serializable] + public class MockDriveInfoFactory : System.IO.Abstractions.IDriveInfoFactory, System.IO.Abstractions.IFileSystemEntity + { + public MockDriveInfoFactory(System.IO.Abstractions.TestingHelpers.IMockFileDataAccessor mockFileSystem) { } + public System.IO.Abstractions.IFileSystem FileSystem { get; } + public System.IO.Abstractions.IDriveInfo[] GetDrives() { } + public System.IO.Abstractions.IDriveInfo New(string driveName) { } + public System.IO.Abstractions.IDriveInfo Wrap(System.IO.DriveInfo driveInfo) { } + } + [System.Serializable] + public class MockFile : System.IO.Abstractions.FileBase + { + public MockFile(System.IO.Abstractions.TestingHelpers.IMockFileDataAccessor mockFileDataAccessor) { } + public override void AppendAllLines(string path, System.Collections.Generic.IEnumerable contents) { } + public override void AppendAllLines(string path, System.Collections.Generic.IEnumerable contents, System.Text.Encoding encoding) { } + public override System.Threading.Tasks.Task AppendAllLinesAsync(string path, System.Collections.Generic.IEnumerable contents, System.Threading.CancellationToken cancellationToken = default) { } + public override System.Threading.Tasks.Task AppendAllLinesAsync(string path, System.Collections.Generic.IEnumerable contents, System.Text.Encoding encoding, System.Threading.CancellationToken cancellationToken = default) { } + public override void AppendAllText(string path, string contents) { } + public override void AppendAllText(string path, string contents, System.Text.Encoding encoding) { } + public override System.Threading.Tasks.Task AppendAllTextAsync(string path, string contents, System.Threading.CancellationToken cancellationToken = default) { } + public override System.Threading.Tasks.Task AppendAllTextAsync(string path, string contents, System.Text.Encoding encoding, System.Threading.CancellationToken cancellationToken = default) { } + public override System.IO.StreamWriter AppendText(string path) { } + public override void Copy(string sourceFileName, string destFileName) { } + public override void Copy(string sourceFileName, string destFileName, bool overwrite) { } + public override System.IO.Abstractions.FileSystemStream Create(string path) { } + public override System.IO.Abstractions.FileSystemStream Create(string path, int bufferSize) { } + public override System.IO.Abstractions.FileSystemStream Create(string path, int bufferSize, System.IO.FileOptions options) { } + public override System.IO.StreamWriter CreateText(string path) { } + public override void Decrypt(string path) { } + public override void Delete(string path) { } + public override void Encrypt(string path) { } + public override bool Exists(string path) { } + public override System.IO.FileAttributes GetAttributes(string path) { } + public override System.DateTime GetCreationTime(string path) { } + public override System.DateTime GetCreationTimeUtc(string path) { } + public override System.DateTime GetLastAccessTime(string path) { } + public override System.DateTime GetLastAccessTimeUtc(string path) { } + public override System.DateTime GetLastWriteTime(string path) { } + public override System.DateTime GetLastWriteTimeUtc(string path) { } + public override void Move(string sourceFileName, string destFileName) { } + public override System.IO.Abstractions.FileSystemStream Open(string path, System.IO.FileMode mode) { } + public override System.IO.Abstractions.FileSystemStream Open(string path, System.IO.FileMode mode, System.IO.FileAccess access) { } + public override System.IO.Abstractions.FileSystemStream Open(string path, System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share) { } + public override System.IO.Abstractions.FileSystemStream OpenRead(string path) { } + public override System.IO.StreamReader OpenText(string path) { } + public override System.IO.Abstractions.FileSystemStream OpenWrite(string path) { } + public override byte[] ReadAllBytes(string path) { } + public override System.Threading.Tasks.Task ReadAllBytesAsync(string path, System.Threading.CancellationToken cancellationToken = default) { } + public override string[] ReadAllLines(string path) { } + public override string[] ReadAllLines(string path, System.Text.Encoding encoding) { } + public override System.Threading.Tasks.Task ReadAllLinesAsync(string path, System.Threading.CancellationToken cancellationToken = default) { } + public override System.Threading.Tasks.Task ReadAllLinesAsync(string path, System.Text.Encoding encoding, System.Threading.CancellationToken cancellationToken = default) { } + public override string ReadAllText(string path) { } + public override string ReadAllText(string path, System.Text.Encoding encoding) { } + public override System.Threading.Tasks.Task ReadAllTextAsync(string path, System.Threading.CancellationToken cancellationToken = default) { } + public override System.Threading.Tasks.Task ReadAllTextAsync(string path, System.Text.Encoding encoding, System.Threading.CancellationToken cancellationToken = default) { } + public override System.Collections.Generic.IEnumerable ReadLines(string path) { } + public override System.Collections.Generic.IEnumerable ReadLines(string path, System.Text.Encoding encoding) { } + public override void Replace(string sourceFileName, string destinationFileName, string destinationBackupFileName) { } + public override void Replace(string sourceFileName, string destinationFileName, string destinationBackupFileName, bool ignoreMetadataErrors) { } + public override void SetAttributes(string path, System.IO.FileAttributes fileAttributes) { } + public override void SetCreationTime(string path, System.DateTime creationTime) { } + public override void SetCreationTimeUtc(string path, System.DateTime creationTimeUtc) { } + public override void SetLastAccessTime(string path, System.DateTime lastAccessTime) { } + public override void SetLastAccessTimeUtc(string path, System.DateTime lastAccessTimeUtc) { } + public override void SetLastWriteTime(string path, System.DateTime lastWriteTime) { } + public override void SetLastWriteTimeUtc(string path, System.DateTime lastWriteTimeUtc) { } + public override void WriteAllBytes(string path, byte[] bytes) { } + public override System.Threading.Tasks.Task WriteAllBytesAsync(string path, byte[] bytes, System.Threading.CancellationToken cancellationToken = default) { } + public override void WriteAllLines(string path, System.Collections.Generic.IEnumerable contents) { } + public override void WriteAllLines(string path, string[] contents) { } + public override void WriteAllLines(string path, System.Collections.Generic.IEnumerable contents, System.Text.Encoding encoding) { } + public override void WriteAllLines(string path, string[] contents, System.Text.Encoding encoding) { } + public override System.Threading.Tasks.Task WriteAllLinesAsync(string path, System.Collections.Generic.IEnumerable contents, System.Threading.CancellationToken cancellationToken = default) { } + public override System.Threading.Tasks.Task WriteAllLinesAsync(string path, System.Collections.Generic.IEnumerable contents, System.Text.Encoding encoding, System.Threading.CancellationToken cancellationToken = default) { } + public override void WriteAllText(string path, string contents) { } + public override void WriteAllText(string path, string contents, System.Text.Encoding encoding) { } + public override System.Threading.Tasks.Task WriteAllTextAsync(string path, string contents, System.Threading.CancellationToken cancellationToken = default) { } + public override System.Threading.Tasks.Task WriteAllTextAsync(string path, string contents, System.Text.Encoding encoding, System.Threading.CancellationToken cancellationToken = default) { } + } + [System.Serializable] + public class MockFileData + { + public static readonly System.DateTimeOffset DefaultDateTimeOffset; + public static readonly System.Text.Encoding DefaultEncoding; + public MockFileData(System.IO.Abstractions.TestingHelpers.MockFileData template) { } + public MockFileData(byte[] contents) { } + public MockFileData(string textContents) { } + public MockFileData(string textContents, System.Text.Encoding encoding) { } + public System.Security.AccessControl.FileSecurity AccessControl { get; set; } + public System.IO.FileShare AllowedFileShare { get; set; } + public System.IO.FileAttributes Attributes { get; set; } + public byte[] Contents { get; set; } + public System.DateTimeOffset CreationTime { get; set; } + public System.IO.Abstractions.IFileVersionInfo FileVersionInfo { get; set; } + public bool IsDirectory { get; } + public System.DateTimeOffset LastAccessTime { get; set; } + public System.DateTimeOffset LastWriteTime { get; set; } + public string TextContents { get; set; } + public static System.IO.Abstractions.TestingHelpers.MockFileData op_Implicit(string s) { } + } + [System.Serializable] + public class MockFileInfo : System.IO.Abstractions.FileInfoBase, System.IO.Abstractions.IFileSystemAclSupport + { + public MockFileInfo(System.IO.Abstractions.TestingHelpers.IMockFileDataAccessor mockFileSystem, string path) { } + public override System.IO.FileAttributes Attributes { get; set; } + public override System.DateTime CreationTime { get; set; } + public override System.DateTime CreationTimeUtc { get; set; } + public override System.IO.Abstractions.IDirectoryInfo Directory { get; } + public override string DirectoryName { get; } + public override bool Exists { get; } + public override string Extension { get; } + public override string FullName { get; } + public override bool IsReadOnly { get; set; } + public override System.DateTime LastAccessTime { get; set; } + public override System.DateTime LastAccessTimeUtc { get; set; } + public override System.DateTime LastWriteTime { get; set; } + public override System.DateTime LastWriteTimeUtc { get; set; } + public override long Length { get; } + public override string Name { get; } + public override System.IO.StreamWriter AppendText() { } + public override System.IO.Abstractions.IFileInfo CopyTo(string destFileName) { } + public override System.IO.Abstractions.IFileInfo CopyTo(string destFileName, bool overwrite) { } + public override System.IO.Abstractions.FileSystemStream Create() { } + public override System.IO.StreamWriter CreateText() { } + public override void Decrypt() { } + public override void Delete() { } + public override void Encrypt() { } + public object GetAccessControl() { } + public object GetAccessControl(System.IO.Abstractions.IFileSystemAclSupport.AccessControlSections includeSections) { } + public override void MoveTo(string destFileName) { } + public override System.IO.Abstractions.FileSystemStream Open(System.IO.FileMode mode) { } + public override System.IO.Abstractions.FileSystemStream Open(System.IO.FileMode mode, System.IO.FileAccess access) { } + public override System.IO.Abstractions.FileSystemStream Open(System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share) { } + public override System.IO.Abstractions.FileSystemStream OpenRead() { } + public override System.IO.StreamReader OpenText() { } + public override System.IO.Abstractions.FileSystemStream OpenWrite() { } + public override void Refresh() { } + public override System.IO.Abstractions.IFileInfo Replace(string destinationFileName, string destinationBackupFileName) { } + public override System.IO.Abstractions.IFileInfo Replace(string destinationFileName, string destinationBackupFileName, bool ignoreMetadataErrors) { } + public void SetAccessControl(object value) { } + public override string ToString() { } + } + [System.Serializable] + public class MockFileInfoFactory : System.IO.Abstractions.IFileInfoFactory, System.IO.Abstractions.IFileSystemEntity + { + public MockFileInfoFactory(System.IO.Abstractions.TestingHelpers.IMockFileDataAccessor mockFileSystem) { } + public System.IO.Abstractions.IFileSystem FileSystem { get; } + public System.IO.Abstractions.IFileInfo New(string fileName) { } + public System.IO.Abstractions.IFileInfo Wrap(System.IO.FileInfo fileInfo) { } + } + [System.Serializable] + public class MockFileStream : System.IO.Abstractions.FileSystemStream, System.IO.Abstractions.IFileSystemAclSupport + { + public MockFileStream(System.IO.Abstractions.TestingHelpers.IMockFileDataAccessor mockFileDataAccessor, string path, System.IO.FileMode mode, System.IO.FileAccess access = 3, System.IO.FileShare share = 1, System.IO.FileOptions options = 0) { } + public override bool CanRead { get; } + public override bool CanWrite { get; } + public static System.IO.Abstractions.FileSystemStream Null { get; } + protected override void Dispose(bool disposing) { } + public override void EndWrite(System.IAsyncResult asyncResult) { } + public override void Flush() { } + public override void Flush(bool flushToDisk) { } + public override System.Threading.Tasks.Task FlushAsync(System.Threading.CancellationToken cancellationToken) { } + public object GetAccessControl() { } + public object GetAccessControl(System.IO.Abstractions.IFileSystemAclSupport.AccessControlSections includeSections) { } + public override int Read(byte[] buffer, int offset, int count) { } + public void SetAccessControl(object value) { } + public override void SetLength(long value) { } + public override void Write(System.ReadOnlySpan buffer) { } + public override void Write(byte[] buffer, int offset, int count) { } + public override System.Threading.Tasks.ValueTask WriteAsync(System.ReadOnlyMemory buffer, System.Threading.CancellationToken cancellationToken = default) { } + public override System.Threading.Tasks.Task WriteAsync(byte[] buffer, int offset, int count, System.Threading.CancellationToken cancellationToken) { } + public override void WriteByte(byte value) { } + } + [System.Serializable] + public class MockFileStreamFactory : System.IO.Abstractions.IFileStreamFactory, System.IO.Abstractions.IFileSystemEntity + { + public MockFileStreamFactory(System.IO.Abstractions.TestingHelpers.IMockFileDataAccessor mockFileSystem) { } + public System.IO.Abstractions.IFileSystem FileSystem { get; } + public System.IO.Abstractions.FileSystemStream New(Microsoft.Win32.SafeHandles.SafeFileHandle handle, System.IO.FileAccess access) { } + public System.IO.Abstractions.FileSystemStream New(string path, System.IO.FileMode mode) { } + public System.IO.Abstractions.FileSystemStream New(Microsoft.Win32.SafeHandles.SafeFileHandle handle, System.IO.FileAccess access, int bufferSize) { } + public System.IO.Abstractions.FileSystemStream New(string path, System.IO.FileMode mode, System.IO.FileAccess access) { } + public System.IO.Abstractions.FileSystemStream New(Microsoft.Win32.SafeHandles.SafeFileHandle handle, System.IO.FileAccess access, int bufferSize, bool isAsync) { } + public System.IO.Abstractions.FileSystemStream New(string path, System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share) { } + public System.IO.Abstractions.FileSystemStream New(string path, System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share, int bufferSize) { } + public System.IO.Abstractions.FileSystemStream New(string path, System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share, int bufferSize, System.IO.FileOptions options) { } + public System.IO.Abstractions.FileSystemStream New(string path, System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share, int bufferSize, bool useAsync) { } + public System.IO.Abstractions.FileSystemStream Wrap(System.IO.FileStream fileStream) { } + } + [System.Serializable] + public class MockFileSystem : System.IO.Abstractions.FileSystemBase, System.IO.Abstractions.IFileSystem, System.IO.Abstractions.TestingHelpers.IMockFileDataAccessor + { + public MockFileSystem() { } + public MockFileSystem(System.IO.Abstractions.TestingHelpers.MockFileSystemOptions options) { } + public MockFileSystem(System.Collections.Generic.IDictionary files, System.IO.Abstractions.TestingHelpers.MockFileSystemOptions options) { } + public MockFileSystem(System.Collections.Generic.IDictionary files, string currentDirectory = "") { } + public System.Collections.Generic.IEnumerable AllDirectories { get; } + public System.Collections.Generic.IEnumerable AllDrives { get; } + public System.Collections.Generic.IEnumerable AllFiles { get; } + public System.Collections.Generic.IEnumerable AllNodes { get; } + public System.Collections.Generic.IEnumerable AllPaths { get; } + public override System.IO.Abstractions.IDirectory Directory { get; } + public override System.IO.Abstractions.IDirectoryInfoFactory DirectoryInfo { get; } + public override System.IO.Abstractions.IDriveInfoFactory DriveInfo { get; } + public override System.IO.Abstractions.IFile File { get; } + public FileHandles FileHandles { get; } + public override System.IO.Abstractions.IFileInfoFactory FileInfo { get; } + public override System.IO.Abstractions.IFileStreamFactory FileStream { get; } + public System.IO.Abstractions.IFileSystem FileSystem { get; } + public override System.IO.Abstractions.IFileSystemWatcherFactory FileSystemWatcher { get; } + public override System.IO.Abstractions.IFileVersionInfoFactory FileVersionInfo { get; } + public override System.IO.Abstractions.IPath Path { get; } + public System.IO.Abstractions.TestingHelpers.PathVerifier PathVerifier { get; } + public System.IO.Abstractions.TestingHelpers.StringOperations StringOperations { get; } + public void AddDirectory(System.IO.Abstractions.IDirectoryInfo path) { } + public void AddDirectory(string path) { } + public void AddDrive(string name, System.IO.Abstractions.TestingHelpers.MockDriveData mockDrive) { } + public void AddEmptyFile(System.IO.Abstractions.IFileInfo path) { } + public void AddEmptyFile(string path) { } + public void AddFile(System.IO.Abstractions.IFileInfo path, System.IO.Abstractions.TestingHelpers.MockFileData data, bool verifyAccess = true) { } + public void AddFile(string path, System.IO.Abstractions.TestingHelpers.MockFileData mockFile, bool verifyAccess = true) { } + public void AddFileFromEmbeddedResource(string path, System.Reflection.Assembly resourceAssembly, string embeddedResourcePath) { } + public void AddFilesFromEmbeddedNamespace(string path, System.Reflection.Assembly resourceAssembly, string embeddedResourcePath) { } + public System.IO.Abstractions.TestingHelpers.MockFileData AdjustTimes(System.IO.Abstractions.TestingHelpers.MockFileData fileData, System.IO.Abstractions.TestingHelpers.TimeAdjustments timeAdjustments) { } + public bool FileExists(string path) { } + public System.IO.Abstractions.TestingHelpers.MockDriveData GetDrive(string name) { } + public System.IO.Abstractions.TestingHelpers.MockFileData GetFile(System.IO.Abstractions.IFileInfo path) { } + public System.IO.Abstractions.TestingHelpers.MockFileData GetFile(string path) { } + public System.IO.Abstractions.TestingHelpers.MockFileSystem MockTime(System.Func dateTimeProvider) { } + public void MoveDirectory(string sourcePath, string destPath) { } + public void RemoveFile(string path, bool verifyAccess = true) { } + } + public class MockFileSystemOptions + { + public MockFileSystemOptions() { } + public bool CreateDefaultTempDir { get; init; } + public string CurrentDirectory { get; init; } + } + [System.Serializable] + public class MockFileSystemWatcherFactory : System.IO.Abstractions.IFileSystemEntity, System.IO.Abstractions.IFileSystemWatcherFactory + { + public MockFileSystemWatcherFactory(System.IO.Abstractions.TestingHelpers.MockFileSystem mockFileSystem) { } + public System.IO.Abstractions.IFileSystem FileSystem { get; } + public System.IO.Abstractions.IFileSystemWatcher New() { } + public System.IO.Abstractions.IFileSystemWatcher New(string path) { } + public System.IO.Abstractions.IFileSystemWatcher New(string path, string filter) { } + public System.IO.Abstractions.IFileSystemWatcher Wrap(System.IO.FileSystemWatcher fileSystemWatcher) { } + } + [System.Serializable] + public class MockFileVersionInfo : System.IO.Abstractions.FileVersionInfoBase + { + public MockFileVersionInfo( + string fileName, + string fileVersion = null, + string productVersion = null, + string fileDescription = null, + string productName = null, + string companyName = null, + string comments = null, + string internalName = null, + bool isDebug = false, + bool isPatched = false, + bool isPrivateBuild = false, + bool isPreRelease = false, + bool isSpecialBuild = false, + string language = null, + string legalCopyright = null, + string legalTrademarks = null, + string originalFilename = null, + string privateBuild = null, + string specialBuild = null) { } + public override string Comments { get; } + public override string CompanyName { get; } + public override int FileBuildPart { get; } + public override string FileDescription { get; } + public override int FileMajorPart { get; } + public override int FileMinorPart { get; } + public override string FileName { get; } + public override int FilePrivatePart { get; } + public override string FileVersion { get; } + public override string InternalName { get; } + public override bool IsDebug { get; } + public override bool IsPatched { get; } + public override bool IsPreRelease { get; } + public override bool IsPrivateBuild { get; } + public override bool IsSpecialBuild { get; } + public override string Language { get; } + public override string LegalCopyright { get; } + public override string LegalTrademarks { get; } + public override string OriginalFilename { get; } + public override string PrivateBuild { get; } + public override int ProductBuildPart { get; } + public override int ProductMajorPart { get; } + public override int ProductMinorPart { get; } + public override string ProductName { get; } + public override int ProductPrivatePart { get; } + public override string ProductVersion { get; } + public override string SpecialBuild { get; } + public override string ToString() { } + } + [System.Serializable] + public class MockFileVersionInfoFactory : System.IO.Abstractions.IFileSystemEntity, System.IO.Abstractions.IFileVersionInfoFactory + { + public MockFileVersionInfoFactory(System.IO.Abstractions.TestingHelpers.IMockFileDataAccessor mockFileSystem) { } + public System.IO.Abstractions.IFileSystem FileSystem { get; } + public System.IO.Abstractions.IFileVersionInfo GetVersionInfo(string fileName) { } + } + [System.Serializable] + public class MockPath : System.IO.Abstractions.PathWrapper + { + public MockPath(System.IO.Abstractions.TestingHelpers.IMockFileDataAccessor mockFileDataAccessor) { } + public MockPath(System.IO.Abstractions.TestingHelpers.IMockFileDataAccessor mockFileDataAccessor, string defaultTempDirectory) { } + public override string GetFullPath(string path) { } + public override string GetRelativePath(string relativeTo, string path) { } + public override string GetTempFileName() { } + public override string GetTempPath() { } + } + public static class MockUnixSupport + { + public static bool IsUnixPlatform() { } + public static bool IsWindowsPlatform() { } + public static string Path(string path) { } + } + [System.Serializable] + public class PathVerifier + { + public PathVerifier(System.IO.Abstractions.TestingHelpers.IMockFileDataAccessor mockFileDataAccessor) { } + public void CheckInvalidPathChars(string path, bool checkAdditional = false) { } + public bool HasIllegalCharacters(string path, bool checkAdditional) { } + public void IsLegalAbsoluteOrRelative(string path, string paramName) { } + public string NormalizeDriveName(string name) { } + public bool TryNormalizeDriveName(string name, out string result) { } + } + [System.Serializable] + public class StringOperations + { + public StringOperations(bool caseSensitive) { } + public System.StringComparer Comparer { get; } + public bool Contains(string s, string substring) { } + public bool EndsWith(string s, string suffix) { } + public bool Equals(char x, char y) { } + public bool Equals(string x, string y) { } + public int IndexOf(string s, string substring) { } + public int IndexOf(string s, string substring, int startIndex) { } + public string Replace(string s, string oldValue, string newValue) { } + public bool StartsWith(string s, string prefix) { } + public char ToLower(char c) { } + public string ToLower(string s) { } + public char ToUpper(char c) { } + public string ToUpper(string s) { } + } + [System.Flags] + public enum TimeAdjustments + { + None = 0, + CreationTime = 1, + LastAccessTime = 2, + LastWriteTime = 4, + All = -1, + } +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.Api.Tests/Expected/TestableIO.System.IO.Abstractions.Wrappers_net10.0.txt b/tests/TestableIO.System.IO.Abstractions.Api.Tests/Expected/TestableIO.System.IO.Abstractions.Wrappers_net10.0.txt new file mode 100644 index 000000000..40e2a149c --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.Api.Tests/Expected/TestableIO.System.IO.Abstractions.Wrappers_net10.0.txt @@ -0,0 +1,898 @@ +[assembly: System.CLSCompliant(true)] +[assembly: System.Reflection.AssemblyMetadata("RepositoryUrl", "https://github.com/TestableIO/System.IO.Abstractions.git")] +[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(@"DynamicProxyGenAssembly2, PublicKey=0024000004800000940000000602000000240000525341310004000001000100c547cac37abd99c8db225ef2f6c8a3602f3b3606cc9891605d02baa56104f4cfc0734aa39b93bf7852f7d9266654753cc297e7d2edfe0bac1cdcf9f717241550e0a7b191195b7667bb4f64bcb8e2121380fd1d9d46ad2d92d2d15605093924cceaf74c4861eff62abf69b9291ed0a340e113be11e6a7d3113e92484cf7045cc7")] +[assembly: System.Runtime.Versioning.TargetFramework(".NETCoreApp,Version=v10.0", FrameworkDisplayName=".NET 10.0")] +namespace System.IO.Abstractions +{ + public static class DirectoryAclExtensions + { + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public static void CreateDirectory(this System.IO.Abstractions.IDirectory directory, string path, System.Security.AccessControl.DirectorySecurity directorySecurity) { } + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public static System.Security.AccessControl.DirectorySecurity GetAccessControl(this System.IO.Abstractions.IDirectory directory, string path) { } + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public static System.Security.AccessControl.DirectorySecurity GetAccessControl(this System.IO.Abstractions.IDirectory directory, string path, System.Security.AccessControl.AccessControlSections includeSections) { } + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public static void SetAccessControl(this System.IO.Abstractions.IDirectory directory, string path, System.Security.AccessControl.DirectorySecurity directorySecurity) { } + } + [System.Serializable] + public abstract class DirectoryBase : System.IO.Abstractions.IDirectory, System.IO.Abstractions.IFileSystemEntity + { + protected DirectoryBase(System.IO.Abstractions.IFileSystem fileSystem) { } + public System.IO.Abstractions.IFileSystem FileSystem { get; } + public abstract System.IO.Abstractions.IDirectoryInfo CreateDirectory(string path); + public abstract System.IO.Abstractions.IDirectoryInfo CreateDirectory(string path, System.IO.UnixFileMode unixCreateMode); + public abstract System.IO.Abstractions.IFileSystemInfo CreateSymbolicLink(string path, string pathToTarget); + public abstract System.IO.Abstractions.IDirectoryInfo CreateTempSubdirectory(string prefix = null); + public abstract void Delete(string path); + public abstract void Delete(string path, bool recursive); + public abstract System.Collections.Generic.IEnumerable EnumerateDirectories(string path); + public abstract System.Collections.Generic.IEnumerable EnumerateDirectories(string path, string searchPattern); + public abstract System.Collections.Generic.IEnumerable EnumerateDirectories(string path, string searchPattern, System.IO.EnumerationOptions enumerationOptions); + public abstract System.Collections.Generic.IEnumerable EnumerateDirectories(string path, string searchPattern, System.IO.SearchOption searchOption); + public abstract System.Collections.Generic.IEnumerable EnumerateFileSystemEntries(string path); + public abstract System.Collections.Generic.IEnumerable EnumerateFileSystemEntries(string path, string searchPattern); + public abstract System.Collections.Generic.IEnumerable EnumerateFileSystemEntries(string path, string searchPattern, System.IO.EnumerationOptions enumerationOptions); + public abstract System.Collections.Generic.IEnumerable EnumerateFileSystemEntries(string path, string searchPattern, System.IO.SearchOption searchOption); + public abstract System.Collections.Generic.IEnumerable EnumerateFiles(string path); + public abstract System.Collections.Generic.IEnumerable EnumerateFiles(string path, string searchPattern); + public abstract System.Collections.Generic.IEnumerable EnumerateFiles(string path, string searchPattern, System.IO.EnumerationOptions enumerationOptions); + public abstract System.Collections.Generic.IEnumerable EnumerateFiles(string path, string searchPattern, System.IO.SearchOption searchOption); + public abstract bool Exists(string path); + public abstract System.DateTime GetCreationTime(string path); + public abstract System.DateTime GetCreationTimeUtc(string path); + public abstract string GetCurrentDirectory(); + public abstract string[] GetDirectories(string path); + public abstract string[] GetDirectories(string path, string searchPattern); + public abstract string[] GetDirectories(string path, string searchPattern, System.IO.EnumerationOptions enumerationOptions); + public abstract string[] GetDirectories(string path, string searchPattern, System.IO.SearchOption searchOption); + public abstract string GetDirectoryRoot(string path); + public abstract string[] GetFileSystemEntries(string path); + public abstract string[] GetFileSystemEntries(string path, string searchPattern); + public abstract string[] GetFileSystemEntries(string path, string searchPattern, System.IO.EnumerationOptions enumerationOptions); + public abstract string[] GetFileSystemEntries(string path, string searchPattern, System.IO.SearchOption searchOption); + public abstract string[] GetFiles(string path); + public abstract string[] GetFiles(string path, string searchPattern); + public abstract string[] GetFiles(string path, string searchPattern, System.IO.EnumerationOptions enumerationOptions); + public abstract string[] GetFiles(string path, string searchPattern, System.IO.SearchOption searchOption); + public abstract System.DateTime GetLastAccessTime(string path); + public abstract System.DateTime GetLastAccessTimeUtc(string path); + public abstract System.DateTime GetLastWriteTime(string path); + public abstract System.DateTime GetLastWriteTimeUtc(string path); + public abstract string[] GetLogicalDrives(); + public abstract System.IO.Abstractions.IDirectoryInfo GetParent(string path); + public abstract void Move(string sourceDirName, string destDirName); + public abstract System.IO.Abstractions.IFileSystemInfo ResolveLinkTarget(string linkPath, bool returnFinalTarget); + public abstract void SetCreationTime(string path, System.DateTime creationTime); + public abstract void SetCreationTimeUtc(string path, System.DateTime creationTimeUtc); + public abstract void SetCurrentDirectory(string path); + public abstract void SetLastAccessTime(string path, System.DateTime lastAccessTime); + public abstract void SetLastAccessTimeUtc(string path, System.DateTime lastAccessTimeUtc); + public abstract void SetLastWriteTime(string path, System.DateTime lastWriteTime); + public abstract void SetLastWriteTimeUtc(string path, System.DateTime lastWriteTimeUtc); + } + public static class DirectoryInfoAclExtensions + { + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public static void Create(this System.IO.Abstractions.IDirectoryInfo directoryInfo, System.Security.AccessControl.DirectorySecurity directorySecurity) { } + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public static System.Security.AccessControl.DirectorySecurity GetAccessControl(this System.IO.Abstractions.IDirectoryInfo directoryInfo) { } + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public static System.Security.AccessControl.DirectorySecurity GetAccessControl(this System.IO.Abstractions.IDirectoryInfo directoryInfo, System.Security.AccessControl.AccessControlSections includeSections) { } + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public static void SetAccessControl(this System.IO.Abstractions.IDirectoryInfo directoryInfo, System.Security.AccessControl.DirectorySecurity directorySecurity) { } + } + [System.Serializable] + public abstract class DirectoryInfoBase : System.IO.Abstractions.FileSystemInfoBase, System.IO.Abstractions.IDirectoryInfo, System.IO.Abstractions.IFileSystemInfo + { + protected DirectoryInfoBase(System.IO.Abstractions.IFileSystem fileSystem) { } + public abstract System.IO.Abstractions.IDirectoryInfo Parent { get; } + public abstract System.IO.Abstractions.IDirectoryInfo Root { get; } + public abstract void Create(); + public abstract System.IO.Abstractions.IDirectoryInfo CreateSubdirectory(string path); + public abstract void Delete(bool recursive); + public abstract System.Collections.Generic.IEnumerable EnumerateDirectories(); + public abstract System.Collections.Generic.IEnumerable EnumerateDirectories(string searchPattern); + public abstract System.Collections.Generic.IEnumerable EnumerateDirectories(string searchPattern, System.IO.EnumerationOptions enumerationOptions); + public abstract System.Collections.Generic.IEnumerable EnumerateDirectories(string searchPattern, System.IO.SearchOption searchOption); + public abstract System.Collections.Generic.IEnumerable EnumerateFileSystemInfos(); + public abstract System.Collections.Generic.IEnumerable EnumerateFileSystemInfos(string searchPattern); + public abstract System.Collections.Generic.IEnumerable EnumerateFileSystemInfos(string searchPattern, System.IO.EnumerationOptions enumerationOptions); + public abstract System.Collections.Generic.IEnumerable EnumerateFileSystemInfos(string searchPattern, System.IO.SearchOption searchOption); + public abstract System.Collections.Generic.IEnumerable EnumerateFiles(); + public abstract System.Collections.Generic.IEnumerable EnumerateFiles(string searchPattern); + public abstract System.Collections.Generic.IEnumerable EnumerateFiles(string searchPattern, System.IO.EnumerationOptions enumerationOptions); + public abstract System.Collections.Generic.IEnumerable EnumerateFiles(string searchPattern, System.IO.SearchOption searchOption); + public abstract System.IO.Abstractions.IDirectoryInfo[] GetDirectories(); + public abstract System.IO.Abstractions.IDirectoryInfo[] GetDirectories(string searchPattern); + public abstract System.IO.Abstractions.IDirectoryInfo[] GetDirectories(string searchPattern, System.IO.EnumerationOptions enumerationOptions); + public abstract System.IO.Abstractions.IDirectoryInfo[] GetDirectories(string searchPattern, System.IO.SearchOption searchOption); + public abstract System.IO.Abstractions.IFileSystemInfo[] GetFileSystemInfos(); + public abstract System.IO.Abstractions.IFileSystemInfo[] GetFileSystemInfos(string searchPattern); + public abstract System.IO.Abstractions.IFileSystemInfo[] GetFileSystemInfos(string searchPattern, System.IO.EnumerationOptions enumerationOptions); + public abstract System.IO.Abstractions.IFileSystemInfo[] GetFileSystemInfos(string searchPattern, System.IO.SearchOption searchOption); + public abstract System.IO.Abstractions.IFileInfo[] GetFiles(); + public abstract System.IO.Abstractions.IFileInfo[] GetFiles(string searchPattern); + public abstract System.IO.Abstractions.IFileInfo[] GetFiles(string searchPattern, System.IO.EnumerationOptions enumerationOptions); + public abstract System.IO.Abstractions.IFileInfo[] GetFiles(string searchPattern, System.IO.SearchOption searchOption); + public abstract void MoveTo(string destDirName); + public static System.IO.Abstractions.DirectoryInfoBase op_Implicit(System.IO.DirectoryInfo directoryInfo) { } + } + [System.Serializable] + public class DirectoryInfoWrapper : System.IO.Abstractions.DirectoryInfoBase, System.IO.Abstractions.IFileSystemAclSupport + { + public DirectoryInfoWrapper(System.IO.Abstractions.IFileSystem fileSystem, System.IO.DirectoryInfo instance) { } + public override System.IO.FileAttributes Attributes { get; set; } + public override System.DateTime CreationTime { get; set; } + public override System.DateTime CreationTimeUtc { get; set; } + public override bool Exists { get; } + public override string Extension { get; } + public override string FullName { get; } + public override System.DateTime LastAccessTime { get; set; } + public override System.DateTime LastAccessTimeUtc { get; set; } + public override System.DateTime LastWriteTime { get; set; } + public override System.DateTime LastWriteTimeUtc { get; set; } + public override string LinkTarget { get; } + public override string Name { get; } + public override System.IO.Abstractions.IDirectoryInfo Parent { get; } + public override System.IO.Abstractions.IDirectoryInfo Root { get; } + public override void Create() { } + public override void CreateAsSymbolicLink(string pathToTarget) { } + public override System.IO.Abstractions.IDirectoryInfo CreateSubdirectory(string path) { } + public override void Delete() { } + public override void Delete(bool recursive) { } + public override System.Collections.Generic.IEnumerable EnumerateDirectories() { } + public override System.Collections.Generic.IEnumerable EnumerateDirectories(string searchPattern) { } + public override System.Collections.Generic.IEnumerable EnumerateDirectories(string searchPattern, System.IO.EnumerationOptions enumerationOptions) { } + public override System.Collections.Generic.IEnumerable EnumerateDirectories(string searchPattern, System.IO.SearchOption searchOption) { } + public override System.Collections.Generic.IEnumerable EnumerateFileSystemInfos() { } + public override System.Collections.Generic.IEnumerable EnumerateFileSystemInfos(string searchPattern) { } + public override System.Collections.Generic.IEnumerable EnumerateFileSystemInfos(string searchPattern, System.IO.EnumerationOptions enumerationOptions) { } + public override System.Collections.Generic.IEnumerable EnumerateFileSystemInfos(string searchPattern, System.IO.SearchOption searchOption) { } + public override System.Collections.Generic.IEnumerable EnumerateFiles() { } + public override System.Collections.Generic.IEnumerable EnumerateFiles(string searchPattern) { } + public override System.Collections.Generic.IEnumerable EnumerateFiles(string searchPattern, System.IO.EnumerationOptions enumerationOptions) { } + public override System.Collections.Generic.IEnumerable EnumerateFiles(string searchPattern, System.IO.SearchOption searchOption) { } + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public object GetAccessControl() { } + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public object GetAccessControl(System.IO.Abstractions.IFileSystemAclSupport.AccessControlSections includeSections) { } + public override System.IO.Abstractions.IDirectoryInfo[] GetDirectories() { } + public override System.IO.Abstractions.IDirectoryInfo[] GetDirectories(string searchPattern) { } + public override System.IO.Abstractions.IDirectoryInfo[] GetDirectories(string searchPattern, System.IO.EnumerationOptions enumerationOptions) { } + public override System.IO.Abstractions.IDirectoryInfo[] GetDirectories(string searchPattern, System.IO.SearchOption searchOption) { } + public override System.IO.Abstractions.IFileSystemInfo[] GetFileSystemInfos() { } + public override System.IO.Abstractions.IFileSystemInfo[] GetFileSystemInfos(string searchPattern) { } + public override System.IO.Abstractions.IFileSystemInfo[] GetFileSystemInfos(string searchPattern, System.IO.EnumerationOptions enumerationOptions) { } + public override System.IO.Abstractions.IFileSystemInfo[] GetFileSystemInfos(string searchPattern, System.IO.SearchOption searchOption) { } + public override System.IO.Abstractions.IFileInfo[] GetFiles() { } + public override System.IO.Abstractions.IFileInfo[] GetFiles(string searchPattern) { } + public override System.IO.Abstractions.IFileInfo[] GetFiles(string searchPattern, System.IO.EnumerationOptions enumerationOptions) { } + public override System.IO.Abstractions.IFileInfo[] GetFiles(string searchPattern, System.IO.SearchOption searchOption) { } + public override void MoveTo(string destDirName) { } + public override void Refresh() { } + public override System.IO.Abstractions.IFileSystemInfo ResolveLinkTarget(bool returnFinalTarget) { } + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public void SetAccessControl(object value) { } + public override string ToString() { } + } + [System.Serializable] + public class DirectoryWrapper : System.IO.Abstractions.DirectoryBase + { + public DirectoryWrapper(System.IO.Abstractions.IFileSystem fileSystem) { } + public override System.IO.Abstractions.IDirectoryInfo CreateDirectory(string path) { } + [System.Runtime.Versioning.UnsupportedOSPlatform("windows")] + public override System.IO.Abstractions.IDirectoryInfo CreateDirectory(string path, System.IO.UnixFileMode unixCreateMode) { } + public override System.IO.Abstractions.IFileSystemInfo CreateSymbolicLink(string path, string pathToTarget) { } + public override System.IO.Abstractions.IDirectoryInfo CreateTempSubdirectory(string prefix = null) { } + public override void Delete(string path) { } + public override void Delete(string path, bool recursive) { } + public override System.Collections.Generic.IEnumerable EnumerateDirectories(string path) { } + public override System.Collections.Generic.IEnumerable EnumerateDirectories(string path, string searchPattern) { } + public override System.Collections.Generic.IEnumerable EnumerateDirectories(string path, string searchPattern, System.IO.EnumerationOptions enumerationOptions) { } + public override System.Collections.Generic.IEnumerable EnumerateDirectories(string path, string searchPattern, System.IO.SearchOption searchOption) { } + public override System.Collections.Generic.IEnumerable EnumerateFileSystemEntries(string path) { } + public override System.Collections.Generic.IEnumerable EnumerateFileSystemEntries(string path, string searchPattern) { } + public override System.Collections.Generic.IEnumerable EnumerateFileSystemEntries(string path, string searchPattern, System.IO.EnumerationOptions enumerationOptions) { } + public override System.Collections.Generic.IEnumerable EnumerateFileSystemEntries(string path, string searchPattern, System.IO.SearchOption searchOption) { } + public override System.Collections.Generic.IEnumerable EnumerateFiles(string path) { } + public override System.Collections.Generic.IEnumerable EnumerateFiles(string path, string searchPattern) { } + public override System.Collections.Generic.IEnumerable EnumerateFiles(string path, string searchPattern, System.IO.EnumerationOptions enumerationOptions) { } + public override System.Collections.Generic.IEnumerable EnumerateFiles(string path, string searchPattern, System.IO.SearchOption searchOption) { } + public override bool Exists(string path) { } + public override System.DateTime GetCreationTime(string path) { } + public override System.DateTime GetCreationTimeUtc(string path) { } + public override string GetCurrentDirectory() { } + public override string[] GetDirectories(string path) { } + public override string[] GetDirectories(string path, string searchPattern) { } + public override string[] GetDirectories(string path, string searchPattern, System.IO.EnumerationOptions enumerationOptions) { } + public override string[] GetDirectories(string path, string searchPattern, System.IO.SearchOption searchOption) { } + public override string GetDirectoryRoot(string path) { } + public override string[] GetFileSystemEntries(string path) { } + public override string[] GetFileSystemEntries(string path, string searchPattern) { } + public override string[] GetFileSystemEntries(string path, string searchPattern, System.IO.EnumerationOptions enumerationOptions) { } + public override string[] GetFileSystemEntries(string path, string searchPattern, System.IO.SearchOption searchOption) { } + public override string[] GetFiles(string path) { } + public override string[] GetFiles(string path, string searchPattern) { } + public override string[] GetFiles(string path, string searchPattern, System.IO.EnumerationOptions enumerationOptions) { } + public override string[] GetFiles(string path, string searchPattern, System.IO.SearchOption searchOption) { } + public override System.DateTime GetLastAccessTime(string path) { } + public override System.DateTime GetLastAccessTimeUtc(string path) { } + public override System.DateTime GetLastWriteTime(string path) { } + public override System.DateTime GetLastWriteTimeUtc(string path) { } + public override string[] GetLogicalDrives() { } + public override System.IO.Abstractions.IDirectoryInfo GetParent(string path) { } + public override void Move(string sourceDirName, string destDirName) { } + public override System.IO.Abstractions.IFileSystemInfo ResolveLinkTarget(string linkPath, bool returnFinalTarget) { } + public override void SetCreationTime(string path, System.DateTime creationTime) { } + public override void SetCreationTimeUtc(string path, System.DateTime creationTimeUtc) { } + public override void SetCurrentDirectory(string path) { } + public override void SetLastAccessTime(string path, System.DateTime lastAccessTime) { } + public override void SetLastAccessTimeUtc(string path, System.DateTime lastAccessTimeUtc) { } + public override void SetLastWriteTime(string path, System.DateTime lastWriteTime) { } + public override void SetLastWriteTimeUtc(string path, System.DateTime lastWriteTimeUtc) { } + } + [System.Serializable] + public abstract class DriveInfoBase : System.IO.Abstractions.IDriveInfo, System.IO.Abstractions.IFileSystemEntity + { + protected DriveInfoBase(System.IO.Abstractions.IFileSystem fileSystem) { } + public abstract long AvailableFreeSpace { get; } + public abstract string DriveFormat { get; } + public abstract System.IO.DriveType DriveType { get; } + public System.IO.Abstractions.IFileSystem FileSystem { get; } + public abstract bool IsReady { get; } + public abstract string Name { get; } + public abstract System.IO.Abstractions.IDirectoryInfo RootDirectory { get; } + public abstract long TotalFreeSpace { get; } + public abstract long TotalSize { get; } + public abstract string VolumeLabel { get; set; } + public static System.IO.Abstractions.DriveInfoBase op_Implicit(System.IO.DriveInfo driveInfo) { } + } + [System.Serializable] + public class DriveInfoWrapper : System.IO.Abstractions.DriveInfoBase + { + public DriveInfoWrapper(System.IO.Abstractions.IFileSystem fileSystem, System.IO.DriveInfo instance) { } + public override long AvailableFreeSpace { get; } + public override string DriveFormat { get; } + public override System.IO.DriveType DriveType { get; } + public override bool IsReady { get; } + public override string Name { get; } + public override System.IO.Abstractions.IDirectoryInfo RootDirectory { get; } + public override long TotalFreeSpace { get; } + public override long TotalSize { get; } + [set: System.Runtime.Versioning.SupportedOSPlatform("windows")] + public override string VolumeLabel { get; set; } + public override string ToString() { } + } + public static class FileAclExtensions + { + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public static System.Security.AccessControl.FileSecurity GetAccessControl(this System.IO.Abstractions.IFile file, string path) { } + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public static System.Security.AccessControl.FileSecurity GetAccessControl(this System.IO.Abstractions.IFile file, string path, System.Security.AccessControl.AccessControlSections includeSections) { } + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public static void SetAccessControl(this System.IO.Abstractions.IFile file, string path, System.Security.AccessControl.FileSecurity fileSecurity) { } + } + [System.Serializable] + public abstract class FileBase : System.IO.Abstractions.IFile, System.IO.Abstractions.IFileSystemEntity + { + protected FileBase(System.IO.Abstractions.IFileSystem fileSystem) { } + public System.IO.Abstractions.IFileSystem FileSystem { get; } + public abstract void AppendAllBytes(string path, System.ReadOnlySpan bytes); + public abstract void AppendAllBytes(string path, byte[] bytes); + public abstract System.Threading.Tasks.Task AppendAllBytesAsync(string path, System.ReadOnlyMemory bytes, System.Threading.CancellationToken cancellationToken = default); + public abstract System.Threading.Tasks.Task AppendAllBytesAsync(string path, byte[] bytes, System.Threading.CancellationToken cancellationToken = default); + public abstract void AppendAllLines(string path, System.Collections.Generic.IEnumerable contents); + public abstract void AppendAllLines(string path, System.Collections.Generic.IEnumerable contents, System.Text.Encoding encoding); + public abstract System.Threading.Tasks.Task AppendAllLinesAsync(string path, System.Collections.Generic.IEnumerable contents, System.Threading.CancellationToken cancellationToken = default); + public abstract System.Threading.Tasks.Task AppendAllLinesAsync(string path, System.Collections.Generic.IEnumerable contents, System.Text.Encoding encoding, System.Threading.CancellationToken cancellationToken = default); + public abstract void AppendAllText(string path, System.ReadOnlySpan contents); + public abstract void AppendAllText(string path, string contents); + public abstract void AppendAllText(string path, System.ReadOnlySpan contents, System.Text.Encoding encoding); + public abstract void AppendAllText(string path, string contents, System.Text.Encoding encoding); + public abstract System.Threading.Tasks.Task AppendAllTextAsync(string path, System.ReadOnlyMemory contents, System.Threading.CancellationToken cancellationToken = default); + public abstract System.Threading.Tasks.Task AppendAllTextAsync(string path, string contents, System.Threading.CancellationToken cancellationToken = default); + public abstract System.Threading.Tasks.Task AppendAllTextAsync(string path, System.ReadOnlyMemory contents, System.Text.Encoding encoding, System.Threading.CancellationToken cancellationToken = default); + public abstract System.Threading.Tasks.Task AppendAllTextAsync(string path, string contents, System.Text.Encoding encoding, System.Threading.CancellationToken cancellationToken = default); + public abstract System.IO.StreamWriter AppendText(string path); + public abstract void Copy(string sourceFileName, string destFileName); + public abstract void Copy(string sourceFileName, string destFileName, bool overwrite); + public abstract System.IO.Abstractions.FileSystemStream Create(string path); + public abstract System.IO.Abstractions.FileSystemStream Create(string path, int bufferSize); + public abstract System.IO.Abstractions.FileSystemStream Create(string path, int bufferSize, System.IO.FileOptions options); + public abstract System.IO.Abstractions.IFileSystemInfo CreateSymbolicLink(string path, string pathToTarget); + public abstract System.IO.StreamWriter CreateText(string path); + public abstract void Decrypt(string path); + public abstract void Delete(string path); + public abstract void Encrypt(string path); + public abstract bool Exists(string path); + public abstract System.IO.FileAttributes GetAttributes(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle); + public abstract System.IO.FileAttributes GetAttributes(string path); + public abstract System.DateTime GetCreationTime(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle); + public abstract System.DateTime GetCreationTime(string path); + public abstract System.DateTime GetCreationTimeUtc(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle); + public abstract System.DateTime GetCreationTimeUtc(string path); + public abstract System.DateTime GetLastAccessTime(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle); + public abstract System.DateTime GetLastAccessTime(string path); + public abstract System.DateTime GetLastAccessTimeUtc(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle); + public abstract System.DateTime GetLastAccessTimeUtc(string path); + public abstract System.DateTime GetLastWriteTime(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle); + public abstract System.DateTime GetLastWriteTime(string path); + public abstract System.DateTime GetLastWriteTimeUtc(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle); + public abstract System.DateTime GetLastWriteTimeUtc(string path); + public abstract System.IO.UnixFileMode GetUnixFileMode(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle); + public abstract System.IO.UnixFileMode GetUnixFileMode(string path); + public abstract void Move(string sourceFileName, string destFileName); + public abstract void Move(string sourceFileName, string destFileName, bool overwrite); + public abstract System.IO.Abstractions.FileSystemStream Open(string path, System.IO.FileMode mode); + public abstract System.IO.Abstractions.FileSystemStream Open(string path, System.IO.FileStreamOptions options); + public abstract System.IO.Abstractions.FileSystemStream Open(string path, System.IO.FileMode mode, System.IO.FileAccess access); + public abstract System.IO.Abstractions.FileSystemStream Open(string path, System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share); + public abstract System.IO.Abstractions.FileSystemStream OpenRead(string path); + public abstract System.IO.StreamReader OpenText(string path); + public abstract System.IO.Abstractions.FileSystemStream OpenWrite(string path); + public abstract byte[] ReadAllBytes(string path); + public abstract System.Threading.Tasks.Task ReadAllBytesAsync(string path, System.Threading.CancellationToken cancellationToken = default); + public abstract string[] ReadAllLines(string path); + public abstract string[] ReadAllLines(string path, System.Text.Encoding encoding); + public abstract System.Threading.Tasks.Task ReadAllLinesAsync(string path, System.Threading.CancellationToken cancellationToken = default); + public abstract System.Threading.Tasks.Task ReadAllLinesAsync(string path, System.Text.Encoding encoding, System.Threading.CancellationToken cancellationToken = default); + public abstract string ReadAllText(string path); + public abstract string ReadAllText(string path, System.Text.Encoding encoding); + public abstract System.Threading.Tasks.Task ReadAllTextAsync(string path, System.Threading.CancellationToken cancellationToken = default); + public abstract System.Threading.Tasks.Task ReadAllTextAsync(string path, System.Text.Encoding encoding, System.Threading.CancellationToken cancellationToken = default); + public abstract System.Collections.Generic.IEnumerable ReadLines(string path); + public abstract System.Collections.Generic.IEnumerable ReadLines(string path, System.Text.Encoding encoding); + public abstract System.Collections.Generic.IAsyncEnumerable ReadLinesAsync(string path, System.Threading.CancellationToken cancellationToken = default); + public abstract System.Collections.Generic.IAsyncEnumerable ReadLinesAsync(string path, System.Text.Encoding encoding, System.Threading.CancellationToken cancellationToken = default); + public abstract void Replace(string sourceFileName, string destinationFileName, string destinationBackupFileName); + public abstract void Replace(string sourceFileName, string destinationFileName, string destinationBackupFileName, bool ignoreMetadataErrors); + public abstract System.IO.Abstractions.IFileSystemInfo ResolveLinkTarget(string linkPath, bool returnFinalTarget); + public abstract void SetAttributes(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle, System.IO.FileAttributes fileAttributes); + public abstract void SetAttributes(string path, System.IO.FileAttributes fileAttributes); + public abstract void SetCreationTime(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle, System.DateTime creationTime); + public abstract void SetCreationTime(string path, System.DateTime creationTime); + public abstract void SetCreationTimeUtc(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle, System.DateTime creationTimeUtc); + public abstract void SetCreationTimeUtc(string path, System.DateTime creationTimeUtc); + public abstract void SetLastAccessTime(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle, System.DateTime lastAccessTime); + public abstract void SetLastAccessTime(string path, System.DateTime lastAccessTime); + public abstract void SetLastAccessTimeUtc(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle, System.DateTime lastAccessTimeUtc); + public abstract void SetLastAccessTimeUtc(string path, System.DateTime lastAccessTimeUtc); + public abstract void SetLastWriteTime(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle, System.DateTime lastWriteTime); + public abstract void SetLastWriteTime(string path, System.DateTime lastWriteTime); + public abstract void SetLastWriteTimeUtc(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle, System.DateTime lastWriteTimeUtc); + public abstract void SetLastWriteTimeUtc(string path, System.DateTime lastWriteTimeUtc); + public abstract void SetUnixFileMode(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle, System.IO.UnixFileMode mode); + public abstract void SetUnixFileMode(string path, System.IO.UnixFileMode mode); + public abstract void WriteAllBytes(string path, System.ReadOnlySpan bytes); + public abstract void WriteAllBytes(string path, byte[] bytes); + public abstract System.Threading.Tasks.Task WriteAllBytesAsync(string path, System.ReadOnlyMemory bytes, System.Threading.CancellationToken cancellationToken = default); + public abstract System.Threading.Tasks.Task WriteAllBytesAsync(string path, byte[] bytes, System.Threading.CancellationToken cancellationToken = default); + public abstract void WriteAllLines(string path, System.Collections.Generic.IEnumerable contents); + public abstract void WriteAllLines(string path, string[] contents); + public abstract void WriteAllLines(string path, System.Collections.Generic.IEnumerable contents, System.Text.Encoding encoding); + public abstract void WriteAllLines(string path, string[] contents, System.Text.Encoding encoding); + public abstract System.Threading.Tasks.Task WriteAllLinesAsync(string path, System.Collections.Generic.IEnumerable contents, System.Threading.CancellationToken cancellationToken = default); + public abstract System.Threading.Tasks.Task WriteAllLinesAsync(string path, System.Collections.Generic.IEnumerable contents, System.Text.Encoding encoding, System.Threading.CancellationToken cancellationToken = default); + public abstract void WriteAllText(string path, System.ReadOnlySpan contents); + public abstract void WriteAllText(string path, string contents); + public abstract void WriteAllText(string path, System.ReadOnlySpan contents, System.Text.Encoding encoding); + public abstract void WriteAllText(string path, string contents, System.Text.Encoding encoding); + public abstract System.Threading.Tasks.Task WriteAllTextAsync(string path, System.ReadOnlyMemory contents, System.Threading.CancellationToken cancellationToken = default); + public abstract System.Threading.Tasks.Task WriteAllTextAsync(string path, string contents, System.Threading.CancellationToken cancellationToken = default); + public abstract System.Threading.Tasks.Task WriteAllTextAsync(string path, System.ReadOnlyMemory contents, System.Text.Encoding encoding, System.Threading.CancellationToken cancellationToken = default); + public abstract System.Threading.Tasks.Task WriteAllTextAsync(string path, string contents, System.Text.Encoding encoding, System.Threading.CancellationToken cancellationToken = default); + } + public static class FileInfoAclExtensions + { + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public static System.Security.AccessControl.FileSecurity GetAccessControl(this System.IO.Abstractions.IFileInfo fileInfo) { } + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public static System.Security.AccessControl.FileSecurity GetAccessControl(this System.IO.Abstractions.IFileInfo fileInfo, System.Security.AccessControl.AccessControlSections includeSections) { } + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public static void SetAccessControl(this System.IO.Abstractions.IFileInfo fileInfo, System.Security.AccessControl.FileSecurity fileSecurity) { } + } + [System.Serializable] + public abstract class FileInfoBase : System.IO.Abstractions.FileSystemInfoBase, System.IO.Abstractions.IFileInfo, System.IO.Abstractions.IFileSystemInfo + { + protected FileInfoBase(System.IO.Abstractions.IFileSystem fileSystem) { } + public abstract System.IO.Abstractions.IDirectoryInfo Directory { get; } + public abstract string DirectoryName { get; } + public abstract bool IsReadOnly { get; set; } + public abstract long Length { get; } + public abstract System.IO.StreamWriter AppendText(); + public abstract System.IO.Abstractions.IFileInfo CopyTo(string destFileName); + public abstract System.IO.Abstractions.IFileInfo CopyTo(string destFileName, bool overwrite); + public abstract System.IO.Abstractions.FileSystemStream Create(); + public abstract System.IO.StreamWriter CreateText(); + public abstract void Decrypt(); + public abstract void Encrypt(); + public abstract void MoveTo(string destFileName); + public abstract void MoveTo(string destFileName, bool overwrite); + public abstract System.IO.Abstractions.FileSystemStream Open(System.IO.FileMode mode); + public abstract System.IO.Abstractions.FileSystemStream Open(System.IO.FileStreamOptions options); + public abstract System.IO.Abstractions.FileSystemStream Open(System.IO.FileMode mode, System.IO.FileAccess access); + public abstract System.IO.Abstractions.FileSystemStream Open(System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share); + public abstract System.IO.Abstractions.FileSystemStream OpenRead(); + public abstract System.IO.StreamReader OpenText(); + public abstract System.IO.Abstractions.FileSystemStream OpenWrite(); + public abstract System.IO.Abstractions.IFileInfo Replace(string destinationFileName, string destinationBackupFileName); + public abstract System.IO.Abstractions.IFileInfo Replace(string destinationFileName, string destinationBackupFileName, bool ignoreMetadataErrors); + public static System.IO.Abstractions.FileInfoBase op_Implicit(System.IO.FileInfo fileInfo) { } + } + [System.Serializable] + public class FileInfoWrapper : System.IO.Abstractions.FileInfoBase, System.IO.Abstractions.IFileSystemAclSupport + { + public FileInfoWrapper(System.IO.Abstractions.IFileSystem fileSystem, System.IO.FileInfo instance) { } + public override System.IO.FileAttributes Attributes { get; set; } + public override System.DateTime CreationTime { get; set; } + public override System.DateTime CreationTimeUtc { get; set; } + public override System.IO.Abstractions.IDirectoryInfo Directory { get; } + public override string DirectoryName { get; } + public override bool Exists { get; } + public override string Extension { get; } + public override string FullName { get; } + public override bool IsReadOnly { get; set; } + public override System.DateTime LastAccessTime { get; set; } + public override System.DateTime LastAccessTimeUtc { get; set; } + public override System.DateTime LastWriteTime { get; set; } + public override System.DateTime LastWriteTimeUtc { get; set; } + public override long Length { get; } + public override string LinkTarget { get; } + public override string Name { get; } + public override System.IO.StreamWriter AppendText() { } + public override System.IO.Abstractions.IFileInfo CopyTo(string destFileName) { } + public override System.IO.Abstractions.IFileInfo CopyTo(string destFileName, bool overwrite) { } + public override System.IO.Abstractions.FileSystemStream Create() { } + public override void CreateAsSymbolicLink(string pathToTarget) { } + public override System.IO.StreamWriter CreateText() { } + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public override void Decrypt() { } + public override void Delete() { } + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public override void Encrypt() { } + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public object GetAccessControl() { } + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public object GetAccessControl(System.IO.Abstractions.IFileSystemAclSupport.AccessControlSections includeSections) { } + public override void MoveTo(string destFileName) { } + public override void MoveTo(string destFileName, bool overwrite) { } + public override System.IO.Abstractions.FileSystemStream Open(System.IO.FileMode mode) { } + public override System.IO.Abstractions.FileSystemStream Open(System.IO.FileStreamOptions options) { } + public override System.IO.Abstractions.FileSystemStream Open(System.IO.FileMode mode, System.IO.FileAccess access) { } + public override System.IO.Abstractions.FileSystemStream Open(System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share) { } + public override System.IO.Abstractions.FileSystemStream OpenRead() { } + public override System.IO.StreamReader OpenText() { } + public override System.IO.Abstractions.FileSystemStream OpenWrite() { } + public override void Refresh() { } + public override System.IO.Abstractions.IFileInfo Replace(string destinationFileName, string destinationBackupFileName) { } + public override System.IO.Abstractions.IFileInfo Replace(string destinationFileName, string destinationBackupFileName, bool ignoreMetadataErrors) { } + public override System.IO.Abstractions.IFileSystemInfo ResolveLinkTarget(bool returnFinalTarget) { } + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public void SetAccessControl(object value) { } + public override string ToString() { } + } + public static class FileStreamAclExtensions + { + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public static System.Security.AccessControl.FileSecurity GetAccessControl(this System.IO.Abstractions.FileSystemStream fileStream) { } + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public static void SetAccessControl(this System.IO.Abstractions.FileSystemStream fileStream, System.Security.AccessControl.FileSecurity fileSecurity) { } + } + [System.Serializable] + public class FileSystem : System.IO.Abstractions.FileSystemBase + { + public FileSystem() { } + public override System.IO.Abstractions.IDirectory Directory { get; } + public override System.IO.Abstractions.IDirectoryInfoFactory DirectoryInfo { get; } + public override System.IO.Abstractions.IDriveInfoFactory DriveInfo { get; } + public override System.IO.Abstractions.IFile File { get; } + public override System.IO.Abstractions.IFileInfoFactory FileInfo { get; } + public override System.IO.Abstractions.IFileStreamFactory FileStream { get; } + public override System.IO.Abstractions.IFileSystemWatcherFactory FileSystemWatcher { get; } + public override System.IO.Abstractions.IFileVersionInfoFactory FileVersionInfo { get; } + public override System.IO.Abstractions.IPath Path { get; } + } + [System.Serializable] + public abstract class FileSystemBase : System.IO.Abstractions.IFileSystem + { + protected FileSystemBase() { } + public abstract System.IO.Abstractions.IDirectory Directory { get; } + public abstract System.IO.Abstractions.IDirectoryInfoFactory DirectoryInfo { get; } + public abstract System.IO.Abstractions.IDriveInfoFactory DriveInfo { get; } + public abstract System.IO.Abstractions.IFile File { get; } + public abstract System.IO.Abstractions.IFileInfoFactory FileInfo { get; } + public abstract System.IO.Abstractions.IFileStreamFactory FileStream { get; } + public abstract System.IO.Abstractions.IFileSystemWatcherFactory FileSystemWatcher { get; } + public abstract System.IO.Abstractions.IFileVersionInfoFactory FileVersionInfo { get; } + public abstract System.IO.Abstractions.IPath Path { get; } + } + [System.Serializable] + public abstract class FileSystemInfoBase : System.IO.Abstractions.IFileSystemInfo + { + protected FileSystemInfoBase(System.IO.Abstractions.IFileSystem fileSystem) { } + public abstract System.IO.FileAttributes Attributes { get; set; } + public abstract System.DateTime CreationTime { get; set; } + public abstract System.DateTime CreationTimeUtc { get; set; } + public abstract bool Exists { get; } + public abstract string Extension { get; } + public System.IO.Abstractions.IFileSystem FileSystem { get; } + public abstract string FullName { get; } + public abstract System.DateTime LastAccessTime { get; set; } + public abstract System.DateTime LastAccessTimeUtc { get; set; } + public abstract System.DateTime LastWriteTime { get; set; } + public abstract System.DateTime LastWriteTimeUtc { get; set; } + public abstract string LinkTarget { get; } + public abstract string Name { get; } + [set: System.Runtime.Versioning.UnsupportedOSPlatform("windows")] + public System.IO.UnixFileMode UnixFileMode { get; set; } + public abstract void CreateAsSymbolicLink(string pathToTarget); + public abstract void Delete(); + public abstract void Refresh(); + public abstract System.IO.Abstractions.IFileSystemInfo ResolveLinkTarget(bool returnFinalTarget); + } + [System.Serializable] + public abstract class FileSystemWatcherBase : System.IDisposable, System.IO.Abstractions.IFileSystemEntity, System.IO.Abstractions.IFileSystemWatcher + { + protected FileSystemWatcherBase() { } + public abstract System.ComponentModel.IContainer Container { get; } + public abstract bool EnableRaisingEvents { get; set; } + public abstract System.IO.Abstractions.IFileSystem FileSystem { get; } + public abstract string Filter { get; set; } + public abstract System.Collections.ObjectModel.Collection Filters { get; } + public abstract bool IncludeSubdirectories { get; set; } + public abstract int InternalBufferSize { get; set; } + public abstract System.IO.NotifyFilters NotifyFilter { get; set; } + public abstract string Path { get; set; } + public abstract System.ComponentModel.ISite Site { get; set; } + public abstract System.ComponentModel.ISynchronizeInvoke SynchronizingObject { get; set; } + public virtual event System.IO.FileSystemEventHandler Changed; + public virtual event System.IO.FileSystemEventHandler Created; + public virtual event System.IO.FileSystemEventHandler Deleted; + public virtual event System.IO.ErrorEventHandler Error; + public virtual event System.IO.RenamedEventHandler Renamed; + public abstract void BeginInit(); + public void Dispose() { } + public virtual void Dispose(bool disposing) { } + public abstract void EndInit(); + protected void OnChanged(object sender, System.IO.FileSystemEventArgs args) { } + protected void OnCreated(object sender, System.IO.FileSystemEventArgs args) { } + protected void OnDeleted(object sender, System.IO.FileSystemEventArgs args) { } + protected void OnError(object sender, System.IO.ErrorEventArgs args) { } + protected void OnRenamed(object sender, System.IO.RenamedEventArgs args) { } + public abstract System.IO.Abstractions.IWaitForChangedResult WaitForChanged(System.IO.WatcherChangeTypes changeType); + public abstract System.IO.Abstractions.IWaitForChangedResult WaitForChanged(System.IO.WatcherChangeTypes changeType, System.TimeSpan timeout); + public abstract System.IO.Abstractions.IWaitForChangedResult WaitForChanged(System.IO.WatcherChangeTypes changeType, int timeout); + public static System.IO.Abstractions.FileSystemWatcherBase op_Implicit(System.IO.FileSystemWatcher watcher) { } + } + [System.Serializable] + public class FileSystemWatcherFactory : System.IO.Abstractions.IFileSystemEntity, System.IO.Abstractions.IFileSystemWatcherFactory + { + public FileSystemWatcherFactory(System.IO.Abstractions.IFileSystem fileSystem) { } + public System.IO.Abstractions.IFileSystem FileSystem { get; } + public System.IO.Abstractions.IFileSystemWatcher New() { } + public System.IO.Abstractions.IFileSystemWatcher New(string path) { } + public System.IO.Abstractions.IFileSystemWatcher New(string path, string filter) { } + public System.IO.Abstractions.IFileSystemWatcher Wrap(System.IO.FileSystemWatcher fileSystemWatcher) { } + } + [System.Serializable] + public class FileSystemWatcherWrapper : System.IO.Abstractions.FileSystemWatcherBase + { + public FileSystemWatcherWrapper(System.IO.Abstractions.IFileSystem fileSystem) { } + public FileSystemWatcherWrapper(System.IO.Abstractions.IFileSystem fileSystem, System.IO.FileSystemWatcher watcher) { } + public FileSystemWatcherWrapper(System.IO.Abstractions.IFileSystem fileSystem, string path) { } + public FileSystemWatcherWrapper(System.IO.Abstractions.IFileSystem fileSystem, string path, string filter) { } + public override System.ComponentModel.IContainer Container { get; } + public override bool EnableRaisingEvents { get; set; } + public override System.IO.Abstractions.IFileSystem FileSystem { get; } + public override string Filter { get; set; } + public override System.Collections.ObjectModel.Collection Filters { get; } + public override bool IncludeSubdirectories { get; set; } + public override int InternalBufferSize { get; set; } + public override System.IO.NotifyFilters NotifyFilter { get; set; } + public override string Path { get; set; } + public override System.ComponentModel.ISite Site { get; set; } + public override System.ComponentModel.ISynchronizeInvoke SynchronizingObject { get; set; } + public override void BeginInit() { } + public override void Dispose(bool disposing) { } + public override void EndInit() { } + public override System.IO.Abstractions.IWaitForChangedResult WaitForChanged(System.IO.WatcherChangeTypes changeType) { } + public override System.IO.Abstractions.IWaitForChangedResult WaitForChanged(System.IO.WatcherChangeTypes changeType, System.TimeSpan timeout) { } + public override System.IO.Abstractions.IWaitForChangedResult WaitForChanged(System.IO.WatcherChangeTypes changeType, int timeout) { } + } + [System.Serializable] + public abstract class FileVersionInfoBase : System.IO.Abstractions.IFileVersionInfo + { + protected FileVersionInfoBase() { } + public abstract string Comments { get; } + public abstract string CompanyName { get; } + public abstract int FileBuildPart { get; } + public abstract string FileDescription { get; } + public abstract int FileMajorPart { get; } + public abstract int FileMinorPart { get; } + public abstract string FileName { get; } + public abstract int FilePrivatePart { get; } + public abstract string FileVersion { get; } + public abstract string InternalName { get; } + public abstract bool IsDebug { get; } + public abstract bool IsPatched { get; } + public abstract bool IsPreRelease { get; } + public abstract bool IsPrivateBuild { get; } + public abstract bool IsSpecialBuild { get; } + public abstract string Language { get; } + public abstract string LegalCopyright { get; } + public abstract string LegalTrademarks { get; } + public abstract string OriginalFilename { get; } + public abstract string PrivateBuild { get; } + public abstract int ProductBuildPart { get; } + public abstract int ProductMajorPart { get; } + public abstract int ProductMinorPart { get; } + public abstract string ProductName { get; } + public abstract int ProductPrivatePart { get; } + public abstract string ProductVersion { get; } + public abstract string SpecialBuild { get; } + public abstract string ToString(); + public static System.IO.Abstractions.FileVersionInfoBase op_Implicit(System.Diagnostics.FileVersionInfo fileVersionInfo) { } + } + [System.Serializable] + public class FileVersionInfoWrapper : System.IO.Abstractions.FileVersionInfoBase + { + public FileVersionInfoWrapper(System.Diagnostics.FileVersionInfo fileVersionInfo) { } + public override string Comments { get; } + public override string CompanyName { get; } + public override int FileBuildPart { get; } + public override string FileDescription { get; } + public override int FileMajorPart { get; } + public override int FileMinorPart { get; } + public override string FileName { get; } + public override int FilePrivatePart { get; } + public override string FileVersion { get; } + public override string InternalName { get; } + public override bool IsDebug { get; } + public override bool IsPatched { get; } + public override bool IsPreRelease { get; } + public override bool IsPrivateBuild { get; } + public override bool IsSpecialBuild { get; } + public override string Language { get; } + public override string LegalCopyright { get; } + public override string LegalTrademarks { get; } + public override string OriginalFilename { get; } + public override string PrivateBuild { get; } + public override int ProductBuildPart { get; } + public override int ProductMajorPart { get; } + public override int ProductMinorPart { get; } + public override string ProductName { get; } + public override int ProductPrivatePart { get; } + public override string ProductVersion { get; } + public override string SpecialBuild { get; } + public override string ToString() { } + } + [System.Serializable] + public class FileWrapper : System.IO.Abstractions.FileBase + { + public FileWrapper(System.IO.Abstractions.IFileSystem fileSystem) { } + public override void AppendAllBytes(string path, System.ReadOnlySpan bytes) { } + public override void AppendAllBytes(string path, byte[] bytes) { } + public override System.Threading.Tasks.Task AppendAllBytesAsync(string path, System.ReadOnlyMemory bytes, System.Threading.CancellationToken cancellationToken = default) { } + public override System.Threading.Tasks.Task AppendAllBytesAsync(string path, byte[] bytes, System.Threading.CancellationToken cancellationToken = default) { } + public override void AppendAllLines(string path, System.Collections.Generic.IEnumerable contents) { } + public override void AppendAllLines(string path, System.Collections.Generic.IEnumerable contents, System.Text.Encoding encoding) { } + public override System.Threading.Tasks.Task AppendAllLinesAsync(string path, System.Collections.Generic.IEnumerable contents, System.Threading.CancellationToken cancellationToken = default) { } + public override System.Threading.Tasks.Task AppendAllLinesAsync(string path, System.Collections.Generic.IEnumerable contents, System.Text.Encoding encoding, System.Threading.CancellationToken cancellationToken = default) { } + public override void AppendAllText(string path, System.ReadOnlySpan contents) { } + public override void AppendAllText(string path, string contents) { } + public override void AppendAllText(string path, System.ReadOnlySpan contents, System.Text.Encoding encoding) { } + public override void AppendAllText(string path, string contents, System.Text.Encoding encoding) { } + public override System.Threading.Tasks.Task AppendAllTextAsync(string path, System.ReadOnlyMemory contents, System.Threading.CancellationToken cancellationToken = default) { } + public override System.Threading.Tasks.Task AppendAllTextAsync(string path, string contents, System.Threading.CancellationToken cancellationToken = default) { } + public override System.Threading.Tasks.Task AppendAllTextAsync(string path, System.ReadOnlyMemory contents, System.Text.Encoding encoding, System.Threading.CancellationToken cancellationToken = default) { } + public override System.Threading.Tasks.Task AppendAllTextAsync(string path, string contents, System.Text.Encoding encoding, System.Threading.CancellationToken cancellationToken = default) { } + public override System.IO.StreamWriter AppendText(string path) { } + public override void Copy(string sourceFileName, string destFileName) { } + public override void Copy(string sourceFileName, string destFileName, bool overwrite) { } + public override System.IO.Abstractions.FileSystemStream Create(string path) { } + public override System.IO.Abstractions.FileSystemStream Create(string path, int bufferSize) { } + public override System.IO.Abstractions.FileSystemStream Create(string path, int bufferSize, System.IO.FileOptions options) { } + public override System.IO.Abstractions.IFileSystemInfo CreateSymbolicLink(string path, string pathToTarget) { } + public override System.IO.StreamWriter CreateText(string path) { } + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public override void Decrypt(string path) { } + public override void Delete(string path) { } + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public override void Encrypt(string path) { } + public override bool Exists(string path) { } + public override System.IO.FileAttributes GetAttributes(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle) { } + public override System.IO.FileAttributes GetAttributes(string path) { } + public override System.DateTime GetCreationTime(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle) { } + public override System.DateTime GetCreationTime(string path) { } + public override System.DateTime GetCreationTimeUtc(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle) { } + public override System.DateTime GetCreationTimeUtc(string path) { } + public override System.DateTime GetLastAccessTime(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle) { } + public override System.DateTime GetLastAccessTime(string path) { } + public override System.DateTime GetLastAccessTimeUtc(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle) { } + public override System.DateTime GetLastAccessTimeUtc(string path) { } + public override System.DateTime GetLastWriteTime(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle) { } + public override System.DateTime GetLastWriteTime(string path) { } + public override System.DateTime GetLastWriteTimeUtc(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle) { } + public override System.DateTime GetLastWriteTimeUtc(string path) { } + [System.Runtime.Versioning.UnsupportedOSPlatform("windows")] + public override System.IO.UnixFileMode GetUnixFileMode(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle) { } + [System.Runtime.Versioning.UnsupportedOSPlatform("windows")] + public override System.IO.UnixFileMode GetUnixFileMode(string path) { } + public override void Move(string sourceFileName, string destFileName) { } + public override void Move(string sourceFileName, string destFileName, bool overwrite) { } + public override System.IO.Abstractions.FileSystemStream Open(string path, System.IO.FileMode mode) { } + public override System.IO.Abstractions.FileSystemStream Open(string path, System.IO.FileStreamOptions options) { } + public override System.IO.Abstractions.FileSystemStream Open(string path, System.IO.FileMode mode, System.IO.FileAccess access) { } + public override System.IO.Abstractions.FileSystemStream Open(string path, System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share) { } + public override System.IO.Abstractions.FileSystemStream OpenRead(string path) { } + public override System.IO.StreamReader OpenText(string path) { } + public override System.IO.Abstractions.FileSystemStream OpenWrite(string path) { } + public override byte[] ReadAllBytes(string path) { } + public override System.Threading.Tasks.Task ReadAllBytesAsync(string path, System.Threading.CancellationToken cancellationToken = default) { } + public override string[] ReadAllLines(string path) { } + public override string[] ReadAllLines(string path, System.Text.Encoding encoding) { } + public override System.Threading.Tasks.Task ReadAllLinesAsync(string path, System.Threading.CancellationToken cancellationToken = default) { } + public override System.Threading.Tasks.Task ReadAllLinesAsync(string path, System.Text.Encoding encoding, System.Threading.CancellationToken cancellationToken = default) { } + public override string ReadAllText(string path) { } + public override string ReadAllText(string path, System.Text.Encoding encoding) { } + public override System.Threading.Tasks.Task ReadAllTextAsync(string path, System.Threading.CancellationToken cancellationToken = default) { } + public override System.Threading.Tasks.Task ReadAllTextAsync(string path, System.Text.Encoding encoding, System.Threading.CancellationToken cancellationToken = default) { } + public override System.Collections.Generic.IEnumerable ReadLines(string path) { } + public override System.Collections.Generic.IEnumerable ReadLines(string path, System.Text.Encoding encoding) { } + public override System.Collections.Generic.IAsyncEnumerable ReadLinesAsync(string path, System.Threading.CancellationToken cancellationToken = default) { } + public override System.Collections.Generic.IAsyncEnumerable ReadLinesAsync(string path, System.Text.Encoding encoding, System.Threading.CancellationToken cancellationToken = default) { } + public override void Replace(string sourceFileName, string destinationFileName, string destinationBackupFileName) { } + public override void Replace(string sourceFileName, string destinationFileName, string destinationBackupFileName, bool ignoreMetadataErrors) { } + public override System.IO.Abstractions.IFileSystemInfo ResolveLinkTarget(string linkPath, bool returnFinalTarget) { } + public override void SetAttributes(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle, System.IO.FileAttributes fileAttributes) { } + public override void SetAttributes(string path, System.IO.FileAttributes fileAttributes) { } + public override void SetCreationTime(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle, System.DateTime creationTime) { } + public override void SetCreationTime(string path, System.DateTime creationTime) { } + public override void SetCreationTimeUtc(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle, System.DateTime creationTimeUtc) { } + public override void SetCreationTimeUtc(string path, System.DateTime creationTimeUtc) { } + public override void SetLastAccessTime(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle, System.DateTime lastAccessTime) { } + public override void SetLastAccessTime(string path, System.DateTime lastAccessTime) { } + public override void SetLastAccessTimeUtc(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle, System.DateTime lastAccessTimeUtc) { } + public override void SetLastAccessTimeUtc(string path, System.DateTime lastAccessTimeUtc) { } + public override void SetLastWriteTime(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle, System.DateTime lastWriteTime) { } + public override void SetLastWriteTime(string path, System.DateTime lastWriteTime) { } + public override void SetLastWriteTimeUtc(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle, System.DateTime lastWriteTimeUtc) { } + public override void SetLastWriteTimeUtc(string path, System.DateTime lastWriteTimeUtc) { } + [System.Runtime.Versioning.UnsupportedOSPlatform("windows")] + public override void SetUnixFileMode(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle, System.IO.UnixFileMode mode) { } + [System.Runtime.Versioning.UnsupportedOSPlatform("windows")] + public override void SetUnixFileMode(string path, System.IO.UnixFileMode mode) { } + public override void WriteAllBytes(string path, System.ReadOnlySpan bytes) { } + public override void WriteAllBytes(string path, byte[] bytes) { } + public override System.Threading.Tasks.Task WriteAllBytesAsync(string path, System.ReadOnlyMemory bytes, System.Threading.CancellationToken cancellationToken = default) { } + public override System.Threading.Tasks.Task WriteAllBytesAsync(string path, byte[] bytes, System.Threading.CancellationToken cancellationToken = default) { } + public override void WriteAllLines(string path, System.Collections.Generic.IEnumerable contents) { } + public override void WriteAllLines(string path, string[] contents) { } + public override void WriteAllLines(string path, System.Collections.Generic.IEnumerable contents, System.Text.Encoding encoding) { } + public override void WriteAllLines(string path, string[] contents, System.Text.Encoding encoding) { } + public override System.Threading.Tasks.Task WriteAllLinesAsync(string path, System.Collections.Generic.IEnumerable contents, System.Threading.CancellationToken cancellationToken = default) { } + public override System.Threading.Tasks.Task WriteAllLinesAsync(string path, System.Collections.Generic.IEnumerable contents, System.Text.Encoding encoding, System.Threading.CancellationToken cancellationToken = default) { } + public override void WriteAllText(string path, System.ReadOnlySpan contents) { } + public override void WriteAllText(string path, string contents) { } + public override void WriteAllText(string path, System.ReadOnlySpan contents, System.Text.Encoding encoding) { } + public override void WriteAllText(string path, string contents, System.Text.Encoding encoding) { } + public override System.Threading.Tasks.Task WriteAllTextAsync(string path, System.ReadOnlyMemory contents, System.Threading.CancellationToken cancellationToken = default) { } + public override System.Threading.Tasks.Task WriteAllTextAsync(string path, string contents, System.Threading.CancellationToken cancellationToken = default) { } + public override System.Threading.Tasks.Task WriteAllTextAsync(string path, System.ReadOnlyMemory contents, System.Text.Encoding encoding, System.Threading.CancellationToken cancellationToken = default) { } + public override System.Threading.Tasks.Task WriteAllTextAsync(string path, string contents, System.Text.Encoding encoding, System.Threading.CancellationToken cancellationToken = default) { } + } + [System.Serializable] + public abstract class PathBase : System.IO.Abstractions.IFileSystemEntity, System.IO.Abstractions.IPath + { + protected PathBase(System.IO.Abstractions.IFileSystem fileSystem) { } + public abstract char AltDirectorySeparatorChar { get; } + public abstract char DirectorySeparatorChar { get; } + public System.IO.Abstractions.IFileSystem FileSystem { get; } + [System.Obsolete("Please use GetInvalidPathChars or GetInvalidFileNameChars instead.")] + public abstract char[] InvalidPathChars { get; } + public abstract char PathSeparator { get; } + public abstract char VolumeSeparatorChar { get; } + public abstract string ChangeExtension(string path, string extension); + public abstract string Combine([System.Runtime.CompilerServices.ScopedRef] System.ReadOnlySpan paths); + public abstract string Combine(params string[] paths); + public abstract string Combine(string path1, string path2); + public abstract string Combine(string path1, string path2, string path3); + public abstract string Combine(string path1, string path2, string path3, string path4); + public abstract bool EndsInDirectorySeparator(System.ReadOnlySpan path); + public abstract bool EndsInDirectorySeparator(string path); + public abstract bool Exists(string path); + public abstract System.ReadOnlySpan GetDirectoryName(System.ReadOnlySpan path); + public abstract string GetDirectoryName(string path); + public abstract System.ReadOnlySpan GetExtension(System.ReadOnlySpan path); + public abstract string GetExtension(string path); + public abstract System.ReadOnlySpan GetFileName(System.ReadOnlySpan path); + public abstract string GetFileName(string path); + public abstract System.ReadOnlySpan GetFileNameWithoutExtension(System.ReadOnlySpan path); + public abstract string GetFileNameWithoutExtension(string path); + public abstract string GetFullPath(string path); + public abstract string GetFullPath(string path, string basePath); + public abstract char[] GetInvalidFileNameChars(); + public abstract char[] GetInvalidPathChars(); + public abstract System.ReadOnlySpan GetPathRoot(System.ReadOnlySpan path); + public abstract string GetPathRoot(string path); + public abstract string GetRandomFileName(); + public abstract string GetRelativePath(string relativeTo, string path); + public abstract string GetTempFileName(); + public abstract string GetTempPath(); + public abstract bool HasExtension(System.ReadOnlySpan path); + public abstract bool HasExtension(string path); + public abstract bool IsPathFullyQualified(System.ReadOnlySpan path); + public abstract bool IsPathFullyQualified(string path); + public abstract bool IsPathRooted(System.ReadOnlySpan path); + public abstract bool IsPathRooted(string path); + public abstract string Join([System.Runtime.CompilerServices.ScopedRef] System.ReadOnlySpan paths); + public abstract string Join(params string[] paths); + public abstract string Join(System.ReadOnlySpan path1, System.ReadOnlySpan path2); + public abstract string Join(string path1, string path2); + public abstract string Join(System.ReadOnlySpan path1, System.ReadOnlySpan path2, System.ReadOnlySpan path3); + public abstract string Join(string path1, string path2, string path3); + public abstract string Join(System.ReadOnlySpan path1, System.ReadOnlySpan path2, System.ReadOnlySpan path3, System.ReadOnlySpan path4); + public abstract string Join(string path1, string path2, string path3, string path4); + public abstract System.ReadOnlySpan TrimEndingDirectorySeparator(System.ReadOnlySpan path); + public abstract string TrimEndingDirectorySeparator(string path); + public abstract bool TryJoin(System.ReadOnlySpan path1, System.ReadOnlySpan path2, System.Span destination, out int charsWritten); + public abstract bool TryJoin(System.ReadOnlySpan path1, System.ReadOnlySpan path2, System.ReadOnlySpan path3, System.Span destination, out int charsWritten); + } + [System.Serializable] + public class PathWrapper : System.IO.Abstractions.PathBase + { + public PathWrapper(System.IO.Abstractions.IFileSystem fileSystem) { } + public override char AltDirectorySeparatorChar { get; } + public override char DirectorySeparatorChar { get; } + [System.Obsolete("Please use GetInvalidPathChars or GetInvalidFileNameChars instead.")] + public override char[] InvalidPathChars { get; } + public override char PathSeparator { get; } + public override char VolumeSeparatorChar { get; } + public override string ChangeExtension(string path, string extension) { } + public override string Combine([System.Runtime.CompilerServices.ScopedRef] System.ReadOnlySpan paths) { } + public override string Combine(params string[] paths) { } + public override string Combine(string path1, string path2) { } + public override string Combine(string path1, string path2, string path3) { } + public override string Combine(string path1, string path2, string path3, string path4) { } + public override bool EndsInDirectorySeparator(System.ReadOnlySpan path) { } + public override bool EndsInDirectorySeparator(string path) { } + public override bool Exists(string path) { } + public override System.ReadOnlySpan GetDirectoryName(System.ReadOnlySpan path) { } + public override string GetDirectoryName(string path) { } + public override System.ReadOnlySpan GetExtension(System.ReadOnlySpan path) { } + public override string GetExtension(string path) { } + public override System.ReadOnlySpan GetFileName(System.ReadOnlySpan path) { } + public override string GetFileName(string path) { } + public override System.ReadOnlySpan GetFileNameWithoutExtension(System.ReadOnlySpan path) { } + public override string GetFileNameWithoutExtension(string path) { } + public override string GetFullPath(string path) { } + public override string GetFullPath(string path, string basePath) { } + public override char[] GetInvalidFileNameChars() { } + public override char[] GetInvalidPathChars() { } + public override System.ReadOnlySpan GetPathRoot(System.ReadOnlySpan path) { } + public override string GetPathRoot(string path) { } + public override string GetRandomFileName() { } + public override string GetRelativePath(string relativeTo, string path) { } + public override string GetTempFileName() { } + public override string GetTempPath() { } + public override bool HasExtension(System.ReadOnlySpan path) { } + public override bool HasExtension(string path) { } + public override bool IsPathFullyQualified(System.ReadOnlySpan path) { } + public override bool IsPathFullyQualified(string path) { } + public override bool IsPathRooted(System.ReadOnlySpan path) { } + public override bool IsPathRooted(string path) { } + public override string Join([System.Runtime.CompilerServices.ScopedRef] System.ReadOnlySpan paths) { } + public override string Join(params string[] paths) { } + public override string Join(System.ReadOnlySpan path1, System.ReadOnlySpan path2) { } + public override string Join(string path1, string path2) { } + public override string Join(System.ReadOnlySpan path1, System.ReadOnlySpan path2, System.ReadOnlySpan path3) { } + public override string Join(string path1, string path2, string path3) { } + public override string Join(System.ReadOnlySpan path1, System.ReadOnlySpan path2, System.ReadOnlySpan path3, System.ReadOnlySpan path4) { } + public override string Join(string path1, string path2, string path3, string path4) { } + public override System.ReadOnlySpan TrimEndingDirectorySeparator(System.ReadOnlySpan path) { } + public override string TrimEndingDirectorySeparator(string path) { } + public override bool TryJoin(System.ReadOnlySpan path1, System.ReadOnlySpan path2, System.Span destination, out int charsWritten) { } + public override bool TryJoin(System.ReadOnlySpan path1, System.ReadOnlySpan path2, System.ReadOnlySpan path3, System.Span destination, out int charsWritten) { } + } +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.Api.Tests/Expected/TestableIO.System.IO.Abstractions.Wrappers_net472.txt b/tests/TestableIO.System.IO.Abstractions.Api.Tests/Expected/TestableIO.System.IO.Abstractions.Wrappers_net472.txt new file mode 100644 index 000000000..ae59ef379 --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.Api.Tests/Expected/TestableIO.System.IO.Abstractions.Wrappers_net472.txt @@ -0,0 +1,657 @@ +[assembly: System.CLSCompliant(true)] +[assembly: System.Reflection.AssemblyMetadata("RepositoryUrl", "https://github.com/TestableIO/System.IO.Abstractions.git")] +[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(@"DynamicProxyGenAssembly2, PublicKey=0024000004800000940000000602000000240000525341310004000001000100c547cac37abd99c8db225ef2f6c8a3602f3b3606cc9891605d02baa56104f4cfc0734aa39b93bf7852f7d9266654753cc297e7d2edfe0bac1cdcf9f717241550e0a7b191195b7667bb4f64bcb8e2121380fd1d9d46ad2d92d2d15605093924cceaf74c4861eff62abf69b9291ed0a340e113be11e6a7d3113e92484cf7045cc7")] +[assembly: System.Runtime.Versioning.TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName=".NET Framework 4.7.2")] +namespace System.IO.Abstractions +{ + public static class DirectoryAclExtensions + { + public static void CreateDirectory(this System.IO.Abstractions.IDirectory directory, string path, System.Security.AccessControl.DirectorySecurity directorySecurity) { } + public static System.Security.AccessControl.DirectorySecurity GetAccessControl(this System.IO.Abstractions.IDirectory directory, string path) { } + public static System.Security.AccessControl.DirectorySecurity GetAccessControl(this System.IO.Abstractions.IDirectory directory, string path, System.Security.AccessControl.AccessControlSections includeSections) { } + public static void SetAccessControl(this System.IO.Abstractions.IDirectory directory, string path, System.Security.AccessControl.DirectorySecurity directorySecurity) { } + } + [System.Serializable] + public abstract class DirectoryBase : System.IO.Abstractions.IDirectory, System.IO.Abstractions.IFileSystemEntity + { + protected DirectoryBase(System.IO.Abstractions.IFileSystem fileSystem) { } + public System.IO.Abstractions.IFileSystem FileSystem { get; } + public abstract System.IO.Abstractions.IDirectoryInfo CreateDirectory(string path); + public abstract void Delete(string path); + public abstract void Delete(string path, bool recursive); + public abstract System.Collections.Generic.IEnumerable EnumerateDirectories(string path); + public abstract System.Collections.Generic.IEnumerable EnumerateDirectories(string path, string searchPattern); + public abstract System.Collections.Generic.IEnumerable EnumerateDirectories(string path, string searchPattern, System.IO.SearchOption searchOption); + public abstract System.Collections.Generic.IEnumerable EnumerateFileSystemEntries(string path); + public abstract System.Collections.Generic.IEnumerable EnumerateFileSystemEntries(string path, string searchPattern); + public abstract System.Collections.Generic.IEnumerable EnumerateFileSystemEntries(string path, string searchPattern, System.IO.SearchOption searchOption); + public abstract System.Collections.Generic.IEnumerable EnumerateFiles(string path); + public abstract System.Collections.Generic.IEnumerable EnumerateFiles(string path, string searchPattern); + public abstract System.Collections.Generic.IEnumerable EnumerateFiles(string path, string searchPattern, System.IO.SearchOption searchOption); + public abstract bool Exists(string path); + public abstract System.DateTime GetCreationTime(string path); + public abstract System.DateTime GetCreationTimeUtc(string path); + public abstract string GetCurrentDirectory(); + public abstract string[] GetDirectories(string path); + public abstract string[] GetDirectories(string path, string searchPattern); + public abstract string[] GetDirectories(string path, string searchPattern, System.IO.SearchOption searchOption); + public abstract string GetDirectoryRoot(string path); + public abstract string[] GetFileSystemEntries(string path); + public abstract string[] GetFileSystemEntries(string path, string searchPattern); + public abstract string[] GetFileSystemEntries(string path, string searchPattern, System.IO.SearchOption searchOption); + public abstract string[] GetFiles(string path); + public abstract string[] GetFiles(string path, string searchPattern); + public abstract string[] GetFiles(string path, string searchPattern, System.IO.SearchOption searchOption); + public abstract System.DateTime GetLastAccessTime(string path); + public abstract System.DateTime GetLastAccessTimeUtc(string path); + public abstract System.DateTime GetLastWriteTime(string path); + public abstract System.DateTime GetLastWriteTimeUtc(string path); + public abstract string[] GetLogicalDrives(); + public abstract System.IO.Abstractions.IDirectoryInfo GetParent(string path); + public abstract void Move(string sourceDirName, string destDirName); + public abstract void SetCreationTime(string path, System.DateTime creationTime); + public abstract void SetCreationTimeUtc(string path, System.DateTime creationTimeUtc); + public abstract void SetCurrentDirectory(string path); + public abstract void SetLastAccessTime(string path, System.DateTime lastAccessTime); + public abstract void SetLastAccessTimeUtc(string path, System.DateTime lastAccessTimeUtc); + public abstract void SetLastWriteTime(string path, System.DateTime lastWriteTime); + public abstract void SetLastWriteTimeUtc(string path, System.DateTime lastWriteTimeUtc); + } + public static class DirectoryInfoAclExtensions + { + public static void Create(this System.IO.Abstractions.IDirectoryInfo directoryInfo, System.Security.AccessControl.DirectorySecurity directorySecurity) { } + public static System.Security.AccessControl.DirectorySecurity GetAccessControl(this System.IO.Abstractions.IDirectoryInfo directoryInfo) { } + public static System.Security.AccessControl.DirectorySecurity GetAccessControl(this System.IO.Abstractions.IDirectoryInfo directoryInfo, System.Security.AccessControl.AccessControlSections includeSections) { } + public static void SetAccessControl(this System.IO.Abstractions.IDirectoryInfo directoryInfo, System.Security.AccessControl.DirectorySecurity directorySecurity) { } + } + [System.Serializable] + public abstract class DirectoryInfoBase : System.IO.Abstractions.FileSystemInfoBase, System.IO.Abstractions.IDirectoryInfo, System.IO.Abstractions.IFileSystemInfo + { + protected DirectoryInfoBase(System.IO.Abstractions.IFileSystem fileSystem) { } + public abstract System.IO.Abstractions.IDirectoryInfo Parent { get; } + public abstract System.IO.Abstractions.IDirectoryInfo Root { get; } + public abstract void Create(); + public abstract System.IO.Abstractions.IDirectoryInfo CreateSubdirectory(string path); + public abstract void Delete(bool recursive); + public abstract System.Collections.Generic.IEnumerable EnumerateDirectories(); + public abstract System.Collections.Generic.IEnumerable EnumerateDirectories(string searchPattern); + public abstract System.Collections.Generic.IEnumerable EnumerateDirectories(string searchPattern, System.IO.SearchOption searchOption); + public abstract System.Collections.Generic.IEnumerable EnumerateFileSystemInfos(); + public abstract System.Collections.Generic.IEnumerable EnumerateFileSystemInfos(string searchPattern); + public abstract System.Collections.Generic.IEnumerable EnumerateFileSystemInfos(string searchPattern, System.IO.SearchOption searchOption); + public abstract System.Collections.Generic.IEnumerable EnumerateFiles(); + public abstract System.Collections.Generic.IEnumerable EnumerateFiles(string searchPattern); + public abstract System.Collections.Generic.IEnumerable EnumerateFiles(string searchPattern, System.IO.SearchOption searchOption); + public abstract System.IO.Abstractions.IDirectoryInfo[] GetDirectories(); + public abstract System.IO.Abstractions.IDirectoryInfo[] GetDirectories(string searchPattern); + public abstract System.IO.Abstractions.IDirectoryInfo[] GetDirectories(string searchPattern, System.IO.SearchOption searchOption); + public abstract System.IO.Abstractions.IFileSystemInfo[] GetFileSystemInfos(); + public abstract System.IO.Abstractions.IFileSystemInfo[] GetFileSystemInfos(string searchPattern); + public abstract System.IO.Abstractions.IFileSystemInfo[] GetFileSystemInfos(string searchPattern, System.IO.SearchOption searchOption); + public abstract System.IO.Abstractions.IFileInfo[] GetFiles(); + public abstract System.IO.Abstractions.IFileInfo[] GetFiles(string searchPattern); + public abstract System.IO.Abstractions.IFileInfo[] GetFiles(string searchPattern, System.IO.SearchOption searchOption); + public abstract void MoveTo(string destDirName); + public static System.IO.Abstractions.DirectoryInfoBase op_Implicit(System.IO.DirectoryInfo directoryInfo) { } + } + [System.Serializable] + public class DirectoryInfoWrapper : System.IO.Abstractions.DirectoryInfoBase, System.IO.Abstractions.IFileSystemAclSupport + { + public DirectoryInfoWrapper(System.IO.Abstractions.IFileSystem fileSystem, System.IO.DirectoryInfo instance) { } + public override System.IO.FileAttributes Attributes { get; set; } + public override System.DateTime CreationTime { get; set; } + public override System.DateTime CreationTimeUtc { get; set; } + public override bool Exists { get; } + public override string Extension { get; } + public override string FullName { get; } + public override System.DateTime LastAccessTime { get; set; } + public override System.DateTime LastAccessTimeUtc { get; set; } + public override System.DateTime LastWriteTime { get; set; } + public override System.DateTime LastWriteTimeUtc { get; set; } + public override string Name { get; } + public override System.IO.Abstractions.IDirectoryInfo Parent { get; } + public override System.IO.Abstractions.IDirectoryInfo Root { get; } + public override void Create() { } + public override System.IO.Abstractions.IDirectoryInfo CreateSubdirectory(string path) { } + public override void Delete() { } + public override void Delete(bool recursive) { } + public override System.Collections.Generic.IEnumerable EnumerateDirectories() { } + public override System.Collections.Generic.IEnumerable EnumerateDirectories(string searchPattern) { } + public override System.Collections.Generic.IEnumerable EnumerateDirectories(string searchPattern, System.IO.SearchOption searchOption) { } + public override System.Collections.Generic.IEnumerable EnumerateFileSystemInfos() { } + public override System.Collections.Generic.IEnumerable EnumerateFileSystemInfos(string searchPattern) { } + public override System.Collections.Generic.IEnumerable EnumerateFileSystemInfos(string searchPattern, System.IO.SearchOption searchOption) { } + public override System.Collections.Generic.IEnumerable EnumerateFiles() { } + public override System.Collections.Generic.IEnumerable EnumerateFiles(string searchPattern) { } + public override System.Collections.Generic.IEnumerable EnumerateFiles(string searchPattern, System.IO.SearchOption searchOption) { } + public object GetAccessControl() { } + public object GetAccessControl(System.IO.Abstractions.IFileSystemAclSupport.AccessControlSections includeSections) { } + public override System.IO.Abstractions.IDirectoryInfo[] GetDirectories() { } + public override System.IO.Abstractions.IDirectoryInfo[] GetDirectories(string searchPattern) { } + public override System.IO.Abstractions.IDirectoryInfo[] GetDirectories(string searchPattern, System.IO.SearchOption searchOption) { } + public override System.IO.Abstractions.IFileSystemInfo[] GetFileSystemInfos() { } + public override System.IO.Abstractions.IFileSystemInfo[] GetFileSystemInfos(string searchPattern) { } + public override System.IO.Abstractions.IFileSystemInfo[] GetFileSystemInfos(string searchPattern, System.IO.SearchOption searchOption) { } + public override System.IO.Abstractions.IFileInfo[] GetFiles() { } + public override System.IO.Abstractions.IFileInfo[] GetFiles(string searchPattern) { } + public override System.IO.Abstractions.IFileInfo[] GetFiles(string searchPattern, System.IO.SearchOption searchOption) { } + public override void MoveTo(string destDirName) { } + public override void Refresh() { } + public void SetAccessControl(object value) { } + public override string ToString() { } + } + [System.Serializable] + public class DirectoryWrapper : System.IO.Abstractions.DirectoryBase + { + public DirectoryWrapper(System.IO.Abstractions.IFileSystem fileSystem) { } + public override System.IO.Abstractions.IDirectoryInfo CreateDirectory(string path) { } + public override void Delete(string path) { } + public override void Delete(string path, bool recursive) { } + public override System.Collections.Generic.IEnumerable EnumerateDirectories(string path) { } + public override System.Collections.Generic.IEnumerable EnumerateDirectories(string path, string searchPattern) { } + public override System.Collections.Generic.IEnumerable EnumerateDirectories(string path, string searchPattern, System.IO.SearchOption searchOption) { } + public override System.Collections.Generic.IEnumerable EnumerateFileSystemEntries(string path) { } + public override System.Collections.Generic.IEnumerable EnumerateFileSystemEntries(string path, string searchPattern) { } + public override System.Collections.Generic.IEnumerable EnumerateFileSystemEntries(string path, string searchPattern, System.IO.SearchOption searchOption) { } + public override System.Collections.Generic.IEnumerable EnumerateFiles(string path) { } + public override System.Collections.Generic.IEnumerable EnumerateFiles(string path, string searchPattern) { } + public override System.Collections.Generic.IEnumerable EnumerateFiles(string path, string searchPattern, System.IO.SearchOption searchOption) { } + public override bool Exists(string path) { } + public override System.DateTime GetCreationTime(string path) { } + public override System.DateTime GetCreationTimeUtc(string path) { } + public override string GetCurrentDirectory() { } + public override string[] GetDirectories(string path) { } + public override string[] GetDirectories(string path, string searchPattern) { } + public override string[] GetDirectories(string path, string searchPattern, System.IO.SearchOption searchOption) { } + public override string GetDirectoryRoot(string path) { } + public override string[] GetFileSystemEntries(string path) { } + public override string[] GetFileSystemEntries(string path, string searchPattern) { } + public override string[] GetFileSystemEntries(string path, string searchPattern, System.IO.SearchOption searchOption) { } + public override string[] GetFiles(string path) { } + public override string[] GetFiles(string path, string searchPattern) { } + public override string[] GetFiles(string path, string searchPattern, System.IO.SearchOption searchOption) { } + public override System.DateTime GetLastAccessTime(string path) { } + public override System.DateTime GetLastAccessTimeUtc(string path) { } + public override System.DateTime GetLastWriteTime(string path) { } + public override System.DateTime GetLastWriteTimeUtc(string path) { } + public override string[] GetLogicalDrives() { } + public override System.IO.Abstractions.IDirectoryInfo GetParent(string path) { } + public override void Move(string sourceDirName, string destDirName) { } + public override void SetCreationTime(string path, System.DateTime creationTime) { } + public override void SetCreationTimeUtc(string path, System.DateTime creationTimeUtc) { } + public override void SetCurrentDirectory(string path) { } + public override void SetLastAccessTime(string path, System.DateTime lastAccessTime) { } + public override void SetLastAccessTimeUtc(string path, System.DateTime lastAccessTimeUtc) { } + public override void SetLastWriteTime(string path, System.DateTime lastWriteTime) { } + public override void SetLastWriteTimeUtc(string path, System.DateTime lastWriteTimeUtc) { } + } + [System.Serializable] + public abstract class DriveInfoBase : System.IO.Abstractions.IDriveInfo, System.IO.Abstractions.IFileSystemEntity + { + protected DriveInfoBase(System.IO.Abstractions.IFileSystem fileSystem) { } + public abstract long AvailableFreeSpace { get; } + public abstract string DriveFormat { get; } + public abstract System.IO.DriveType DriveType { get; } + public System.IO.Abstractions.IFileSystem FileSystem { get; } + public abstract bool IsReady { get; } + public abstract string Name { get; } + public abstract System.IO.Abstractions.IDirectoryInfo RootDirectory { get; } + public abstract long TotalFreeSpace { get; } + public abstract long TotalSize { get; } + public abstract string VolumeLabel { get; set; } + public static System.IO.Abstractions.DriveInfoBase op_Implicit(System.IO.DriveInfo driveInfo) { } + } + [System.Serializable] + public class DriveInfoWrapper : System.IO.Abstractions.DriveInfoBase + { + public DriveInfoWrapper(System.IO.Abstractions.IFileSystem fileSystem, System.IO.DriveInfo instance) { } + public override long AvailableFreeSpace { get; } + public override string DriveFormat { get; } + public override System.IO.DriveType DriveType { get; } + public override bool IsReady { get; } + public override string Name { get; } + public override System.IO.Abstractions.IDirectoryInfo RootDirectory { get; } + public override long TotalFreeSpace { get; } + public override long TotalSize { get; } + public override string VolumeLabel { get; set; } + public override string ToString() { } + } + public static class FileAclExtensions + { + public static System.Security.AccessControl.FileSecurity GetAccessControl(this System.IO.Abstractions.IFile file, string path) { } + public static System.Security.AccessControl.FileSecurity GetAccessControl(this System.IO.Abstractions.IFile file, string path, System.Security.AccessControl.AccessControlSections includeSections) { } + public static void SetAccessControl(this System.IO.Abstractions.IFile file, string path, System.Security.AccessControl.FileSecurity fileSecurity) { } + } + [System.Serializable] + public abstract class FileBase : System.IO.Abstractions.IFile, System.IO.Abstractions.IFileSystemEntity + { + protected FileBase(System.IO.Abstractions.IFileSystem fileSystem) { } + public System.IO.Abstractions.IFileSystem FileSystem { get; } + public abstract void AppendAllLines(string path, System.Collections.Generic.IEnumerable contents); + public abstract void AppendAllLines(string path, System.Collections.Generic.IEnumerable contents, System.Text.Encoding encoding); + public abstract void AppendAllText(string path, string contents); + public abstract void AppendAllText(string path, string contents, System.Text.Encoding encoding); + public abstract System.IO.StreamWriter AppendText(string path); + public abstract void Copy(string sourceFileName, string destFileName); + public abstract void Copy(string sourceFileName, string destFileName, bool overwrite); + public abstract System.IO.Abstractions.FileSystemStream Create(string path); + public abstract System.IO.Abstractions.FileSystemStream Create(string path, int bufferSize); + public abstract System.IO.Abstractions.FileSystemStream Create(string path, int bufferSize, System.IO.FileOptions options); + public abstract System.IO.StreamWriter CreateText(string path); + public abstract void Decrypt(string path); + public abstract void Delete(string path); + public abstract void Encrypt(string path); + public abstract bool Exists(string path); + public abstract System.IO.FileAttributes GetAttributes(string path); + public abstract System.DateTime GetCreationTime(string path); + public abstract System.DateTime GetCreationTimeUtc(string path); + public abstract System.DateTime GetLastAccessTime(string path); + public abstract System.DateTime GetLastAccessTimeUtc(string path); + public abstract System.DateTime GetLastWriteTime(string path); + public abstract System.DateTime GetLastWriteTimeUtc(string path); + public abstract void Move(string sourceFileName, string destFileName); + public abstract System.IO.Abstractions.FileSystemStream Open(string path, System.IO.FileMode mode); + public abstract System.IO.Abstractions.FileSystemStream Open(string path, System.IO.FileMode mode, System.IO.FileAccess access); + public abstract System.IO.Abstractions.FileSystemStream Open(string path, System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share); + public abstract System.IO.Abstractions.FileSystemStream OpenRead(string path); + public abstract System.IO.StreamReader OpenText(string path); + public abstract System.IO.Abstractions.FileSystemStream OpenWrite(string path); + public abstract byte[] ReadAllBytes(string path); + public abstract string[] ReadAllLines(string path); + public abstract string[] ReadAllLines(string path, System.Text.Encoding encoding); + public abstract string ReadAllText(string path); + public abstract string ReadAllText(string path, System.Text.Encoding encoding); + public abstract System.Collections.Generic.IEnumerable ReadLines(string path); + public abstract System.Collections.Generic.IEnumerable ReadLines(string path, System.Text.Encoding encoding); + public abstract void Replace(string sourceFileName, string destinationFileName, string destinationBackupFileName); + public abstract void Replace(string sourceFileName, string destinationFileName, string destinationBackupFileName, bool ignoreMetadataErrors); + public abstract void SetAttributes(string path, System.IO.FileAttributes fileAttributes); + public abstract void SetCreationTime(string path, System.DateTime creationTime); + public abstract void SetCreationTimeUtc(string path, System.DateTime creationTimeUtc); + public abstract void SetLastAccessTime(string path, System.DateTime lastAccessTime); + public abstract void SetLastAccessTimeUtc(string path, System.DateTime lastAccessTimeUtc); + public abstract void SetLastWriteTime(string path, System.DateTime lastWriteTime); + public abstract void SetLastWriteTimeUtc(string path, System.DateTime lastWriteTimeUtc); + public abstract void WriteAllBytes(string path, byte[] bytes); + public abstract void WriteAllLines(string path, System.Collections.Generic.IEnumerable contents); + public abstract void WriteAllLines(string path, string[] contents); + public abstract void WriteAllLines(string path, System.Collections.Generic.IEnumerable contents, System.Text.Encoding encoding); + public abstract void WriteAllLines(string path, string[] contents, System.Text.Encoding encoding); + public abstract void WriteAllText(string path, string contents); + public abstract void WriteAllText(string path, string contents, System.Text.Encoding encoding); + } + public static class FileInfoAclExtensions + { + public static System.Security.AccessControl.FileSecurity GetAccessControl(this System.IO.Abstractions.IFileInfo fileInfo) { } + public static System.Security.AccessControl.FileSecurity GetAccessControl(this System.IO.Abstractions.IFileInfo fileInfo, System.Security.AccessControl.AccessControlSections includeSections) { } + public static void SetAccessControl(this System.IO.Abstractions.IFileInfo fileInfo, System.Security.AccessControl.FileSecurity fileSecurity) { } + } + [System.Serializable] + public abstract class FileInfoBase : System.IO.Abstractions.FileSystemInfoBase, System.IO.Abstractions.IFileInfo, System.IO.Abstractions.IFileSystemInfo + { + protected FileInfoBase(System.IO.Abstractions.IFileSystem fileSystem) { } + public abstract System.IO.Abstractions.IDirectoryInfo Directory { get; } + public abstract string DirectoryName { get; } + public abstract bool IsReadOnly { get; set; } + public abstract long Length { get; } + public abstract System.IO.StreamWriter AppendText(); + public abstract System.IO.Abstractions.IFileInfo CopyTo(string destFileName); + public abstract System.IO.Abstractions.IFileInfo CopyTo(string destFileName, bool overwrite); + public abstract System.IO.Abstractions.FileSystemStream Create(); + public abstract System.IO.StreamWriter CreateText(); + public abstract void Decrypt(); + public abstract void Encrypt(); + public abstract void MoveTo(string destFileName); + public abstract System.IO.Abstractions.FileSystemStream Open(System.IO.FileMode mode); + public abstract System.IO.Abstractions.FileSystemStream Open(System.IO.FileMode mode, System.IO.FileAccess access); + public abstract System.IO.Abstractions.FileSystemStream Open(System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share); + public abstract System.IO.Abstractions.FileSystemStream OpenRead(); + public abstract System.IO.StreamReader OpenText(); + public abstract System.IO.Abstractions.FileSystemStream OpenWrite(); + public abstract System.IO.Abstractions.IFileInfo Replace(string destinationFileName, string destinationBackupFileName); + public abstract System.IO.Abstractions.IFileInfo Replace(string destinationFileName, string destinationBackupFileName, bool ignoreMetadataErrors); + public static System.IO.Abstractions.FileInfoBase op_Implicit(System.IO.FileInfo fileInfo) { } + } + [System.Serializable] + public class FileInfoWrapper : System.IO.Abstractions.FileInfoBase, System.IO.Abstractions.IFileSystemAclSupport + { + public FileInfoWrapper(System.IO.Abstractions.IFileSystem fileSystem, System.IO.FileInfo instance) { } + public override System.IO.FileAttributes Attributes { get; set; } + public override System.DateTime CreationTime { get; set; } + public override System.DateTime CreationTimeUtc { get; set; } + public override System.IO.Abstractions.IDirectoryInfo Directory { get; } + public override string DirectoryName { get; } + public override bool Exists { get; } + public override string Extension { get; } + public override string FullName { get; } + public override bool IsReadOnly { get; set; } + public override System.DateTime LastAccessTime { get; set; } + public override System.DateTime LastAccessTimeUtc { get; set; } + public override System.DateTime LastWriteTime { get; set; } + public override System.DateTime LastWriteTimeUtc { get; set; } + public override long Length { get; } + public override string Name { get; } + public override System.IO.StreamWriter AppendText() { } + public override System.IO.Abstractions.IFileInfo CopyTo(string destFileName) { } + public override System.IO.Abstractions.IFileInfo CopyTo(string destFileName, bool overwrite) { } + public override System.IO.Abstractions.FileSystemStream Create() { } + public override System.IO.StreamWriter CreateText() { } + public override void Decrypt() { } + public override void Delete() { } + public override void Encrypt() { } + public object GetAccessControl() { } + public object GetAccessControl(System.IO.Abstractions.IFileSystemAclSupport.AccessControlSections includeSections) { } + public override void MoveTo(string destFileName) { } + public override System.IO.Abstractions.FileSystemStream Open(System.IO.FileMode mode) { } + public override System.IO.Abstractions.FileSystemStream Open(System.IO.FileMode mode, System.IO.FileAccess access) { } + public override System.IO.Abstractions.FileSystemStream Open(System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share) { } + public override System.IO.Abstractions.FileSystemStream OpenRead() { } + public override System.IO.StreamReader OpenText() { } + public override System.IO.Abstractions.FileSystemStream OpenWrite() { } + public override void Refresh() { } + public override System.IO.Abstractions.IFileInfo Replace(string destinationFileName, string destinationBackupFileName) { } + public override System.IO.Abstractions.IFileInfo Replace(string destinationFileName, string destinationBackupFileName, bool ignoreMetadataErrors) { } + public void SetAccessControl(object value) { } + public override string ToString() { } + } + public static class FileStreamAclExtensions + { + public static System.Security.AccessControl.FileSecurity GetAccessControl(this System.IO.Abstractions.FileSystemStream fileStream) { } + public static void SetAccessControl(this System.IO.Abstractions.FileSystemStream fileStream, System.Security.AccessControl.FileSecurity fileSecurity) { } + } + [System.Serializable] + public class FileSystem : System.IO.Abstractions.FileSystemBase + { + public FileSystem() { } + public override System.IO.Abstractions.IDirectory Directory { get; } + public override System.IO.Abstractions.IDirectoryInfoFactory DirectoryInfo { get; } + public override System.IO.Abstractions.IDriveInfoFactory DriveInfo { get; } + public override System.IO.Abstractions.IFile File { get; } + public override System.IO.Abstractions.IFileInfoFactory FileInfo { get; } + public override System.IO.Abstractions.IFileStreamFactory FileStream { get; } + public override System.IO.Abstractions.IFileSystemWatcherFactory FileSystemWatcher { get; } + public override System.IO.Abstractions.IFileVersionInfoFactory FileVersionInfo { get; } + public override System.IO.Abstractions.IPath Path { get; } + } + [System.Serializable] + public abstract class FileSystemBase : System.IO.Abstractions.IFileSystem + { + protected FileSystemBase() { } + public abstract System.IO.Abstractions.IDirectory Directory { get; } + public abstract System.IO.Abstractions.IDirectoryInfoFactory DirectoryInfo { get; } + public abstract System.IO.Abstractions.IDriveInfoFactory DriveInfo { get; } + public abstract System.IO.Abstractions.IFile File { get; } + public abstract System.IO.Abstractions.IFileInfoFactory FileInfo { get; } + public abstract System.IO.Abstractions.IFileStreamFactory FileStream { get; } + public abstract System.IO.Abstractions.IFileSystemWatcherFactory FileSystemWatcher { get; } + public abstract System.IO.Abstractions.IFileVersionInfoFactory FileVersionInfo { get; } + public abstract System.IO.Abstractions.IPath Path { get; } + } + [System.Serializable] + public abstract class FileSystemInfoBase : System.IO.Abstractions.IFileSystemInfo + { + protected FileSystemInfoBase(System.IO.Abstractions.IFileSystem fileSystem) { } + public abstract System.IO.FileAttributes Attributes { get; set; } + public abstract System.DateTime CreationTime { get; set; } + public abstract System.DateTime CreationTimeUtc { get; set; } + public abstract bool Exists { get; } + public abstract string Extension { get; } + public System.IO.Abstractions.IFileSystem FileSystem { get; } + public abstract string FullName { get; } + public abstract System.DateTime LastAccessTime { get; set; } + public abstract System.DateTime LastAccessTimeUtc { get; set; } + public abstract System.DateTime LastWriteTime { get; set; } + public abstract System.DateTime LastWriteTimeUtc { get; set; } + public abstract string Name { get; } + public abstract void Delete(); + public abstract void Refresh(); + } + [System.Serializable] + public abstract class FileSystemWatcherBase : System.IDisposable, System.IO.Abstractions.IFileSystemEntity, System.IO.Abstractions.IFileSystemWatcher + { + protected FileSystemWatcherBase() { } + public abstract System.ComponentModel.IContainer Container { get; } + public abstract bool EnableRaisingEvents { get; set; } + public abstract System.IO.Abstractions.IFileSystem FileSystem { get; } + public abstract string Filter { get; set; } + public abstract bool IncludeSubdirectories { get; set; } + public abstract int InternalBufferSize { get; set; } + public abstract System.IO.NotifyFilters NotifyFilter { get; set; } + public abstract string Path { get; set; } + public abstract System.ComponentModel.ISite Site { get; set; } + public abstract System.ComponentModel.ISynchronizeInvoke SynchronizingObject { get; set; } + public virtual event System.IO.FileSystemEventHandler Changed; + public virtual event System.IO.FileSystemEventHandler Created; + public virtual event System.IO.FileSystemEventHandler Deleted; + public virtual event System.IO.ErrorEventHandler Error; + public virtual event System.IO.RenamedEventHandler Renamed; + public abstract void BeginInit(); + public void Dispose() { } + public virtual void Dispose(bool disposing) { } + public abstract void EndInit(); + protected void OnChanged(object sender, System.IO.FileSystemEventArgs args) { } + protected void OnCreated(object sender, System.IO.FileSystemEventArgs args) { } + protected void OnDeleted(object sender, System.IO.FileSystemEventArgs args) { } + protected void OnError(object sender, System.IO.ErrorEventArgs args) { } + protected void OnRenamed(object sender, System.IO.RenamedEventArgs args) { } + public abstract System.IO.Abstractions.IWaitForChangedResult WaitForChanged(System.IO.WatcherChangeTypes changeType); + public abstract System.IO.Abstractions.IWaitForChangedResult WaitForChanged(System.IO.WatcherChangeTypes changeType, int timeout); + public static System.IO.Abstractions.FileSystemWatcherBase op_Implicit(System.IO.FileSystemWatcher watcher) { } + } + [System.Serializable] + public class FileSystemWatcherFactory : System.IO.Abstractions.IFileSystemEntity, System.IO.Abstractions.IFileSystemWatcherFactory + { + public FileSystemWatcherFactory(System.IO.Abstractions.IFileSystem fileSystem) { } + public System.IO.Abstractions.IFileSystem FileSystem { get; } + public System.IO.Abstractions.IFileSystemWatcher New() { } + public System.IO.Abstractions.IFileSystemWatcher New(string path) { } + public System.IO.Abstractions.IFileSystemWatcher New(string path, string filter) { } + public System.IO.Abstractions.IFileSystemWatcher Wrap(System.IO.FileSystemWatcher fileSystemWatcher) { } + } + [System.Serializable] + public class FileSystemWatcherWrapper : System.IO.Abstractions.FileSystemWatcherBase + { + public FileSystemWatcherWrapper(System.IO.Abstractions.IFileSystem fileSystem) { } + public FileSystemWatcherWrapper(System.IO.Abstractions.IFileSystem fileSystem, System.IO.FileSystemWatcher watcher) { } + public FileSystemWatcherWrapper(System.IO.Abstractions.IFileSystem fileSystem, string path) { } + public FileSystemWatcherWrapper(System.IO.Abstractions.IFileSystem fileSystem, string path, string filter) { } + public override System.ComponentModel.IContainer Container { get; } + public override bool EnableRaisingEvents { get; set; } + public override System.IO.Abstractions.IFileSystem FileSystem { get; } + public override string Filter { get; set; } + public override bool IncludeSubdirectories { get; set; } + public override int InternalBufferSize { get; set; } + public override System.IO.NotifyFilters NotifyFilter { get; set; } + public override string Path { get; set; } + public override System.ComponentModel.ISite Site { get; set; } + public override System.ComponentModel.ISynchronizeInvoke SynchronizingObject { get; set; } + public override void BeginInit() { } + public override void Dispose(bool disposing) { } + public override void EndInit() { } + public override System.IO.Abstractions.IWaitForChangedResult WaitForChanged(System.IO.WatcherChangeTypes changeType) { } + public override System.IO.Abstractions.IWaitForChangedResult WaitForChanged(System.IO.WatcherChangeTypes changeType, int timeout) { } + } + [System.Serializable] + public abstract class FileVersionInfoBase : System.IO.Abstractions.IFileVersionInfo + { + protected FileVersionInfoBase() { } + public abstract string Comments { get; } + public abstract string CompanyName { get; } + public abstract int FileBuildPart { get; } + public abstract string FileDescription { get; } + public abstract int FileMajorPart { get; } + public abstract int FileMinorPart { get; } + public abstract string FileName { get; } + public abstract int FilePrivatePart { get; } + public abstract string FileVersion { get; } + public abstract string InternalName { get; } + public abstract bool IsDebug { get; } + public abstract bool IsPatched { get; } + public abstract bool IsPreRelease { get; } + public abstract bool IsPrivateBuild { get; } + public abstract bool IsSpecialBuild { get; } + public abstract string Language { get; } + public abstract string LegalCopyright { get; } + public abstract string LegalTrademarks { get; } + public abstract string OriginalFilename { get; } + public abstract string PrivateBuild { get; } + public abstract int ProductBuildPart { get; } + public abstract int ProductMajorPart { get; } + public abstract int ProductMinorPart { get; } + public abstract string ProductName { get; } + public abstract int ProductPrivatePart { get; } + public abstract string ProductVersion { get; } + public abstract string SpecialBuild { get; } + public abstract string ToString(); + public static System.IO.Abstractions.FileVersionInfoBase op_Implicit(System.Diagnostics.FileVersionInfo fileVersionInfo) { } + } + [System.Serializable] + public class FileVersionInfoWrapper : System.IO.Abstractions.FileVersionInfoBase + { + public FileVersionInfoWrapper(System.Diagnostics.FileVersionInfo fileVersionInfo) { } + public override string Comments { get; } + public override string CompanyName { get; } + public override int FileBuildPart { get; } + public override string FileDescription { get; } + public override int FileMajorPart { get; } + public override int FileMinorPart { get; } + public override string FileName { get; } + public override int FilePrivatePart { get; } + public override string FileVersion { get; } + public override string InternalName { get; } + public override bool IsDebug { get; } + public override bool IsPatched { get; } + public override bool IsPreRelease { get; } + public override bool IsPrivateBuild { get; } + public override bool IsSpecialBuild { get; } + public override string Language { get; } + public override string LegalCopyright { get; } + public override string LegalTrademarks { get; } + public override string OriginalFilename { get; } + public override string PrivateBuild { get; } + public override int ProductBuildPart { get; } + public override int ProductMajorPart { get; } + public override int ProductMinorPart { get; } + public override string ProductName { get; } + public override int ProductPrivatePart { get; } + public override string ProductVersion { get; } + public override string SpecialBuild { get; } + public override string ToString() { } + } + [System.Serializable] + public class FileWrapper : System.IO.Abstractions.FileBase + { + public FileWrapper(System.IO.Abstractions.IFileSystem fileSystem) { } + public override void AppendAllLines(string path, System.Collections.Generic.IEnumerable contents) { } + public override void AppendAllLines(string path, System.Collections.Generic.IEnumerable contents, System.Text.Encoding encoding) { } + public override void AppendAllText(string path, string contents) { } + public override void AppendAllText(string path, string contents, System.Text.Encoding encoding) { } + public override System.IO.StreamWriter AppendText(string path) { } + public override void Copy(string sourceFileName, string destFileName) { } + public override void Copy(string sourceFileName, string destFileName, bool overwrite) { } + public override System.IO.Abstractions.FileSystemStream Create(string path) { } + public override System.IO.Abstractions.FileSystemStream Create(string path, int bufferSize) { } + public override System.IO.Abstractions.FileSystemStream Create(string path, int bufferSize, System.IO.FileOptions options) { } + public override System.IO.StreamWriter CreateText(string path) { } + public override void Decrypt(string path) { } + public override void Delete(string path) { } + public override void Encrypt(string path) { } + public override bool Exists(string path) { } + public override System.IO.FileAttributes GetAttributes(string path) { } + public override System.DateTime GetCreationTime(string path) { } + public override System.DateTime GetCreationTimeUtc(string path) { } + public override System.DateTime GetLastAccessTime(string path) { } + public override System.DateTime GetLastAccessTimeUtc(string path) { } + public override System.DateTime GetLastWriteTime(string path) { } + public override System.DateTime GetLastWriteTimeUtc(string path) { } + public override void Move(string sourceFileName, string destFileName) { } + public override System.IO.Abstractions.FileSystemStream Open(string path, System.IO.FileMode mode) { } + public override System.IO.Abstractions.FileSystemStream Open(string path, System.IO.FileMode mode, System.IO.FileAccess access) { } + public override System.IO.Abstractions.FileSystemStream Open(string path, System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share) { } + public override System.IO.Abstractions.FileSystemStream OpenRead(string path) { } + public override System.IO.StreamReader OpenText(string path) { } + public override System.IO.Abstractions.FileSystemStream OpenWrite(string path) { } + public override byte[] ReadAllBytes(string path) { } + public override string[] ReadAllLines(string path) { } + public override string[] ReadAllLines(string path, System.Text.Encoding encoding) { } + public override string ReadAllText(string path) { } + public override string ReadAllText(string path, System.Text.Encoding encoding) { } + public override System.Collections.Generic.IEnumerable ReadLines(string path) { } + public override System.Collections.Generic.IEnumerable ReadLines(string path, System.Text.Encoding encoding) { } + public override void Replace(string sourceFileName, string destinationFileName, string destinationBackupFileName) { } + public override void Replace(string sourceFileName, string destinationFileName, string destinationBackupFileName, bool ignoreMetadataErrors) { } + public override void SetAttributes(string path, System.IO.FileAttributes fileAttributes) { } + public override void SetCreationTime(string path, System.DateTime creationTime) { } + public override void SetCreationTimeUtc(string path, System.DateTime creationTimeUtc) { } + public override void SetLastAccessTime(string path, System.DateTime lastAccessTime) { } + public override void SetLastAccessTimeUtc(string path, System.DateTime lastAccessTimeUtc) { } + public override void SetLastWriteTime(string path, System.DateTime lastWriteTime) { } + public override void SetLastWriteTimeUtc(string path, System.DateTime lastWriteTimeUtc) { } + public override void WriteAllBytes(string path, byte[] bytes) { } + public override void WriteAllLines(string path, System.Collections.Generic.IEnumerable contents) { } + public override void WriteAllLines(string path, string[] contents) { } + public override void WriteAllLines(string path, System.Collections.Generic.IEnumerable contents, System.Text.Encoding encoding) { } + public override void WriteAllLines(string path, string[] contents, System.Text.Encoding encoding) { } + public override void WriteAllText(string path, string contents) { } + public override void WriteAllText(string path, string contents, System.Text.Encoding encoding) { } + } + [System.Serializable] + public abstract class PathBase : System.IO.Abstractions.IFileSystemEntity, System.IO.Abstractions.IPath + { + protected PathBase(System.IO.Abstractions.IFileSystem fileSystem) { } + public abstract char AltDirectorySeparatorChar { get; } + public abstract char DirectorySeparatorChar { get; } + public System.IO.Abstractions.IFileSystem FileSystem { get; } + [System.Obsolete("Please use GetInvalidPathChars or GetInvalidFileNameChars instead.")] + public abstract char[] InvalidPathChars { get; } + public abstract char PathSeparator { get; } + public abstract char VolumeSeparatorChar { get; } + public abstract string ChangeExtension(string path, string extension); + public abstract string Combine(params string[] paths); + public abstract string Combine(string path1, string path2); + public abstract string Combine(string path1, string path2, string path3); + public abstract string Combine(string path1, string path2, string path3, string path4); + public abstract string GetDirectoryName(string path); + public abstract string GetExtension(string path); + public abstract string GetFileName(string path); + public abstract string GetFileNameWithoutExtension(string path); + public abstract string GetFullPath(string path); + public abstract char[] GetInvalidFileNameChars(); + public abstract char[] GetInvalidPathChars(); + public abstract string GetPathRoot(string path); + public abstract string GetRandomFileName(); + public abstract string GetTempFileName(); + public abstract string GetTempPath(); + public abstract bool HasExtension(string path); + public abstract bool IsPathRooted(string path); + } + [System.Serializable] + public class PathWrapper : System.IO.Abstractions.PathBase + { + public PathWrapper(System.IO.Abstractions.IFileSystem fileSystem) { } + public override char AltDirectorySeparatorChar { get; } + public override char DirectorySeparatorChar { get; } + [System.Obsolete("Please use GetInvalidPathChars or GetInvalidFileNameChars instead.")] + public override char[] InvalidPathChars { get; } + public override char PathSeparator { get; } + public override char VolumeSeparatorChar { get; } + public override string ChangeExtension(string path, string extension) { } + public override string Combine(params string[] paths) { } + public override string Combine(string path1, string path2) { } + public override string Combine(string path1, string path2, string path3) { } + public override string Combine(string path1, string path2, string path3, string path4) { } + public override string GetDirectoryName(string path) { } + public override string GetExtension(string path) { } + public override string GetFileName(string path) { } + public override string GetFileNameWithoutExtension(string path) { } + public override string GetFullPath(string path) { } + public override char[] GetInvalidFileNameChars() { } + public override char[] GetInvalidPathChars() { } + public override string GetPathRoot(string path) { } + public override string GetRandomFileName() { } + public override string GetTempFileName() { } + public override string GetTempPath() { } + public override bool HasExtension(string path) { } + public override bool IsPathRooted(string path) { } + } +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.Api.Tests/Expected/TestableIO.System.IO.Abstractions.Wrappers_net6.0.txt b/tests/TestableIO.System.IO.Abstractions.Api.Tests/Expected/TestableIO.System.IO.Abstractions.Wrappers_net6.0.txt new file mode 100644 index 000000000..a9edda72e --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.Api.Tests/Expected/TestableIO.System.IO.Abstractions.Wrappers_net6.0.txt @@ -0,0 +1,811 @@ +[assembly: System.CLSCompliant(true)] +[assembly: System.Reflection.AssemblyMetadata("RepositoryUrl", "https://github.com/TestableIO/System.IO.Abstractions.git")] +[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(@"DynamicProxyGenAssembly2, PublicKey=0024000004800000940000000602000000240000525341310004000001000100c547cac37abd99c8db225ef2f6c8a3602f3b3606cc9891605d02baa56104f4cfc0734aa39b93bf7852f7d9266654753cc297e7d2edfe0bac1cdcf9f717241550e0a7b191195b7667bb4f64bcb8e2121380fd1d9d46ad2d92d2d15605093924cceaf74c4861eff62abf69b9291ed0a340e113be11e6a7d3113e92484cf7045cc7")] +[assembly: System.Runtime.Versioning.TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName=".NET 6.0")] +namespace System.IO.Abstractions +{ + public static class DirectoryAclExtensions + { + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public static void CreateDirectory(this System.IO.Abstractions.IDirectory directory, string path, System.Security.AccessControl.DirectorySecurity directorySecurity) { } + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public static System.Security.AccessControl.DirectorySecurity GetAccessControl(this System.IO.Abstractions.IDirectory directory, string path) { } + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public static System.Security.AccessControl.DirectorySecurity GetAccessControl(this System.IO.Abstractions.IDirectory directory, string path, System.Security.AccessControl.AccessControlSections includeSections) { } + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public static void SetAccessControl(this System.IO.Abstractions.IDirectory directory, string path, System.Security.AccessControl.DirectorySecurity directorySecurity) { } + } + [System.Serializable] + public abstract class DirectoryBase : System.IO.Abstractions.IDirectory, System.IO.Abstractions.IFileSystemEntity + { + protected DirectoryBase(System.IO.Abstractions.IFileSystem fileSystem) { } + public System.IO.Abstractions.IFileSystem FileSystem { get; } + public abstract System.IO.Abstractions.IDirectoryInfo CreateDirectory(string path); + public abstract System.IO.Abstractions.IFileSystemInfo CreateSymbolicLink(string path, string pathToTarget); + public abstract void Delete(string path); + public abstract void Delete(string path, bool recursive); + public abstract System.Collections.Generic.IEnumerable EnumerateDirectories(string path); + public abstract System.Collections.Generic.IEnumerable EnumerateDirectories(string path, string searchPattern); + public abstract System.Collections.Generic.IEnumerable EnumerateDirectories(string path, string searchPattern, System.IO.EnumerationOptions enumerationOptions); + public abstract System.Collections.Generic.IEnumerable EnumerateDirectories(string path, string searchPattern, System.IO.SearchOption searchOption); + public abstract System.Collections.Generic.IEnumerable EnumerateFileSystemEntries(string path); + public abstract System.Collections.Generic.IEnumerable EnumerateFileSystemEntries(string path, string searchPattern); + public abstract System.Collections.Generic.IEnumerable EnumerateFileSystemEntries(string path, string searchPattern, System.IO.EnumerationOptions enumerationOptions); + public abstract System.Collections.Generic.IEnumerable EnumerateFileSystemEntries(string path, string searchPattern, System.IO.SearchOption searchOption); + public abstract System.Collections.Generic.IEnumerable EnumerateFiles(string path); + public abstract System.Collections.Generic.IEnumerable EnumerateFiles(string path, string searchPattern); + public abstract System.Collections.Generic.IEnumerable EnumerateFiles(string path, string searchPattern, System.IO.EnumerationOptions enumerationOptions); + public abstract System.Collections.Generic.IEnumerable EnumerateFiles(string path, string searchPattern, System.IO.SearchOption searchOption); + public abstract bool Exists(string path); + public abstract System.DateTime GetCreationTime(string path); + public abstract System.DateTime GetCreationTimeUtc(string path); + public abstract string GetCurrentDirectory(); + public abstract string[] GetDirectories(string path); + public abstract string[] GetDirectories(string path, string searchPattern); + public abstract string[] GetDirectories(string path, string searchPattern, System.IO.EnumerationOptions enumerationOptions); + public abstract string[] GetDirectories(string path, string searchPattern, System.IO.SearchOption searchOption); + public abstract string GetDirectoryRoot(string path); + public abstract string[] GetFileSystemEntries(string path); + public abstract string[] GetFileSystemEntries(string path, string searchPattern); + public abstract string[] GetFileSystemEntries(string path, string searchPattern, System.IO.EnumerationOptions enumerationOptions); + public abstract string[] GetFileSystemEntries(string path, string searchPattern, System.IO.SearchOption searchOption); + public abstract string[] GetFiles(string path); + public abstract string[] GetFiles(string path, string searchPattern); + public abstract string[] GetFiles(string path, string searchPattern, System.IO.EnumerationOptions enumerationOptions); + public abstract string[] GetFiles(string path, string searchPattern, System.IO.SearchOption searchOption); + public abstract System.DateTime GetLastAccessTime(string path); + public abstract System.DateTime GetLastAccessTimeUtc(string path); + public abstract System.DateTime GetLastWriteTime(string path); + public abstract System.DateTime GetLastWriteTimeUtc(string path); + public abstract string[] GetLogicalDrives(); + public abstract System.IO.Abstractions.IDirectoryInfo GetParent(string path); + public abstract void Move(string sourceDirName, string destDirName); + public abstract System.IO.Abstractions.IFileSystemInfo ResolveLinkTarget(string linkPath, bool returnFinalTarget); + public abstract void SetCreationTime(string path, System.DateTime creationTime); + public abstract void SetCreationTimeUtc(string path, System.DateTime creationTimeUtc); + public abstract void SetCurrentDirectory(string path); + public abstract void SetLastAccessTime(string path, System.DateTime lastAccessTime); + public abstract void SetLastAccessTimeUtc(string path, System.DateTime lastAccessTimeUtc); + public abstract void SetLastWriteTime(string path, System.DateTime lastWriteTime); + public abstract void SetLastWriteTimeUtc(string path, System.DateTime lastWriteTimeUtc); + } + public static class DirectoryInfoAclExtensions + { + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public static void Create(this System.IO.Abstractions.IDirectoryInfo directoryInfo, System.Security.AccessControl.DirectorySecurity directorySecurity) { } + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public static System.Security.AccessControl.DirectorySecurity GetAccessControl(this System.IO.Abstractions.IDirectoryInfo directoryInfo) { } + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public static System.Security.AccessControl.DirectorySecurity GetAccessControl(this System.IO.Abstractions.IDirectoryInfo directoryInfo, System.Security.AccessControl.AccessControlSections includeSections) { } + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public static void SetAccessControl(this System.IO.Abstractions.IDirectoryInfo directoryInfo, System.Security.AccessControl.DirectorySecurity directorySecurity) { } + } + [System.Serializable] + public abstract class DirectoryInfoBase : System.IO.Abstractions.FileSystemInfoBase, System.IO.Abstractions.IDirectoryInfo, System.IO.Abstractions.IFileSystemInfo + { + protected DirectoryInfoBase(System.IO.Abstractions.IFileSystem fileSystem) { } + public abstract System.IO.Abstractions.IDirectoryInfo Parent { get; } + public abstract System.IO.Abstractions.IDirectoryInfo Root { get; } + public abstract void Create(); + public abstract System.IO.Abstractions.IDirectoryInfo CreateSubdirectory(string path); + public abstract void Delete(bool recursive); + public abstract System.Collections.Generic.IEnumerable EnumerateDirectories(); + public abstract System.Collections.Generic.IEnumerable EnumerateDirectories(string searchPattern); + public abstract System.Collections.Generic.IEnumerable EnumerateDirectories(string searchPattern, System.IO.EnumerationOptions enumerationOptions); + public abstract System.Collections.Generic.IEnumerable EnumerateDirectories(string searchPattern, System.IO.SearchOption searchOption); + public abstract System.Collections.Generic.IEnumerable EnumerateFileSystemInfos(); + public abstract System.Collections.Generic.IEnumerable EnumerateFileSystemInfos(string searchPattern); + public abstract System.Collections.Generic.IEnumerable EnumerateFileSystemInfos(string searchPattern, System.IO.EnumerationOptions enumerationOptions); + public abstract System.Collections.Generic.IEnumerable EnumerateFileSystemInfos(string searchPattern, System.IO.SearchOption searchOption); + public abstract System.Collections.Generic.IEnumerable EnumerateFiles(); + public abstract System.Collections.Generic.IEnumerable EnumerateFiles(string searchPattern); + public abstract System.Collections.Generic.IEnumerable EnumerateFiles(string searchPattern, System.IO.EnumerationOptions enumerationOptions); + public abstract System.Collections.Generic.IEnumerable EnumerateFiles(string searchPattern, System.IO.SearchOption searchOption); + public abstract System.IO.Abstractions.IDirectoryInfo[] GetDirectories(); + public abstract System.IO.Abstractions.IDirectoryInfo[] GetDirectories(string searchPattern); + public abstract System.IO.Abstractions.IDirectoryInfo[] GetDirectories(string searchPattern, System.IO.EnumerationOptions enumerationOptions); + public abstract System.IO.Abstractions.IDirectoryInfo[] GetDirectories(string searchPattern, System.IO.SearchOption searchOption); + public abstract System.IO.Abstractions.IFileSystemInfo[] GetFileSystemInfos(); + public abstract System.IO.Abstractions.IFileSystemInfo[] GetFileSystemInfos(string searchPattern); + public abstract System.IO.Abstractions.IFileSystemInfo[] GetFileSystemInfos(string searchPattern, System.IO.EnumerationOptions enumerationOptions); + public abstract System.IO.Abstractions.IFileSystemInfo[] GetFileSystemInfos(string searchPattern, System.IO.SearchOption searchOption); + public abstract System.IO.Abstractions.IFileInfo[] GetFiles(); + public abstract System.IO.Abstractions.IFileInfo[] GetFiles(string searchPattern); + public abstract System.IO.Abstractions.IFileInfo[] GetFiles(string searchPattern, System.IO.EnumerationOptions enumerationOptions); + public abstract System.IO.Abstractions.IFileInfo[] GetFiles(string searchPattern, System.IO.SearchOption searchOption); + public abstract void MoveTo(string destDirName); + public static System.IO.Abstractions.DirectoryInfoBase op_Implicit(System.IO.DirectoryInfo directoryInfo) { } + } + [System.Serializable] + public class DirectoryInfoWrapper : System.IO.Abstractions.DirectoryInfoBase, System.IO.Abstractions.IFileSystemAclSupport + { + public DirectoryInfoWrapper(System.IO.Abstractions.IFileSystem fileSystem, System.IO.DirectoryInfo instance) { } + public override System.IO.FileAttributes Attributes { get; set; } + public override System.DateTime CreationTime { get; set; } + public override System.DateTime CreationTimeUtc { get; set; } + public override bool Exists { get; } + public override string Extension { get; } + public override string FullName { get; } + public override System.DateTime LastAccessTime { get; set; } + public override System.DateTime LastAccessTimeUtc { get; set; } + public override System.DateTime LastWriteTime { get; set; } + public override System.DateTime LastWriteTimeUtc { get; set; } + public override string LinkTarget { get; } + public override string Name { get; } + public override System.IO.Abstractions.IDirectoryInfo Parent { get; } + public override System.IO.Abstractions.IDirectoryInfo Root { get; } + public override void Create() { } + public override void CreateAsSymbolicLink(string pathToTarget) { } + public override System.IO.Abstractions.IDirectoryInfo CreateSubdirectory(string path) { } + public override void Delete() { } + public override void Delete(bool recursive) { } + public override System.Collections.Generic.IEnumerable EnumerateDirectories() { } + public override System.Collections.Generic.IEnumerable EnumerateDirectories(string searchPattern) { } + public override System.Collections.Generic.IEnumerable EnumerateDirectories(string searchPattern, System.IO.EnumerationOptions enumerationOptions) { } + public override System.Collections.Generic.IEnumerable EnumerateDirectories(string searchPattern, System.IO.SearchOption searchOption) { } + public override System.Collections.Generic.IEnumerable EnumerateFileSystemInfos() { } + public override System.Collections.Generic.IEnumerable EnumerateFileSystemInfos(string searchPattern) { } + public override System.Collections.Generic.IEnumerable EnumerateFileSystemInfos(string searchPattern, System.IO.EnumerationOptions enumerationOptions) { } + public override System.Collections.Generic.IEnumerable EnumerateFileSystemInfos(string searchPattern, System.IO.SearchOption searchOption) { } + public override System.Collections.Generic.IEnumerable EnumerateFiles() { } + public override System.Collections.Generic.IEnumerable EnumerateFiles(string searchPattern) { } + public override System.Collections.Generic.IEnumerable EnumerateFiles(string searchPattern, System.IO.EnumerationOptions enumerationOptions) { } + public override System.Collections.Generic.IEnumerable EnumerateFiles(string searchPattern, System.IO.SearchOption searchOption) { } + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public object GetAccessControl() { } + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public object GetAccessControl(System.IO.Abstractions.IFileSystemAclSupport.AccessControlSections includeSections) { } + public override System.IO.Abstractions.IDirectoryInfo[] GetDirectories() { } + public override System.IO.Abstractions.IDirectoryInfo[] GetDirectories(string searchPattern) { } + public override System.IO.Abstractions.IDirectoryInfo[] GetDirectories(string searchPattern, System.IO.EnumerationOptions enumerationOptions) { } + public override System.IO.Abstractions.IDirectoryInfo[] GetDirectories(string searchPattern, System.IO.SearchOption searchOption) { } + public override System.IO.Abstractions.IFileSystemInfo[] GetFileSystemInfos() { } + public override System.IO.Abstractions.IFileSystemInfo[] GetFileSystemInfos(string searchPattern) { } + public override System.IO.Abstractions.IFileSystemInfo[] GetFileSystemInfos(string searchPattern, System.IO.EnumerationOptions enumerationOptions) { } + public override System.IO.Abstractions.IFileSystemInfo[] GetFileSystemInfos(string searchPattern, System.IO.SearchOption searchOption) { } + public override System.IO.Abstractions.IFileInfo[] GetFiles() { } + public override System.IO.Abstractions.IFileInfo[] GetFiles(string searchPattern) { } + public override System.IO.Abstractions.IFileInfo[] GetFiles(string searchPattern, System.IO.EnumerationOptions enumerationOptions) { } + public override System.IO.Abstractions.IFileInfo[] GetFiles(string searchPattern, System.IO.SearchOption searchOption) { } + public override void MoveTo(string destDirName) { } + public override void Refresh() { } + public override System.IO.Abstractions.IFileSystemInfo ResolveLinkTarget(bool returnFinalTarget) { } + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public void SetAccessControl(object value) { } + public override string ToString() { } + } + [System.Serializable] + public class DirectoryWrapper : System.IO.Abstractions.DirectoryBase + { + public DirectoryWrapper(System.IO.Abstractions.IFileSystem fileSystem) { } + public override System.IO.Abstractions.IDirectoryInfo CreateDirectory(string path) { } + public override System.IO.Abstractions.IFileSystemInfo CreateSymbolicLink(string path, string pathToTarget) { } + public override void Delete(string path) { } + public override void Delete(string path, bool recursive) { } + public override System.Collections.Generic.IEnumerable EnumerateDirectories(string path) { } + public override System.Collections.Generic.IEnumerable EnumerateDirectories(string path, string searchPattern) { } + public override System.Collections.Generic.IEnumerable EnumerateDirectories(string path, string searchPattern, System.IO.EnumerationOptions enumerationOptions) { } + public override System.Collections.Generic.IEnumerable EnumerateDirectories(string path, string searchPattern, System.IO.SearchOption searchOption) { } + public override System.Collections.Generic.IEnumerable EnumerateFileSystemEntries(string path) { } + public override System.Collections.Generic.IEnumerable EnumerateFileSystemEntries(string path, string searchPattern) { } + public override System.Collections.Generic.IEnumerable EnumerateFileSystemEntries(string path, string searchPattern, System.IO.EnumerationOptions enumerationOptions) { } + public override System.Collections.Generic.IEnumerable EnumerateFileSystemEntries(string path, string searchPattern, System.IO.SearchOption searchOption) { } + public override System.Collections.Generic.IEnumerable EnumerateFiles(string path) { } + public override System.Collections.Generic.IEnumerable EnumerateFiles(string path, string searchPattern) { } + public override System.Collections.Generic.IEnumerable EnumerateFiles(string path, string searchPattern, System.IO.EnumerationOptions enumerationOptions) { } + public override System.Collections.Generic.IEnumerable EnumerateFiles(string path, string searchPattern, System.IO.SearchOption searchOption) { } + public override bool Exists(string path) { } + public override System.DateTime GetCreationTime(string path) { } + public override System.DateTime GetCreationTimeUtc(string path) { } + public override string GetCurrentDirectory() { } + public override string[] GetDirectories(string path) { } + public override string[] GetDirectories(string path, string searchPattern) { } + public override string[] GetDirectories(string path, string searchPattern, System.IO.EnumerationOptions enumerationOptions) { } + public override string[] GetDirectories(string path, string searchPattern, System.IO.SearchOption searchOption) { } + public override string GetDirectoryRoot(string path) { } + public override string[] GetFileSystemEntries(string path) { } + public override string[] GetFileSystemEntries(string path, string searchPattern) { } + public override string[] GetFileSystemEntries(string path, string searchPattern, System.IO.EnumerationOptions enumerationOptions) { } + public override string[] GetFileSystemEntries(string path, string searchPattern, System.IO.SearchOption searchOption) { } + public override string[] GetFiles(string path) { } + public override string[] GetFiles(string path, string searchPattern) { } + public override string[] GetFiles(string path, string searchPattern, System.IO.EnumerationOptions enumerationOptions) { } + public override string[] GetFiles(string path, string searchPattern, System.IO.SearchOption searchOption) { } + public override System.DateTime GetLastAccessTime(string path) { } + public override System.DateTime GetLastAccessTimeUtc(string path) { } + public override System.DateTime GetLastWriteTime(string path) { } + public override System.DateTime GetLastWriteTimeUtc(string path) { } + public override string[] GetLogicalDrives() { } + public override System.IO.Abstractions.IDirectoryInfo GetParent(string path) { } + public override void Move(string sourceDirName, string destDirName) { } + public override System.IO.Abstractions.IFileSystemInfo ResolveLinkTarget(string linkPath, bool returnFinalTarget) { } + public override void SetCreationTime(string path, System.DateTime creationTime) { } + public override void SetCreationTimeUtc(string path, System.DateTime creationTimeUtc) { } + public override void SetCurrentDirectory(string path) { } + public override void SetLastAccessTime(string path, System.DateTime lastAccessTime) { } + public override void SetLastAccessTimeUtc(string path, System.DateTime lastAccessTimeUtc) { } + public override void SetLastWriteTime(string path, System.DateTime lastWriteTime) { } + public override void SetLastWriteTimeUtc(string path, System.DateTime lastWriteTimeUtc) { } + } + [System.Serializable] + public abstract class DriveInfoBase : System.IO.Abstractions.IDriveInfo, System.IO.Abstractions.IFileSystemEntity + { + protected DriveInfoBase(System.IO.Abstractions.IFileSystem fileSystem) { } + public abstract long AvailableFreeSpace { get; } + public abstract string DriveFormat { get; } + public abstract System.IO.DriveType DriveType { get; } + public System.IO.Abstractions.IFileSystem FileSystem { get; } + public abstract bool IsReady { get; } + public abstract string Name { get; } + public abstract System.IO.Abstractions.IDirectoryInfo RootDirectory { get; } + public abstract long TotalFreeSpace { get; } + public abstract long TotalSize { get; } + public abstract string VolumeLabel { get; set; } + public static System.IO.Abstractions.DriveInfoBase op_Implicit(System.IO.DriveInfo driveInfo) { } + } + [System.Serializable] + public class DriveInfoWrapper : System.IO.Abstractions.DriveInfoBase + { + public DriveInfoWrapper(System.IO.Abstractions.IFileSystem fileSystem, System.IO.DriveInfo instance) { } + public override long AvailableFreeSpace { get; } + public override string DriveFormat { get; } + public override System.IO.DriveType DriveType { get; } + public override bool IsReady { get; } + public override string Name { get; } + public override System.IO.Abstractions.IDirectoryInfo RootDirectory { get; } + public override long TotalFreeSpace { get; } + public override long TotalSize { get; } + [set: System.Runtime.Versioning.SupportedOSPlatform("windows")] + public override string VolumeLabel { get; set; } + public override string ToString() { } + } + public static class FileAclExtensions + { + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public static System.Security.AccessControl.FileSecurity GetAccessControl(this System.IO.Abstractions.IFile file, string path) { } + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public static System.Security.AccessControl.FileSecurity GetAccessControl(this System.IO.Abstractions.IFile file, string path, System.Security.AccessControl.AccessControlSections includeSections) { } + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public static void SetAccessControl(this System.IO.Abstractions.IFile file, string path, System.Security.AccessControl.FileSecurity fileSecurity) { } + } + [System.Serializable] + public abstract class FileBase : System.IO.Abstractions.IFile, System.IO.Abstractions.IFileSystemEntity + { + protected FileBase(System.IO.Abstractions.IFileSystem fileSystem) { } + public System.IO.Abstractions.IFileSystem FileSystem { get; } + public abstract void AppendAllLines(string path, System.Collections.Generic.IEnumerable contents); + public abstract void AppendAllLines(string path, System.Collections.Generic.IEnumerable contents, System.Text.Encoding encoding); + public abstract System.Threading.Tasks.Task AppendAllLinesAsync(string path, System.Collections.Generic.IEnumerable contents, System.Threading.CancellationToken cancellationToken = default); + public abstract System.Threading.Tasks.Task AppendAllLinesAsync(string path, System.Collections.Generic.IEnumerable contents, System.Text.Encoding encoding, System.Threading.CancellationToken cancellationToken = default); + public abstract void AppendAllText(string path, string contents); + public abstract void AppendAllText(string path, string contents, System.Text.Encoding encoding); + public abstract System.Threading.Tasks.Task AppendAllTextAsync(string path, string contents, System.Threading.CancellationToken cancellationToken = default); + public abstract System.Threading.Tasks.Task AppendAllTextAsync(string path, string contents, System.Text.Encoding encoding, System.Threading.CancellationToken cancellationToken = default); + public abstract System.IO.StreamWriter AppendText(string path); + public abstract void Copy(string sourceFileName, string destFileName); + public abstract void Copy(string sourceFileName, string destFileName, bool overwrite); + public abstract System.IO.Abstractions.FileSystemStream Create(string path); + public abstract System.IO.Abstractions.FileSystemStream Create(string path, int bufferSize); + public abstract System.IO.Abstractions.FileSystemStream Create(string path, int bufferSize, System.IO.FileOptions options); + public abstract System.IO.Abstractions.IFileSystemInfo CreateSymbolicLink(string path, string pathToTarget); + public abstract System.IO.StreamWriter CreateText(string path); + public abstract void Decrypt(string path); + public abstract void Delete(string path); + public abstract void Encrypt(string path); + public abstract bool Exists(string path); + public abstract System.IO.FileAttributes GetAttributes(string path); + public abstract System.DateTime GetCreationTime(string path); + public abstract System.DateTime GetCreationTimeUtc(string path); + public abstract System.DateTime GetLastAccessTime(string path); + public abstract System.DateTime GetLastAccessTimeUtc(string path); + public abstract System.DateTime GetLastWriteTime(string path); + public abstract System.DateTime GetLastWriteTimeUtc(string path); + public abstract void Move(string sourceFileName, string destFileName); + public abstract void Move(string sourceFileName, string destFileName, bool overwrite); + public abstract System.IO.Abstractions.FileSystemStream Open(string path, System.IO.FileMode mode); + public abstract System.IO.Abstractions.FileSystemStream Open(string path, System.IO.FileStreamOptions options); + public abstract System.IO.Abstractions.FileSystemStream Open(string path, System.IO.FileMode mode, System.IO.FileAccess access); + public abstract System.IO.Abstractions.FileSystemStream Open(string path, System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share); + public abstract System.IO.Abstractions.FileSystemStream OpenRead(string path); + public abstract System.IO.StreamReader OpenText(string path); + public abstract System.IO.Abstractions.FileSystemStream OpenWrite(string path); + public abstract byte[] ReadAllBytes(string path); + public abstract System.Threading.Tasks.Task ReadAllBytesAsync(string path, System.Threading.CancellationToken cancellationToken = default); + public abstract string[] ReadAllLines(string path); + public abstract string[] ReadAllLines(string path, System.Text.Encoding encoding); + public abstract System.Threading.Tasks.Task ReadAllLinesAsync(string path, System.Threading.CancellationToken cancellationToken = default); + public abstract System.Threading.Tasks.Task ReadAllLinesAsync(string path, System.Text.Encoding encoding, System.Threading.CancellationToken cancellationToken = default); + public abstract string ReadAllText(string path); + public abstract string ReadAllText(string path, System.Text.Encoding encoding); + public abstract System.Threading.Tasks.Task ReadAllTextAsync(string path, System.Threading.CancellationToken cancellationToken = default); + public abstract System.Threading.Tasks.Task ReadAllTextAsync(string path, System.Text.Encoding encoding, System.Threading.CancellationToken cancellationToken = default); + public abstract System.Collections.Generic.IEnumerable ReadLines(string path); + public abstract System.Collections.Generic.IEnumerable ReadLines(string path, System.Text.Encoding encoding); + public abstract void Replace(string sourceFileName, string destinationFileName, string destinationBackupFileName); + public abstract void Replace(string sourceFileName, string destinationFileName, string destinationBackupFileName, bool ignoreMetadataErrors); + public abstract System.IO.Abstractions.IFileSystemInfo ResolveLinkTarget(string linkPath, bool returnFinalTarget); + public abstract void SetAttributes(string path, System.IO.FileAttributes fileAttributes); + public abstract void SetCreationTime(string path, System.DateTime creationTime); + public abstract void SetCreationTimeUtc(string path, System.DateTime creationTimeUtc); + public abstract void SetLastAccessTime(string path, System.DateTime lastAccessTime); + public abstract void SetLastAccessTimeUtc(string path, System.DateTime lastAccessTimeUtc); + public abstract void SetLastWriteTime(string path, System.DateTime lastWriteTime); + public abstract void SetLastWriteTimeUtc(string path, System.DateTime lastWriteTimeUtc); + public abstract void WriteAllBytes(string path, byte[] bytes); + public abstract System.Threading.Tasks.Task WriteAllBytesAsync(string path, byte[] bytes, System.Threading.CancellationToken cancellationToken = default); + public abstract void WriteAllLines(string path, System.Collections.Generic.IEnumerable contents); + public abstract void WriteAllLines(string path, string[] contents); + public abstract void WriteAllLines(string path, System.Collections.Generic.IEnumerable contents, System.Text.Encoding encoding); + public abstract void WriteAllLines(string path, string[] contents, System.Text.Encoding encoding); + public abstract System.Threading.Tasks.Task WriteAllLinesAsync(string path, System.Collections.Generic.IEnumerable contents, System.Threading.CancellationToken cancellationToken = default); + public abstract System.Threading.Tasks.Task WriteAllLinesAsync(string path, System.Collections.Generic.IEnumerable contents, System.Text.Encoding encoding, System.Threading.CancellationToken cancellationToken = default); + public abstract void WriteAllText(string path, string contents); + public abstract void WriteAllText(string path, string contents, System.Text.Encoding encoding); + public abstract System.Threading.Tasks.Task WriteAllTextAsync(string path, string contents, System.Threading.CancellationToken cancellationToken = default); + public abstract System.Threading.Tasks.Task WriteAllTextAsync(string path, string contents, System.Text.Encoding encoding, System.Threading.CancellationToken cancellationToken = default); + } + public static class FileInfoAclExtensions + { + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public static System.Security.AccessControl.FileSecurity GetAccessControl(this System.IO.Abstractions.IFileInfo fileInfo) { } + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public static System.Security.AccessControl.FileSecurity GetAccessControl(this System.IO.Abstractions.IFileInfo fileInfo, System.Security.AccessControl.AccessControlSections includeSections) { } + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public static void SetAccessControl(this System.IO.Abstractions.IFileInfo fileInfo, System.Security.AccessControl.FileSecurity fileSecurity) { } + } + [System.Serializable] + public abstract class FileInfoBase : System.IO.Abstractions.FileSystemInfoBase, System.IO.Abstractions.IFileInfo, System.IO.Abstractions.IFileSystemInfo + { + protected FileInfoBase(System.IO.Abstractions.IFileSystem fileSystem) { } + public abstract System.IO.Abstractions.IDirectoryInfo Directory { get; } + public abstract string DirectoryName { get; } + public abstract bool IsReadOnly { get; set; } + public abstract long Length { get; } + public abstract System.IO.StreamWriter AppendText(); + public abstract System.IO.Abstractions.IFileInfo CopyTo(string destFileName); + public abstract System.IO.Abstractions.IFileInfo CopyTo(string destFileName, bool overwrite); + public abstract System.IO.Abstractions.FileSystemStream Create(); + public abstract System.IO.StreamWriter CreateText(); + public abstract void Decrypt(); + public abstract void Encrypt(); + public abstract void MoveTo(string destFileName); + public abstract void MoveTo(string destFileName, bool overwrite); + public abstract System.IO.Abstractions.FileSystemStream Open(System.IO.FileMode mode); + public abstract System.IO.Abstractions.FileSystemStream Open(System.IO.FileStreamOptions options); + public abstract System.IO.Abstractions.FileSystemStream Open(System.IO.FileMode mode, System.IO.FileAccess access); + public abstract System.IO.Abstractions.FileSystemStream Open(System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share); + public abstract System.IO.Abstractions.FileSystemStream OpenRead(); + public abstract System.IO.StreamReader OpenText(); + public abstract System.IO.Abstractions.FileSystemStream OpenWrite(); + public abstract System.IO.Abstractions.IFileInfo Replace(string destinationFileName, string destinationBackupFileName); + public abstract System.IO.Abstractions.IFileInfo Replace(string destinationFileName, string destinationBackupFileName, bool ignoreMetadataErrors); + public static System.IO.Abstractions.FileInfoBase op_Implicit(System.IO.FileInfo fileInfo) { } + } + [System.Serializable] + public class FileInfoWrapper : System.IO.Abstractions.FileInfoBase, System.IO.Abstractions.IFileSystemAclSupport + { + public FileInfoWrapper(System.IO.Abstractions.IFileSystem fileSystem, System.IO.FileInfo instance) { } + public override System.IO.FileAttributes Attributes { get; set; } + public override System.DateTime CreationTime { get; set; } + public override System.DateTime CreationTimeUtc { get; set; } + public override System.IO.Abstractions.IDirectoryInfo Directory { get; } + public override string DirectoryName { get; } + public override bool Exists { get; } + public override string Extension { get; } + public override string FullName { get; } + public override bool IsReadOnly { get; set; } + public override System.DateTime LastAccessTime { get; set; } + public override System.DateTime LastAccessTimeUtc { get; set; } + public override System.DateTime LastWriteTime { get; set; } + public override System.DateTime LastWriteTimeUtc { get; set; } + public override long Length { get; } + public override string LinkTarget { get; } + public override string Name { get; } + public override System.IO.StreamWriter AppendText() { } + public override System.IO.Abstractions.IFileInfo CopyTo(string destFileName) { } + public override System.IO.Abstractions.IFileInfo CopyTo(string destFileName, bool overwrite) { } + public override System.IO.Abstractions.FileSystemStream Create() { } + public override void CreateAsSymbolicLink(string pathToTarget) { } + public override System.IO.StreamWriter CreateText() { } + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public override void Decrypt() { } + public override void Delete() { } + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public override void Encrypt() { } + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public object GetAccessControl() { } + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public object GetAccessControl(System.IO.Abstractions.IFileSystemAclSupport.AccessControlSections includeSections) { } + public override void MoveTo(string destFileName) { } + public override void MoveTo(string destFileName, bool overwrite) { } + public override System.IO.Abstractions.FileSystemStream Open(System.IO.FileMode mode) { } + public override System.IO.Abstractions.FileSystemStream Open(System.IO.FileStreamOptions options) { } + public override System.IO.Abstractions.FileSystemStream Open(System.IO.FileMode mode, System.IO.FileAccess access) { } + public override System.IO.Abstractions.FileSystemStream Open(System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share) { } + public override System.IO.Abstractions.FileSystemStream OpenRead() { } + public override System.IO.StreamReader OpenText() { } + public override System.IO.Abstractions.FileSystemStream OpenWrite() { } + public override void Refresh() { } + public override System.IO.Abstractions.IFileInfo Replace(string destinationFileName, string destinationBackupFileName) { } + public override System.IO.Abstractions.IFileInfo Replace(string destinationFileName, string destinationBackupFileName, bool ignoreMetadataErrors) { } + public override System.IO.Abstractions.IFileSystemInfo ResolveLinkTarget(bool returnFinalTarget) { } + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public void SetAccessControl(object value) { } + public override string ToString() { } + } + public static class FileStreamAclExtensions + { + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public static System.Security.AccessControl.FileSecurity GetAccessControl(this System.IO.Abstractions.FileSystemStream fileStream) { } + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public static void SetAccessControl(this System.IO.Abstractions.FileSystemStream fileStream, System.Security.AccessControl.FileSecurity fileSecurity) { } + } + [System.Serializable] + public class FileSystem : System.IO.Abstractions.FileSystemBase + { + public FileSystem() { } + public override System.IO.Abstractions.IDirectory Directory { get; } + public override System.IO.Abstractions.IDirectoryInfoFactory DirectoryInfo { get; } + public override System.IO.Abstractions.IDriveInfoFactory DriveInfo { get; } + public override System.IO.Abstractions.IFile File { get; } + public override System.IO.Abstractions.IFileInfoFactory FileInfo { get; } + public override System.IO.Abstractions.IFileStreamFactory FileStream { get; } + public override System.IO.Abstractions.IFileSystemWatcherFactory FileSystemWatcher { get; } + public override System.IO.Abstractions.IFileVersionInfoFactory FileVersionInfo { get; } + public override System.IO.Abstractions.IPath Path { get; } + } + [System.Serializable] + public abstract class FileSystemBase : System.IO.Abstractions.IFileSystem + { + protected FileSystemBase() { } + public abstract System.IO.Abstractions.IDirectory Directory { get; } + public abstract System.IO.Abstractions.IDirectoryInfoFactory DirectoryInfo { get; } + public abstract System.IO.Abstractions.IDriveInfoFactory DriveInfo { get; } + public abstract System.IO.Abstractions.IFile File { get; } + public abstract System.IO.Abstractions.IFileInfoFactory FileInfo { get; } + public abstract System.IO.Abstractions.IFileStreamFactory FileStream { get; } + public abstract System.IO.Abstractions.IFileSystemWatcherFactory FileSystemWatcher { get; } + public abstract System.IO.Abstractions.IFileVersionInfoFactory FileVersionInfo { get; } + public abstract System.IO.Abstractions.IPath Path { get; } + } + [System.Serializable] + public abstract class FileSystemInfoBase : System.IO.Abstractions.IFileSystemInfo + { + protected FileSystemInfoBase(System.IO.Abstractions.IFileSystem fileSystem) { } + public abstract System.IO.FileAttributes Attributes { get; set; } + public abstract System.DateTime CreationTime { get; set; } + public abstract System.DateTime CreationTimeUtc { get; set; } + public abstract bool Exists { get; } + public abstract string Extension { get; } + public System.IO.Abstractions.IFileSystem FileSystem { get; } + public abstract string FullName { get; } + public abstract System.DateTime LastAccessTime { get; set; } + public abstract System.DateTime LastAccessTimeUtc { get; set; } + public abstract System.DateTime LastWriteTime { get; set; } + public abstract System.DateTime LastWriteTimeUtc { get; set; } + public abstract string LinkTarget { get; } + public abstract string Name { get; } + public abstract void CreateAsSymbolicLink(string pathToTarget); + public abstract void Delete(); + public abstract void Refresh(); + public abstract System.IO.Abstractions.IFileSystemInfo ResolveLinkTarget(bool returnFinalTarget); + } + [System.Serializable] + public abstract class FileSystemWatcherBase : System.IDisposable, System.IO.Abstractions.IFileSystemEntity, System.IO.Abstractions.IFileSystemWatcher + { + protected FileSystemWatcherBase() { } + public abstract System.ComponentModel.IContainer Container { get; } + public abstract bool EnableRaisingEvents { get; set; } + public abstract System.IO.Abstractions.IFileSystem FileSystem { get; } + public abstract string Filter { get; set; } + public abstract System.Collections.ObjectModel.Collection Filters { get; } + public abstract bool IncludeSubdirectories { get; set; } + public abstract int InternalBufferSize { get; set; } + public abstract System.IO.NotifyFilters NotifyFilter { get; set; } + public abstract string Path { get; set; } + public abstract System.ComponentModel.ISite Site { get; set; } + public abstract System.ComponentModel.ISynchronizeInvoke SynchronizingObject { get; set; } + public virtual event System.IO.FileSystemEventHandler Changed; + public virtual event System.IO.FileSystemEventHandler Created; + public virtual event System.IO.FileSystemEventHandler Deleted; + public virtual event System.IO.ErrorEventHandler Error; + public virtual event System.IO.RenamedEventHandler Renamed; + public abstract void BeginInit(); + public void Dispose() { } + public virtual void Dispose(bool disposing) { } + public abstract void EndInit(); + protected void OnChanged(object sender, System.IO.FileSystemEventArgs args) { } + protected void OnCreated(object sender, System.IO.FileSystemEventArgs args) { } + protected void OnDeleted(object sender, System.IO.FileSystemEventArgs args) { } + protected void OnError(object sender, System.IO.ErrorEventArgs args) { } + protected void OnRenamed(object sender, System.IO.RenamedEventArgs args) { } + public abstract System.IO.Abstractions.IWaitForChangedResult WaitForChanged(System.IO.WatcherChangeTypes changeType); + public abstract System.IO.Abstractions.IWaitForChangedResult WaitForChanged(System.IO.WatcherChangeTypes changeType, int timeout); + public static System.IO.Abstractions.FileSystemWatcherBase op_Implicit(System.IO.FileSystemWatcher watcher) { } + } + [System.Serializable] + public class FileSystemWatcherFactory : System.IO.Abstractions.IFileSystemEntity, System.IO.Abstractions.IFileSystemWatcherFactory + { + public FileSystemWatcherFactory(System.IO.Abstractions.IFileSystem fileSystem) { } + public System.IO.Abstractions.IFileSystem FileSystem { get; } + public System.IO.Abstractions.IFileSystemWatcher New() { } + public System.IO.Abstractions.IFileSystemWatcher New(string path) { } + public System.IO.Abstractions.IFileSystemWatcher New(string path, string filter) { } + public System.IO.Abstractions.IFileSystemWatcher Wrap(System.IO.FileSystemWatcher fileSystemWatcher) { } + } + [System.Serializable] + public class FileSystemWatcherWrapper : System.IO.Abstractions.FileSystemWatcherBase + { + public FileSystemWatcherWrapper(System.IO.Abstractions.IFileSystem fileSystem) { } + public FileSystemWatcherWrapper(System.IO.Abstractions.IFileSystem fileSystem, System.IO.FileSystemWatcher watcher) { } + public FileSystemWatcherWrapper(System.IO.Abstractions.IFileSystem fileSystem, string path) { } + public FileSystemWatcherWrapper(System.IO.Abstractions.IFileSystem fileSystem, string path, string filter) { } + public override System.ComponentModel.IContainer Container { get; } + public override bool EnableRaisingEvents { get; set; } + public override System.IO.Abstractions.IFileSystem FileSystem { get; } + public override string Filter { get; set; } + public override System.Collections.ObjectModel.Collection Filters { get; } + public override bool IncludeSubdirectories { get; set; } + public override int InternalBufferSize { get; set; } + public override System.IO.NotifyFilters NotifyFilter { get; set; } + public override string Path { get; set; } + public override System.ComponentModel.ISite Site { get; set; } + public override System.ComponentModel.ISynchronizeInvoke SynchronizingObject { get; set; } + public override void BeginInit() { } + public override void Dispose(bool disposing) { } + public override void EndInit() { } + public override System.IO.Abstractions.IWaitForChangedResult WaitForChanged(System.IO.WatcherChangeTypes changeType) { } + public override System.IO.Abstractions.IWaitForChangedResult WaitForChanged(System.IO.WatcherChangeTypes changeType, int timeout) { } + } + [System.Serializable] + public abstract class FileVersionInfoBase : System.IO.Abstractions.IFileVersionInfo + { + protected FileVersionInfoBase() { } + public abstract string Comments { get; } + public abstract string CompanyName { get; } + public abstract int FileBuildPart { get; } + public abstract string FileDescription { get; } + public abstract int FileMajorPart { get; } + public abstract int FileMinorPart { get; } + public abstract string FileName { get; } + public abstract int FilePrivatePart { get; } + public abstract string FileVersion { get; } + public abstract string InternalName { get; } + public abstract bool IsDebug { get; } + public abstract bool IsPatched { get; } + public abstract bool IsPreRelease { get; } + public abstract bool IsPrivateBuild { get; } + public abstract bool IsSpecialBuild { get; } + public abstract string Language { get; } + public abstract string LegalCopyright { get; } + public abstract string LegalTrademarks { get; } + public abstract string OriginalFilename { get; } + public abstract string PrivateBuild { get; } + public abstract int ProductBuildPart { get; } + public abstract int ProductMajorPart { get; } + public abstract int ProductMinorPart { get; } + public abstract string ProductName { get; } + public abstract int ProductPrivatePart { get; } + public abstract string ProductVersion { get; } + public abstract string SpecialBuild { get; } + public abstract string ToString(); + public static System.IO.Abstractions.FileVersionInfoBase op_Implicit(System.Diagnostics.FileVersionInfo fileVersionInfo) { } + } + [System.Serializable] + public class FileVersionInfoWrapper : System.IO.Abstractions.FileVersionInfoBase + { + public FileVersionInfoWrapper(System.Diagnostics.FileVersionInfo fileVersionInfo) { } + public override string Comments { get; } + public override string CompanyName { get; } + public override int FileBuildPart { get; } + public override string FileDescription { get; } + public override int FileMajorPart { get; } + public override int FileMinorPart { get; } + public override string FileName { get; } + public override int FilePrivatePart { get; } + public override string FileVersion { get; } + public override string InternalName { get; } + public override bool IsDebug { get; } + public override bool IsPatched { get; } + public override bool IsPreRelease { get; } + public override bool IsPrivateBuild { get; } + public override bool IsSpecialBuild { get; } + public override string Language { get; } + public override string LegalCopyright { get; } + public override string LegalTrademarks { get; } + public override string OriginalFilename { get; } + public override string PrivateBuild { get; } + public override int ProductBuildPart { get; } + public override int ProductMajorPart { get; } + public override int ProductMinorPart { get; } + public override string ProductName { get; } + public override int ProductPrivatePart { get; } + public override string ProductVersion { get; } + public override string SpecialBuild { get; } + public override string ToString() { } + } + [System.Serializable] + public class FileWrapper : System.IO.Abstractions.FileBase + { + public FileWrapper(System.IO.Abstractions.IFileSystem fileSystem) { } + public override void AppendAllLines(string path, System.Collections.Generic.IEnumerable contents) { } + public override void AppendAllLines(string path, System.Collections.Generic.IEnumerable contents, System.Text.Encoding encoding) { } + public override System.Threading.Tasks.Task AppendAllLinesAsync(string path, System.Collections.Generic.IEnumerable contents, System.Threading.CancellationToken cancellationToken = default) { } + public override System.Threading.Tasks.Task AppendAllLinesAsync(string path, System.Collections.Generic.IEnumerable contents, System.Text.Encoding encoding, System.Threading.CancellationToken cancellationToken = default) { } + public override void AppendAllText(string path, string contents) { } + public override void AppendAllText(string path, string contents, System.Text.Encoding encoding) { } + public override System.Threading.Tasks.Task AppendAllTextAsync(string path, string contents, System.Threading.CancellationToken cancellationToken = default) { } + public override System.Threading.Tasks.Task AppendAllTextAsync(string path, string contents, System.Text.Encoding encoding, System.Threading.CancellationToken cancellationToken = default) { } + public override System.IO.StreamWriter AppendText(string path) { } + public override void Copy(string sourceFileName, string destFileName) { } + public override void Copy(string sourceFileName, string destFileName, bool overwrite) { } + public override System.IO.Abstractions.FileSystemStream Create(string path) { } + public override System.IO.Abstractions.FileSystemStream Create(string path, int bufferSize) { } + public override System.IO.Abstractions.FileSystemStream Create(string path, int bufferSize, System.IO.FileOptions options) { } + public override System.IO.Abstractions.IFileSystemInfo CreateSymbolicLink(string path, string pathToTarget) { } + public override System.IO.StreamWriter CreateText(string path) { } + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public override void Decrypt(string path) { } + public override void Delete(string path) { } + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public override void Encrypt(string path) { } + public override bool Exists(string path) { } + public override System.IO.FileAttributes GetAttributes(string path) { } + public override System.DateTime GetCreationTime(string path) { } + public override System.DateTime GetCreationTimeUtc(string path) { } + public override System.DateTime GetLastAccessTime(string path) { } + public override System.DateTime GetLastAccessTimeUtc(string path) { } + public override System.DateTime GetLastWriteTime(string path) { } + public override System.DateTime GetLastWriteTimeUtc(string path) { } + public override void Move(string sourceFileName, string destFileName) { } + public override void Move(string sourceFileName, string destFileName, bool overwrite) { } + public override System.IO.Abstractions.FileSystemStream Open(string path, System.IO.FileMode mode) { } + public override System.IO.Abstractions.FileSystemStream Open(string path, System.IO.FileStreamOptions options) { } + public override System.IO.Abstractions.FileSystemStream Open(string path, System.IO.FileMode mode, System.IO.FileAccess access) { } + public override System.IO.Abstractions.FileSystemStream Open(string path, System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share) { } + public override System.IO.Abstractions.FileSystemStream OpenRead(string path) { } + public override System.IO.StreamReader OpenText(string path) { } + public override System.IO.Abstractions.FileSystemStream OpenWrite(string path) { } + public override byte[] ReadAllBytes(string path) { } + public override System.Threading.Tasks.Task ReadAllBytesAsync(string path, System.Threading.CancellationToken cancellationToken = default) { } + public override string[] ReadAllLines(string path) { } + public override string[] ReadAllLines(string path, System.Text.Encoding encoding) { } + public override System.Threading.Tasks.Task ReadAllLinesAsync(string path, System.Threading.CancellationToken cancellationToken = default) { } + public override System.Threading.Tasks.Task ReadAllLinesAsync(string path, System.Text.Encoding encoding, System.Threading.CancellationToken cancellationToken = default) { } + public override string ReadAllText(string path) { } + public override string ReadAllText(string path, System.Text.Encoding encoding) { } + public override System.Threading.Tasks.Task ReadAllTextAsync(string path, System.Threading.CancellationToken cancellationToken = default) { } + public override System.Threading.Tasks.Task ReadAllTextAsync(string path, System.Text.Encoding encoding, System.Threading.CancellationToken cancellationToken = default) { } + public override System.Collections.Generic.IEnumerable ReadLines(string path) { } + public override System.Collections.Generic.IEnumerable ReadLines(string path, System.Text.Encoding encoding) { } + public override void Replace(string sourceFileName, string destinationFileName, string destinationBackupFileName) { } + public override void Replace(string sourceFileName, string destinationFileName, string destinationBackupFileName, bool ignoreMetadataErrors) { } + public override System.IO.Abstractions.IFileSystemInfo ResolveLinkTarget(string linkPath, bool returnFinalTarget) { } + public override void SetAttributes(string path, System.IO.FileAttributes fileAttributes) { } + public override void SetCreationTime(string path, System.DateTime creationTime) { } + public override void SetCreationTimeUtc(string path, System.DateTime creationTimeUtc) { } + public override void SetLastAccessTime(string path, System.DateTime lastAccessTime) { } + public override void SetLastAccessTimeUtc(string path, System.DateTime lastAccessTimeUtc) { } + public override void SetLastWriteTime(string path, System.DateTime lastWriteTime) { } + public override void SetLastWriteTimeUtc(string path, System.DateTime lastWriteTimeUtc) { } + public override void WriteAllBytes(string path, byte[] bytes) { } + public override System.Threading.Tasks.Task WriteAllBytesAsync(string path, byte[] bytes, System.Threading.CancellationToken cancellationToken = default) { } + public override void WriteAllLines(string path, System.Collections.Generic.IEnumerable contents) { } + public override void WriteAllLines(string path, string[] contents) { } + public override void WriteAllLines(string path, System.Collections.Generic.IEnumerable contents, System.Text.Encoding encoding) { } + public override void WriteAllLines(string path, string[] contents, System.Text.Encoding encoding) { } + public override System.Threading.Tasks.Task WriteAllLinesAsync(string path, System.Collections.Generic.IEnumerable contents, System.Threading.CancellationToken cancellationToken = default) { } + public override System.Threading.Tasks.Task WriteAllLinesAsync(string path, System.Collections.Generic.IEnumerable contents, System.Text.Encoding encoding, System.Threading.CancellationToken cancellationToken = default) { } + public override void WriteAllText(string path, string contents) { } + public override void WriteAllText(string path, string contents, System.Text.Encoding encoding) { } + public override System.Threading.Tasks.Task WriteAllTextAsync(string path, string contents, System.Threading.CancellationToken cancellationToken = default) { } + public override System.Threading.Tasks.Task WriteAllTextAsync(string path, string contents, System.Text.Encoding encoding, System.Threading.CancellationToken cancellationToken = default) { } + } + [System.Serializable] + public abstract class PathBase : System.IO.Abstractions.IFileSystemEntity, System.IO.Abstractions.IPath + { + protected PathBase(System.IO.Abstractions.IFileSystem fileSystem) { } + public abstract char AltDirectorySeparatorChar { get; } + public abstract char DirectorySeparatorChar { get; } + public System.IO.Abstractions.IFileSystem FileSystem { get; } + [System.Obsolete("Please use GetInvalidPathChars or GetInvalidFileNameChars instead.")] + public abstract char[] InvalidPathChars { get; } + public abstract char PathSeparator { get; } + public abstract char VolumeSeparatorChar { get; } + public abstract string ChangeExtension(string path, string extension); + public abstract string Combine(params string[] paths); + public abstract string Combine(string path1, string path2); + public abstract string Combine(string path1, string path2, string path3); + public abstract string Combine(string path1, string path2, string path3, string path4); + public abstract bool EndsInDirectorySeparator(System.ReadOnlySpan path); + public abstract bool EndsInDirectorySeparator(string path); + public abstract System.ReadOnlySpan GetDirectoryName(System.ReadOnlySpan path); + public abstract string GetDirectoryName(string path); + public abstract System.ReadOnlySpan GetExtension(System.ReadOnlySpan path); + public abstract string GetExtension(string path); + public abstract System.ReadOnlySpan GetFileName(System.ReadOnlySpan path); + public abstract string GetFileName(string path); + public abstract System.ReadOnlySpan GetFileNameWithoutExtension(System.ReadOnlySpan path); + public abstract string GetFileNameWithoutExtension(string path); + public abstract string GetFullPath(string path); + public abstract string GetFullPath(string path, string basePath); + public abstract char[] GetInvalidFileNameChars(); + public abstract char[] GetInvalidPathChars(); + public abstract System.ReadOnlySpan GetPathRoot(System.ReadOnlySpan path); + public abstract string GetPathRoot(string path); + public abstract string GetRandomFileName(); + public abstract string GetRelativePath(string relativeTo, string path); + public abstract string GetTempFileName(); + public abstract string GetTempPath(); + public abstract bool HasExtension(System.ReadOnlySpan path); + public abstract bool HasExtension(string path); + public abstract bool IsPathFullyQualified(System.ReadOnlySpan path); + public abstract bool IsPathFullyQualified(string path); + public abstract bool IsPathRooted(System.ReadOnlySpan path); + public abstract bool IsPathRooted(string path); + public abstract string Join(params string[] paths); + public abstract string Join(System.ReadOnlySpan path1, System.ReadOnlySpan path2); + public abstract string Join(string path1, string path2); + public abstract string Join(System.ReadOnlySpan path1, System.ReadOnlySpan path2, System.ReadOnlySpan path3); + public abstract string Join(string path1, string path2, string path3); + public abstract string Join(System.ReadOnlySpan path1, System.ReadOnlySpan path2, System.ReadOnlySpan path3, System.ReadOnlySpan path4); + public abstract string Join(string path1, string path2, string path3, string path4); + public abstract System.ReadOnlySpan TrimEndingDirectorySeparator(System.ReadOnlySpan path); + public abstract string TrimEndingDirectorySeparator(string path); + public abstract bool TryJoin(System.ReadOnlySpan path1, System.ReadOnlySpan path2, System.Span destination, out int charsWritten); + public abstract bool TryJoin(System.ReadOnlySpan path1, System.ReadOnlySpan path2, System.ReadOnlySpan path3, System.Span destination, out int charsWritten); + } + [System.Serializable] + public class PathWrapper : System.IO.Abstractions.PathBase + { + public PathWrapper(System.IO.Abstractions.IFileSystem fileSystem) { } + public override char AltDirectorySeparatorChar { get; } + public override char DirectorySeparatorChar { get; } + [System.Obsolete("Please use GetInvalidPathChars or GetInvalidFileNameChars instead.")] + public override char[] InvalidPathChars { get; } + public override char PathSeparator { get; } + public override char VolumeSeparatorChar { get; } + public override string ChangeExtension(string path, string extension) { } + public override string Combine(params string[] paths) { } + public override string Combine(string path1, string path2) { } + public override string Combine(string path1, string path2, string path3) { } + public override string Combine(string path1, string path2, string path3, string path4) { } + public override bool EndsInDirectorySeparator(System.ReadOnlySpan path) { } + public override bool EndsInDirectorySeparator(string path) { } + public override System.ReadOnlySpan GetDirectoryName(System.ReadOnlySpan path) { } + public override string GetDirectoryName(string path) { } + public override System.ReadOnlySpan GetExtension(System.ReadOnlySpan path) { } + public override string GetExtension(string path) { } + public override System.ReadOnlySpan GetFileName(System.ReadOnlySpan path) { } + public override string GetFileName(string path) { } + public override System.ReadOnlySpan GetFileNameWithoutExtension(System.ReadOnlySpan path) { } + public override string GetFileNameWithoutExtension(string path) { } + public override string GetFullPath(string path) { } + public override string GetFullPath(string path, string basePath) { } + public override char[] GetInvalidFileNameChars() { } + public override char[] GetInvalidPathChars() { } + public override System.ReadOnlySpan GetPathRoot(System.ReadOnlySpan path) { } + public override string GetPathRoot(string path) { } + public override string GetRandomFileName() { } + public override string GetRelativePath(string relativeTo, string path) { } + public override string GetTempFileName() { } + public override string GetTempPath() { } + public override bool HasExtension(System.ReadOnlySpan path) { } + public override bool HasExtension(string path) { } + public override bool IsPathFullyQualified(System.ReadOnlySpan path) { } + public override bool IsPathFullyQualified(string path) { } + public override bool IsPathRooted(System.ReadOnlySpan path) { } + public override bool IsPathRooted(string path) { } + public override string Join(params string[] paths) { } + public override string Join(System.ReadOnlySpan path1, System.ReadOnlySpan path2) { } + public override string Join(string path1, string path2) { } + public override string Join(System.ReadOnlySpan path1, System.ReadOnlySpan path2, System.ReadOnlySpan path3) { } + public override string Join(string path1, string path2, string path3) { } + public override string Join(System.ReadOnlySpan path1, System.ReadOnlySpan path2, System.ReadOnlySpan path3, System.ReadOnlySpan path4) { } + public override string Join(string path1, string path2, string path3, string path4) { } + public override System.ReadOnlySpan TrimEndingDirectorySeparator(System.ReadOnlySpan path) { } + public override string TrimEndingDirectorySeparator(string path) { } + public override bool TryJoin(System.ReadOnlySpan path1, System.ReadOnlySpan path2, System.Span destination, out int charsWritten) { } + public override bool TryJoin(System.ReadOnlySpan path1, System.ReadOnlySpan path2, System.ReadOnlySpan path3, System.Span destination, out int charsWritten) { } + } +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.Api.Tests/Expected/TestableIO.System.IO.Abstractions.Wrappers_net8.0.txt b/tests/TestableIO.System.IO.Abstractions.Api.Tests/Expected/TestableIO.System.IO.Abstractions.Wrappers_net8.0.txt new file mode 100644 index 000000000..bc8a031ac --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.Api.Tests/Expected/TestableIO.System.IO.Abstractions.Wrappers_net8.0.txt @@ -0,0 +1,866 @@ +[assembly: System.CLSCompliant(true)] +[assembly: System.Reflection.AssemblyMetadata("RepositoryUrl", "https://github.com/TestableIO/System.IO.Abstractions.git")] +[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(@"DynamicProxyGenAssembly2, PublicKey=0024000004800000940000000602000000240000525341310004000001000100c547cac37abd99c8db225ef2f6c8a3602f3b3606cc9891605d02baa56104f4cfc0734aa39b93bf7852f7d9266654753cc297e7d2edfe0bac1cdcf9f717241550e0a7b191195b7667bb4f64bcb8e2121380fd1d9d46ad2d92d2d15605093924cceaf74c4861eff62abf69b9291ed0a340e113be11e6a7d3113e92484cf7045cc7")] +[assembly: System.Runtime.Versioning.TargetFramework(".NETCoreApp,Version=v8.0", FrameworkDisplayName=".NET 8.0")] +namespace System.IO.Abstractions +{ + public static class DirectoryAclExtensions + { + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public static void CreateDirectory(this System.IO.Abstractions.IDirectory directory, string path, System.Security.AccessControl.DirectorySecurity directorySecurity) { } + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public static System.Security.AccessControl.DirectorySecurity GetAccessControl(this System.IO.Abstractions.IDirectory directory, string path) { } + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public static System.Security.AccessControl.DirectorySecurity GetAccessControl(this System.IO.Abstractions.IDirectory directory, string path, System.Security.AccessControl.AccessControlSections includeSections) { } + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public static void SetAccessControl(this System.IO.Abstractions.IDirectory directory, string path, System.Security.AccessControl.DirectorySecurity directorySecurity) { } + } + [System.Serializable] + public abstract class DirectoryBase : System.IO.Abstractions.IDirectory, System.IO.Abstractions.IFileSystemEntity + { + protected DirectoryBase(System.IO.Abstractions.IFileSystem fileSystem) { } + public System.IO.Abstractions.IFileSystem FileSystem { get; } + public abstract System.IO.Abstractions.IDirectoryInfo CreateDirectory(string path); + public abstract System.IO.Abstractions.IDirectoryInfo CreateDirectory(string path, System.IO.UnixFileMode unixCreateMode); + public abstract System.IO.Abstractions.IFileSystemInfo CreateSymbolicLink(string path, string pathToTarget); + public abstract System.IO.Abstractions.IDirectoryInfo CreateTempSubdirectory(string prefix = null); + public abstract void Delete(string path); + public abstract void Delete(string path, bool recursive); + public abstract System.Collections.Generic.IEnumerable EnumerateDirectories(string path); + public abstract System.Collections.Generic.IEnumerable EnumerateDirectories(string path, string searchPattern); + public abstract System.Collections.Generic.IEnumerable EnumerateDirectories(string path, string searchPattern, System.IO.EnumerationOptions enumerationOptions); + public abstract System.Collections.Generic.IEnumerable EnumerateDirectories(string path, string searchPattern, System.IO.SearchOption searchOption); + public abstract System.Collections.Generic.IEnumerable EnumerateFileSystemEntries(string path); + public abstract System.Collections.Generic.IEnumerable EnumerateFileSystemEntries(string path, string searchPattern); + public abstract System.Collections.Generic.IEnumerable EnumerateFileSystemEntries(string path, string searchPattern, System.IO.EnumerationOptions enumerationOptions); + public abstract System.Collections.Generic.IEnumerable EnumerateFileSystemEntries(string path, string searchPattern, System.IO.SearchOption searchOption); + public abstract System.Collections.Generic.IEnumerable EnumerateFiles(string path); + public abstract System.Collections.Generic.IEnumerable EnumerateFiles(string path, string searchPattern); + public abstract System.Collections.Generic.IEnumerable EnumerateFiles(string path, string searchPattern, System.IO.EnumerationOptions enumerationOptions); + public abstract System.Collections.Generic.IEnumerable EnumerateFiles(string path, string searchPattern, System.IO.SearchOption searchOption); + public abstract bool Exists(string path); + public abstract System.DateTime GetCreationTime(string path); + public abstract System.DateTime GetCreationTimeUtc(string path); + public abstract string GetCurrentDirectory(); + public abstract string[] GetDirectories(string path); + public abstract string[] GetDirectories(string path, string searchPattern); + public abstract string[] GetDirectories(string path, string searchPattern, System.IO.EnumerationOptions enumerationOptions); + public abstract string[] GetDirectories(string path, string searchPattern, System.IO.SearchOption searchOption); + public abstract string GetDirectoryRoot(string path); + public abstract string[] GetFileSystemEntries(string path); + public abstract string[] GetFileSystemEntries(string path, string searchPattern); + public abstract string[] GetFileSystemEntries(string path, string searchPattern, System.IO.EnumerationOptions enumerationOptions); + public abstract string[] GetFileSystemEntries(string path, string searchPattern, System.IO.SearchOption searchOption); + public abstract string[] GetFiles(string path); + public abstract string[] GetFiles(string path, string searchPattern); + public abstract string[] GetFiles(string path, string searchPattern, System.IO.EnumerationOptions enumerationOptions); + public abstract string[] GetFiles(string path, string searchPattern, System.IO.SearchOption searchOption); + public abstract System.DateTime GetLastAccessTime(string path); + public abstract System.DateTime GetLastAccessTimeUtc(string path); + public abstract System.DateTime GetLastWriteTime(string path); + public abstract System.DateTime GetLastWriteTimeUtc(string path); + public abstract string[] GetLogicalDrives(); + public abstract System.IO.Abstractions.IDirectoryInfo GetParent(string path); + public abstract void Move(string sourceDirName, string destDirName); + public abstract System.IO.Abstractions.IFileSystemInfo ResolveLinkTarget(string linkPath, bool returnFinalTarget); + public abstract void SetCreationTime(string path, System.DateTime creationTime); + public abstract void SetCreationTimeUtc(string path, System.DateTime creationTimeUtc); + public abstract void SetCurrentDirectory(string path); + public abstract void SetLastAccessTime(string path, System.DateTime lastAccessTime); + public abstract void SetLastAccessTimeUtc(string path, System.DateTime lastAccessTimeUtc); + public abstract void SetLastWriteTime(string path, System.DateTime lastWriteTime); + public abstract void SetLastWriteTimeUtc(string path, System.DateTime lastWriteTimeUtc); + } + public static class DirectoryInfoAclExtensions + { + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public static void Create(this System.IO.Abstractions.IDirectoryInfo directoryInfo, System.Security.AccessControl.DirectorySecurity directorySecurity) { } + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public static System.Security.AccessControl.DirectorySecurity GetAccessControl(this System.IO.Abstractions.IDirectoryInfo directoryInfo) { } + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public static System.Security.AccessControl.DirectorySecurity GetAccessControl(this System.IO.Abstractions.IDirectoryInfo directoryInfo, System.Security.AccessControl.AccessControlSections includeSections) { } + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public static void SetAccessControl(this System.IO.Abstractions.IDirectoryInfo directoryInfo, System.Security.AccessControl.DirectorySecurity directorySecurity) { } + } + [System.Serializable] + public abstract class DirectoryInfoBase : System.IO.Abstractions.FileSystemInfoBase, System.IO.Abstractions.IDirectoryInfo, System.IO.Abstractions.IFileSystemInfo + { + protected DirectoryInfoBase(System.IO.Abstractions.IFileSystem fileSystem) { } + public abstract System.IO.Abstractions.IDirectoryInfo Parent { get; } + public abstract System.IO.Abstractions.IDirectoryInfo Root { get; } + public abstract void Create(); + public abstract System.IO.Abstractions.IDirectoryInfo CreateSubdirectory(string path); + public abstract void Delete(bool recursive); + public abstract System.Collections.Generic.IEnumerable EnumerateDirectories(); + public abstract System.Collections.Generic.IEnumerable EnumerateDirectories(string searchPattern); + public abstract System.Collections.Generic.IEnumerable EnumerateDirectories(string searchPattern, System.IO.EnumerationOptions enumerationOptions); + public abstract System.Collections.Generic.IEnumerable EnumerateDirectories(string searchPattern, System.IO.SearchOption searchOption); + public abstract System.Collections.Generic.IEnumerable EnumerateFileSystemInfos(); + public abstract System.Collections.Generic.IEnumerable EnumerateFileSystemInfos(string searchPattern); + public abstract System.Collections.Generic.IEnumerable EnumerateFileSystemInfos(string searchPattern, System.IO.EnumerationOptions enumerationOptions); + public abstract System.Collections.Generic.IEnumerable EnumerateFileSystemInfos(string searchPattern, System.IO.SearchOption searchOption); + public abstract System.Collections.Generic.IEnumerable EnumerateFiles(); + public abstract System.Collections.Generic.IEnumerable EnumerateFiles(string searchPattern); + public abstract System.Collections.Generic.IEnumerable EnumerateFiles(string searchPattern, System.IO.EnumerationOptions enumerationOptions); + public abstract System.Collections.Generic.IEnumerable EnumerateFiles(string searchPattern, System.IO.SearchOption searchOption); + public abstract System.IO.Abstractions.IDirectoryInfo[] GetDirectories(); + public abstract System.IO.Abstractions.IDirectoryInfo[] GetDirectories(string searchPattern); + public abstract System.IO.Abstractions.IDirectoryInfo[] GetDirectories(string searchPattern, System.IO.EnumerationOptions enumerationOptions); + public abstract System.IO.Abstractions.IDirectoryInfo[] GetDirectories(string searchPattern, System.IO.SearchOption searchOption); + public abstract System.IO.Abstractions.IFileSystemInfo[] GetFileSystemInfos(); + public abstract System.IO.Abstractions.IFileSystemInfo[] GetFileSystemInfos(string searchPattern); + public abstract System.IO.Abstractions.IFileSystemInfo[] GetFileSystemInfos(string searchPattern, System.IO.EnumerationOptions enumerationOptions); + public abstract System.IO.Abstractions.IFileSystemInfo[] GetFileSystemInfos(string searchPattern, System.IO.SearchOption searchOption); + public abstract System.IO.Abstractions.IFileInfo[] GetFiles(); + public abstract System.IO.Abstractions.IFileInfo[] GetFiles(string searchPattern); + public abstract System.IO.Abstractions.IFileInfo[] GetFiles(string searchPattern, System.IO.EnumerationOptions enumerationOptions); + public abstract System.IO.Abstractions.IFileInfo[] GetFiles(string searchPattern, System.IO.SearchOption searchOption); + public abstract void MoveTo(string destDirName); + public static System.IO.Abstractions.DirectoryInfoBase op_Implicit(System.IO.DirectoryInfo directoryInfo) { } + } + [System.Serializable] + public class DirectoryInfoWrapper : System.IO.Abstractions.DirectoryInfoBase, System.IO.Abstractions.IFileSystemAclSupport + { + public DirectoryInfoWrapper(System.IO.Abstractions.IFileSystem fileSystem, System.IO.DirectoryInfo instance) { } + public override System.IO.FileAttributes Attributes { get; set; } + public override System.DateTime CreationTime { get; set; } + public override System.DateTime CreationTimeUtc { get; set; } + public override bool Exists { get; } + public override string Extension { get; } + public override string FullName { get; } + public override System.DateTime LastAccessTime { get; set; } + public override System.DateTime LastAccessTimeUtc { get; set; } + public override System.DateTime LastWriteTime { get; set; } + public override System.DateTime LastWriteTimeUtc { get; set; } + public override string LinkTarget { get; } + public override string Name { get; } + public override System.IO.Abstractions.IDirectoryInfo Parent { get; } + public override System.IO.Abstractions.IDirectoryInfo Root { get; } + public override void Create() { } + public override void CreateAsSymbolicLink(string pathToTarget) { } + public override System.IO.Abstractions.IDirectoryInfo CreateSubdirectory(string path) { } + public override void Delete() { } + public override void Delete(bool recursive) { } + public override System.Collections.Generic.IEnumerable EnumerateDirectories() { } + public override System.Collections.Generic.IEnumerable EnumerateDirectories(string searchPattern) { } + public override System.Collections.Generic.IEnumerable EnumerateDirectories(string searchPattern, System.IO.EnumerationOptions enumerationOptions) { } + public override System.Collections.Generic.IEnumerable EnumerateDirectories(string searchPattern, System.IO.SearchOption searchOption) { } + public override System.Collections.Generic.IEnumerable EnumerateFileSystemInfos() { } + public override System.Collections.Generic.IEnumerable EnumerateFileSystemInfos(string searchPattern) { } + public override System.Collections.Generic.IEnumerable EnumerateFileSystemInfos(string searchPattern, System.IO.EnumerationOptions enumerationOptions) { } + public override System.Collections.Generic.IEnumerable EnumerateFileSystemInfos(string searchPattern, System.IO.SearchOption searchOption) { } + public override System.Collections.Generic.IEnumerable EnumerateFiles() { } + public override System.Collections.Generic.IEnumerable EnumerateFiles(string searchPattern) { } + public override System.Collections.Generic.IEnumerable EnumerateFiles(string searchPattern, System.IO.EnumerationOptions enumerationOptions) { } + public override System.Collections.Generic.IEnumerable EnumerateFiles(string searchPattern, System.IO.SearchOption searchOption) { } + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public object GetAccessControl() { } + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public object GetAccessControl(System.IO.Abstractions.IFileSystemAclSupport.AccessControlSections includeSections) { } + public override System.IO.Abstractions.IDirectoryInfo[] GetDirectories() { } + public override System.IO.Abstractions.IDirectoryInfo[] GetDirectories(string searchPattern) { } + public override System.IO.Abstractions.IDirectoryInfo[] GetDirectories(string searchPattern, System.IO.EnumerationOptions enumerationOptions) { } + public override System.IO.Abstractions.IDirectoryInfo[] GetDirectories(string searchPattern, System.IO.SearchOption searchOption) { } + public override System.IO.Abstractions.IFileSystemInfo[] GetFileSystemInfos() { } + public override System.IO.Abstractions.IFileSystemInfo[] GetFileSystemInfos(string searchPattern) { } + public override System.IO.Abstractions.IFileSystemInfo[] GetFileSystemInfos(string searchPattern, System.IO.EnumerationOptions enumerationOptions) { } + public override System.IO.Abstractions.IFileSystemInfo[] GetFileSystemInfos(string searchPattern, System.IO.SearchOption searchOption) { } + public override System.IO.Abstractions.IFileInfo[] GetFiles() { } + public override System.IO.Abstractions.IFileInfo[] GetFiles(string searchPattern) { } + public override System.IO.Abstractions.IFileInfo[] GetFiles(string searchPattern, System.IO.EnumerationOptions enumerationOptions) { } + public override System.IO.Abstractions.IFileInfo[] GetFiles(string searchPattern, System.IO.SearchOption searchOption) { } + public override void MoveTo(string destDirName) { } + public override void Refresh() { } + public override System.IO.Abstractions.IFileSystemInfo ResolveLinkTarget(bool returnFinalTarget) { } + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public void SetAccessControl(object value) { } + public override string ToString() { } + } + [System.Serializable] + public class DirectoryWrapper : System.IO.Abstractions.DirectoryBase + { + public DirectoryWrapper(System.IO.Abstractions.IFileSystem fileSystem) { } + public override System.IO.Abstractions.IDirectoryInfo CreateDirectory(string path) { } + [System.Runtime.Versioning.UnsupportedOSPlatform("windows")] + public override System.IO.Abstractions.IDirectoryInfo CreateDirectory(string path, System.IO.UnixFileMode unixCreateMode) { } + public override System.IO.Abstractions.IFileSystemInfo CreateSymbolicLink(string path, string pathToTarget) { } + public override System.IO.Abstractions.IDirectoryInfo CreateTempSubdirectory(string prefix = null) { } + public override void Delete(string path) { } + public override void Delete(string path, bool recursive) { } + public override System.Collections.Generic.IEnumerable EnumerateDirectories(string path) { } + public override System.Collections.Generic.IEnumerable EnumerateDirectories(string path, string searchPattern) { } + public override System.Collections.Generic.IEnumerable EnumerateDirectories(string path, string searchPattern, System.IO.EnumerationOptions enumerationOptions) { } + public override System.Collections.Generic.IEnumerable EnumerateDirectories(string path, string searchPattern, System.IO.SearchOption searchOption) { } + public override System.Collections.Generic.IEnumerable EnumerateFileSystemEntries(string path) { } + public override System.Collections.Generic.IEnumerable EnumerateFileSystemEntries(string path, string searchPattern) { } + public override System.Collections.Generic.IEnumerable EnumerateFileSystemEntries(string path, string searchPattern, System.IO.EnumerationOptions enumerationOptions) { } + public override System.Collections.Generic.IEnumerable EnumerateFileSystemEntries(string path, string searchPattern, System.IO.SearchOption searchOption) { } + public override System.Collections.Generic.IEnumerable EnumerateFiles(string path) { } + public override System.Collections.Generic.IEnumerable EnumerateFiles(string path, string searchPattern) { } + public override System.Collections.Generic.IEnumerable EnumerateFiles(string path, string searchPattern, System.IO.EnumerationOptions enumerationOptions) { } + public override System.Collections.Generic.IEnumerable EnumerateFiles(string path, string searchPattern, System.IO.SearchOption searchOption) { } + public override bool Exists(string path) { } + public override System.DateTime GetCreationTime(string path) { } + public override System.DateTime GetCreationTimeUtc(string path) { } + public override string GetCurrentDirectory() { } + public override string[] GetDirectories(string path) { } + public override string[] GetDirectories(string path, string searchPattern) { } + public override string[] GetDirectories(string path, string searchPattern, System.IO.EnumerationOptions enumerationOptions) { } + public override string[] GetDirectories(string path, string searchPattern, System.IO.SearchOption searchOption) { } + public override string GetDirectoryRoot(string path) { } + public override string[] GetFileSystemEntries(string path) { } + public override string[] GetFileSystemEntries(string path, string searchPattern) { } + public override string[] GetFileSystemEntries(string path, string searchPattern, System.IO.EnumerationOptions enumerationOptions) { } + public override string[] GetFileSystemEntries(string path, string searchPattern, System.IO.SearchOption searchOption) { } + public override string[] GetFiles(string path) { } + public override string[] GetFiles(string path, string searchPattern) { } + public override string[] GetFiles(string path, string searchPattern, System.IO.EnumerationOptions enumerationOptions) { } + public override string[] GetFiles(string path, string searchPattern, System.IO.SearchOption searchOption) { } + public override System.DateTime GetLastAccessTime(string path) { } + public override System.DateTime GetLastAccessTimeUtc(string path) { } + public override System.DateTime GetLastWriteTime(string path) { } + public override System.DateTime GetLastWriteTimeUtc(string path) { } + public override string[] GetLogicalDrives() { } + public override System.IO.Abstractions.IDirectoryInfo GetParent(string path) { } + public override void Move(string sourceDirName, string destDirName) { } + public override System.IO.Abstractions.IFileSystemInfo ResolveLinkTarget(string linkPath, bool returnFinalTarget) { } + public override void SetCreationTime(string path, System.DateTime creationTime) { } + public override void SetCreationTimeUtc(string path, System.DateTime creationTimeUtc) { } + public override void SetCurrentDirectory(string path) { } + public override void SetLastAccessTime(string path, System.DateTime lastAccessTime) { } + public override void SetLastAccessTimeUtc(string path, System.DateTime lastAccessTimeUtc) { } + public override void SetLastWriteTime(string path, System.DateTime lastWriteTime) { } + public override void SetLastWriteTimeUtc(string path, System.DateTime lastWriteTimeUtc) { } + } + [System.Serializable] + public abstract class DriveInfoBase : System.IO.Abstractions.IDriveInfo, System.IO.Abstractions.IFileSystemEntity + { + protected DriveInfoBase(System.IO.Abstractions.IFileSystem fileSystem) { } + public abstract long AvailableFreeSpace { get; } + public abstract string DriveFormat { get; } + public abstract System.IO.DriveType DriveType { get; } + public System.IO.Abstractions.IFileSystem FileSystem { get; } + public abstract bool IsReady { get; } + public abstract string Name { get; } + public abstract System.IO.Abstractions.IDirectoryInfo RootDirectory { get; } + public abstract long TotalFreeSpace { get; } + public abstract long TotalSize { get; } + public abstract string VolumeLabel { get; set; } + public static System.IO.Abstractions.DriveInfoBase op_Implicit(System.IO.DriveInfo driveInfo) { } + } + [System.Serializable] + public class DriveInfoWrapper : System.IO.Abstractions.DriveInfoBase + { + public DriveInfoWrapper(System.IO.Abstractions.IFileSystem fileSystem, System.IO.DriveInfo instance) { } + public override long AvailableFreeSpace { get; } + public override string DriveFormat { get; } + public override System.IO.DriveType DriveType { get; } + public override bool IsReady { get; } + public override string Name { get; } + public override System.IO.Abstractions.IDirectoryInfo RootDirectory { get; } + public override long TotalFreeSpace { get; } + public override long TotalSize { get; } + [set: System.Runtime.Versioning.SupportedOSPlatform("windows")] + public override string VolumeLabel { get; set; } + public override string ToString() { } + } + public static class FileAclExtensions + { + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public static System.Security.AccessControl.FileSecurity GetAccessControl(this System.IO.Abstractions.IFile file, string path) { } + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public static System.Security.AccessControl.FileSecurity GetAccessControl(this System.IO.Abstractions.IFile file, string path, System.Security.AccessControl.AccessControlSections includeSections) { } + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public static void SetAccessControl(this System.IO.Abstractions.IFile file, string path, System.Security.AccessControl.FileSecurity fileSecurity) { } + } + [System.Serializable] + public abstract class FileBase : System.IO.Abstractions.IFile, System.IO.Abstractions.IFileSystemEntity + { + protected FileBase(System.IO.Abstractions.IFileSystem fileSystem) { } + public System.IO.Abstractions.IFileSystem FileSystem { get; } + public abstract void AppendAllLines(string path, System.Collections.Generic.IEnumerable contents); + public abstract void AppendAllLines(string path, System.Collections.Generic.IEnumerable contents, System.Text.Encoding encoding); + public abstract System.Threading.Tasks.Task AppendAllLinesAsync(string path, System.Collections.Generic.IEnumerable contents, System.Threading.CancellationToken cancellationToken = default); + public abstract System.Threading.Tasks.Task AppendAllLinesAsync(string path, System.Collections.Generic.IEnumerable contents, System.Text.Encoding encoding, System.Threading.CancellationToken cancellationToken = default); + public abstract void AppendAllText(string path, string contents); + public abstract void AppendAllText(string path, string contents, System.Text.Encoding encoding); + public abstract System.Threading.Tasks.Task AppendAllTextAsync(string path, string contents, System.Threading.CancellationToken cancellationToken = default); + public abstract System.Threading.Tasks.Task AppendAllTextAsync(string path, string contents, System.Text.Encoding encoding, System.Threading.CancellationToken cancellationToken = default); + public abstract System.IO.StreamWriter AppendText(string path); + public abstract void Copy(string sourceFileName, string destFileName); + public abstract void Copy(string sourceFileName, string destFileName, bool overwrite); + public abstract System.IO.Abstractions.FileSystemStream Create(string path); + public abstract System.IO.Abstractions.FileSystemStream Create(string path, int bufferSize); + public abstract System.IO.Abstractions.FileSystemStream Create(string path, int bufferSize, System.IO.FileOptions options); + public abstract System.IO.Abstractions.IFileSystemInfo CreateSymbolicLink(string path, string pathToTarget); + public abstract System.IO.StreamWriter CreateText(string path); + public abstract void Decrypt(string path); + public abstract void Delete(string path); + public abstract void Encrypt(string path); + public abstract bool Exists(string path); + public abstract System.IO.FileAttributes GetAttributes(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle); + public abstract System.IO.FileAttributes GetAttributes(string path); + public abstract System.DateTime GetCreationTime(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle); + public abstract System.DateTime GetCreationTime(string path); + public abstract System.DateTime GetCreationTimeUtc(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle); + public abstract System.DateTime GetCreationTimeUtc(string path); + public abstract System.DateTime GetLastAccessTime(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle); + public abstract System.DateTime GetLastAccessTime(string path); + public abstract System.DateTime GetLastAccessTimeUtc(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle); + public abstract System.DateTime GetLastAccessTimeUtc(string path); + public abstract System.DateTime GetLastWriteTime(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle); + public abstract System.DateTime GetLastWriteTime(string path); + public abstract System.DateTime GetLastWriteTimeUtc(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle); + public abstract System.DateTime GetLastWriteTimeUtc(string path); + public abstract System.IO.UnixFileMode GetUnixFileMode(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle); + public abstract System.IO.UnixFileMode GetUnixFileMode(string path); + public abstract void Move(string sourceFileName, string destFileName); + public abstract void Move(string sourceFileName, string destFileName, bool overwrite); + public abstract System.IO.Abstractions.FileSystemStream Open(string path, System.IO.FileMode mode); + public abstract System.IO.Abstractions.FileSystemStream Open(string path, System.IO.FileStreamOptions options); + public abstract System.IO.Abstractions.FileSystemStream Open(string path, System.IO.FileMode mode, System.IO.FileAccess access); + public abstract System.IO.Abstractions.FileSystemStream Open(string path, System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share); + public abstract System.IO.Abstractions.FileSystemStream OpenRead(string path); + public abstract System.IO.StreamReader OpenText(string path); + public abstract System.IO.Abstractions.FileSystemStream OpenWrite(string path); + public abstract byte[] ReadAllBytes(string path); + public abstract System.Threading.Tasks.Task ReadAllBytesAsync(string path, System.Threading.CancellationToken cancellationToken = default); + public abstract string[] ReadAllLines(string path); + public abstract string[] ReadAllLines(string path, System.Text.Encoding encoding); + public abstract System.Threading.Tasks.Task ReadAllLinesAsync(string path, System.Threading.CancellationToken cancellationToken = default); + public abstract System.Threading.Tasks.Task ReadAllLinesAsync(string path, System.Text.Encoding encoding, System.Threading.CancellationToken cancellationToken = default); + public abstract string ReadAllText(string path); + public abstract string ReadAllText(string path, System.Text.Encoding encoding); + public abstract System.Threading.Tasks.Task ReadAllTextAsync(string path, System.Threading.CancellationToken cancellationToken = default); + public abstract System.Threading.Tasks.Task ReadAllTextAsync(string path, System.Text.Encoding encoding, System.Threading.CancellationToken cancellationToken = default); + public abstract System.Collections.Generic.IEnumerable ReadLines(string path); + public abstract System.Collections.Generic.IEnumerable ReadLines(string path, System.Text.Encoding encoding); + public abstract System.Collections.Generic.IAsyncEnumerable ReadLinesAsync(string path, System.Threading.CancellationToken cancellationToken = default); + public abstract System.Collections.Generic.IAsyncEnumerable ReadLinesAsync(string path, System.Text.Encoding encoding, System.Threading.CancellationToken cancellationToken = default); + public abstract void Replace(string sourceFileName, string destinationFileName, string destinationBackupFileName); + public abstract void Replace(string sourceFileName, string destinationFileName, string destinationBackupFileName, bool ignoreMetadataErrors); + public abstract System.IO.Abstractions.IFileSystemInfo ResolveLinkTarget(string linkPath, bool returnFinalTarget); + public abstract void SetAttributes(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle, System.IO.FileAttributes fileAttributes); + public abstract void SetAttributes(string path, System.IO.FileAttributes fileAttributes); + public abstract void SetCreationTime(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle, System.DateTime creationTime); + public abstract void SetCreationTime(string path, System.DateTime creationTime); + public abstract void SetCreationTimeUtc(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle, System.DateTime creationTimeUtc); + public abstract void SetCreationTimeUtc(string path, System.DateTime creationTimeUtc); + public abstract void SetLastAccessTime(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle, System.DateTime lastAccessTime); + public abstract void SetLastAccessTime(string path, System.DateTime lastAccessTime); + public abstract void SetLastAccessTimeUtc(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle, System.DateTime lastAccessTimeUtc); + public abstract void SetLastAccessTimeUtc(string path, System.DateTime lastAccessTimeUtc); + public abstract void SetLastWriteTime(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle, System.DateTime lastWriteTime); + public abstract void SetLastWriteTime(string path, System.DateTime lastWriteTime); + public abstract void SetLastWriteTimeUtc(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle, System.DateTime lastWriteTimeUtc); + public abstract void SetLastWriteTimeUtc(string path, System.DateTime lastWriteTimeUtc); + public abstract void SetUnixFileMode(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle, System.IO.UnixFileMode mode); + public abstract void SetUnixFileMode(string path, System.IO.UnixFileMode mode); + public abstract void WriteAllBytes(string path, byte[] bytes); + public abstract System.Threading.Tasks.Task WriteAllBytesAsync(string path, byte[] bytes, System.Threading.CancellationToken cancellationToken = default); + public abstract void WriteAllLines(string path, System.Collections.Generic.IEnumerable contents); + public abstract void WriteAllLines(string path, string[] contents); + public abstract void WriteAllLines(string path, System.Collections.Generic.IEnumerable contents, System.Text.Encoding encoding); + public abstract void WriteAllLines(string path, string[] contents, System.Text.Encoding encoding); + public abstract System.Threading.Tasks.Task WriteAllLinesAsync(string path, System.Collections.Generic.IEnumerable contents, System.Threading.CancellationToken cancellationToken = default); + public abstract System.Threading.Tasks.Task WriteAllLinesAsync(string path, System.Collections.Generic.IEnumerable contents, System.Text.Encoding encoding, System.Threading.CancellationToken cancellationToken = default); + public abstract void WriteAllText(string path, string contents); + public abstract void WriteAllText(string path, string contents, System.Text.Encoding encoding); + public abstract System.Threading.Tasks.Task WriteAllTextAsync(string path, string contents, System.Threading.CancellationToken cancellationToken = default); + public abstract System.Threading.Tasks.Task WriteAllTextAsync(string path, string contents, System.Text.Encoding encoding, System.Threading.CancellationToken cancellationToken = default); + } + public static class FileInfoAclExtensions + { + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public static System.Security.AccessControl.FileSecurity GetAccessControl(this System.IO.Abstractions.IFileInfo fileInfo) { } + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public static System.Security.AccessControl.FileSecurity GetAccessControl(this System.IO.Abstractions.IFileInfo fileInfo, System.Security.AccessControl.AccessControlSections includeSections) { } + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public static void SetAccessControl(this System.IO.Abstractions.IFileInfo fileInfo, System.Security.AccessControl.FileSecurity fileSecurity) { } + } + [System.Serializable] + public abstract class FileInfoBase : System.IO.Abstractions.FileSystemInfoBase, System.IO.Abstractions.IFileInfo, System.IO.Abstractions.IFileSystemInfo + { + protected FileInfoBase(System.IO.Abstractions.IFileSystem fileSystem) { } + public abstract System.IO.Abstractions.IDirectoryInfo Directory { get; } + public abstract string DirectoryName { get; } + public abstract bool IsReadOnly { get; set; } + public abstract long Length { get; } + public abstract System.IO.StreamWriter AppendText(); + public abstract System.IO.Abstractions.IFileInfo CopyTo(string destFileName); + public abstract System.IO.Abstractions.IFileInfo CopyTo(string destFileName, bool overwrite); + public abstract System.IO.Abstractions.FileSystemStream Create(); + public abstract System.IO.StreamWriter CreateText(); + public abstract void Decrypt(); + public abstract void Encrypt(); + public abstract void MoveTo(string destFileName); + public abstract void MoveTo(string destFileName, bool overwrite); + public abstract System.IO.Abstractions.FileSystemStream Open(System.IO.FileMode mode); + public abstract System.IO.Abstractions.FileSystemStream Open(System.IO.FileStreamOptions options); + public abstract System.IO.Abstractions.FileSystemStream Open(System.IO.FileMode mode, System.IO.FileAccess access); + public abstract System.IO.Abstractions.FileSystemStream Open(System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share); + public abstract System.IO.Abstractions.FileSystemStream OpenRead(); + public abstract System.IO.StreamReader OpenText(); + public abstract System.IO.Abstractions.FileSystemStream OpenWrite(); + public abstract System.IO.Abstractions.IFileInfo Replace(string destinationFileName, string destinationBackupFileName); + public abstract System.IO.Abstractions.IFileInfo Replace(string destinationFileName, string destinationBackupFileName, bool ignoreMetadataErrors); + public static System.IO.Abstractions.FileInfoBase op_Implicit(System.IO.FileInfo fileInfo) { } + } + [System.Serializable] + public class FileInfoWrapper : System.IO.Abstractions.FileInfoBase, System.IO.Abstractions.IFileSystemAclSupport + { + public FileInfoWrapper(System.IO.Abstractions.IFileSystem fileSystem, System.IO.FileInfo instance) { } + public override System.IO.FileAttributes Attributes { get; set; } + public override System.DateTime CreationTime { get; set; } + public override System.DateTime CreationTimeUtc { get; set; } + public override System.IO.Abstractions.IDirectoryInfo Directory { get; } + public override string DirectoryName { get; } + public override bool Exists { get; } + public override string Extension { get; } + public override string FullName { get; } + public override bool IsReadOnly { get; set; } + public override System.DateTime LastAccessTime { get; set; } + public override System.DateTime LastAccessTimeUtc { get; set; } + public override System.DateTime LastWriteTime { get; set; } + public override System.DateTime LastWriteTimeUtc { get; set; } + public override long Length { get; } + public override string LinkTarget { get; } + public override string Name { get; } + public override System.IO.StreamWriter AppendText() { } + public override System.IO.Abstractions.IFileInfo CopyTo(string destFileName) { } + public override System.IO.Abstractions.IFileInfo CopyTo(string destFileName, bool overwrite) { } + public override System.IO.Abstractions.FileSystemStream Create() { } + public override void CreateAsSymbolicLink(string pathToTarget) { } + public override System.IO.StreamWriter CreateText() { } + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public override void Decrypt() { } + public override void Delete() { } + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public override void Encrypt() { } + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public object GetAccessControl() { } + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public object GetAccessControl(System.IO.Abstractions.IFileSystemAclSupport.AccessControlSections includeSections) { } + public override void MoveTo(string destFileName) { } + public override void MoveTo(string destFileName, bool overwrite) { } + public override System.IO.Abstractions.FileSystemStream Open(System.IO.FileMode mode) { } + public override System.IO.Abstractions.FileSystemStream Open(System.IO.FileStreamOptions options) { } + public override System.IO.Abstractions.FileSystemStream Open(System.IO.FileMode mode, System.IO.FileAccess access) { } + public override System.IO.Abstractions.FileSystemStream Open(System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share) { } + public override System.IO.Abstractions.FileSystemStream OpenRead() { } + public override System.IO.StreamReader OpenText() { } + public override System.IO.Abstractions.FileSystemStream OpenWrite() { } + public override void Refresh() { } + public override System.IO.Abstractions.IFileInfo Replace(string destinationFileName, string destinationBackupFileName) { } + public override System.IO.Abstractions.IFileInfo Replace(string destinationFileName, string destinationBackupFileName, bool ignoreMetadataErrors) { } + public override System.IO.Abstractions.IFileSystemInfo ResolveLinkTarget(bool returnFinalTarget) { } + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public void SetAccessControl(object value) { } + public override string ToString() { } + } + public static class FileStreamAclExtensions + { + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public static System.Security.AccessControl.FileSecurity GetAccessControl(this System.IO.Abstractions.FileSystemStream fileStream) { } + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public static void SetAccessControl(this System.IO.Abstractions.FileSystemStream fileStream, System.Security.AccessControl.FileSecurity fileSecurity) { } + } + [System.Serializable] + public class FileSystem : System.IO.Abstractions.FileSystemBase + { + public FileSystem() { } + public override System.IO.Abstractions.IDirectory Directory { get; } + public override System.IO.Abstractions.IDirectoryInfoFactory DirectoryInfo { get; } + public override System.IO.Abstractions.IDriveInfoFactory DriveInfo { get; } + public override System.IO.Abstractions.IFile File { get; } + public override System.IO.Abstractions.IFileInfoFactory FileInfo { get; } + public override System.IO.Abstractions.IFileStreamFactory FileStream { get; } + public override System.IO.Abstractions.IFileSystemWatcherFactory FileSystemWatcher { get; } + public override System.IO.Abstractions.IFileVersionInfoFactory FileVersionInfo { get; } + public override System.IO.Abstractions.IPath Path { get; } + } + [System.Serializable] + public abstract class FileSystemBase : System.IO.Abstractions.IFileSystem + { + protected FileSystemBase() { } + public abstract System.IO.Abstractions.IDirectory Directory { get; } + public abstract System.IO.Abstractions.IDirectoryInfoFactory DirectoryInfo { get; } + public abstract System.IO.Abstractions.IDriveInfoFactory DriveInfo { get; } + public abstract System.IO.Abstractions.IFile File { get; } + public abstract System.IO.Abstractions.IFileInfoFactory FileInfo { get; } + public abstract System.IO.Abstractions.IFileStreamFactory FileStream { get; } + public abstract System.IO.Abstractions.IFileSystemWatcherFactory FileSystemWatcher { get; } + public abstract System.IO.Abstractions.IFileVersionInfoFactory FileVersionInfo { get; } + public abstract System.IO.Abstractions.IPath Path { get; } + } + [System.Serializable] + public abstract class FileSystemInfoBase : System.IO.Abstractions.IFileSystemInfo + { + protected FileSystemInfoBase(System.IO.Abstractions.IFileSystem fileSystem) { } + public abstract System.IO.FileAttributes Attributes { get; set; } + public abstract System.DateTime CreationTime { get; set; } + public abstract System.DateTime CreationTimeUtc { get; set; } + public abstract bool Exists { get; } + public abstract string Extension { get; } + public System.IO.Abstractions.IFileSystem FileSystem { get; } + public abstract string FullName { get; } + public abstract System.DateTime LastAccessTime { get; set; } + public abstract System.DateTime LastAccessTimeUtc { get; set; } + public abstract System.DateTime LastWriteTime { get; set; } + public abstract System.DateTime LastWriteTimeUtc { get; set; } + public abstract string LinkTarget { get; } + public abstract string Name { get; } + [set: System.Runtime.Versioning.UnsupportedOSPlatform("windows")] + public System.IO.UnixFileMode UnixFileMode { get; set; } + public abstract void CreateAsSymbolicLink(string pathToTarget); + public abstract void Delete(); + public abstract void Refresh(); + public abstract System.IO.Abstractions.IFileSystemInfo ResolveLinkTarget(bool returnFinalTarget); + } + [System.Serializable] + public abstract class FileSystemWatcherBase : System.IDisposable, System.IO.Abstractions.IFileSystemEntity, System.IO.Abstractions.IFileSystemWatcher + { + protected FileSystemWatcherBase() { } + public abstract System.ComponentModel.IContainer Container { get; } + public abstract bool EnableRaisingEvents { get; set; } + public abstract System.IO.Abstractions.IFileSystem FileSystem { get; } + public abstract string Filter { get; set; } + public abstract System.Collections.ObjectModel.Collection Filters { get; } + public abstract bool IncludeSubdirectories { get; set; } + public abstract int InternalBufferSize { get; set; } + public abstract System.IO.NotifyFilters NotifyFilter { get; set; } + public abstract string Path { get; set; } + public abstract System.ComponentModel.ISite Site { get; set; } + public abstract System.ComponentModel.ISynchronizeInvoke SynchronizingObject { get; set; } + public virtual event System.IO.FileSystemEventHandler Changed; + public virtual event System.IO.FileSystemEventHandler Created; + public virtual event System.IO.FileSystemEventHandler Deleted; + public virtual event System.IO.ErrorEventHandler Error; + public virtual event System.IO.RenamedEventHandler Renamed; + public abstract void BeginInit(); + public void Dispose() { } + public virtual void Dispose(bool disposing) { } + public abstract void EndInit(); + protected void OnChanged(object sender, System.IO.FileSystemEventArgs args) { } + protected void OnCreated(object sender, System.IO.FileSystemEventArgs args) { } + protected void OnDeleted(object sender, System.IO.FileSystemEventArgs args) { } + protected void OnError(object sender, System.IO.ErrorEventArgs args) { } + protected void OnRenamed(object sender, System.IO.RenamedEventArgs args) { } + public abstract System.IO.Abstractions.IWaitForChangedResult WaitForChanged(System.IO.WatcherChangeTypes changeType); + public abstract System.IO.Abstractions.IWaitForChangedResult WaitForChanged(System.IO.WatcherChangeTypes changeType, System.TimeSpan timeout); + public abstract System.IO.Abstractions.IWaitForChangedResult WaitForChanged(System.IO.WatcherChangeTypes changeType, int timeout); + public static System.IO.Abstractions.FileSystemWatcherBase op_Implicit(System.IO.FileSystemWatcher watcher) { } + } + [System.Serializable] + public class FileSystemWatcherFactory : System.IO.Abstractions.IFileSystemEntity, System.IO.Abstractions.IFileSystemWatcherFactory + { + public FileSystemWatcherFactory(System.IO.Abstractions.IFileSystem fileSystem) { } + public System.IO.Abstractions.IFileSystem FileSystem { get; } + public System.IO.Abstractions.IFileSystemWatcher New() { } + public System.IO.Abstractions.IFileSystemWatcher New(string path) { } + public System.IO.Abstractions.IFileSystemWatcher New(string path, string filter) { } + public System.IO.Abstractions.IFileSystemWatcher Wrap(System.IO.FileSystemWatcher fileSystemWatcher) { } + } + [System.Serializable] + public class FileSystemWatcherWrapper : System.IO.Abstractions.FileSystemWatcherBase + { + public FileSystemWatcherWrapper(System.IO.Abstractions.IFileSystem fileSystem) { } + public FileSystemWatcherWrapper(System.IO.Abstractions.IFileSystem fileSystem, System.IO.FileSystemWatcher watcher) { } + public FileSystemWatcherWrapper(System.IO.Abstractions.IFileSystem fileSystem, string path) { } + public FileSystemWatcherWrapper(System.IO.Abstractions.IFileSystem fileSystem, string path, string filter) { } + public override System.ComponentModel.IContainer Container { get; } + public override bool EnableRaisingEvents { get; set; } + public override System.IO.Abstractions.IFileSystem FileSystem { get; } + public override string Filter { get; set; } + public override System.Collections.ObjectModel.Collection Filters { get; } + public override bool IncludeSubdirectories { get; set; } + public override int InternalBufferSize { get; set; } + public override System.IO.NotifyFilters NotifyFilter { get; set; } + public override string Path { get; set; } + public override System.ComponentModel.ISite Site { get; set; } + public override System.ComponentModel.ISynchronizeInvoke SynchronizingObject { get; set; } + public override void BeginInit() { } + public override void Dispose(bool disposing) { } + public override void EndInit() { } + public override System.IO.Abstractions.IWaitForChangedResult WaitForChanged(System.IO.WatcherChangeTypes changeType) { } + public override System.IO.Abstractions.IWaitForChangedResult WaitForChanged(System.IO.WatcherChangeTypes changeType, System.TimeSpan timeout) { } + public override System.IO.Abstractions.IWaitForChangedResult WaitForChanged(System.IO.WatcherChangeTypes changeType, int timeout) { } + } + [System.Serializable] + public abstract class FileVersionInfoBase : System.IO.Abstractions.IFileVersionInfo + { + protected FileVersionInfoBase() { } + public abstract string Comments { get; } + public abstract string CompanyName { get; } + public abstract int FileBuildPart { get; } + public abstract string FileDescription { get; } + public abstract int FileMajorPart { get; } + public abstract int FileMinorPart { get; } + public abstract string FileName { get; } + public abstract int FilePrivatePart { get; } + public abstract string FileVersion { get; } + public abstract string InternalName { get; } + public abstract bool IsDebug { get; } + public abstract bool IsPatched { get; } + public abstract bool IsPreRelease { get; } + public abstract bool IsPrivateBuild { get; } + public abstract bool IsSpecialBuild { get; } + public abstract string Language { get; } + public abstract string LegalCopyright { get; } + public abstract string LegalTrademarks { get; } + public abstract string OriginalFilename { get; } + public abstract string PrivateBuild { get; } + public abstract int ProductBuildPart { get; } + public abstract int ProductMajorPart { get; } + public abstract int ProductMinorPart { get; } + public abstract string ProductName { get; } + public abstract int ProductPrivatePart { get; } + public abstract string ProductVersion { get; } + public abstract string SpecialBuild { get; } + public abstract string ToString(); + public static System.IO.Abstractions.FileVersionInfoBase op_Implicit(System.Diagnostics.FileVersionInfo fileVersionInfo) { } + } + [System.Serializable] + public class FileVersionInfoWrapper : System.IO.Abstractions.FileVersionInfoBase + { + public FileVersionInfoWrapper(System.Diagnostics.FileVersionInfo fileVersionInfo) { } + public override string Comments { get; } + public override string CompanyName { get; } + public override int FileBuildPart { get; } + public override string FileDescription { get; } + public override int FileMajorPart { get; } + public override int FileMinorPart { get; } + public override string FileName { get; } + public override int FilePrivatePart { get; } + public override string FileVersion { get; } + public override string InternalName { get; } + public override bool IsDebug { get; } + public override bool IsPatched { get; } + public override bool IsPreRelease { get; } + public override bool IsPrivateBuild { get; } + public override bool IsSpecialBuild { get; } + public override string Language { get; } + public override string LegalCopyright { get; } + public override string LegalTrademarks { get; } + public override string OriginalFilename { get; } + public override string PrivateBuild { get; } + public override int ProductBuildPart { get; } + public override int ProductMajorPart { get; } + public override int ProductMinorPart { get; } + public override string ProductName { get; } + public override int ProductPrivatePart { get; } + public override string ProductVersion { get; } + public override string SpecialBuild { get; } + public override string ToString() { } + } + [System.Serializable] + public class FileWrapper : System.IO.Abstractions.FileBase + { + public FileWrapper(System.IO.Abstractions.IFileSystem fileSystem) { } + public override void AppendAllLines(string path, System.Collections.Generic.IEnumerable contents) { } + public override void AppendAllLines(string path, System.Collections.Generic.IEnumerable contents, System.Text.Encoding encoding) { } + public override System.Threading.Tasks.Task AppendAllLinesAsync(string path, System.Collections.Generic.IEnumerable contents, System.Threading.CancellationToken cancellationToken = default) { } + public override System.Threading.Tasks.Task AppendAllLinesAsync(string path, System.Collections.Generic.IEnumerable contents, System.Text.Encoding encoding, System.Threading.CancellationToken cancellationToken = default) { } + public override void AppendAllText(string path, string contents) { } + public override void AppendAllText(string path, string contents, System.Text.Encoding encoding) { } + public override System.Threading.Tasks.Task AppendAllTextAsync(string path, string contents, System.Threading.CancellationToken cancellationToken = default) { } + public override System.Threading.Tasks.Task AppendAllTextAsync(string path, string contents, System.Text.Encoding encoding, System.Threading.CancellationToken cancellationToken = default) { } + public override System.IO.StreamWriter AppendText(string path) { } + public override void Copy(string sourceFileName, string destFileName) { } + public override void Copy(string sourceFileName, string destFileName, bool overwrite) { } + public override System.IO.Abstractions.FileSystemStream Create(string path) { } + public override System.IO.Abstractions.FileSystemStream Create(string path, int bufferSize) { } + public override System.IO.Abstractions.FileSystemStream Create(string path, int bufferSize, System.IO.FileOptions options) { } + public override System.IO.Abstractions.IFileSystemInfo CreateSymbolicLink(string path, string pathToTarget) { } + public override System.IO.StreamWriter CreateText(string path) { } + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public override void Decrypt(string path) { } + public override void Delete(string path) { } + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public override void Encrypt(string path) { } + public override bool Exists(string path) { } + public override System.IO.FileAttributes GetAttributes(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle) { } + public override System.IO.FileAttributes GetAttributes(string path) { } + public override System.DateTime GetCreationTime(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle) { } + public override System.DateTime GetCreationTime(string path) { } + public override System.DateTime GetCreationTimeUtc(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle) { } + public override System.DateTime GetCreationTimeUtc(string path) { } + public override System.DateTime GetLastAccessTime(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle) { } + public override System.DateTime GetLastAccessTime(string path) { } + public override System.DateTime GetLastAccessTimeUtc(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle) { } + public override System.DateTime GetLastAccessTimeUtc(string path) { } + public override System.DateTime GetLastWriteTime(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle) { } + public override System.DateTime GetLastWriteTime(string path) { } + public override System.DateTime GetLastWriteTimeUtc(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle) { } + public override System.DateTime GetLastWriteTimeUtc(string path) { } + [System.Runtime.Versioning.UnsupportedOSPlatform("windows")] + public override System.IO.UnixFileMode GetUnixFileMode(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle) { } + [System.Runtime.Versioning.UnsupportedOSPlatform("windows")] + public override System.IO.UnixFileMode GetUnixFileMode(string path) { } + public override void Move(string sourceFileName, string destFileName) { } + public override void Move(string sourceFileName, string destFileName, bool overwrite) { } + public override System.IO.Abstractions.FileSystemStream Open(string path, System.IO.FileMode mode) { } + public override System.IO.Abstractions.FileSystemStream Open(string path, System.IO.FileStreamOptions options) { } + public override System.IO.Abstractions.FileSystemStream Open(string path, System.IO.FileMode mode, System.IO.FileAccess access) { } + public override System.IO.Abstractions.FileSystemStream Open(string path, System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share) { } + public override System.IO.Abstractions.FileSystemStream OpenRead(string path) { } + public override System.IO.StreamReader OpenText(string path) { } + public override System.IO.Abstractions.FileSystemStream OpenWrite(string path) { } + public override byte[] ReadAllBytes(string path) { } + public override System.Threading.Tasks.Task ReadAllBytesAsync(string path, System.Threading.CancellationToken cancellationToken = default) { } + public override string[] ReadAllLines(string path) { } + public override string[] ReadAllLines(string path, System.Text.Encoding encoding) { } + public override System.Threading.Tasks.Task ReadAllLinesAsync(string path, System.Threading.CancellationToken cancellationToken = default) { } + public override System.Threading.Tasks.Task ReadAllLinesAsync(string path, System.Text.Encoding encoding, System.Threading.CancellationToken cancellationToken = default) { } + public override string ReadAllText(string path) { } + public override string ReadAllText(string path, System.Text.Encoding encoding) { } + public override System.Threading.Tasks.Task ReadAllTextAsync(string path, System.Threading.CancellationToken cancellationToken = default) { } + public override System.Threading.Tasks.Task ReadAllTextAsync(string path, System.Text.Encoding encoding, System.Threading.CancellationToken cancellationToken = default) { } + public override System.Collections.Generic.IEnumerable ReadLines(string path) { } + public override System.Collections.Generic.IEnumerable ReadLines(string path, System.Text.Encoding encoding) { } + public override System.Collections.Generic.IAsyncEnumerable ReadLinesAsync(string path, System.Threading.CancellationToken cancellationToken = default) { } + public override System.Collections.Generic.IAsyncEnumerable ReadLinesAsync(string path, System.Text.Encoding encoding, System.Threading.CancellationToken cancellationToken = default) { } + public override void Replace(string sourceFileName, string destinationFileName, string destinationBackupFileName) { } + public override void Replace(string sourceFileName, string destinationFileName, string destinationBackupFileName, bool ignoreMetadataErrors) { } + public override System.IO.Abstractions.IFileSystemInfo ResolveLinkTarget(string linkPath, bool returnFinalTarget) { } + public override void SetAttributes(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle, System.IO.FileAttributes fileAttributes) { } + public override void SetAttributes(string path, System.IO.FileAttributes fileAttributes) { } + public override void SetCreationTime(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle, System.DateTime creationTime) { } + public override void SetCreationTime(string path, System.DateTime creationTime) { } + public override void SetCreationTimeUtc(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle, System.DateTime creationTimeUtc) { } + public override void SetCreationTimeUtc(string path, System.DateTime creationTimeUtc) { } + public override void SetLastAccessTime(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle, System.DateTime lastAccessTime) { } + public override void SetLastAccessTime(string path, System.DateTime lastAccessTime) { } + public override void SetLastAccessTimeUtc(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle, System.DateTime lastAccessTimeUtc) { } + public override void SetLastAccessTimeUtc(string path, System.DateTime lastAccessTimeUtc) { } + public override void SetLastWriteTime(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle, System.DateTime lastWriteTime) { } + public override void SetLastWriteTime(string path, System.DateTime lastWriteTime) { } + public override void SetLastWriteTimeUtc(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle, System.DateTime lastWriteTimeUtc) { } + public override void SetLastWriteTimeUtc(string path, System.DateTime lastWriteTimeUtc) { } + [System.Runtime.Versioning.UnsupportedOSPlatform("windows")] + public override void SetUnixFileMode(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle, System.IO.UnixFileMode mode) { } + [System.Runtime.Versioning.UnsupportedOSPlatform("windows")] + public override void SetUnixFileMode(string path, System.IO.UnixFileMode mode) { } + public override void WriteAllBytes(string path, byte[] bytes) { } + public override System.Threading.Tasks.Task WriteAllBytesAsync(string path, byte[] bytes, System.Threading.CancellationToken cancellationToken = default) { } + public override void WriteAllLines(string path, System.Collections.Generic.IEnumerable contents) { } + public override void WriteAllLines(string path, string[] contents) { } + public override void WriteAllLines(string path, System.Collections.Generic.IEnumerable contents, System.Text.Encoding encoding) { } + public override void WriteAllLines(string path, string[] contents, System.Text.Encoding encoding) { } + public override System.Threading.Tasks.Task WriteAllLinesAsync(string path, System.Collections.Generic.IEnumerable contents, System.Threading.CancellationToken cancellationToken = default) { } + public override System.Threading.Tasks.Task WriteAllLinesAsync(string path, System.Collections.Generic.IEnumerable contents, System.Text.Encoding encoding, System.Threading.CancellationToken cancellationToken = default) { } + public override void WriteAllText(string path, string contents) { } + public override void WriteAllText(string path, string contents, System.Text.Encoding encoding) { } + public override System.Threading.Tasks.Task WriteAllTextAsync(string path, string contents, System.Threading.CancellationToken cancellationToken = default) { } + public override System.Threading.Tasks.Task WriteAllTextAsync(string path, string contents, System.Text.Encoding encoding, System.Threading.CancellationToken cancellationToken = default) { } + } + [System.Serializable] + public abstract class PathBase : System.IO.Abstractions.IFileSystemEntity, System.IO.Abstractions.IPath + { + protected PathBase(System.IO.Abstractions.IFileSystem fileSystem) { } + public abstract char AltDirectorySeparatorChar { get; } + public abstract char DirectorySeparatorChar { get; } + public System.IO.Abstractions.IFileSystem FileSystem { get; } + [System.Obsolete("Please use GetInvalidPathChars or GetInvalidFileNameChars instead.")] + public abstract char[] InvalidPathChars { get; } + public abstract char PathSeparator { get; } + public abstract char VolumeSeparatorChar { get; } + public abstract string ChangeExtension(string path, string extension); + public abstract string Combine(params string[] paths); + public abstract string Combine(string path1, string path2); + public abstract string Combine(string path1, string path2, string path3); + public abstract string Combine(string path1, string path2, string path3, string path4); + public abstract bool EndsInDirectorySeparator(System.ReadOnlySpan path); + public abstract bool EndsInDirectorySeparator(string path); + public abstract bool Exists(string path); + public abstract System.ReadOnlySpan GetDirectoryName(System.ReadOnlySpan path); + public abstract string GetDirectoryName(string path); + public abstract System.ReadOnlySpan GetExtension(System.ReadOnlySpan path); + public abstract string GetExtension(string path); + public abstract System.ReadOnlySpan GetFileName(System.ReadOnlySpan path); + public abstract string GetFileName(string path); + public abstract System.ReadOnlySpan GetFileNameWithoutExtension(System.ReadOnlySpan path); + public abstract string GetFileNameWithoutExtension(string path); + public abstract string GetFullPath(string path); + public abstract string GetFullPath(string path, string basePath); + public abstract char[] GetInvalidFileNameChars(); + public abstract char[] GetInvalidPathChars(); + public abstract System.ReadOnlySpan GetPathRoot(System.ReadOnlySpan path); + public abstract string GetPathRoot(string path); + public abstract string GetRandomFileName(); + public abstract string GetRelativePath(string relativeTo, string path); + public abstract string GetTempFileName(); + public abstract string GetTempPath(); + public abstract bool HasExtension(System.ReadOnlySpan path); + public abstract bool HasExtension(string path); + public abstract bool IsPathFullyQualified(System.ReadOnlySpan path); + public abstract bool IsPathFullyQualified(string path); + public abstract bool IsPathRooted(System.ReadOnlySpan path); + public abstract bool IsPathRooted(string path); + public abstract string Join(params string[] paths); + public abstract string Join(System.ReadOnlySpan path1, System.ReadOnlySpan path2); + public abstract string Join(string path1, string path2); + public abstract string Join(System.ReadOnlySpan path1, System.ReadOnlySpan path2, System.ReadOnlySpan path3); + public abstract string Join(string path1, string path2, string path3); + public abstract string Join(System.ReadOnlySpan path1, System.ReadOnlySpan path2, System.ReadOnlySpan path3, System.ReadOnlySpan path4); + public abstract string Join(string path1, string path2, string path3, string path4); + public abstract System.ReadOnlySpan TrimEndingDirectorySeparator(System.ReadOnlySpan path); + public abstract string TrimEndingDirectorySeparator(string path); + public abstract bool TryJoin(System.ReadOnlySpan path1, System.ReadOnlySpan path2, System.Span destination, out int charsWritten); + public abstract bool TryJoin(System.ReadOnlySpan path1, System.ReadOnlySpan path2, System.ReadOnlySpan path3, System.Span destination, out int charsWritten); + } + [System.Serializable] + public class PathWrapper : System.IO.Abstractions.PathBase + { + public PathWrapper(System.IO.Abstractions.IFileSystem fileSystem) { } + public override char AltDirectorySeparatorChar { get; } + public override char DirectorySeparatorChar { get; } + [System.Obsolete("Please use GetInvalidPathChars or GetInvalidFileNameChars instead.")] + public override char[] InvalidPathChars { get; } + public override char PathSeparator { get; } + public override char VolumeSeparatorChar { get; } + public override string ChangeExtension(string path, string extension) { } + public override string Combine(params string[] paths) { } + public override string Combine(string path1, string path2) { } + public override string Combine(string path1, string path2, string path3) { } + public override string Combine(string path1, string path2, string path3, string path4) { } + public override bool EndsInDirectorySeparator(System.ReadOnlySpan path) { } + public override bool EndsInDirectorySeparator(string path) { } + public override bool Exists(string path) { } + public override System.ReadOnlySpan GetDirectoryName(System.ReadOnlySpan path) { } + public override string GetDirectoryName(string path) { } + public override System.ReadOnlySpan GetExtension(System.ReadOnlySpan path) { } + public override string GetExtension(string path) { } + public override System.ReadOnlySpan GetFileName(System.ReadOnlySpan path) { } + public override string GetFileName(string path) { } + public override System.ReadOnlySpan GetFileNameWithoutExtension(System.ReadOnlySpan path) { } + public override string GetFileNameWithoutExtension(string path) { } + public override string GetFullPath(string path) { } + public override string GetFullPath(string path, string basePath) { } + public override char[] GetInvalidFileNameChars() { } + public override char[] GetInvalidPathChars() { } + public override System.ReadOnlySpan GetPathRoot(System.ReadOnlySpan path) { } + public override string GetPathRoot(string path) { } + public override string GetRandomFileName() { } + public override string GetRelativePath(string relativeTo, string path) { } + public override string GetTempFileName() { } + public override string GetTempPath() { } + public override bool HasExtension(System.ReadOnlySpan path) { } + public override bool HasExtension(string path) { } + public override bool IsPathFullyQualified(System.ReadOnlySpan path) { } + public override bool IsPathFullyQualified(string path) { } + public override bool IsPathRooted(System.ReadOnlySpan path) { } + public override bool IsPathRooted(string path) { } + public override string Join(params string[] paths) { } + public override string Join(System.ReadOnlySpan path1, System.ReadOnlySpan path2) { } + public override string Join(string path1, string path2) { } + public override string Join(System.ReadOnlySpan path1, System.ReadOnlySpan path2, System.ReadOnlySpan path3) { } + public override string Join(string path1, string path2, string path3) { } + public override string Join(System.ReadOnlySpan path1, System.ReadOnlySpan path2, System.ReadOnlySpan path3, System.ReadOnlySpan path4) { } + public override string Join(string path1, string path2, string path3, string path4) { } + public override System.ReadOnlySpan TrimEndingDirectorySeparator(System.ReadOnlySpan path) { } + public override string TrimEndingDirectorySeparator(string path) { } + public override bool TryJoin(System.ReadOnlySpan path1, System.ReadOnlySpan path2, System.Span destination, out int charsWritten) { } + public override bool TryJoin(System.ReadOnlySpan path1, System.ReadOnlySpan path2, System.ReadOnlySpan path3, System.Span destination, out int charsWritten) { } + } +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.Api.Tests/Expected/TestableIO.System.IO.Abstractions.Wrappers_net9.0.txt b/tests/TestableIO.System.IO.Abstractions.Api.Tests/Expected/TestableIO.System.IO.Abstractions.Wrappers_net9.0.txt new file mode 100644 index 000000000..b66ca94d4 --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.Api.Tests/Expected/TestableIO.System.IO.Abstractions.Wrappers_net9.0.txt @@ -0,0 +1,898 @@ +[assembly: System.CLSCompliant(true)] +[assembly: System.Reflection.AssemblyMetadata("RepositoryUrl", "https://github.com/TestableIO/System.IO.Abstractions.git")] +[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(@"DynamicProxyGenAssembly2, PublicKey=0024000004800000940000000602000000240000525341310004000001000100c547cac37abd99c8db225ef2f6c8a3602f3b3606cc9891605d02baa56104f4cfc0734aa39b93bf7852f7d9266654753cc297e7d2edfe0bac1cdcf9f717241550e0a7b191195b7667bb4f64bcb8e2121380fd1d9d46ad2d92d2d15605093924cceaf74c4861eff62abf69b9291ed0a340e113be11e6a7d3113e92484cf7045cc7")] +[assembly: System.Runtime.Versioning.TargetFramework(".NETCoreApp,Version=v9.0", FrameworkDisplayName=".NET 9.0")] +namespace System.IO.Abstractions +{ + public static class DirectoryAclExtensions + { + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public static void CreateDirectory(this System.IO.Abstractions.IDirectory directory, string path, System.Security.AccessControl.DirectorySecurity directorySecurity) { } + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public static System.Security.AccessControl.DirectorySecurity GetAccessControl(this System.IO.Abstractions.IDirectory directory, string path) { } + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public static System.Security.AccessControl.DirectorySecurity GetAccessControl(this System.IO.Abstractions.IDirectory directory, string path, System.Security.AccessControl.AccessControlSections includeSections) { } + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public static void SetAccessControl(this System.IO.Abstractions.IDirectory directory, string path, System.Security.AccessControl.DirectorySecurity directorySecurity) { } + } + [System.Serializable] + public abstract class DirectoryBase : System.IO.Abstractions.IDirectory, System.IO.Abstractions.IFileSystemEntity + { + protected DirectoryBase(System.IO.Abstractions.IFileSystem fileSystem) { } + public System.IO.Abstractions.IFileSystem FileSystem { get; } + public abstract System.IO.Abstractions.IDirectoryInfo CreateDirectory(string path); + public abstract System.IO.Abstractions.IDirectoryInfo CreateDirectory(string path, System.IO.UnixFileMode unixCreateMode); + public abstract System.IO.Abstractions.IFileSystemInfo CreateSymbolicLink(string path, string pathToTarget); + public abstract System.IO.Abstractions.IDirectoryInfo CreateTempSubdirectory(string prefix = null); + public abstract void Delete(string path); + public abstract void Delete(string path, bool recursive); + public abstract System.Collections.Generic.IEnumerable EnumerateDirectories(string path); + public abstract System.Collections.Generic.IEnumerable EnumerateDirectories(string path, string searchPattern); + public abstract System.Collections.Generic.IEnumerable EnumerateDirectories(string path, string searchPattern, System.IO.EnumerationOptions enumerationOptions); + public abstract System.Collections.Generic.IEnumerable EnumerateDirectories(string path, string searchPattern, System.IO.SearchOption searchOption); + public abstract System.Collections.Generic.IEnumerable EnumerateFileSystemEntries(string path); + public abstract System.Collections.Generic.IEnumerable EnumerateFileSystemEntries(string path, string searchPattern); + public abstract System.Collections.Generic.IEnumerable EnumerateFileSystemEntries(string path, string searchPattern, System.IO.EnumerationOptions enumerationOptions); + public abstract System.Collections.Generic.IEnumerable EnumerateFileSystemEntries(string path, string searchPattern, System.IO.SearchOption searchOption); + public abstract System.Collections.Generic.IEnumerable EnumerateFiles(string path); + public abstract System.Collections.Generic.IEnumerable EnumerateFiles(string path, string searchPattern); + public abstract System.Collections.Generic.IEnumerable EnumerateFiles(string path, string searchPattern, System.IO.EnumerationOptions enumerationOptions); + public abstract System.Collections.Generic.IEnumerable EnumerateFiles(string path, string searchPattern, System.IO.SearchOption searchOption); + public abstract bool Exists(string path); + public abstract System.DateTime GetCreationTime(string path); + public abstract System.DateTime GetCreationTimeUtc(string path); + public abstract string GetCurrentDirectory(); + public abstract string[] GetDirectories(string path); + public abstract string[] GetDirectories(string path, string searchPattern); + public abstract string[] GetDirectories(string path, string searchPattern, System.IO.EnumerationOptions enumerationOptions); + public abstract string[] GetDirectories(string path, string searchPattern, System.IO.SearchOption searchOption); + public abstract string GetDirectoryRoot(string path); + public abstract string[] GetFileSystemEntries(string path); + public abstract string[] GetFileSystemEntries(string path, string searchPattern); + public abstract string[] GetFileSystemEntries(string path, string searchPattern, System.IO.EnumerationOptions enumerationOptions); + public abstract string[] GetFileSystemEntries(string path, string searchPattern, System.IO.SearchOption searchOption); + public abstract string[] GetFiles(string path); + public abstract string[] GetFiles(string path, string searchPattern); + public abstract string[] GetFiles(string path, string searchPattern, System.IO.EnumerationOptions enumerationOptions); + public abstract string[] GetFiles(string path, string searchPattern, System.IO.SearchOption searchOption); + public abstract System.DateTime GetLastAccessTime(string path); + public abstract System.DateTime GetLastAccessTimeUtc(string path); + public abstract System.DateTime GetLastWriteTime(string path); + public abstract System.DateTime GetLastWriteTimeUtc(string path); + public abstract string[] GetLogicalDrives(); + public abstract System.IO.Abstractions.IDirectoryInfo GetParent(string path); + public abstract void Move(string sourceDirName, string destDirName); + public abstract System.IO.Abstractions.IFileSystemInfo ResolveLinkTarget(string linkPath, bool returnFinalTarget); + public abstract void SetCreationTime(string path, System.DateTime creationTime); + public abstract void SetCreationTimeUtc(string path, System.DateTime creationTimeUtc); + public abstract void SetCurrentDirectory(string path); + public abstract void SetLastAccessTime(string path, System.DateTime lastAccessTime); + public abstract void SetLastAccessTimeUtc(string path, System.DateTime lastAccessTimeUtc); + public abstract void SetLastWriteTime(string path, System.DateTime lastWriteTime); + public abstract void SetLastWriteTimeUtc(string path, System.DateTime lastWriteTimeUtc); + } + public static class DirectoryInfoAclExtensions + { + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public static void Create(this System.IO.Abstractions.IDirectoryInfo directoryInfo, System.Security.AccessControl.DirectorySecurity directorySecurity) { } + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public static System.Security.AccessControl.DirectorySecurity GetAccessControl(this System.IO.Abstractions.IDirectoryInfo directoryInfo) { } + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public static System.Security.AccessControl.DirectorySecurity GetAccessControl(this System.IO.Abstractions.IDirectoryInfo directoryInfo, System.Security.AccessControl.AccessControlSections includeSections) { } + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public static void SetAccessControl(this System.IO.Abstractions.IDirectoryInfo directoryInfo, System.Security.AccessControl.DirectorySecurity directorySecurity) { } + } + [System.Serializable] + public abstract class DirectoryInfoBase : System.IO.Abstractions.FileSystemInfoBase, System.IO.Abstractions.IDirectoryInfo, System.IO.Abstractions.IFileSystemInfo + { + protected DirectoryInfoBase(System.IO.Abstractions.IFileSystem fileSystem) { } + public abstract System.IO.Abstractions.IDirectoryInfo Parent { get; } + public abstract System.IO.Abstractions.IDirectoryInfo Root { get; } + public abstract void Create(); + public abstract System.IO.Abstractions.IDirectoryInfo CreateSubdirectory(string path); + public abstract void Delete(bool recursive); + public abstract System.Collections.Generic.IEnumerable EnumerateDirectories(); + public abstract System.Collections.Generic.IEnumerable EnumerateDirectories(string searchPattern); + public abstract System.Collections.Generic.IEnumerable EnumerateDirectories(string searchPattern, System.IO.EnumerationOptions enumerationOptions); + public abstract System.Collections.Generic.IEnumerable EnumerateDirectories(string searchPattern, System.IO.SearchOption searchOption); + public abstract System.Collections.Generic.IEnumerable EnumerateFileSystemInfos(); + public abstract System.Collections.Generic.IEnumerable EnumerateFileSystemInfos(string searchPattern); + public abstract System.Collections.Generic.IEnumerable EnumerateFileSystemInfos(string searchPattern, System.IO.EnumerationOptions enumerationOptions); + public abstract System.Collections.Generic.IEnumerable EnumerateFileSystemInfos(string searchPattern, System.IO.SearchOption searchOption); + public abstract System.Collections.Generic.IEnumerable EnumerateFiles(); + public abstract System.Collections.Generic.IEnumerable EnumerateFiles(string searchPattern); + public abstract System.Collections.Generic.IEnumerable EnumerateFiles(string searchPattern, System.IO.EnumerationOptions enumerationOptions); + public abstract System.Collections.Generic.IEnumerable EnumerateFiles(string searchPattern, System.IO.SearchOption searchOption); + public abstract System.IO.Abstractions.IDirectoryInfo[] GetDirectories(); + public abstract System.IO.Abstractions.IDirectoryInfo[] GetDirectories(string searchPattern); + public abstract System.IO.Abstractions.IDirectoryInfo[] GetDirectories(string searchPattern, System.IO.EnumerationOptions enumerationOptions); + public abstract System.IO.Abstractions.IDirectoryInfo[] GetDirectories(string searchPattern, System.IO.SearchOption searchOption); + public abstract System.IO.Abstractions.IFileSystemInfo[] GetFileSystemInfos(); + public abstract System.IO.Abstractions.IFileSystemInfo[] GetFileSystemInfos(string searchPattern); + public abstract System.IO.Abstractions.IFileSystemInfo[] GetFileSystemInfos(string searchPattern, System.IO.EnumerationOptions enumerationOptions); + public abstract System.IO.Abstractions.IFileSystemInfo[] GetFileSystemInfos(string searchPattern, System.IO.SearchOption searchOption); + public abstract System.IO.Abstractions.IFileInfo[] GetFiles(); + public abstract System.IO.Abstractions.IFileInfo[] GetFiles(string searchPattern); + public abstract System.IO.Abstractions.IFileInfo[] GetFiles(string searchPattern, System.IO.EnumerationOptions enumerationOptions); + public abstract System.IO.Abstractions.IFileInfo[] GetFiles(string searchPattern, System.IO.SearchOption searchOption); + public abstract void MoveTo(string destDirName); + public static System.IO.Abstractions.DirectoryInfoBase op_Implicit(System.IO.DirectoryInfo directoryInfo) { } + } + [System.Serializable] + public class DirectoryInfoWrapper : System.IO.Abstractions.DirectoryInfoBase, System.IO.Abstractions.IFileSystemAclSupport + { + public DirectoryInfoWrapper(System.IO.Abstractions.IFileSystem fileSystem, System.IO.DirectoryInfo instance) { } + public override System.IO.FileAttributes Attributes { get; set; } + public override System.DateTime CreationTime { get; set; } + public override System.DateTime CreationTimeUtc { get; set; } + public override bool Exists { get; } + public override string Extension { get; } + public override string FullName { get; } + public override System.DateTime LastAccessTime { get; set; } + public override System.DateTime LastAccessTimeUtc { get; set; } + public override System.DateTime LastWriteTime { get; set; } + public override System.DateTime LastWriteTimeUtc { get; set; } + public override string LinkTarget { get; } + public override string Name { get; } + public override System.IO.Abstractions.IDirectoryInfo Parent { get; } + public override System.IO.Abstractions.IDirectoryInfo Root { get; } + public override void Create() { } + public override void CreateAsSymbolicLink(string pathToTarget) { } + public override System.IO.Abstractions.IDirectoryInfo CreateSubdirectory(string path) { } + public override void Delete() { } + public override void Delete(bool recursive) { } + public override System.Collections.Generic.IEnumerable EnumerateDirectories() { } + public override System.Collections.Generic.IEnumerable EnumerateDirectories(string searchPattern) { } + public override System.Collections.Generic.IEnumerable EnumerateDirectories(string searchPattern, System.IO.EnumerationOptions enumerationOptions) { } + public override System.Collections.Generic.IEnumerable EnumerateDirectories(string searchPattern, System.IO.SearchOption searchOption) { } + public override System.Collections.Generic.IEnumerable EnumerateFileSystemInfos() { } + public override System.Collections.Generic.IEnumerable EnumerateFileSystemInfos(string searchPattern) { } + public override System.Collections.Generic.IEnumerable EnumerateFileSystemInfos(string searchPattern, System.IO.EnumerationOptions enumerationOptions) { } + public override System.Collections.Generic.IEnumerable EnumerateFileSystemInfos(string searchPattern, System.IO.SearchOption searchOption) { } + public override System.Collections.Generic.IEnumerable EnumerateFiles() { } + public override System.Collections.Generic.IEnumerable EnumerateFiles(string searchPattern) { } + public override System.Collections.Generic.IEnumerable EnumerateFiles(string searchPattern, System.IO.EnumerationOptions enumerationOptions) { } + public override System.Collections.Generic.IEnumerable EnumerateFiles(string searchPattern, System.IO.SearchOption searchOption) { } + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public object GetAccessControl() { } + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public object GetAccessControl(System.IO.Abstractions.IFileSystemAclSupport.AccessControlSections includeSections) { } + public override System.IO.Abstractions.IDirectoryInfo[] GetDirectories() { } + public override System.IO.Abstractions.IDirectoryInfo[] GetDirectories(string searchPattern) { } + public override System.IO.Abstractions.IDirectoryInfo[] GetDirectories(string searchPattern, System.IO.EnumerationOptions enumerationOptions) { } + public override System.IO.Abstractions.IDirectoryInfo[] GetDirectories(string searchPattern, System.IO.SearchOption searchOption) { } + public override System.IO.Abstractions.IFileSystemInfo[] GetFileSystemInfos() { } + public override System.IO.Abstractions.IFileSystemInfo[] GetFileSystemInfos(string searchPattern) { } + public override System.IO.Abstractions.IFileSystemInfo[] GetFileSystemInfos(string searchPattern, System.IO.EnumerationOptions enumerationOptions) { } + public override System.IO.Abstractions.IFileSystemInfo[] GetFileSystemInfos(string searchPattern, System.IO.SearchOption searchOption) { } + public override System.IO.Abstractions.IFileInfo[] GetFiles() { } + public override System.IO.Abstractions.IFileInfo[] GetFiles(string searchPattern) { } + public override System.IO.Abstractions.IFileInfo[] GetFiles(string searchPattern, System.IO.EnumerationOptions enumerationOptions) { } + public override System.IO.Abstractions.IFileInfo[] GetFiles(string searchPattern, System.IO.SearchOption searchOption) { } + public override void MoveTo(string destDirName) { } + public override void Refresh() { } + public override System.IO.Abstractions.IFileSystemInfo ResolveLinkTarget(bool returnFinalTarget) { } + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public void SetAccessControl(object value) { } + public override string ToString() { } + } + [System.Serializable] + public class DirectoryWrapper : System.IO.Abstractions.DirectoryBase + { + public DirectoryWrapper(System.IO.Abstractions.IFileSystem fileSystem) { } + public override System.IO.Abstractions.IDirectoryInfo CreateDirectory(string path) { } + [System.Runtime.Versioning.UnsupportedOSPlatform("windows")] + public override System.IO.Abstractions.IDirectoryInfo CreateDirectory(string path, System.IO.UnixFileMode unixCreateMode) { } + public override System.IO.Abstractions.IFileSystemInfo CreateSymbolicLink(string path, string pathToTarget) { } + public override System.IO.Abstractions.IDirectoryInfo CreateTempSubdirectory(string prefix = null) { } + public override void Delete(string path) { } + public override void Delete(string path, bool recursive) { } + public override System.Collections.Generic.IEnumerable EnumerateDirectories(string path) { } + public override System.Collections.Generic.IEnumerable EnumerateDirectories(string path, string searchPattern) { } + public override System.Collections.Generic.IEnumerable EnumerateDirectories(string path, string searchPattern, System.IO.EnumerationOptions enumerationOptions) { } + public override System.Collections.Generic.IEnumerable EnumerateDirectories(string path, string searchPattern, System.IO.SearchOption searchOption) { } + public override System.Collections.Generic.IEnumerable EnumerateFileSystemEntries(string path) { } + public override System.Collections.Generic.IEnumerable EnumerateFileSystemEntries(string path, string searchPattern) { } + public override System.Collections.Generic.IEnumerable EnumerateFileSystemEntries(string path, string searchPattern, System.IO.EnumerationOptions enumerationOptions) { } + public override System.Collections.Generic.IEnumerable EnumerateFileSystemEntries(string path, string searchPattern, System.IO.SearchOption searchOption) { } + public override System.Collections.Generic.IEnumerable EnumerateFiles(string path) { } + public override System.Collections.Generic.IEnumerable EnumerateFiles(string path, string searchPattern) { } + public override System.Collections.Generic.IEnumerable EnumerateFiles(string path, string searchPattern, System.IO.EnumerationOptions enumerationOptions) { } + public override System.Collections.Generic.IEnumerable EnumerateFiles(string path, string searchPattern, System.IO.SearchOption searchOption) { } + public override bool Exists(string path) { } + public override System.DateTime GetCreationTime(string path) { } + public override System.DateTime GetCreationTimeUtc(string path) { } + public override string GetCurrentDirectory() { } + public override string[] GetDirectories(string path) { } + public override string[] GetDirectories(string path, string searchPattern) { } + public override string[] GetDirectories(string path, string searchPattern, System.IO.EnumerationOptions enumerationOptions) { } + public override string[] GetDirectories(string path, string searchPattern, System.IO.SearchOption searchOption) { } + public override string GetDirectoryRoot(string path) { } + public override string[] GetFileSystemEntries(string path) { } + public override string[] GetFileSystemEntries(string path, string searchPattern) { } + public override string[] GetFileSystemEntries(string path, string searchPattern, System.IO.EnumerationOptions enumerationOptions) { } + public override string[] GetFileSystemEntries(string path, string searchPattern, System.IO.SearchOption searchOption) { } + public override string[] GetFiles(string path) { } + public override string[] GetFiles(string path, string searchPattern) { } + public override string[] GetFiles(string path, string searchPattern, System.IO.EnumerationOptions enumerationOptions) { } + public override string[] GetFiles(string path, string searchPattern, System.IO.SearchOption searchOption) { } + public override System.DateTime GetLastAccessTime(string path) { } + public override System.DateTime GetLastAccessTimeUtc(string path) { } + public override System.DateTime GetLastWriteTime(string path) { } + public override System.DateTime GetLastWriteTimeUtc(string path) { } + public override string[] GetLogicalDrives() { } + public override System.IO.Abstractions.IDirectoryInfo GetParent(string path) { } + public override void Move(string sourceDirName, string destDirName) { } + public override System.IO.Abstractions.IFileSystemInfo ResolveLinkTarget(string linkPath, bool returnFinalTarget) { } + public override void SetCreationTime(string path, System.DateTime creationTime) { } + public override void SetCreationTimeUtc(string path, System.DateTime creationTimeUtc) { } + public override void SetCurrentDirectory(string path) { } + public override void SetLastAccessTime(string path, System.DateTime lastAccessTime) { } + public override void SetLastAccessTimeUtc(string path, System.DateTime lastAccessTimeUtc) { } + public override void SetLastWriteTime(string path, System.DateTime lastWriteTime) { } + public override void SetLastWriteTimeUtc(string path, System.DateTime lastWriteTimeUtc) { } + } + [System.Serializable] + public abstract class DriveInfoBase : System.IO.Abstractions.IDriveInfo, System.IO.Abstractions.IFileSystemEntity + { + protected DriveInfoBase(System.IO.Abstractions.IFileSystem fileSystem) { } + public abstract long AvailableFreeSpace { get; } + public abstract string DriveFormat { get; } + public abstract System.IO.DriveType DriveType { get; } + public System.IO.Abstractions.IFileSystem FileSystem { get; } + public abstract bool IsReady { get; } + public abstract string Name { get; } + public abstract System.IO.Abstractions.IDirectoryInfo RootDirectory { get; } + public abstract long TotalFreeSpace { get; } + public abstract long TotalSize { get; } + public abstract string VolumeLabel { get; set; } + public static System.IO.Abstractions.DriveInfoBase op_Implicit(System.IO.DriveInfo driveInfo) { } + } + [System.Serializable] + public class DriveInfoWrapper : System.IO.Abstractions.DriveInfoBase + { + public DriveInfoWrapper(System.IO.Abstractions.IFileSystem fileSystem, System.IO.DriveInfo instance) { } + public override long AvailableFreeSpace { get; } + public override string DriveFormat { get; } + public override System.IO.DriveType DriveType { get; } + public override bool IsReady { get; } + public override string Name { get; } + public override System.IO.Abstractions.IDirectoryInfo RootDirectory { get; } + public override long TotalFreeSpace { get; } + public override long TotalSize { get; } + [set: System.Runtime.Versioning.SupportedOSPlatform("windows")] + public override string VolumeLabel { get; set; } + public override string ToString() { } + } + public static class FileAclExtensions + { + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public static System.Security.AccessControl.FileSecurity GetAccessControl(this System.IO.Abstractions.IFile file, string path) { } + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public static System.Security.AccessControl.FileSecurity GetAccessControl(this System.IO.Abstractions.IFile file, string path, System.Security.AccessControl.AccessControlSections includeSections) { } + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public static void SetAccessControl(this System.IO.Abstractions.IFile file, string path, System.Security.AccessControl.FileSecurity fileSecurity) { } + } + [System.Serializable] + public abstract class FileBase : System.IO.Abstractions.IFile, System.IO.Abstractions.IFileSystemEntity + { + protected FileBase(System.IO.Abstractions.IFileSystem fileSystem) { } + public System.IO.Abstractions.IFileSystem FileSystem { get; } + public abstract void AppendAllBytes(string path, System.ReadOnlySpan bytes); + public abstract void AppendAllBytes(string path, byte[] bytes); + public abstract System.Threading.Tasks.Task AppendAllBytesAsync(string path, System.ReadOnlyMemory bytes, System.Threading.CancellationToken cancellationToken = default); + public abstract System.Threading.Tasks.Task AppendAllBytesAsync(string path, byte[] bytes, System.Threading.CancellationToken cancellationToken = default); + public abstract void AppendAllLines(string path, System.Collections.Generic.IEnumerable contents); + public abstract void AppendAllLines(string path, System.Collections.Generic.IEnumerable contents, System.Text.Encoding encoding); + public abstract System.Threading.Tasks.Task AppendAllLinesAsync(string path, System.Collections.Generic.IEnumerable contents, System.Threading.CancellationToken cancellationToken = default); + public abstract System.Threading.Tasks.Task AppendAllLinesAsync(string path, System.Collections.Generic.IEnumerable contents, System.Text.Encoding encoding, System.Threading.CancellationToken cancellationToken = default); + public abstract void AppendAllText(string path, System.ReadOnlySpan contents); + public abstract void AppendAllText(string path, string contents); + public abstract void AppendAllText(string path, System.ReadOnlySpan contents, System.Text.Encoding encoding); + public abstract void AppendAllText(string path, string contents, System.Text.Encoding encoding); + public abstract System.Threading.Tasks.Task AppendAllTextAsync(string path, System.ReadOnlyMemory contents, System.Threading.CancellationToken cancellationToken = default); + public abstract System.Threading.Tasks.Task AppendAllTextAsync(string path, string contents, System.Threading.CancellationToken cancellationToken = default); + public abstract System.Threading.Tasks.Task AppendAllTextAsync(string path, System.ReadOnlyMemory contents, System.Text.Encoding encoding, System.Threading.CancellationToken cancellationToken = default); + public abstract System.Threading.Tasks.Task AppendAllTextAsync(string path, string contents, System.Text.Encoding encoding, System.Threading.CancellationToken cancellationToken = default); + public abstract System.IO.StreamWriter AppendText(string path); + public abstract void Copy(string sourceFileName, string destFileName); + public abstract void Copy(string sourceFileName, string destFileName, bool overwrite); + public abstract System.IO.Abstractions.FileSystemStream Create(string path); + public abstract System.IO.Abstractions.FileSystemStream Create(string path, int bufferSize); + public abstract System.IO.Abstractions.FileSystemStream Create(string path, int bufferSize, System.IO.FileOptions options); + public abstract System.IO.Abstractions.IFileSystemInfo CreateSymbolicLink(string path, string pathToTarget); + public abstract System.IO.StreamWriter CreateText(string path); + public abstract void Decrypt(string path); + public abstract void Delete(string path); + public abstract void Encrypt(string path); + public abstract bool Exists(string path); + public abstract System.IO.FileAttributes GetAttributes(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle); + public abstract System.IO.FileAttributes GetAttributes(string path); + public abstract System.DateTime GetCreationTime(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle); + public abstract System.DateTime GetCreationTime(string path); + public abstract System.DateTime GetCreationTimeUtc(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle); + public abstract System.DateTime GetCreationTimeUtc(string path); + public abstract System.DateTime GetLastAccessTime(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle); + public abstract System.DateTime GetLastAccessTime(string path); + public abstract System.DateTime GetLastAccessTimeUtc(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle); + public abstract System.DateTime GetLastAccessTimeUtc(string path); + public abstract System.DateTime GetLastWriteTime(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle); + public abstract System.DateTime GetLastWriteTime(string path); + public abstract System.DateTime GetLastWriteTimeUtc(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle); + public abstract System.DateTime GetLastWriteTimeUtc(string path); + public abstract System.IO.UnixFileMode GetUnixFileMode(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle); + public abstract System.IO.UnixFileMode GetUnixFileMode(string path); + public abstract void Move(string sourceFileName, string destFileName); + public abstract void Move(string sourceFileName, string destFileName, bool overwrite); + public abstract System.IO.Abstractions.FileSystemStream Open(string path, System.IO.FileMode mode); + public abstract System.IO.Abstractions.FileSystemStream Open(string path, System.IO.FileStreamOptions options); + public abstract System.IO.Abstractions.FileSystemStream Open(string path, System.IO.FileMode mode, System.IO.FileAccess access); + public abstract System.IO.Abstractions.FileSystemStream Open(string path, System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share); + public abstract System.IO.Abstractions.FileSystemStream OpenRead(string path); + public abstract System.IO.StreamReader OpenText(string path); + public abstract System.IO.Abstractions.FileSystemStream OpenWrite(string path); + public abstract byte[] ReadAllBytes(string path); + public abstract System.Threading.Tasks.Task ReadAllBytesAsync(string path, System.Threading.CancellationToken cancellationToken = default); + public abstract string[] ReadAllLines(string path); + public abstract string[] ReadAllLines(string path, System.Text.Encoding encoding); + public abstract System.Threading.Tasks.Task ReadAllLinesAsync(string path, System.Threading.CancellationToken cancellationToken = default); + public abstract System.Threading.Tasks.Task ReadAllLinesAsync(string path, System.Text.Encoding encoding, System.Threading.CancellationToken cancellationToken = default); + public abstract string ReadAllText(string path); + public abstract string ReadAllText(string path, System.Text.Encoding encoding); + public abstract System.Threading.Tasks.Task ReadAllTextAsync(string path, System.Threading.CancellationToken cancellationToken = default); + public abstract System.Threading.Tasks.Task ReadAllTextAsync(string path, System.Text.Encoding encoding, System.Threading.CancellationToken cancellationToken = default); + public abstract System.Collections.Generic.IEnumerable ReadLines(string path); + public abstract System.Collections.Generic.IEnumerable ReadLines(string path, System.Text.Encoding encoding); + public abstract System.Collections.Generic.IAsyncEnumerable ReadLinesAsync(string path, System.Threading.CancellationToken cancellationToken = default); + public abstract System.Collections.Generic.IAsyncEnumerable ReadLinesAsync(string path, System.Text.Encoding encoding, System.Threading.CancellationToken cancellationToken = default); + public abstract void Replace(string sourceFileName, string destinationFileName, string destinationBackupFileName); + public abstract void Replace(string sourceFileName, string destinationFileName, string destinationBackupFileName, bool ignoreMetadataErrors); + public abstract System.IO.Abstractions.IFileSystemInfo ResolveLinkTarget(string linkPath, bool returnFinalTarget); + public abstract void SetAttributes(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle, System.IO.FileAttributes fileAttributes); + public abstract void SetAttributes(string path, System.IO.FileAttributes fileAttributes); + public abstract void SetCreationTime(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle, System.DateTime creationTime); + public abstract void SetCreationTime(string path, System.DateTime creationTime); + public abstract void SetCreationTimeUtc(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle, System.DateTime creationTimeUtc); + public abstract void SetCreationTimeUtc(string path, System.DateTime creationTimeUtc); + public abstract void SetLastAccessTime(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle, System.DateTime lastAccessTime); + public abstract void SetLastAccessTime(string path, System.DateTime lastAccessTime); + public abstract void SetLastAccessTimeUtc(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle, System.DateTime lastAccessTimeUtc); + public abstract void SetLastAccessTimeUtc(string path, System.DateTime lastAccessTimeUtc); + public abstract void SetLastWriteTime(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle, System.DateTime lastWriteTime); + public abstract void SetLastWriteTime(string path, System.DateTime lastWriteTime); + public abstract void SetLastWriteTimeUtc(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle, System.DateTime lastWriteTimeUtc); + public abstract void SetLastWriteTimeUtc(string path, System.DateTime lastWriteTimeUtc); + public abstract void SetUnixFileMode(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle, System.IO.UnixFileMode mode); + public abstract void SetUnixFileMode(string path, System.IO.UnixFileMode mode); + public abstract void WriteAllBytes(string path, System.ReadOnlySpan bytes); + public abstract void WriteAllBytes(string path, byte[] bytes); + public abstract System.Threading.Tasks.Task WriteAllBytesAsync(string path, System.ReadOnlyMemory bytes, System.Threading.CancellationToken cancellationToken = default); + public abstract System.Threading.Tasks.Task WriteAllBytesAsync(string path, byte[] bytes, System.Threading.CancellationToken cancellationToken = default); + public abstract void WriteAllLines(string path, System.Collections.Generic.IEnumerable contents); + public abstract void WriteAllLines(string path, string[] contents); + public abstract void WriteAllLines(string path, System.Collections.Generic.IEnumerable contents, System.Text.Encoding encoding); + public abstract void WriteAllLines(string path, string[] contents, System.Text.Encoding encoding); + public abstract System.Threading.Tasks.Task WriteAllLinesAsync(string path, System.Collections.Generic.IEnumerable contents, System.Threading.CancellationToken cancellationToken = default); + public abstract System.Threading.Tasks.Task WriteAllLinesAsync(string path, System.Collections.Generic.IEnumerable contents, System.Text.Encoding encoding, System.Threading.CancellationToken cancellationToken = default); + public abstract void WriteAllText(string path, System.ReadOnlySpan contents); + public abstract void WriteAllText(string path, string contents); + public abstract void WriteAllText(string path, System.ReadOnlySpan contents, System.Text.Encoding encoding); + public abstract void WriteAllText(string path, string contents, System.Text.Encoding encoding); + public abstract System.Threading.Tasks.Task WriteAllTextAsync(string path, System.ReadOnlyMemory contents, System.Threading.CancellationToken cancellationToken = default); + public abstract System.Threading.Tasks.Task WriteAllTextAsync(string path, string contents, System.Threading.CancellationToken cancellationToken = default); + public abstract System.Threading.Tasks.Task WriteAllTextAsync(string path, System.ReadOnlyMemory contents, System.Text.Encoding encoding, System.Threading.CancellationToken cancellationToken = default); + public abstract System.Threading.Tasks.Task WriteAllTextAsync(string path, string contents, System.Text.Encoding encoding, System.Threading.CancellationToken cancellationToken = default); + } + public static class FileInfoAclExtensions + { + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public static System.Security.AccessControl.FileSecurity GetAccessControl(this System.IO.Abstractions.IFileInfo fileInfo) { } + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public static System.Security.AccessControl.FileSecurity GetAccessControl(this System.IO.Abstractions.IFileInfo fileInfo, System.Security.AccessControl.AccessControlSections includeSections) { } + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public static void SetAccessControl(this System.IO.Abstractions.IFileInfo fileInfo, System.Security.AccessControl.FileSecurity fileSecurity) { } + } + [System.Serializable] + public abstract class FileInfoBase : System.IO.Abstractions.FileSystemInfoBase, System.IO.Abstractions.IFileInfo, System.IO.Abstractions.IFileSystemInfo + { + protected FileInfoBase(System.IO.Abstractions.IFileSystem fileSystem) { } + public abstract System.IO.Abstractions.IDirectoryInfo Directory { get; } + public abstract string DirectoryName { get; } + public abstract bool IsReadOnly { get; set; } + public abstract long Length { get; } + public abstract System.IO.StreamWriter AppendText(); + public abstract System.IO.Abstractions.IFileInfo CopyTo(string destFileName); + public abstract System.IO.Abstractions.IFileInfo CopyTo(string destFileName, bool overwrite); + public abstract System.IO.Abstractions.FileSystemStream Create(); + public abstract System.IO.StreamWriter CreateText(); + public abstract void Decrypt(); + public abstract void Encrypt(); + public abstract void MoveTo(string destFileName); + public abstract void MoveTo(string destFileName, bool overwrite); + public abstract System.IO.Abstractions.FileSystemStream Open(System.IO.FileMode mode); + public abstract System.IO.Abstractions.FileSystemStream Open(System.IO.FileStreamOptions options); + public abstract System.IO.Abstractions.FileSystemStream Open(System.IO.FileMode mode, System.IO.FileAccess access); + public abstract System.IO.Abstractions.FileSystemStream Open(System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share); + public abstract System.IO.Abstractions.FileSystemStream OpenRead(); + public abstract System.IO.StreamReader OpenText(); + public abstract System.IO.Abstractions.FileSystemStream OpenWrite(); + public abstract System.IO.Abstractions.IFileInfo Replace(string destinationFileName, string destinationBackupFileName); + public abstract System.IO.Abstractions.IFileInfo Replace(string destinationFileName, string destinationBackupFileName, bool ignoreMetadataErrors); + public static System.IO.Abstractions.FileInfoBase op_Implicit(System.IO.FileInfo fileInfo) { } + } + [System.Serializable] + public class FileInfoWrapper : System.IO.Abstractions.FileInfoBase, System.IO.Abstractions.IFileSystemAclSupport + { + public FileInfoWrapper(System.IO.Abstractions.IFileSystem fileSystem, System.IO.FileInfo instance) { } + public override System.IO.FileAttributes Attributes { get; set; } + public override System.DateTime CreationTime { get; set; } + public override System.DateTime CreationTimeUtc { get; set; } + public override System.IO.Abstractions.IDirectoryInfo Directory { get; } + public override string DirectoryName { get; } + public override bool Exists { get; } + public override string Extension { get; } + public override string FullName { get; } + public override bool IsReadOnly { get; set; } + public override System.DateTime LastAccessTime { get; set; } + public override System.DateTime LastAccessTimeUtc { get; set; } + public override System.DateTime LastWriteTime { get; set; } + public override System.DateTime LastWriteTimeUtc { get; set; } + public override long Length { get; } + public override string LinkTarget { get; } + public override string Name { get; } + public override System.IO.StreamWriter AppendText() { } + public override System.IO.Abstractions.IFileInfo CopyTo(string destFileName) { } + public override System.IO.Abstractions.IFileInfo CopyTo(string destFileName, bool overwrite) { } + public override System.IO.Abstractions.FileSystemStream Create() { } + public override void CreateAsSymbolicLink(string pathToTarget) { } + public override System.IO.StreamWriter CreateText() { } + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public override void Decrypt() { } + public override void Delete() { } + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public override void Encrypt() { } + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public object GetAccessControl() { } + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public object GetAccessControl(System.IO.Abstractions.IFileSystemAclSupport.AccessControlSections includeSections) { } + public override void MoveTo(string destFileName) { } + public override void MoveTo(string destFileName, bool overwrite) { } + public override System.IO.Abstractions.FileSystemStream Open(System.IO.FileMode mode) { } + public override System.IO.Abstractions.FileSystemStream Open(System.IO.FileStreamOptions options) { } + public override System.IO.Abstractions.FileSystemStream Open(System.IO.FileMode mode, System.IO.FileAccess access) { } + public override System.IO.Abstractions.FileSystemStream Open(System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share) { } + public override System.IO.Abstractions.FileSystemStream OpenRead() { } + public override System.IO.StreamReader OpenText() { } + public override System.IO.Abstractions.FileSystemStream OpenWrite() { } + public override void Refresh() { } + public override System.IO.Abstractions.IFileInfo Replace(string destinationFileName, string destinationBackupFileName) { } + public override System.IO.Abstractions.IFileInfo Replace(string destinationFileName, string destinationBackupFileName, bool ignoreMetadataErrors) { } + public override System.IO.Abstractions.IFileSystemInfo ResolveLinkTarget(bool returnFinalTarget) { } + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public void SetAccessControl(object value) { } + public override string ToString() { } + } + public static class FileStreamAclExtensions + { + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public static System.Security.AccessControl.FileSecurity GetAccessControl(this System.IO.Abstractions.FileSystemStream fileStream) { } + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public static void SetAccessControl(this System.IO.Abstractions.FileSystemStream fileStream, System.Security.AccessControl.FileSecurity fileSecurity) { } + } + [System.Serializable] + public class FileSystem : System.IO.Abstractions.FileSystemBase + { + public FileSystem() { } + public override System.IO.Abstractions.IDirectory Directory { get; } + public override System.IO.Abstractions.IDirectoryInfoFactory DirectoryInfo { get; } + public override System.IO.Abstractions.IDriveInfoFactory DriveInfo { get; } + public override System.IO.Abstractions.IFile File { get; } + public override System.IO.Abstractions.IFileInfoFactory FileInfo { get; } + public override System.IO.Abstractions.IFileStreamFactory FileStream { get; } + public override System.IO.Abstractions.IFileSystemWatcherFactory FileSystemWatcher { get; } + public override System.IO.Abstractions.IFileVersionInfoFactory FileVersionInfo { get; } + public override System.IO.Abstractions.IPath Path { get; } + } + [System.Serializable] + public abstract class FileSystemBase : System.IO.Abstractions.IFileSystem + { + protected FileSystemBase() { } + public abstract System.IO.Abstractions.IDirectory Directory { get; } + public abstract System.IO.Abstractions.IDirectoryInfoFactory DirectoryInfo { get; } + public abstract System.IO.Abstractions.IDriveInfoFactory DriveInfo { get; } + public abstract System.IO.Abstractions.IFile File { get; } + public abstract System.IO.Abstractions.IFileInfoFactory FileInfo { get; } + public abstract System.IO.Abstractions.IFileStreamFactory FileStream { get; } + public abstract System.IO.Abstractions.IFileSystemWatcherFactory FileSystemWatcher { get; } + public abstract System.IO.Abstractions.IFileVersionInfoFactory FileVersionInfo { get; } + public abstract System.IO.Abstractions.IPath Path { get; } + } + [System.Serializable] + public abstract class FileSystemInfoBase : System.IO.Abstractions.IFileSystemInfo + { + protected FileSystemInfoBase(System.IO.Abstractions.IFileSystem fileSystem) { } + public abstract System.IO.FileAttributes Attributes { get; set; } + public abstract System.DateTime CreationTime { get; set; } + public abstract System.DateTime CreationTimeUtc { get; set; } + public abstract bool Exists { get; } + public abstract string Extension { get; } + public System.IO.Abstractions.IFileSystem FileSystem { get; } + public abstract string FullName { get; } + public abstract System.DateTime LastAccessTime { get; set; } + public abstract System.DateTime LastAccessTimeUtc { get; set; } + public abstract System.DateTime LastWriteTime { get; set; } + public abstract System.DateTime LastWriteTimeUtc { get; set; } + public abstract string LinkTarget { get; } + public abstract string Name { get; } + [set: System.Runtime.Versioning.UnsupportedOSPlatform("windows")] + public System.IO.UnixFileMode UnixFileMode { get; set; } + public abstract void CreateAsSymbolicLink(string pathToTarget); + public abstract void Delete(); + public abstract void Refresh(); + public abstract System.IO.Abstractions.IFileSystemInfo ResolveLinkTarget(bool returnFinalTarget); + } + [System.Serializable] + public abstract class FileSystemWatcherBase : System.IDisposable, System.IO.Abstractions.IFileSystemEntity, System.IO.Abstractions.IFileSystemWatcher + { + protected FileSystemWatcherBase() { } + public abstract System.ComponentModel.IContainer Container { get; } + public abstract bool EnableRaisingEvents { get; set; } + public abstract System.IO.Abstractions.IFileSystem FileSystem { get; } + public abstract string Filter { get; set; } + public abstract System.Collections.ObjectModel.Collection Filters { get; } + public abstract bool IncludeSubdirectories { get; set; } + public abstract int InternalBufferSize { get; set; } + public abstract System.IO.NotifyFilters NotifyFilter { get; set; } + public abstract string Path { get; set; } + public abstract System.ComponentModel.ISite Site { get; set; } + public abstract System.ComponentModel.ISynchronizeInvoke SynchronizingObject { get; set; } + public virtual event System.IO.FileSystemEventHandler Changed; + public virtual event System.IO.FileSystemEventHandler Created; + public virtual event System.IO.FileSystemEventHandler Deleted; + public virtual event System.IO.ErrorEventHandler Error; + public virtual event System.IO.RenamedEventHandler Renamed; + public abstract void BeginInit(); + public void Dispose() { } + public virtual void Dispose(bool disposing) { } + public abstract void EndInit(); + protected void OnChanged(object sender, System.IO.FileSystemEventArgs args) { } + protected void OnCreated(object sender, System.IO.FileSystemEventArgs args) { } + protected void OnDeleted(object sender, System.IO.FileSystemEventArgs args) { } + protected void OnError(object sender, System.IO.ErrorEventArgs args) { } + protected void OnRenamed(object sender, System.IO.RenamedEventArgs args) { } + public abstract System.IO.Abstractions.IWaitForChangedResult WaitForChanged(System.IO.WatcherChangeTypes changeType); + public abstract System.IO.Abstractions.IWaitForChangedResult WaitForChanged(System.IO.WatcherChangeTypes changeType, System.TimeSpan timeout); + public abstract System.IO.Abstractions.IWaitForChangedResult WaitForChanged(System.IO.WatcherChangeTypes changeType, int timeout); + public static System.IO.Abstractions.FileSystemWatcherBase op_Implicit(System.IO.FileSystemWatcher watcher) { } + } + [System.Serializable] + public class FileSystemWatcherFactory : System.IO.Abstractions.IFileSystemEntity, System.IO.Abstractions.IFileSystemWatcherFactory + { + public FileSystemWatcherFactory(System.IO.Abstractions.IFileSystem fileSystem) { } + public System.IO.Abstractions.IFileSystem FileSystem { get; } + public System.IO.Abstractions.IFileSystemWatcher New() { } + public System.IO.Abstractions.IFileSystemWatcher New(string path) { } + public System.IO.Abstractions.IFileSystemWatcher New(string path, string filter) { } + public System.IO.Abstractions.IFileSystemWatcher Wrap(System.IO.FileSystemWatcher fileSystemWatcher) { } + } + [System.Serializable] + public class FileSystemWatcherWrapper : System.IO.Abstractions.FileSystemWatcherBase + { + public FileSystemWatcherWrapper(System.IO.Abstractions.IFileSystem fileSystem) { } + public FileSystemWatcherWrapper(System.IO.Abstractions.IFileSystem fileSystem, System.IO.FileSystemWatcher watcher) { } + public FileSystemWatcherWrapper(System.IO.Abstractions.IFileSystem fileSystem, string path) { } + public FileSystemWatcherWrapper(System.IO.Abstractions.IFileSystem fileSystem, string path, string filter) { } + public override System.ComponentModel.IContainer Container { get; } + public override bool EnableRaisingEvents { get; set; } + public override System.IO.Abstractions.IFileSystem FileSystem { get; } + public override string Filter { get; set; } + public override System.Collections.ObjectModel.Collection Filters { get; } + public override bool IncludeSubdirectories { get; set; } + public override int InternalBufferSize { get; set; } + public override System.IO.NotifyFilters NotifyFilter { get; set; } + public override string Path { get; set; } + public override System.ComponentModel.ISite Site { get; set; } + public override System.ComponentModel.ISynchronizeInvoke SynchronizingObject { get; set; } + public override void BeginInit() { } + public override void Dispose(bool disposing) { } + public override void EndInit() { } + public override System.IO.Abstractions.IWaitForChangedResult WaitForChanged(System.IO.WatcherChangeTypes changeType) { } + public override System.IO.Abstractions.IWaitForChangedResult WaitForChanged(System.IO.WatcherChangeTypes changeType, System.TimeSpan timeout) { } + public override System.IO.Abstractions.IWaitForChangedResult WaitForChanged(System.IO.WatcherChangeTypes changeType, int timeout) { } + } + [System.Serializable] + public abstract class FileVersionInfoBase : System.IO.Abstractions.IFileVersionInfo + { + protected FileVersionInfoBase() { } + public abstract string Comments { get; } + public abstract string CompanyName { get; } + public abstract int FileBuildPart { get; } + public abstract string FileDescription { get; } + public abstract int FileMajorPart { get; } + public abstract int FileMinorPart { get; } + public abstract string FileName { get; } + public abstract int FilePrivatePart { get; } + public abstract string FileVersion { get; } + public abstract string InternalName { get; } + public abstract bool IsDebug { get; } + public abstract bool IsPatched { get; } + public abstract bool IsPreRelease { get; } + public abstract bool IsPrivateBuild { get; } + public abstract bool IsSpecialBuild { get; } + public abstract string Language { get; } + public abstract string LegalCopyright { get; } + public abstract string LegalTrademarks { get; } + public abstract string OriginalFilename { get; } + public abstract string PrivateBuild { get; } + public abstract int ProductBuildPart { get; } + public abstract int ProductMajorPart { get; } + public abstract int ProductMinorPart { get; } + public abstract string ProductName { get; } + public abstract int ProductPrivatePart { get; } + public abstract string ProductVersion { get; } + public abstract string SpecialBuild { get; } + public abstract string ToString(); + public static System.IO.Abstractions.FileVersionInfoBase op_Implicit(System.Diagnostics.FileVersionInfo fileVersionInfo) { } + } + [System.Serializable] + public class FileVersionInfoWrapper : System.IO.Abstractions.FileVersionInfoBase + { + public FileVersionInfoWrapper(System.Diagnostics.FileVersionInfo fileVersionInfo) { } + public override string Comments { get; } + public override string CompanyName { get; } + public override int FileBuildPart { get; } + public override string FileDescription { get; } + public override int FileMajorPart { get; } + public override int FileMinorPart { get; } + public override string FileName { get; } + public override int FilePrivatePart { get; } + public override string FileVersion { get; } + public override string InternalName { get; } + public override bool IsDebug { get; } + public override bool IsPatched { get; } + public override bool IsPreRelease { get; } + public override bool IsPrivateBuild { get; } + public override bool IsSpecialBuild { get; } + public override string Language { get; } + public override string LegalCopyright { get; } + public override string LegalTrademarks { get; } + public override string OriginalFilename { get; } + public override string PrivateBuild { get; } + public override int ProductBuildPart { get; } + public override int ProductMajorPart { get; } + public override int ProductMinorPart { get; } + public override string ProductName { get; } + public override int ProductPrivatePart { get; } + public override string ProductVersion { get; } + public override string SpecialBuild { get; } + public override string ToString() { } + } + [System.Serializable] + public class FileWrapper : System.IO.Abstractions.FileBase + { + public FileWrapper(System.IO.Abstractions.IFileSystem fileSystem) { } + public override void AppendAllBytes(string path, System.ReadOnlySpan bytes) { } + public override void AppendAllBytes(string path, byte[] bytes) { } + public override System.Threading.Tasks.Task AppendAllBytesAsync(string path, System.ReadOnlyMemory bytes, System.Threading.CancellationToken cancellationToken = default) { } + public override System.Threading.Tasks.Task AppendAllBytesAsync(string path, byte[] bytes, System.Threading.CancellationToken cancellationToken = default) { } + public override void AppendAllLines(string path, System.Collections.Generic.IEnumerable contents) { } + public override void AppendAllLines(string path, System.Collections.Generic.IEnumerable contents, System.Text.Encoding encoding) { } + public override System.Threading.Tasks.Task AppendAllLinesAsync(string path, System.Collections.Generic.IEnumerable contents, System.Threading.CancellationToken cancellationToken = default) { } + public override System.Threading.Tasks.Task AppendAllLinesAsync(string path, System.Collections.Generic.IEnumerable contents, System.Text.Encoding encoding, System.Threading.CancellationToken cancellationToken = default) { } + public override void AppendAllText(string path, System.ReadOnlySpan contents) { } + public override void AppendAllText(string path, string contents) { } + public override void AppendAllText(string path, System.ReadOnlySpan contents, System.Text.Encoding encoding) { } + public override void AppendAllText(string path, string contents, System.Text.Encoding encoding) { } + public override System.Threading.Tasks.Task AppendAllTextAsync(string path, System.ReadOnlyMemory contents, System.Threading.CancellationToken cancellationToken = default) { } + public override System.Threading.Tasks.Task AppendAllTextAsync(string path, string contents, System.Threading.CancellationToken cancellationToken = default) { } + public override System.Threading.Tasks.Task AppendAllTextAsync(string path, System.ReadOnlyMemory contents, System.Text.Encoding encoding, System.Threading.CancellationToken cancellationToken = default) { } + public override System.Threading.Tasks.Task AppendAllTextAsync(string path, string contents, System.Text.Encoding encoding, System.Threading.CancellationToken cancellationToken = default) { } + public override System.IO.StreamWriter AppendText(string path) { } + public override void Copy(string sourceFileName, string destFileName) { } + public override void Copy(string sourceFileName, string destFileName, bool overwrite) { } + public override System.IO.Abstractions.FileSystemStream Create(string path) { } + public override System.IO.Abstractions.FileSystemStream Create(string path, int bufferSize) { } + public override System.IO.Abstractions.FileSystemStream Create(string path, int bufferSize, System.IO.FileOptions options) { } + public override System.IO.Abstractions.IFileSystemInfo CreateSymbolicLink(string path, string pathToTarget) { } + public override System.IO.StreamWriter CreateText(string path) { } + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public override void Decrypt(string path) { } + public override void Delete(string path) { } + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public override void Encrypt(string path) { } + public override bool Exists(string path) { } + public override System.IO.FileAttributes GetAttributes(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle) { } + public override System.IO.FileAttributes GetAttributes(string path) { } + public override System.DateTime GetCreationTime(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle) { } + public override System.DateTime GetCreationTime(string path) { } + public override System.DateTime GetCreationTimeUtc(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle) { } + public override System.DateTime GetCreationTimeUtc(string path) { } + public override System.DateTime GetLastAccessTime(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle) { } + public override System.DateTime GetLastAccessTime(string path) { } + public override System.DateTime GetLastAccessTimeUtc(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle) { } + public override System.DateTime GetLastAccessTimeUtc(string path) { } + public override System.DateTime GetLastWriteTime(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle) { } + public override System.DateTime GetLastWriteTime(string path) { } + public override System.DateTime GetLastWriteTimeUtc(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle) { } + public override System.DateTime GetLastWriteTimeUtc(string path) { } + [System.Runtime.Versioning.UnsupportedOSPlatform("windows")] + public override System.IO.UnixFileMode GetUnixFileMode(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle) { } + [System.Runtime.Versioning.UnsupportedOSPlatform("windows")] + public override System.IO.UnixFileMode GetUnixFileMode(string path) { } + public override void Move(string sourceFileName, string destFileName) { } + public override void Move(string sourceFileName, string destFileName, bool overwrite) { } + public override System.IO.Abstractions.FileSystemStream Open(string path, System.IO.FileMode mode) { } + public override System.IO.Abstractions.FileSystemStream Open(string path, System.IO.FileStreamOptions options) { } + public override System.IO.Abstractions.FileSystemStream Open(string path, System.IO.FileMode mode, System.IO.FileAccess access) { } + public override System.IO.Abstractions.FileSystemStream Open(string path, System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share) { } + public override System.IO.Abstractions.FileSystemStream OpenRead(string path) { } + public override System.IO.StreamReader OpenText(string path) { } + public override System.IO.Abstractions.FileSystemStream OpenWrite(string path) { } + public override byte[] ReadAllBytes(string path) { } + public override System.Threading.Tasks.Task ReadAllBytesAsync(string path, System.Threading.CancellationToken cancellationToken = default) { } + public override string[] ReadAllLines(string path) { } + public override string[] ReadAllLines(string path, System.Text.Encoding encoding) { } + public override System.Threading.Tasks.Task ReadAllLinesAsync(string path, System.Threading.CancellationToken cancellationToken = default) { } + public override System.Threading.Tasks.Task ReadAllLinesAsync(string path, System.Text.Encoding encoding, System.Threading.CancellationToken cancellationToken = default) { } + public override string ReadAllText(string path) { } + public override string ReadAllText(string path, System.Text.Encoding encoding) { } + public override System.Threading.Tasks.Task ReadAllTextAsync(string path, System.Threading.CancellationToken cancellationToken = default) { } + public override System.Threading.Tasks.Task ReadAllTextAsync(string path, System.Text.Encoding encoding, System.Threading.CancellationToken cancellationToken = default) { } + public override System.Collections.Generic.IEnumerable ReadLines(string path) { } + public override System.Collections.Generic.IEnumerable ReadLines(string path, System.Text.Encoding encoding) { } + public override System.Collections.Generic.IAsyncEnumerable ReadLinesAsync(string path, System.Threading.CancellationToken cancellationToken = default) { } + public override System.Collections.Generic.IAsyncEnumerable ReadLinesAsync(string path, System.Text.Encoding encoding, System.Threading.CancellationToken cancellationToken = default) { } + public override void Replace(string sourceFileName, string destinationFileName, string destinationBackupFileName) { } + public override void Replace(string sourceFileName, string destinationFileName, string destinationBackupFileName, bool ignoreMetadataErrors) { } + public override System.IO.Abstractions.IFileSystemInfo ResolveLinkTarget(string linkPath, bool returnFinalTarget) { } + public override void SetAttributes(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle, System.IO.FileAttributes fileAttributes) { } + public override void SetAttributes(string path, System.IO.FileAttributes fileAttributes) { } + public override void SetCreationTime(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle, System.DateTime creationTime) { } + public override void SetCreationTime(string path, System.DateTime creationTime) { } + public override void SetCreationTimeUtc(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle, System.DateTime creationTimeUtc) { } + public override void SetCreationTimeUtc(string path, System.DateTime creationTimeUtc) { } + public override void SetLastAccessTime(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle, System.DateTime lastAccessTime) { } + public override void SetLastAccessTime(string path, System.DateTime lastAccessTime) { } + public override void SetLastAccessTimeUtc(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle, System.DateTime lastAccessTimeUtc) { } + public override void SetLastAccessTimeUtc(string path, System.DateTime lastAccessTimeUtc) { } + public override void SetLastWriteTime(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle, System.DateTime lastWriteTime) { } + public override void SetLastWriteTime(string path, System.DateTime lastWriteTime) { } + public override void SetLastWriteTimeUtc(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle, System.DateTime lastWriteTimeUtc) { } + public override void SetLastWriteTimeUtc(string path, System.DateTime lastWriteTimeUtc) { } + [System.Runtime.Versioning.UnsupportedOSPlatform("windows")] + public override void SetUnixFileMode(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle, System.IO.UnixFileMode mode) { } + [System.Runtime.Versioning.UnsupportedOSPlatform("windows")] + public override void SetUnixFileMode(string path, System.IO.UnixFileMode mode) { } + public override void WriteAllBytes(string path, System.ReadOnlySpan bytes) { } + public override void WriteAllBytes(string path, byte[] bytes) { } + public override System.Threading.Tasks.Task WriteAllBytesAsync(string path, System.ReadOnlyMemory bytes, System.Threading.CancellationToken cancellationToken = default) { } + public override System.Threading.Tasks.Task WriteAllBytesAsync(string path, byte[] bytes, System.Threading.CancellationToken cancellationToken = default) { } + public override void WriteAllLines(string path, System.Collections.Generic.IEnumerable contents) { } + public override void WriteAllLines(string path, string[] contents) { } + public override void WriteAllLines(string path, System.Collections.Generic.IEnumerable contents, System.Text.Encoding encoding) { } + public override void WriteAllLines(string path, string[] contents, System.Text.Encoding encoding) { } + public override System.Threading.Tasks.Task WriteAllLinesAsync(string path, System.Collections.Generic.IEnumerable contents, System.Threading.CancellationToken cancellationToken = default) { } + public override System.Threading.Tasks.Task WriteAllLinesAsync(string path, System.Collections.Generic.IEnumerable contents, System.Text.Encoding encoding, System.Threading.CancellationToken cancellationToken = default) { } + public override void WriteAllText(string path, System.ReadOnlySpan contents) { } + public override void WriteAllText(string path, string contents) { } + public override void WriteAllText(string path, System.ReadOnlySpan contents, System.Text.Encoding encoding) { } + public override void WriteAllText(string path, string contents, System.Text.Encoding encoding) { } + public override System.Threading.Tasks.Task WriteAllTextAsync(string path, System.ReadOnlyMemory contents, System.Threading.CancellationToken cancellationToken = default) { } + public override System.Threading.Tasks.Task WriteAllTextAsync(string path, string contents, System.Threading.CancellationToken cancellationToken = default) { } + public override System.Threading.Tasks.Task WriteAllTextAsync(string path, System.ReadOnlyMemory contents, System.Text.Encoding encoding, System.Threading.CancellationToken cancellationToken = default) { } + public override System.Threading.Tasks.Task WriteAllTextAsync(string path, string contents, System.Text.Encoding encoding, System.Threading.CancellationToken cancellationToken = default) { } + } + [System.Serializable] + public abstract class PathBase : System.IO.Abstractions.IFileSystemEntity, System.IO.Abstractions.IPath + { + protected PathBase(System.IO.Abstractions.IFileSystem fileSystem) { } + public abstract char AltDirectorySeparatorChar { get; } + public abstract char DirectorySeparatorChar { get; } + public System.IO.Abstractions.IFileSystem FileSystem { get; } + [System.Obsolete("Please use GetInvalidPathChars or GetInvalidFileNameChars instead.")] + public abstract char[] InvalidPathChars { get; } + public abstract char PathSeparator { get; } + public abstract char VolumeSeparatorChar { get; } + public abstract string ChangeExtension(string path, string extension); + public abstract string Combine([System.Runtime.CompilerServices.ScopedRef] System.ReadOnlySpan paths); + public abstract string Combine(params string[] paths); + public abstract string Combine(string path1, string path2); + public abstract string Combine(string path1, string path2, string path3); + public abstract string Combine(string path1, string path2, string path3, string path4); + public abstract bool EndsInDirectorySeparator(System.ReadOnlySpan path); + public abstract bool EndsInDirectorySeparator(string path); + public abstract bool Exists(string path); + public abstract System.ReadOnlySpan GetDirectoryName(System.ReadOnlySpan path); + public abstract string GetDirectoryName(string path); + public abstract System.ReadOnlySpan GetExtension(System.ReadOnlySpan path); + public abstract string GetExtension(string path); + public abstract System.ReadOnlySpan GetFileName(System.ReadOnlySpan path); + public abstract string GetFileName(string path); + public abstract System.ReadOnlySpan GetFileNameWithoutExtension(System.ReadOnlySpan path); + public abstract string GetFileNameWithoutExtension(string path); + public abstract string GetFullPath(string path); + public abstract string GetFullPath(string path, string basePath); + public abstract char[] GetInvalidFileNameChars(); + public abstract char[] GetInvalidPathChars(); + public abstract System.ReadOnlySpan GetPathRoot(System.ReadOnlySpan path); + public abstract string GetPathRoot(string path); + public abstract string GetRandomFileName(); + public abstract string GetRelativePath(string relativeTo, string path); + public abstract string GetTempFileName(); + public abstract string GetTempPath(); + public abstract bool HasExtension(System.ReadOnlySpan path); + public abstract bool HasExtension(string path); + public abstract bool IsPathFullyQualified(System.ReadOnlySpan path); + public abstract bool IsPathFullyQualified(string path); + public abstract bool IsPathRooted(System.ReadOnlySpan path); + public abstract bool IsPathRooted(string path); + public abstract string Join([System.Runtime.CompilerServices.ScopedRef] System.ReadOnlySpan paths); + public abstract string Join(params string[] paths); + public abstract string Join(System.ReadOnlySpan path1, System.ReadOnlySpan path2); + public abstract string Join(string path1, string path2); + public abstract string Join(System.ReadOnlySpan path1, System.ReadOnlySpan path2, System.ReadOnlySpan path3); + public abstract string Join(string path1, string path2, string path3); + public abstract string Join(System.ReadOnlySpan path1, System.ReadOnlySpan path2, System.ReadOnlySpan path3, System.ReadOnlySpan path4); + public abstract string Join(string path1, string path2, string path3, string path4); + public abstract System.ReadOnlySpan TrimEndingDirectorySeparator(System.ReadOnlySpan path); + public abstract string TrimEndingDirectorySeparator(string path); + public abstract bool TryJoin(System.ReadOnlySpan path1, System.ReadOnlySpan path2, System.Span destination, out int charsWritten); + public abstract bool TryJoin(System.ReadOnlySpan path1, System.ReadOnlySpan path2, System.ReadOnlySpan path3, System.Span destination, out int charsWritten); + } + [System.Serializable] + public class PathWrapper : System.IO.Abstractions.PathBase + { + public PathWrapper(System.IO.Abstractions.IFileSystem fileSystem) { } + public override char AltDirectorySeparatorChar { get; } + public override char DirectorySeparatorChar { get; } + [System.Obsolete("Please use GetInvalidPathChars or GetInvalidFileNameChars instead.")] + public override char[] InvalidPathChars { get; } + public override char PathSeparator { get; } + public override char VolumeSeparatorChar { get; } + public override string ChangeExtension(string path, string extension) { } + public override string Combine([System.Runtime.CompilerServices.ScopedRef] System.ReadOnlySpan paths) { } + public override string Combine(params string[] paths) { } + public override string Combine(string path1, string path2) { } + public override string Combine(string path1, string path2, string path3) { } + public override string Combine(string path1, string path2, string path3, string path4) { } + public override bool EndsInDirectorySeparator(System.ReadOnlySpan path) { } + public override bool EndsInDirectorySeparator(string path) { } + public override bool Exists(string path) { } + public override System.ReadOnlySpan GetDirectoryName(System.ReadOnlySpan path) { } + public override string GetDirectoryName(string path) { } + public override System.ReadOnlySpan GetExtension(System.ReadOnlySpan path) { } + public override string GetExtension(string path) { } + public override System.ReadOnlySpan GetFileName(System.ReadOnlySpan path) { } + public override string GetFileName(string path) { } + public override System.ReadOnlySpan GetFileNameWithoutExtension(System.ReadOnlySpan path) { } + public override string GetFileNameWithoutExtension(string path) { } + public override string GetFullPath(string path) { } + public override string GetFullPath(string path, string basePath) { } + public override char[] GetInvalidFileNameChars() { } + public override char[] GetInvalidPathChars() { } + public override System.ReadOnlySpan GetPathRoot(System.ReadOnlySpan path) { } + public override string GetPathRoot(string path) { } + public override string GetRandomFileName() { } + public override string GetRelativePath(string relativeTo, string path) { } + public override string GetTempFileName() { } + public override string GetTempPath() { } + public override bool HasExtension(System.ReadOnlySpan path) { } + public override bool HasExtension(string path) { } + public override bool IsPathFullyQualified(System.ReadOnlySpan path) { } + public override bool IsPathFullyQualified(string path) { } + public override bool IsPathRooted(System.ReadOnlySpan path) { } + public override bool IsPathRooted(string path) { } + public override string Join([System.Runtime.CompilerServices.ScopedRef] System.ReadOnlySpan paths) { } + public override string Join(params string[] paths) { } + public override string Join(System.ReadOnlySpan path1, System.ReadOnlySpan path2) { } + public override string Join(string path1, string path2) { } + public override string Join(System.ReadOnlySpan path1, System.ReadOnlySpan path2, System.ReadOnlySpan path3) { } + public override string Join(string path1, string path2, string path3) { } + public override string Join(System.ReadOnlySpan path1, System.ReadOnlySpan path2, System.ReadOnlySpan path3, System.ReadOnlySpan path4) { } + public override string Join(string path1, string path2, string path3, string path4) { } + public override System.ReadOnlySpan TrimEndingDirectorySeparator(System.ReadOnlySpan path) { } + public override string TrimEndingDirectorySeparator(string path) { } + public override bool TryJoin(System.ReadOnlySpan path1, System.ReadOnlySpan path2, System.Span destination, out int charsWritten) { } + public override bool TryJoin(System.ReadOnlySpan path1, System.ReadOnlySpan path2, System.ReadOnlySpan path3, System.Span destination, out int charsWritten) { } + } +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.Api.Tests/Expected/TestableIO.System.IO.Abstractions.Wrappers_netstandard2.0.txt b/tests/TestableIO.System.IO.Abstractions.Api.Tests/Expected/TestableIO.System.IO.Abstractions.Wrappers_netstandard2.0.txt new file mode 100644 index 000000000..41cc10bbe --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.Api.Tests/Expected/TestableIO.System.IO.Abstractions.Wrappers_netstandard2.0.txt @@ -0,0 +1,657 @@ +[assembly: System.CLSCompliant(true)] +[assembly: System.Reflection.AssemblyMetadata("RepositoryUrl", "https://github.com/TestableIO/System.IO.Abstractions.git")] +[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(@"DynamicProxyGenAssembly2, PublicKey=0024000004800000940000000602000000240000525341310004000001000100c547cac37abd99c8db225ef2f6c8a3602f3b3606cc9891605d02baa56104f4cfc0734aa39b93bf7852f7d9266654753cc297e7d2edfe0bac1cdcf9f717241550e0a7b191195b7667bb4f64bcb8e2121380fd1d9d46ad2d92d2d15605093924cceaf74c4861eff62abf69b9291ed0a340e113be11e6a7d3113e92484cf7045cc7")] +[assembly: System.Runtime.Versioning.TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName=".NET Standard 2.0")] +namespace System.IO.Abstractions +{ + public static class DirectoryAclExtensions + { + public static void CreateDirectory(this System.IO.Abstractions.IDirectory directory, string path, System.Security.AccessControl.DirectorySecurity directorySecurity) { } + public static System.Security.AccessControl.DirectorySecurity GetAccessControl(this System.IO.Abstractions.IDirectory directory, string path) { } + public static System.Security.AccessControl.DirectorySecurity GetAccessControl(this System.IO.Abstractions.IDirectory directory, string path, System.Security.AccessControl.AccessControlSections includeSections) { } + public static void SetAccessControl(this System.IO.Abstractions.IDirectory directory, string path, System.Security.AccessControl.DirectorySecurity directorySecurity) { } + } + [System.Serializable] + public abstract class DirectoryBase : System.IO.Abstractions.IDirectory, System.IO.Abstractions.IFileSystemEntity + { + protected DirectoryBase(System.IO.Abstractions.IFileSystem fileSystem) { } + public System.IO.Abstractions.IFileSystem FileSystem { get; } + public abstract System.IO.Abstractions.IDirectoryInfo CreateDirectory(string path); + public abstract void Delete(string path); + public abstract void Delete(string path, bool recursive); + public abstract System.Collections.Generic.IEnumerable EnumerateDirectories(string path); + public abstract System.Collections.Generic.IEnumerable EnumerateDirectories(string path, string searchPattern); + public abstract System.Collections.Generic.IEnumerable EnumerateDirectories(string path, string searchPattern, System.IO.SearchOption searchOption); + public abstract System.Collections.Generic.IEnumerable EnumerateFileSystemEntries(string path); + public abstract System.Collections.Generic.IEnumerable EnumerateFileSystemEntries(string path, string searchPattern); + public abstract System.Collections.Generic.IEnumerable EnumerateFileSystemEntries(string path, string searchPattern, System.IO.SearchOption searchOption); + public abstract System.Collections.Generic.IEnumerable EnumerateFiles(string path); + public abstract System.Collections.Generic.IEnumerable EnumerateFiles(string path, string searchPattern); + public abstract System.Collections.Generic.IEnumerable EnumerateFiles(string path, string searchPattern, System.IO.SearchOption searchOption); + public abstract bool Exists(string path); + public abstract System.DateTime GetCreationTime(string path); + public abstract System.DateTime GetCreationTimeUtc(string path); + public abstract string GetCurrentDirectory(); + public abstract string[] GetDirectories(string path); + public abstract string[] GetDirectories(string path, string searchPattern); + public abstract string[] GetDirectories(string path, string searchPattern, System.IO.SearchOption searchOption); + public abstract string GetDirectoryRoot(string path); + public abstract string[] GetFileSystemEntries(string path); + public abstract string[] GetFileSystemEntries(string path, string searchPattern); + public abstract string[] GetFileSystemEntries(string path, string searchPattern, System.IO.SearchOption searchOption); + public abstract string[] GetFiles(string path); + public abstract string[] GetFiles(string path, string searchPattern); + public abstract string[] GetFiles(string path, string searchPattern, System.IO.SearchOption searchOption); + public abstract System.DateTime GetLastAccessTime(string path); + public abstract System.DateTime GetLastAccessTimeUtc(string path); + public abstract System.DateTime GetLastWriteTime(string path); + public abstract System.DateTime GetLastWriteTimeUtc(string path); + public abstract string[] GetLogicalDrives(); + public abstract System.IO.Abstractions.IDirectoryInfo GetParent(string path); + public abstract void Move(string sourceDirName, string destDirName); + public abstract void SetCreationTime(string path, System.DateTime creationTime); + public abstract void SetCreationTimeUtc(string path, System.DateTime creationTimeUtc); + public abstract void SetCurrentDirectory(string path); + public abstract void SetLastAccessTime(string path, System.DateTime lastAccessTime); + public abstract void SetLastAccessTimeUtc(string path, System.DateTime lastAccessTimeUtc); + public abstract void SetLastWriteTime(string path, System.DateTime lastWriteTime); + public abstract void SetLastWriteTimeUtc(string path, System.DateTime lastWriteTimeUtc); + } + public static class DirectoryInfoAclExtensions + { + public static void Create(this System.IO.Abstractions.IDirectoryInfo directoryInfo, System.Security.AccessControl.DirectorySecurity directorySecurity) { } + public static System.Security.AccessControl.DirectorySecurity GetAccessControl(this System.IO.Abstractions.IDirectoryInfo directoryInfo) { } + public static System.Security.AccessControl.DirectorySecurity GetAccessControl(this System.IO.Abstractions.IDirectoryInfo directoryInfo, System.Security.AccessControl.AccessControlSections includeSections) { } + public static void SetAccessControl(this System.IO.Abstractions.IDirectoryInfo directoryInfo, System.Security.AccessControl.DirectorySecurity directorySecurity) { } + } + [System.Serializable] + public abstract class DirectoryInfoBase : System.IO.Abstractions.FileSystemInfoBase, System.IO.Abstractions.IDirectoryInfo, System.IO.Abstractions.IFileSystemInfo + { + protected DirectoryInfoBase(System.IO.Abstractions.IFileSystem fileSystem) { } + public abstract System.IO.Abstractions.IDirectoryInfo Parent { get; } + public abstract System.IO.Abstractions.IDirectoryInfo Root { get; } + public abstract void Create(); + public abstract System.IO.Abstractions.IDirectoryInfo CreateSubdirectory(string path); + public abstract void Delete(bool recursive); + public abstract System.Collections.Generic.IEnumerable EnumerateDirectories(); + public abstract System.Collections.Generic.IEnumerable EnumerateDirectories(string searchPattern); + public abstract System.Collections.Generic.IEnumerable EnumerateDirectories(string searchPattern, System.IO.SearchOption searchOption); + public abstract System.Collections.Generic.IEnumerable EnumerateFileSystemInfos(); + public abstract System.Collections.Generic.IEnumerable EnumerateFileSystemInfos(string searchPattern); + public abstract System.Collections.Generic.IEnumerable EnumerateFileSystemInfos(string searchPattern, System.IO.SearchOption searchOption); + public abstract System.Collections.Generic.IEnumerable EnumerateFiles(); + public abstract System.Collections.Generic.IEnumerable EnumerateFiles(string searchPattern); + public abstract System.Collections.Generic.IEnumerable EnumerateFiles(string searchPattern, System.IO.SearchOption searchOption); + public abstract System.IO.Abstractions.IDirectoryInfo[] GetDirectories(); + public abstract System.IO.Abstractions.IDirectoryInfo[] GetDirectories(string searchPattern); + public abstract System.IO.Abstractions.IDirectoryInfo[] GetDirectories(string searchPattern, System.IO.SearchOption searchOption); + public abstract System.IO.Abstractions.IFileSystemInfo[] GetFileSystemInfos(); + public abstract System.IO.Abstractions.IFileSystemInfo[] GetFileSystemInfos(string searchPattern); + public abstract System.IO.Abstractions.IFileSystemInfo[] GetFileSystemInfos(string searchPattern, System.IO.SearchOption searchOption); + public abstract System.IO.Abstractions.IFileInfo[] GetFiles(); + public abstract System.IO.Abstractions.IFileInfo[] GetFiles(string searchPattern); + public abstract System.IO.Abstractions.IFileInfo[] GetFiles(string searchPattern, System.IO.SearchOption searchOption); + public abstract void MoveTo(string destDirName); + public static System.IO.Abstractions.DirectoryInfoBase op_Implicit(System.IO.DirectoryInfo directoryInfo) { } + } + [System.Serializable] + public class DirectoryInfoWrapper : System.IO.Abstractions.DirectoryInfoBase, System.IO.Abstractions.IFileSystemAclSupport + { + public DirectoryInfoWrapper(System.IO.Abstractions.IFileSystem fileSystem, System.IO.DirectoryInfo instance) { } + public override System.IO.FileAttributes Attributes { get; set; } + public override System.DateTime CreationTime { get; set; } + public override System.DateTime CreationTimeUtc { get; set; } + public override bool Exists { get; } + public override string Extension { get; } + public override string FullName { get; } + public override System.DateTime LastAccessTime { get; set; } + public override System.DateTime LastAccessTimeUtc { get; set; } + public override System.DateTime LastWriteTime { get; set; } + public override System.DateTime LastWriteTimeUtc { get; set; } + public override string Name { get; } + public override System.IO.Abstractions.IDirectoryInfo Parent { get; } + public override System.IO.Abstractions.IDirectoryInfo Root { get; } + public override void Create() { } + public override System.IO.Abstractions.IDirectoryInfo CreateSubdirectory(string path) { } + public override void Delete() { } + public override void Delete(bool recursive) { } + public override System.Collections.Generic.IEnumerable EnumerateDirectories() { } + public override System.Collections.Generic.IEnumerable EnumerateDirectories(string searchPattern) { } + public override System.Collections.Generic.IEnumerable EnumerateDirectories(string searchPattern, System.IO.SearchOption searchOption) { } + public override System.Collections.Generic.IEnumerable EnumerateFileSystemInfos() { } + public override System.Collections.Generic.IEnumerable EnumerateFileSystemInfos(string searchPattern) { } + public override System.Collections.Generic.IEnumerable EnumerateFileSystemInfos(string searchPattern, System.IO.SearchOption searchOption) { } + public override System.Collections.Generic.IEnumerable EnumerateFiles() { } + public override System.Collections.Generic.IEnumerable EnumerateFiles(string searchPattern) { } + public override System.Collections.Generic.IEnumerable EnumerateFiles(string searchPattern, System.IO.SearchOption searchOption) { } + public object GetAccessControl() { } + public object GetAccessControl(System.IO.Abstractions.IFileSystemAclSupport.AccessControlSections includeSections) { } + public override System.IO.Abstractions.IDirectoryInfo[] GetDirectories() { } + public override System.IO.Abstractions.IDirectoryInfo[] GetDirectories(string searchPattern) { } + public override System.IO.Abstractions.IDirectoryInfo[] GetDirectories(string searchPattern, System.IO.SearchOption searchOption) { } + public override System.IO.Abstractions.IFileSystemInfo[] GetFileSystemInfos() { } + public override System.IO.Abstractions.IFileSystemInfo[] GetFileSystemInfos(string searchPattern) { } + public override System.IO.Abstractions.IFileSystemInfo[] GetFileSystemInfos(string searchPattern, System.IO.SearchOption searchOption) { } + public override System.IO.Abstractions.IFileInfo[] GetFiles() { } + public override System.IO.Abstractions.IFileInfo[] GetFiles(string searchPattern) { } + public override System.IO.Abstractions.IFileInfo[] GetFiles(string searchPattern, System.IO.SearchOption searchOption) { } + public override void MoveTo(string destDirName) { } + public override void Refresh() { } + public void SetAccessControl(object value) { } + public override string ToString() { } + } + [System.Serializable] + public class DirectoryWrapper : System.IO.Abstractions.DirectoryBase + { + public DirectoryWrapper(System.IO.Abstractions.IFileSystem fileSystem) { } + public override System.IO.Abstractions.IDirectoryInfo CreateDirectory(string path) { } + public override void Delete(string path) { } + public override void Delete(string path, bool recursive) { } + public override System.Collections.Generic.IEnumerable EnumerateDirectories(string path) { } + public override System.Collections.Generic.IEnumerable EnumerateDirectories(string path, string searchPattern) { } + public override System.Collections.Generic.IEnumerable EnumerateDirectories(string path, string searchPattern, System.IO.SearchOption searchOption) { } + public override System.Collections.Generic.IEnumerable EnumerateFileSystemEntries(string path) { } + public override System.Collections.Generic.IEnumerable EnumerateFileSystemEntries(string path, string searchPattern) { } + public override System.Collections.Generic.IEnumerable EnumerateFileSystemEntries(string path, string searchPattern, System.IO.SearchOption searchOption) { } + public override System.Collections.Generic.IEnumerable EnumerateFiles(string path) { } + public override System.Collections.Generic.IEnumerable EnumerateFiles(string path, string searchPattern) { } + public override System.Collections.Generic.IEnumerable EnumerateFiles(string path, string searchPattern, System.IO.SearchOption searchOption) { } + public override bool Exists(string path) { } + public override System.DateTime GetCreationTime(string path) { } + public override System.DateTime GetCreationTimeUtc(string path) { } + public override string GetCurrentDirectory() { } + public override string[] GetDirectories(string path) { } + public override string[] GetDirectories(string path, string searchPattern) { } + public override string[] GetDirectories(string path, string searchPattern, System.IO.SearchOption searchOption) { } + public override string GetDirectoryRoot(string path) { } + public override string[] GetFileSystemEntries(string path) { } + public override string[] GetFileSystemEntries(string path, string searchPattern) { } + public override string[] GetFileSystemEntries(string path, string searchPattern, System.IO.SearchOption searchOption) { } + public override string[] GetFiles(string path) { } + public override string[] GetFiles(string path, string searchPattern) { } + public override string[] GetFiles(string path, string searchPattern, System.IO.SearchOption searchOption) { } + public override System.DateTime GetLastAccessTime(string path) { } + public override System.DateTime GetLastAccessTimeUtc(string path) { } + public override System.DateTime GetLastWriteTime(string path) { } + public override System.DateTime GetLastWriteTimeUtc(string path) { } + public override string[] GetLogicalDrives() { } + public override System.IO.Abstractions.IDirectoryInfo GetParent(string path) { } + public override void Move(string sourceDirName, string destDirName) { } + public override void SetCreationTime(string path, System.DateTime creationTime) { } + public override void SetCreationTimeUtc(string path, System.DateTime creationTimeUtc) { } + public override void SetCurrentDirectory(string path) { } + public override void SetLastAccessTime(string path, System.DateTime lastAccessTime) { } + public override void SetLastAccessTimeUtc(string path, System.DateTime lastAccessTimeUtc) { } + public override void SetLastWriteTime(string path, System.DateTime lastWriteTime) { } + public override void SetLastWriteTimeUtc(string path, System.DateTime lastWriteTimeUtc) { } + } + [System.Serializable] + public abstract class DriveInfoBase : System.IO.Abstractions.IDriveInfo, System.IO.Abstractions.IFileSystemEntity + { + protected DriveInfoBase(System.IO.Abstractions.IFileSystem fileSystem) { } + public abstract long AvailableFreeSpace { get; } + public abstract string DriveFormat { get; } + public abstract System.IO.DriveType DriveType { get; } + public System.IO.Abstractions.IFileSystem FileSystem { get; } + public abstract bool IsReady { get; } + public abstract string Name { get; } + public abstract System.IO.Abstractions.IDirectoryInfo RootDirectory { get; } + public abstract long TotalFreeSpace { get; } + public abstract long TotalSize { get; } + public abstract string VolumeLabel { get; set; } + public static System.IO.Abstractions.DriveInfoBase op_Implicit(System.IO.DriveInfo driveInfo) { } + } + [System.Serializable] + public class DriveInfoWrapper : System.IO.Abstractions.DriveInfoBase + { + public DriveInfoWrapper(System.IO.Abstractions.IFileSystem fileSystem, System.IO.DriveInfo instance) { } + public override long AvailableFreeSpace { get; } + public override string DriveFormat { get; } + public override System.IO.DriveType DriveType { get; } + public override bool IsReady { get; } + public override string Name { get; } + public override System.IO.Abstractions.IDirectoryInfo RootDirectory { get; } + public override long TotalFreeSpace { get; } + public override long TotalSize { get; } + public override string VolumeLabel { get; set; } + public override string ToString() { } + } + public static class FileAclExtensions + { + public static System.Security.AccessControl.FileSecurity GetAccessControl(this System.IO.Abstractions.IFile file, string path) { } + public static System.Security.AccessControl.FileSecurity GetAccessControl(this System.IO.Abstractions.IFile file, string path, System.Security.AccessControl.AccessControlSections includeSections) { } + public static void SetAccessControl(this System.IO.Abstractions.IFile file, string path, System.Security.AccessControl.FileSecurity fileSecurity) { } + } + [System.Serializable] + public abstract class FileBase : System.IO.Abstractions.IFile, System.IO.Abstractions.IFileSystemEntity + { + protected FileBase(System.IO.Abstractions.IFileSystem fileSystem) { } + public System.IO.Abstractions.IFileSystem FileSystem { get; } + public abstract void AppendAllLines(string path, System.Collections.Generic.IEnumerable contents); + public abstract void AppendAllLines(string path, System.Collections.Generic.IEnumerable contents, System.Text.Encoding encoding); + public abstract void AppendAllText(string path, string contents); + public abstract void AppendAllText(string path, string contents, System.Text.Encoding encoding); + public abstract System.IO.StreamWriter AppendText(string path); + public abstract void Copy(string sourceFileName, string destFileName); + public abstract void Copy(string sourceFileName, string destFileName, bool overwrite); + public abstract System.IO.Abstractions.FileSystemStream Create(string path); + public abstract System.IO.Abstractions.FileSystemStream Create(string path, int bufferSize); + public abstract System.IO.Abstractions.FileSystemStream Create(string path, int bufferSize, System.IO.FileOptions options); + public abstract System.IO.StreamWriter CreateText(string path); + public abstract void Decrypt(string path); + public abstract void Delete(string path); + public abstract void Encrypt(string path); + public abstract bool Exists(string path); + public abstract System.IO.FileAttributes GetAttributes(string path); + public abstract System.DateTime GetCreationTime(string path); + public abstract System.DateTime GetCreationTimeUtc(string path); + public abstract System.DateTime GetLastAccessTime(string path); + public abstract System.DateTime GetLastAccessTimeUtc(string path); + public abstract System.DateTime GetLastWriteTime(string path); + public abstract System.DateTime GetLastWriteTimeUtc(string path); + public abstract void Move(string sourceFileName, string destFileName); + public abstract System.IO.Abstractions.FileSystemStream Open(string path, System.IO.FileMode mode); + public abstract System.IO.Abstractions.FileSystemStream Open(string path, System.IO.FileMode mode, System.IO.FileAccess access); + public abstract System.IO.Abstractions.FileSystemStream Open(string path, System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share); + public abstract System.IO.Abstractions.FileSystemStream OpenRead(string path); + public abstract System.IO.StreamReader OpenText(string path); + public abstract System.IO.Abstractions.FileSystemStream OpenWrite(string path); + public abstract byte[] ReadAllBytes(string path); + public abstract string[] ReadAllLines(string path); + public abstract string[] ReadAllLines(string path, System.Text.Encoding encoding); + public abstract string ReadAllText(string path); + public abstract string ReadAllText(string path, System.Text.Encoding encoding); + public abstract System.Collections.Generic.IEnumerable ReadLines(string path); + public abstract System.Collections.Generic.IEnumerable ReadLines(string path, System.Text.Encoding encoding); + public abstract void Replace(string sourceFileName, string destinationFileName, string destinationBackupFileName); + public abstract void Replace(string sourceFileName, string destinationFileName, string destinationBackupFileName, bool ignoreMetadataErrors); + public abstract void SetAttributes(string path, System.IO.FileAttributes fileAttributes); + public abstract void SetCreationTime(string path, System.DateTime creationTime); + public abstract void SetCreationTimeUtc(string path, System.DateTime creationTimeUtc); + public abstract void SetLastAccessTime(string path, System.DateTime lastAccessTime); + public abstract void SetLastAccessTimeUtc(string path, System.DateTime lastAccessTimeUtc); + public abstract void SetLastWriteTime(string path, System.DateTime lastWriteTime); + public abstract void SetLastWriteTimeUtc(string path, System.DateTime lastWriteTimeUtc); + public abstract void WriteAllBytes(string path, byte[] bytes); + public abstract void WriteAllLines(string path, System.Collections.Generic.IEnumerable contents); + public abstract void WriteAllLines(string path, string[] contents); + public abstract void WriteAllLines(string path, System.Collections.Generic.IEnumerable contents, System.Text.Encoding encoding); + public abstract void WriteAllLines(string path, string[] contents, System.Text.Encoding encoding); + public abstract void WriteAllText(string path, string contents); + public abstract void WriteAllText(string path, string contents, System.Text.Encoding encoding); + } + public static class FileInfoAclExtensions + { + public static System.Security.AccessControl.FileSecurity GetAccessControl(this System.IO.Abstractions.IFileInfo fileInfo) { } + public static System.Security.AccessControl.FileSecurity GetAccessControl(this System.IO.Abstractions.IFileInfo fileInfo, System.Security.AccessControl.AccessControlSections includeSections) { } + public static void SetAccessControl(this System.IO.Abstractions.IFileInfo fileInfo, System.Security.AccessControl.FileSecurity fileSecurity) { } + } + [System.Serializable] + public abstract class FileInfoBase : System.IO.Abstractions.FileSystemInfoBase, System.IO.Abstractions.IFileInfo, System.IO.Abstractions.IFileSystemInfo + { + protected FileInfoBase(System.IO.Abstractions.IFileSystem fileSystem) { } + public abstract System.IO.Abstractions.IDirectoryInfo Directory { get; } + public abstract string DirectoryName { get; } + public abstract bool IsReadOnly { get; set; } + public abstract long Length { get; } + public abstract System.IO.StreamWriter AppendText(); + public abstract System.IO.Abstractions.IFileInfo CopyTo(string destFileName); + public abstract System.IO.Abstractions.IFileInfo CopyTo(string destFileName, bool overwrite); + public abstract System.IO.Abstractions.FileSystemStream Create(); + public abstract System.IO.StreamWriter CreateText(); + public abstract void Decrypt(); + public abstract void Encrypt(); + public abstract void MoveTo(string destFileName); + public abstract System.IO.Abstractions.FileSystemStream Open(System.IO.FileMode mode); + public abstract System.IO.Abstractions.FileSystemStream Open(System.IO.FileMode mode, System.IO.FileAccess access); + public abstract System.IO.Abstractions.FileSystemStream Open(System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share); + public abstract System.IO.Abstractions.FileSystemStream OpenRead(); + public abstract System.IO.StreamReader OpenText(); + public abstract System.IO.Abstractions.FileSystemStream OpenWrite(); + public abstract System.IO.Abstractions.IFileInfo Replace(string destinationFileName, string destinationBackupFileName); + public abstract System.IO.Abstractions.IFileInfo Replace(string destinationFileName, string destinationBackupFileName, bool ignoreMetadataErrors); + public static System.IO.Abstractions.FileInfoBase op_Implicit(System.IO.FileInfo fileInfo) { } + } + [System.Serializable] + public class FileInfoWrapper : System.IO.Abstractions.FileInfoBase, System.IO.Abstractions.IFileSystemAclSupport + { + public FileInfoWrapper(System.IO.Abstractions.IFileSystem fileSystem, System.IO.FileInfo instance) { } + public override System.IO.FileAttributes Attributes { get; set; } + public override System.DateTime CreationTime { get; set; } + public override System.DateTime CreationTimeUtc { get; set; } + public override System.IO.Abstractions.IDirectoryInfo Directory { get; } + public override string DirectoryName { get; } + public override bool Exists { get; } + public override string Extension { get; } + public override string FullName { get; } + public override bool IsReadOnly { get; set; } + public override System.DateTime LastAccessTime { get; set; } + public override System.DateTime LastAccessTimeUtc { get; set; } + public override System.DateTime LastWriteTime { get; set; } + public override System.DateTime LastWriteTimeUtc { get; set; } + public override long Length { get; } + public override string Name { get; } + public override System.IO.StreamWriter AppendText() { } + public override System.IO.Abstractions.IFileInfo CopyTo(string destFileName) { } + public override System.IO.Abstractions.IFileInfo CopyTo(string destFileName, bool overwrite) { } + public override System.IO.Abstractions.FileSystemStream Create() { } + public override System.IO.StreamWriter CreateText() { } + public override void Decrypt() { } + public override void Delete() { } + public override void Encrypt() { } + public object GetAccessControl() { } + public object GetAccessControl(System.IO.Abstractions.IFileSystemAclSupport.AccessControlSections includeSections) { } + public override void MoveTo(string destFileName) { } + public override System.IO.Abstractions.FileSystemStream Open(System.IO.FileMode mode) { } + public override System.IO.Abstractions.FileSystemStream Open(System.IO.FileMode mode, System.IO.FileAccess access) { } + public override System.IO.Abstractions.FileSystemStream Open(System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share) { } + public override System.IO.Abstractions.FileSystemStream OpenRead() { } + public override System.IO.StreamReader OpenText() { } + public override System.IO.Abstractions.FileSystemStream OpenWrite() { } + public override void Refresh() { } + public override System.IO.Abstractions.IFileInfo Replace(string destinationFileName, string destinationBackupFileName) { } + public override System.IO.Abstractions.IFileInfo Replace(string destinationFileName, string destinationBackupFileName, bool ignoreMetadataErrors) { } + public void SetAccessControl(object value) { } + public override string ToString() { } + } + public static class FileStreamAclExtensions + { + public static System.Security.AccessControl.FileSecurity GetAccessControl(this System.IO.Abstractions.FileSystemStream fileStream) { } + public static void SetAccessControl(this System.IO.Abstractions.FileSystemStream fileStream, System.Security.AccessControl.FileSecurity fileSecurity) { } + } + [System.Serializable] + public class FileSystem : System.IO.Abstractions.FileSystemBase + { + public FileSystem() { } + public override System.IO.Abstractions.IDirectory Directory { get; } + public override System.IO.Abstractions.IDirectoryInfoFactory DirectoryInfo { get; } + public override System.IO.Abstractions.IDriveInfoFactory DriveInfo { get; } + public override System.IO.Abstractions.IFile File { get; } + public override System.IO.Abstractions.IFileInfoFactory FileInfo { get; } + public override System.IO.Abstractions.IFileStreamFactory FileStream { get; } + public override System.IO.Abstractions.IFileSystemWatcherFactory FileSystemWatcher { get; } + public override System.IO.Abstractions.IFileVersionInfoFactory FileVersionInfo { get; } + public override System.IO.Abstractions.IPath Path { get; } + } + [System.Serializable] + public abstract class FileSystemBase : System.IO.Abstractions.IFileSystem + { + protected FileSystemBase() { } + public abstract System.IO.Abstractions.IDirectory Directory { get; } + public abstract System.IO.Abstractions.IDirectoryInfoFactory DirectoryInfo { get; } + public abstract System.IO.Abstractions.IDriveInfoFactory DriveInfo { get; } + public abstract System.IO.Abstractions.IFile File { get; } + public abstract System.IO.Abstractions.IFileInfoFactory FileInfo { get; } + public abstract System.IO.Abstractions.IFileStreamFactory FileStream { get; } + public abstract System.IO.Abstractions.IFileSystemWatcherFactory FileSystemWatcher { get; } + public abstract System.IO.Abstractions.IFileVersionInfoFactory FileVersionInfo { get; } + public abstract System.IO.Abstractions.IPath Path { get; } + } + [System.Serializable] + public abstract class FileSystemInfoBase : System.IO.Abstractions.IFileSystemInfo + { + protected FileSystemInfoBase(System.IO.Abstractions.IFileSystem fileSystem) { } + public abstract System.IO.FileAttributes Attributes { get; set; } + public abstract System.DateTime CreationTime { get; set; } + public abstract System.DateTime CreationTimeUtc { get; set; } + public abstract bool Exists { get; } + public abstract string Extension { get; } + public System.IO.Abstractions.IFileSystem FileSystem { get; } + public abstract string FullName { get; } + public abstract System.DateTime LastAccessTime { get; set; } + public abstract System.DateTime LastAccessTimeUtc { get; set; } + public abstract System.DateTime LastWriteTime { get; set; } + public abstract System.DateTime LastWriteTimeUtc { get; set; } + public abstract string Name { get; } + public abstract void Delete(); + public abstract void Refresh(); + } + [System.Serializable] + public abstract class FileSystemWatcherBase : System.IDisposable, System.IO.Abstractions.IFileSystemEntity, System.IO.Abstractions.IFileSystemWatcher + { + protected FileSystemWatcherBase() { } + public abstract System.ComponentModel.IContainer Container { get; } + public abstract bool EnableRaisingEvents { get; set; } + public abstract System.IO.Abstractions.IFileSystem FileSystem { get; } + public abstract string Filter { get; set; } + public abstract bool IncludeSubdirectories { get; set; } + public abstract int InternalBufferSize { get; set; } + public abstract System.IO.NotifyFilters NotifyFilter { get; set; } + public abstract string Path { get; set; } + public abstract System.ComponentModel.ISite Site { get; set; } + public abstract System.ComponentModel.ISynchronizeInvoke SynchronizingObject { get; set; } + public virtual event System.IO.FileSystemEventHandler Changed; + public virtual event System.IO.FileSystemEventHandler Created; + public virtual event System.IO.FileSystemEventHandler Deleted; + public virtual event System.IO.ErrorEventHandler Error; + public virtual event System.IO.RenamedEventHandler Renamed; + public abstract void BeginInit(); + public void Dispose() { } + public virtual void Dispose(bool disposing) { } + public abstract void EndInit(); + protected void OnChanged(object sender, System.IO.FileSystemEventArgs args) { } + protected void OnCreated(object sender, System.IO.FileSystemEventArgs args) { } + protected void OnDeleted(object sender, System.IO.FileSystemEventArgs args) { } + protected void OnError(object sender, System.IO.ErrorEventArgs args) { } + protected void OnRenamed(object sender, System.IO.RenamedEventArgs args) { } + public abstract System.IO.Abstractions.IWaitForChangedResult WaitForChanged(System.IO.WatcherChangeTypes changeType); + public abstract System.IO.Abstractions.IWaitForChangedResult WaitForChanged(System.IO.WatcherChangeTypes changeType, int timeout); + public static System.IO.Abstractions.FileSystemWatcherBase op_Implicit(System.IO.FileSystemWatcher watcher) { } + } + [System.Serializable] + public class FileSystemWatcherFactory : System.IO.Abstractions.IFileSystemEntity, System.IO.Abstractions.IFileSystemWatcherFactory + { + public FileSystemWatcherFactory(System.IO.Abstractions.IFileSystem fileSystem) { } + public System.IO.Abstractions.IFileSystem FileSystem { get; } + public System.IO.Abstractions.IFileSystemWatcher New() { } + public System.IO.Abstractions.IFileSystemWatcher New(string path) { } + public System.IO.Abstractions.IFileSystemWatcher New(string path, string filter) { } + public System.IO.Abstractions.IFileSystemWatcher Wrap(System.IO.FileSystemWatcher fileSystemWatcher) { } + } + [System.Serializable] + public class FileSystemWatcherWrapper : System.IO.Abstractions.FileSystemWatcherBase + { + public FileSystemWatcherWrapper(System.IO.Abstractions.IFileSystem fileSystem) { } + public FileSystemWatcherWrapper(System.IO.Abstractions.IFileSystem fileSystem, System.IO.FileSystemWatcher watcher) { } + public FileSystemWatcherWrapper(System.IO.Abstractions.IFileSystem fileSystem, string path) { } + public FileSystemWatcherWrapper(System.IO.Abstractions.IFileSystem fileSystem, string path, string filter) { } + public override System.ComponentModel.IContainer Container { get; } + public override bool EnableRaisingEvents { get; set; } + public override System.IO.Abstractions.IFileSystem FileSystem { get; } + public override string Filter { get; set; } + public override bool IncludeSubdirectories { get; set; } + public override int InternalBufferSize { get; set; } + public override System.IO.NotifyFilters NotifyFilter { get; set; } + public override string Path { get; set; } + public override System.ComponentModel.ISite Site { get; set; } + public override System.ComponentModel.ISynchronizeInvoke SynchronizingObject { get; set; } + public override void BeginInit() { } + public override void Dispose(bool disposing) { } + public override void EndInit() { } + public override System.IO.Abstractions.IWaitForChangedResult WaitForChanged(System.IO.WatcherChangeTypes changeType) { } + public override System.IO.Abstractions.IWaitForChangedResult WaitForChanged(System.IO.WatcherChangeTypes changeType, int timeout) { } + } + [System.Serializable] + public abstract class FileVersionInfoBase : System.IO.Abstractions.IFileVersionInfo + { + protected FileVersionInfoBase() { } + public abstract string Comments { get; } + public abstract string CompanyName { get; } + public abstract int FileBuildPart { get; } + public abstract string FileDescription { get; } + public abstract int FileMajorPart { get; } + public abstract int FileMinorPart { get; } + public abstract string FileName { get; } + public abstract int FilePrivatePart { get; } + public abstract string FileVersion { get; } + public abstract string InternalName { get; } + public abstract bool IsDebug { get; } + public abstract bool IsPatched { get; } + public abstract bool IsPreRelease { get; } + public abstract bool IsPrivateBuild { get; } + public abstract bool IsSpecialBuild { get; } + public abstract string Language { get; } + public abstract string LegalCopyright { get; } + public abstract string LegalTrademarks { get; } + public abstract string OriginalFilename { get; } + public abstract string PrivateBuild { get; } + public abstract int ProductBuildPart { get; } + public abstract int ProductMajorPart { get; } + public abstract int ProductMinorPart { get; } + public abstract string ProductName { get; } + public abstract int ProductPrivatePart { get; } + public abstract string ProductVersion { get; } + public abstract string SpecialBuild { get; } + public abstract string ToString(); + public static System.IO.Abstractions.FileVersionInfoBase op_Implicit(System.Diagnostics.FileVersionInfo fileVersionInfo) { } + } + [System.Serializable] + public class FileVersionInfoWrapper : System.IO.Abstractions.FileVersionInfoBase + { + public FileVersionInfoWrapper(System.Diagnostics.FileVersionInfo fileVersionInfo) { } + public override string Comments { get; } + public override string CompanyName { get; } + public override int FileBuildPart { get; } + public override string FileDescription { get; } + public override int FileMajorPart { get; } + public override int FileMinorPart { get; } + public override string FileName { get; } + public override int FilePrivatePart { get; } + public override string FileVersion { get; } + public override string InternalName { get; } + public override bool IsDebug { get; } + public override bool IsPatched { get; } + public override bool IsPreRelease { get; } + public override bool IsPrivateBuild { get; } + public override bool IsSpecialBuild { get; } + public override string Language { get; } + public override string LegalCopyright { get; } + public override string LegalTrademarks { get; } + public override string OriginalFilename { get; } + public override string PrivateBuild { get; } + public override int ProductBuildPart { get; } + public override int ProductMajorPart { get; } + public override int ProductMinorPart { get; } + public override string ProductName { get; } + public override int ProductPrivatePart { get; } + public override string ProductVersion { get; } + public override string SpecialBuild { get; } + public override string ToString() { } + } + [System.Serializable] + public class FileWrapper : System.IO.Abstractions.FileBase + { + public FileWrapper(System.IO.Abstractions.IFileSystem fileSystem) { } + public override void AppendAllLines(string path, System.Collections.Generic.IEnumerable contents) { } + public override void AppendAllLines(string path, System.Collections.Generic.IEnumerable contents, System.Text.Encoding encoding) { } + public override void AppendAllText(string path, string contents) { } + public override void AppendAllText(string path, string contents, System.Text.Encoding encoding) { } + public override System.IO.StreamWriter AppendText(string path) { } + public override void Copy(string sourceFileName, string destFileName) { } + public override void Copy(string sourceFileName, string destFileName, bool overwrite) { } + public override System.IO.Abstractions.FileSystemStream Create(string path) { } + public override System.IO.Abstractions.FileSystemStream Create(string path, int bufferSize) { } + public override System.IO.Abstractions.FileSystemStream Create(string path, int bufferSize, System.IO.FileOptions options) { } + public override System.IO.StreamWriter CreateText(string path) { } + public override void Decrypt(string path) { } + public override void Delete(string path) { } + public override void Encrypt(string path) { } + public override bool Exists(string path) { } + public override System.IO.FileAttributes GetAttributes(string path) { } + public override System.DateTime GetCreationTime(string path) { } + public override System.DateTime GetCreationTimeUtc(string path) { } + public override System.DateTime GetLastAccessTime(string path) { } + public override System.DateTime GetLastAccessTimeUtc(string path) { } + public override System.DateTime GetLastWriteTime(string path) { } + public override System.DateTime GetLastWriteTimeUtc(string path) { } + public override void Move(string sourceFileName, string destFileName) { } + public override System.IO.Abstractions.FileSystemStream Open(string path, System.IO.FileMode mode) { } + public override System.IO.Abstractions.FileSystemStream Open(string path, System.IO.FileMode mode, System.IO.FileAccess access) { } + public override System.IO.Abstractions.FileSystemStream Open(string path, System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share) { } + public override System.IO.Abstractions.FileSystemStream OpenRead(string path) { } + public override System.IO.StreamReader OpenText(string path) { } + public override System.IO.Abstractions.FileSystemStream OpenWrite(string path) { } + public override byte[] ReadAllBytes(string path) { } + public override string[] ReadAllLines(string path) { } + public override string[] ReadAllLines(string path, System.Text.Encoding encoding) { } + public override string ReadAllText(string path) { } + public override string ReadAllText(string path, System.Text.Encoding encoding) { } + public override System.Collections.Generic.IEnumerable ReadLines(string path) { } + public override System.Collections.Generic.IEnumerable ReadLines(string path, System.Text.Encoding encoding) { } + public override void Replace(string sourceFileName, string destinationFileName, string destinationBackupFileName) { } + public override void Replace(string sourceFileName, string destinationFileName, string destinationBackupFileName, bool ignoreMetadataErrors) { } + public override void SetAttributes(string path, System.IO.FileAttributes fileAttributes) { } + public override void SetCreationTime(string path, System.DateTime creationTime) { } + public override void SetCreationTimeUtc(string path, System.DateTime creationTimeUtc) { } + public override void SetLastAccessTime(string path, System.DateTime lastAccessTime) { } + public override void SetLastAccessTimeUtc(string path, System.DateTime lastAccessTimeUtc) { } + public override void SetLastWriteTime(string path, System.DateTime lastWriteTime) { } + public override void SetLastWriteTimeUtc(string path, System.DateTime lastWriteTimeUtc) { } + public override void WriteAllBytes(string path, byte[] bytes) { } + public override void WriteAllLines(string path, System.Collections.Generic.IEnumerable contents) { } + public override void WriteAllLines(string path, string[] contents) { } + public override void WriteAllLines(string path, System.Collections.Generic.IEnumerable contents, System.Text.Encoding encoding) { } + public override void WriteAllLines(string path, string[] contents, System.Text.Encoding encoding) { } + public override void WriteAllText(string path, string contents) { } + public override void WriteAllText(string path, string contents, System.Text.Encoding encoding) { } + } + [System.Serializable] + public abstract class PathBase : System.IO.Abstractions.IFileSystemEntity, System.IO.Abstractions.IPath + { + protected PathBase(System.IO.Abstractions.IFileSystem fileSystem) { } + public abstract char AltDirectorySeparatorChar { get; } + public abstract char DirectorySeparatorChar { get; } + public System.IO.Abstractions.IFileSystem FileSystem { get; } + [System.Obsolete("Please use GetInvalidPathChars or GetInvalidFileNameChars instead.")] + public abstract char[] InvalidPathChars { get; } + public abstract char PathSeparator { get; } + public abstract char VolumeSeparatorChar { get; } + public abstract string ChangeExtension(string path, string extension); + public abstract string Combine(params string[] paths); + public abstract string Combine(string path1, string path2); + public abstract string Combine(string path1, string path2, string path3); + public abstract string Combine(string path1, string path2, string path3, string path4); + public abstract string GetDirectoryName(string path); + public abstract string GetExtension(string path); + public abstract string GetFileName(string path); + public abstract string GetFileNameWithoutExtension(string path); + public abstract string GetFullPath(string path); + public abstract char[] GetInvalidFileNameChars(); + public abstract char[] GetInvalidPathChars(); + public abstract string GetPathRoot(string path); + public abstract string GetRandomFileName(); + public abstract string GetTempFileName(); + public abstract string GetTempPath(); + public abstract bool HasExtension(string path); + public abstract bool IsPathRooted(string path); + } + [System.Serializable] + public class PathWrapper : System.IO.Abstractions.PathBase + { + public PathWrapper(System.IO.Abstractions.IFileSystem fileSystem) { } + public override char AltDirectorySeparatorChar { get; } + public override char DirectorySeparatorChar { get; } + [System.Obsolete("Please use GetInvalidPathChars or GetInvalidFileNameChars instead.")] + public override char[] InvalidPathChars { get; } + public override char PathSeparator { get; } + public override char VolumeSeparatorChar { get; } + public override string ChangeExtension(string path, string extension) { } + public override string Combine(params string[] paths) { } + public override string Combine(string path1, string path2) { } + public override string Combine(string path1, string path2, string path3) { } + public override string Combine(string path1, string path2, string path3, string path4) { } + public override string GetDirectoryName(string path) { } + public override string GetExtension(string path) { } + public override string GetFileName(string path) { } + public override string GetFileNameWithoutExtension(string path) { } + public override string GetFullPath(string path) { } + public override char[] GetInvalidFileNameChars() { } + public override char[] GetInvalidPathChars() { } + public override string GetPathRoot(string path) { } + public override string GetRandomFileName() { } + public override string GetTempFileName() { } + public override string GetTempPath() { } + public override bool HasExtension(string path) { } + public override bool IsPathRooted(string path) { } + } +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.Api.Tests/Expected/TestableIO.System.IO.Abstractions.Wrappers_netstandard2.1.txt b/tests/TestableIO.System.IO.Abstractions.Api.Tests/Expected/TestableIO.System.IO.Abstractions.Wrappers_netstandard2.1.txt new file mode 100644 index 000000000..a159f9c70 --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.Api.Tests/Expected/TestableIO.System.IO.Abstractions.Wrappers_netstandard2.1.txt @@ -0,0 +1,739 @@ +[assembly: System.CLSCompliant(true)] +[assembly: System.Reflection.AssemblyMetadata("RepositoryUrl", "https://github.com/TestableIO/System.IO.Abstractions.git")] +[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(@"DynamicProxyGenAssembly2, PublicKey=0024000004800000940000000602000000240000525341310004000001000100c547cac37abd99c8db225ef2f6c8a3602f3b3606cc9891605d02baa56104f4cfc0734aa39b93bf7852f7d9266654753cc297e7d2edfe0bac1cdcf9f717241550e0a7b191195b7667bb4f64bcb8e2121380fd1d9d46ad2d92d2d15605093924cceaf74c4861eff62abf69b9291ed0a340e113be11e6a7d3113e92484cf7045cc7")] +[assembly: System.Runtime.Versioning.TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName=".NET Standard 2.1")] +namespace System.IO.Abstractions +{ + public static class DirectoryAclExtensions + { + public static void CreateDirectory(this System.IO.Abstractions.IDirectory directory, string path, System.Security.AccessControl.DirectorySecurity directorySecurity) { } + public static System.Security.AccessControl.DirectorySecurity GetAccessControl(this System.IO.Abstractions.IDirectory directory, string path) { } + public static System.Security.AccessControl.DirectorySecurity GetAccessControl(this System.IO.Abstractions.IDirectory directory, string path, System.Security.AccessControl.AccessControlSections includeSections) { } + public static void SetAccessControl(this System.IO.Abstractions.IDirectory directory, string path, System.Security.AccessControl.DirectorySecurity directorySecurity) { } + } + [System.Serializable] + public abstract class DirectoryBase : System.IO.Abstractions.IDirectory, System.IO.Abstractions.IFileSystemEntity + { + protected DirectoryBase(System.IO.Abstractions.IFileSystem fileSystem) { } + public System.IO.Abstractions.IFileSystem FileSystem { get; } + public abstract System.IO.Abstractions.IDirectoryInfo CreateDirectory(string path); + public abstract void Delete(string path); + public abstract void Delete(string path, bool recursive); + public abstract System.Collections.Generic.IEnumerable EnumerateDirectories(string path); + public abstract System.Collections.Generic.IEnumerable EnumerateDirectories(string path, string searchPattern); + public abstract System.Collections.Generic.IEnumerable EnumerateDirectories(string path, string searchPattern, System.IO.EnumerationOptions enumerationOptions); + public abstract System.Collections.Generic.IEnumerable EnumerateDirectories(string path, string searchPattern, System.IO.SearchOption searchOption); + public abstract System.Collections.Generic.IEnumerable EnumerateFileSystemEntries(string path); + public abstract System.Collections.Generic.IEnumerable EnumerateFileSystemEntries(string path, string searchPattern); + public abstract System.Collections.Generic.IEnumerable EnumerateFileSystemEntries(string path, string searchPattern, System.IO.EnumerationOptions enumerationOptions); + public abstract System.Collections.Generic.IEnumerable EnumerateFileSystemEntries(string path, string searchPattern, System.IO.SearchOption searchOption); + public abstract System.Collections.Generic.IEnumerable EnumerateFiles(string path); + public abstract System.Collections.Generic.IEnumerable EnumerateFiles(string path, string searchPattern); + public abstract System.Collections.Generic.IEnumerable EnumerateFiles(string path, string searchPattern, System.IO.EnumerationOptions enumerationOptions); + public abstract System.Collections.Generic.IEnumerable EnumerateFiles(string path, string searchPattern, System.IO.SearchOption searchOption); + public abstract bool Exists(string path); + public abstract System.DateTime GetCreationTime(string path); + public abstract System.DateTime GetCreationTimeUtc(string path); + public abstract string GetCurrentDirectory(); + public abstract string[] GetDirectories(string path); + public abstract string[] GetDirectories(string path, string searchPattern); + public abstract string[] GetDirectories(string path, string searchPattern, System.IO.EnumerationOptions enumerationOptions); + public abstract string[] GetDirectories(string path, string searchPattern, System.IO.SearchOption searchOption); + public abstract string GetDirectoryRoot(string path); + public abstract string[] GetFileSystemEntries(string path); + public abstract string[] GetFileSystemEntries(string path, string searchPattern); + public abstract string[] GetFileSystemEntries(string path, string searchPattern, System.IO.EnumerationOptions enumerationOptions); + public abstract string[] GetFileSystemEntries(string path, string searchPattern, System.IO.SearchOption searchOption); + public abstract string[] GetFiles(string path); + public abstract string[] GetFiles(string path, string searchPattern); + public abstract string[] GetFiles(string path, string searchPattern, System.IO.EnumerationOptions enumerationOptions); + public abstract string[] GetFiles(string path, string searchPattern, System.IO.SearchOption searchOption); + public abstract System.DateTime GetLastAccessTime(string path); + public abstract System.DateTime GetLastAccessTimeUtc(string path); + public abstract System.DateTime GetLastWriteTime(string path); + public abstract System.DateTime GetLastWriteTimeUtc(string path); + public abstract string[] GetLogicalDrives(); + public abstract System.IO.Abstractions.IDirectoryInfo GetParent(string path); + public abstract void Move(string sourceDirName, string destDirName); + public abstract void SetCreationTime(string path, System.DateTime creationTime); + public abstract void SetCreationTimeUtc(string path, System.DateTime creationTimeUtc); + public abstract void SetCurrentDirectory(string path); + public abstract void SetLastAccessTime(string path, System.DateTime lastAccessTime); + public abstract void SetLastAccessTimeUtc(string path, System.DateTime lastAccessTimeUtc); + public abstract void SetLastWriteTime(string path, System.DateTime lastWriteTime); + public abstract void SetLastWriteTimeUtc(string path, System.DateTime lastWriteTimeUtc); + } + public static class DirectoryInfoAclExtensions + { + public static void Create(this System.IO.Abstractions.IDirectoryInfo directoryInfo, System.Security.AccessControl.DirectorySecurity directorySecurity) { } + public static System.Security.AccessControl.DirectorySecurity GetAccessControl(this System.IO.Abstractions.IDirectoryInfo directoryInfo) { } + public static System.Security.AccessControl.DirectorySecurity GetAccessControl(this System.IO.Abstractions.IDirectoryInfo directoryInfo, System.Security.AccessControl.AccessControlSections includeSections) { } + public static void SetAccessControl(this System.IO.Abstractions.IDirectoryInfo directoryInfo, System.Security.AccessControl.DirectorySecurity directorySecurity) { } + } + [System.Serializable] + public abstract class DirectoryInfoBase : System.IO.Abstractions.FileSystemInfoBase, System.IO.Abstractions.IDirectoryInfo, System.IO.Abstractions.IFileSystemInfo + { + protected DirectoryInfoBase(System.IO.Abstractions.IFileSystem fileSystem) { } + public abstract System.IO.Abstractions.IDirectoryInfo Parent { get; } + public abstract System.IO.Abstractions.IDirectoryInfo Root { get; } + public abstract void Create(); + public abstract System.IO.Abstractions.IDirectoryInfo CreateSubdirectory(string path); + public abstract void Delete(bool recursive); + public abstract System.Collections.Generic.IEnumerable EnumerateDirectories(); + public abstract System.Collections.Generic.IEnumerable EnumerateDirectories(string searchPattern); + public abstract System.Collections.Generic.IEnumerable EnumerateDirectories(string searchPattern, System.IO.EnumerationOptions enumerationOptions); + public abstract System.Collections.Generic.IEnumerable EnumerateDirectories(string searchPattern, System.IO.SearchOption searchOption); + public abstract System.Collections.Generic.IEnumerable EnumerateFileSystemInfos(); + public abstract System.Collections.Generic.IEnumerable EnumerateFileSystemInfos(string searchPattern); + public abstract System.Collections.Generic.IEnumerable EnumerateFileSystemInfos(string searchPattern, System.IO.EnumerationOptions enumerationOptions); + public abstract System.Collections.Generic.IEnumerable EnumerateFileSystemInfos(string searchPattern, System.IO.SearchOption searchOption); + public abstract System.Collections.Generic.IEnumerable EnumerateFiles(); + public abstract System.Collections.Generic.IEnumerable EnumerateFiles(string searchPattern); + public abstract System.Collections.Generic.IEnumerable EnumerateFiles(string searchPattern, System.IO.EnumerationOptions enumerationOptions); + public abstract System.Collections.Generic.IEnumerable EnumerateFiles(string searchPattern, System.IO.SearchOption searchOption); + public abstract System.IO.Abstractions.IDirectoryInfo[] GetDirectories(); + public abstract System.IO.Abstractions.IDirectoryInfo[] GetDirectories(string searchPattern); + public abstract System.IO.Abstractions.IDirectoryInfo[] GetDirectories(string searchPattern, System.IO.EnumerationOptions enumerationOptions); + public abstract System.IO.Abstractions.IDirectoryInfo[] GetDirectories(string searchPattern, System.IO.SearchOption searchOption); + public abstract System.IO.Abstractions.IFileSystemInfo[] GetFileSystemInfos(); + public abstract System.IO.Abstractions.IFileSystemInfo[] GetFileSystemInfos(string searchPattern); + public abstract System.IO.Abstractions.IFileSystemInfo[] GetFileSystemInfos(string searchPattern, System.IO.EnumerationOptions enumerationOptions); + public abstract System.IO.Abstractions.IFileSystemInfo[] GetFileSystemInfos(string searchPattern, System.IO.SearchOption searchOption); + public abstract System.IO.Abstractions.IFileInfo[] GetFiles(); + public abstract System.IO.Abstractions.IFileInfo[] GetFiles(string searchPattern); + public abstract System.IO.Abstractions.IFileInfo[] GetFiles(string searchPattern, System.IO.EnumerationOptions enumerationOptions); + public abstract System.IO.Abstractions.IFileInfo[] GetFiles(string searchPattern, System.IO.SearchOption searchOption); + public abstract void MoveTo(string destDirName); + public static System.IO.Abstractions.DirectoryInfoBase op_Implicit(System.IO.DirectoryInfo directoryInfo) { } + } + [System.Serializable] + public class DirectoryInfoWrapper : System.IO.Abstractions.DirectoryInfoBase, System.IO.Abstractions.IFileSystemAclSupport + { + public DirectoryInfoWrapper(System.IO.Abstractions.IFileSystem fileSystem, System.IO.DirectoryInfo instance) { } + public override System.IO.FileAttributes Attributes { get; set; } + public override System.DateTime CreationTime { get; set; } + public override System.DateTime CreationTimeUtc { get; set; } + public override bool Exists { get; } + public override string Extension { get; } + public override string FullName { get; } + public override System.DateTime LastAccessTime { get; set; } + public override System.DateTime LastAccessTimeUtc { get; set; } + public override System.DateTime LastWriteTime { get; set; } + public override System.DateTime LastWriteTimeUtc { get; set; } + public override string Name { get; } + public override System.IO.Abstractions.IDirectoryInfo Parent { get; } + public override System.IO.Abstractions.IDirectoryInfo Root { get; } + public override void Create() { } + public override System.IO.Abstractions.IDirectoryInfo CreateSubdirectory(string path) { } + public override void Delete() { } + public override void Delete(bool recursive) { } + public override System.Collections.Generic.IEnumerable EnumerateDirectories() { } + public override System.Collections.Generic.IEnumerable EnumerateDirectories(string searchPattern) { } + public override System.Collections.Generic.IEnumerable EnumerateDirectories(string searchPattern, System.IO.EnumerationOptions enumerationOptions) { } + public override System.Collections.Generic.IEnumerable EnumerateDirectories(string searchPattern, System.IO.SearchOption searchOption) { } + public override System.Collections.Generic.IEnumerable EnumerateFileSystemInfos() { } + public override System.Collections.Generic.IEnumerable EnumerateFileSystemInfos(string searchPattern) { } + public override System.Collections.Generic.IEnumerable EnumerateFileSystemInfos(string searchPattern, System.IO.EnumerationOptions enumerationOptions) { } + public override System.Collections.Generic.IEnumerable EnumerateFileSystemInfos(string searchPattern, System.IO.SearchOption searchOption) { } + public override System.Collections.Generic.IEnumerable EnumerateFiles() { } + public override System.Collections.Generic.IEnumerable EnumerateFiles(string searchPattern) { } + public override System.Collections.Generic.IEnumerable EnumerateFiles(string searchPattern, System.IO.EnumerationOptions enumerationOptions) { } + public override System.Collections.Generic.IEnumerable EnumerateFiles(string searchPattern, System.IO.SearchOption searchOption) { } + public object GetAccessControl() { } + public object GetAccessControl(System.IO.Abstractions.IFileSystemAclSupport.AccessControlSections includeSections) { } + public override System.IO.Abstractions.IDirectoryInfo[] GetDirectories() { } + public override System.IO.Abstractions.IDirectoryInfo[] GetDirectories(string searchPattern) { } + public override System.IO.Abstractions.IDirectoryInfo[] GetDirectories(string searchPattern, System.IO.EnumerationOptions enumerationOptions) { } + public override System.IO.Abstractions.IDirectoryInfo[] GetDirectories(string searchPattern, System.IO.SearchOption searchOption) { } + public override System.IO.Abstractions.IFileSystemInfo[] GetFileSystemInfos() { } + public override System.IO.Abstractions.IFileSystemInfo[] GetFileSystemInfos(string searchPattern) { } + public override System.IO.Abstractions.IFileSystemInfo[] GetFileSystemInfos(string searchPattern, System.IO.EnumerationOptions enumerationOptions) { } + public override System.IO.Abstractions.IFileSystemInfo[] GetFileSystemInfos(string searchPattern, System.IO.SearchOption searchOption) { } + public override System.IO.Abstractions.IFileInfo[] GetFiles() { } + public override System.IO.Abstractions.IFileInfo[] GetFiles(string searchPattern) { } + public override System.IO.Abstractions.IFileInfo[] GetFiles(string searchPattern, System.IO.EnumerationOptions enumerationOptions) { } + public override System.IO.Abstractions.IFileInfo[] GetFiles(string searchPattern, System.IO.SearchOption searchOption) { } + public override void MoveTo(string destDirName) { } + public override void Refresh() { } + public void SetAccessControl(object value) { } + public override string ToString() { } + } + [System.Serializable] + public class DirectoryWrapper : System.IO.Abstractions.DirectoryBase + { + public DirectoryWrapper(System.IO.Abstractions.IFileSystem fileSystem) { } + public override System.IO.Abstractions.IDirectoryInfo CreateDirectory(string path) { } + public override void Delete(string path) { } + public override void Delete(string path, bool recursive) { } + public override System.Collections.Generic.IEnumerable EnumerateDirectories(string path) { } + public override System.Collections.Generic.IEnumerable EnumerateDirectories(string path, string searchPattern) { } + public override System.Collections.Generic.IEnumerable EnumerateDirectories(string path, string searchPattern, System.IO.EnumerationOptions enumerationOptions) { } + public override System.Collections.Generic.IEnumerable EnumerateDirectories(string path, string searchPattern, System.IO.SearchOption searchOption) { } + public override System.Collections.Generic.IEnumerable EnumerateFileSystemEntries(string path) { } + public override System.Collections.Generic.IEnumerable EnumerateFileSystemEntries(string path, string searchPattern) { } + public override System.Collections.Generic.IEnumerable EnumerateFileSystemEntries(string path, string searchPattern, System.IO.EnumerationOptions enumerationOptions) { } + public override System.Collections.Generic.IEnumerable EnumerateFileSystemEntries(string path, string searchPattern, System.IO.SearchOption searchOption) { } + public override System.Collections.Generic.IEnumerable EnumerateFiles(string path) { } + public override System.Collections.Generic.IEnumerable EnumerateFiles(string path, string searchPattern) { } + public override System.Collections.Generic.IEnumerable EnumerateFiles(string path, string searchPattern, System.IO.EnumerationOptions enumerationOptions) { } + public override System.Collections.Generic.IEnumerable EnumerateFiles(string path, string searchPattern, System.IO.SearchOption searchOption) { } + public override bool Exists(string path) { } + public override System.DateTime GetCreationTime(string path) { } + public override System.DateTime GetCreationTimeUtc(string path) { } + public override string GetCurrentDirectory() { } + public override string[] GetDirectories(string path) { } + public override string[] GetDirectories(string path, string searchPattern) { } + public override string[] GetDirectories(string path, string searchPattern, System.IO.EnumerationOptions enumerationOptions) { } + public override string[] GetDirectories(string path, string searchPattern, System.IO.SearchOption searchOption) { } + public override string GetDirectoryRoot(string path) { } + public override string[] GetFileSystemEntries(string path) { } + public override string[] GetFileSystemEntries(string path, string searchPattern) { } + public override string[] GetFileSystemEntries(string path, string searchPattern, System.IO.EnumerationOptions enumerationOptions) { } + public override string[] GetFileSystemEntries(string path, string searchPattern, System.IO.SearchOption searchOption) { } + public override string[] GetFiles(string path) { } + public override string[] GetFiles(string path, string searchPattern) { } + public override string[] GetFiles(string path, string searchPattern, System.IO.EnumerationOptions enumerationOptions) { } + public override string[] GetFiles(string path, string searchPattern, System.IO.SearchOption searchOption) { } + public override System.DateTime GetLastAccessTime(string path) { } + public override System.DateTime GetLastAccessTimeUtc(string path) { } + public override System.DateTime GetLastWriteTime(string path) { } + public override System.DateTime GetLastWriteTimeUtc(string path) { } + public override string[] GetLogicalDrives() { } + public override System.IO.Abstractions.IDirectoryInfo GetParent(string path) { } + public override void Move(string sourceDirName, string destDirName) { } + public override void SetCreationTime(string path, System.DateTime creationTime) { } + public override void SetCreationTimeUtc(string path, System.DateTime creationTimeUtc) { } + public override void SetCurrentDirectory(string path) { } + public override void SetLastAccessTime(string path, System.DateTime lastAccessTime) { } + public override void SetLastAccessTimeUtc(string path, System.DateTime lastAccessTimeUtc) { } + public override void SetLastWriteTime(string path, System.DateTime lastWriteTime) { } + public override void SetLastWriteTimeUtc(string path, System.DateTime lastWriteTimeUtc) { } + } + [System.Serializable] + public abstract class DriveInfoBase : System.IO.Abstractions.IDriveInfo, System.IO.Abstractions.IFileSystemEntity + { + protected DriveInfoBase(System.IO.Abstractions.IFileSystem fileSystem) { } + public abstract long AvailableFreeSpace { get; } + public abstract string DriveFormat { get; } + public abstract System.IO.DriveType DriveType { get; } + public System.IO.Abstractions.IFileSystem FileSystem { get; } + public abstract bool IsReady { get; } + public abstract string Name { get; } + public abstract System.IO.Abstractions.IDirectoryInfo RootDirectory { get; } + public abstract long TotalFreeSpace { get; } + public abstract long TotalSize { get; } + public abstract string VolumeLabel { get; set; } + public static System.IO.Abstractions.DriveInfoBase op_Implicit(System.IO.DriveInfo driveInfo) { } + } + [System.Serializable] + public class DriveInfoWrapper : System.IO.Abstractions.DriveInfoBase + { + public DriveInfoWrapper(System.IO.Abstractions.IFileSystem fileSystem, System.IO.DriveInfo instance) { } + public override long AvailableFreeSpace { get; } + public override string DriveFormat { get; } + public override System.IO.DriveType DriveType { get; } + public override bool IsReady { get; } + public override string Name { get; } + public override System.IO.Abstractions.IDirectoryInfo RootDirectory { get; } + public override long TotalFreeSpace { get; } + public override long TotalSize { get; } + public override string VolumeLabel { get; set; } + public override string ToString() { } + } + public static class FileAclExtensions + { + public static System.Security.AccessControl.FileSecurity GetAccessControl(this System.IO.Abstractions.IFile file, string path) { } + public static System.Security.AccessControl.FileSecurity GetAccessControl(this System.IO.Abstractions.IFile file, string path, System.Security.AccessControl.AccessControlSections includeSections) { } + public static void SetAccessControl(this System.IO.Abstractions.IFile file, string path, System.Security.AccessControl.FileSecurity fileSecurity) { } + } + [System.Serializable] + public abstract class FileBase : System.IO.Abstractions.IFile, System.IO.Abstractions.IFileSystemEntity + { + protected FileBase(System.IO.Abstractions.IFileSystem fileSystem) { } + public System.IO.Abstractions.IFileSystem FileSystem { get; } + public abstract void AppendAllLines(string path, System.Collections.Generic.IEnumerable contents); + public abstract void AppendAllLines(string path, System.Collections.Generic.IEnumerable contents, System.Text.Encoding encoding); + public abstract System.Threading.Tasks.Task AppendAllLinesAsync(string path, System.Collections.Generic.IEnumerable contents, System.Threading.CancellationToken cancellationToken = default); + public abstract System.Threading.Tasks.Task AppendAllLinesAsync(string path, System.Collections.Generic.IEnumerable contents, System.Text.Encoding encoding, System.Threading.CancellationToken cancellationToken = default); + public abstract void AppendAllText(string path, string contents); + public abstract void AppendAllText(string path, string contents, System.Text.Encoding encoding); + public abstract System.Threading.Tasks.Task AppendAllTextAsync(string path, string contents, System.Threading.CancellationToken cancellationToken = default); + public abstract System.Threading.Tasks.Task AppendAllTextAsync(string path, string contents, System.Text.Encoding encoding, System.Threading.CancellationToken cancellationToken = default); + public abstract System.IO.StreamWriter AppendText(string path); + public abstract void Copy(string sourceFileName, string destFileName); + public abstract void Copy(string sourceFileName, string destFileName, bool overwrite); + public abstract System.IO.Abstractions.FileSystemStream Create(string path); + public abstract System.IO.Abstractions.FileSystemStream Create(string path, int bufferSize); + public abstract System.IO.Abstractions.FileSystemStream Create(string path, int bufferSize, System.IO.FileOptions options); + public abstract System.IO.StreamWriter CreateText(string path); + public abstract void Decrypt(string path); + public abstract void Delete(string path); + public abstract void Encrypt(string path); + public abstract bool Exists(string path); + public abstract System.IO.FileAttributes GetAttributes(string path); + public abstract System.DateTime GetCreationTime(string path); + public abstract System.DateTime GetCreationTimeUtc(string path); + public abstract System.DateTime GetLastAccessTime(string path); + public abstract System.DateTime GetLastAccessTimeUtc(string path); + public abstract System.DateTime GetLastWriteTime(string path); + public abstract System.DateTime GetLastWriteTimeUtc(string path); + public abstract void Move(string sourceFileName, string destFileName); + public abstract System.IO.Abstractions.FileSystemStream Open(string path, System.IO.FileMode mode); + public abstract System.IO.Abstractions.FileSystemStream Open(string path, System.IO.FileMode mode, System.IO.FileAccess access); + public abstract System.IO.Abstractions.FileSystemStream Open(string path, System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share); + public abstract System.IO.Abstractions.FileSystemStream OpenRead(string path); + public abstract System.IO.StreamReader OpenText(string path); + public abstract System.IO.Abstractions.FileSystemStream OpenWrite(string path); + public abstract byte[] ReadAllBytes(string path); + public abstract System.Threading.Tasks.Task ReadAllBytesAsync(string path, System.Threading.CancellationToken cancellationToken = default); + public abstract string[] ReadAllLines(string path); + public abstract string[] ReadAllLines(string path, System.Text.Encoding encoding); + public abstract System.Threading.Tasks.Task ReadAllLinesAsync(string path, System.Threading.CancellationToken cancellationToken = default); + public abstract System.Threading.Tasks.Task ReadAllLinesAsync(string path, System.Text.Encoding encoding, System.Threading.CancellationToken cancellationToken = default); + public abstract string ReadAllText(string path); + public abstract string ReadAllText(string path, System.Text.Encoding encoding); + public abstract System.Threading.Tasks.Task ReadAllTextAsync(string path, System.Threading.CancellationToken cancellationToken = default); + public abstract System.Threading.Tasks.Task ReadAllTextAsync(string path, System.Text.Encoding encoding, System.Threading.CancellationToken cancellationToken = default); + public abstract System.Collections.Generic.IEnumerable ReadLines(string path); + public abstract System.Collections.Generic.IEnumerable ReadLines(string path, System.Text.Encoding encoding); + public abstract void Replace(string sourceFileName, string destinationFileName, string destinationBackupFileName); + public abstract void Replace(string sourceFileName, string destinationFileName, string destinationBackupFileName, bool ignoreMetadataErrors); + public abstract void SetAttributes(string path, System.IO.FileAttributes fileAttributes); + public abstract void SetCreationTime(string path, System.DateTime creationTime); + public abstract void SetCreationTimeUtc(string path, System.DateTime creationTimeUtc); + public abstract void SetLastAccessTime(string path, System.DateTime lastAccessTime); + public abstract void SetLastAccessTimeUtc(string path, System.DateTime lastAccessTimeUtc); + public abstract void SetLastWriteTime(string path, System.DateTime lastWriteTime); + public abstract void SetLastWriteTimeUtc(string path, System.DateTime lastWriteTimeUtc); + public abstract void WriteAllBytes(string path, byte[] bytes); + public abstract System.Threading.Tasks.Task WriteAllBytesAsync(string path, byte[] bytes, System.Threading.CancellationToken cancellationToken = default); + public abstract void WriteAllLines(string path, System.Collections.Generic.IEnumerable contents); + public abstract void WriteAllLines(string path, string[] contents); + public abstract void WriteAllLines(string path, System.Collections.Generic.IEnumerable contents, System.Text.Encoding encoding); + public abstract void WriteAllLines(string path, string[] contents, System.Text.Encoding encoding); + public abstract System.Threading.Tasks.Task WriteAllLinesAsync(string path, System.Collections.Generic.IEnumerable contents, System.Threading.CancellationToken cancellationToken = default); + public abstract System.Threading.Tasks.Task WriteAllLinesAsync(string path, System.Collections.Generic.IEnumerable contents, System.Text.Encoding encoding, System.Threading.CancellationToken cancellationToken = default); + public abstract void WriteAllText(string path, string contents); + public abstract void WriteAllText(string path, string contents, System.Text.Encoding encoding); + public abstract System.Threading.Tasks.Task WriteAllTextAsync(string path, string contents, System.Threading.CancellationToken cancellationToken = default); + public abstract System.Threading.Tasks.Task WriteAllTextAsync(string path, string contents, System.Text.Encoding encoding, System.Threading.CancellationToken cancellationToken = default); + } + public static class FileInfoAclExtensions + { + public static System.Security.AccessControl.FileSecurity GetAccessControl(this System.IO.Abstractions.IFileInfo fileInfo) { } + public static System.Security.AccessControl.FileSecurity GetAccessControl(this System.IO.Abstractions.IFileInfo fileInfo, System.Security.AccessControl.AccessControlSections includeSections) { } + public static void SetAccessControl(this System.IO.Abstractions.IFileInfo fileInfo, System.Security.AccessControl.FileSecurity fileSecurity) { } + } + [System.Serializable] + public abstract class FileInfoBase : System.IO.Abstractions.FileSystemInfoBase, System.IO.Abstractions.IFileInfo, System.IO.Abstractions.IFileSystemInfo + { + protected FileInfoBase(System.IO.Abstractions.IFileSystem fileSystem) { } + public abstract System.IO.Abstractions.IDirectoryInfo Directory { get; } + public abstract string DirectoryName { get; } + public abstract bool IsReadOnly { get; set; } + public abstract long Length { get; } + public abstract System.IO.StreamWriter AppendText(); + public abstract System.IO.Abstractions.IFileInfo CopyTo(string destFileName); + public abstract System.IO.Abstractions.IFileInfo CopyTo(string destFileName, bool overwrite); + public abstract System.IO.Abstractions.FileSystemStream Create(); + public abstract System.IO.StreamWriter CreateText(); + public abstract void Decrypt(); + public abstract void Encrypt(); + public abstract void MoveTo(string destFileName); + public abstract System.IO.Abstractions.FileSystemStream Open(System.IO.FileMode mode); + public abstract System.IO.Abstractions.FileSystemStream Open(System.IO.FileMode mode, System.IO.FileAccess access); + public abstract System.IO.Abstractions.FileSystemStream Open(System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share); + public abstract System.IO.Abstractions.FileSystemStream OpenRead(); + public abstract System.IO.StreamReader OpenText(); + public abstract System.IO.Abstractions.FileSystemStream OpenWrite(); + public abstract System.IO.Abstractions.IFileInfo Replace(string destinationFileName, string destinationBackupFileName); + public abstract System.IO.Abstractions.IFileInfo Replace(string destinationFileName, string destinationBackupFileName, bool ignoreMetadataErrors); + public static System.IO.Abstractions.FileInfoBase op_Implicit(System.IO.FileInfo fileInfo) { } + } + [System.Serializable] + public class FileInfoWrapper : System.IO.Abstractions.FileInfoBase, System.IO.Abstractions.IFileSystemAclSupport + { + public FileInfoWrapper(System.IO.Abstractions.IFileSystem fileSystem, System.IO.FileInfo instance) { } + public override System.IO.FileAttributes Attributes { get; set; } + public override System.DateTime CreationTime { get; set; } + public override System.DateTime CreationTimeUtc { get; set; } + public override System.IO.Abstractions.IDirectoryInfo Directory { get; } + public override string DirectoryName { get; } + public override bool Exists { get; } + public override string Extension { get; } + public override string FullName { get; } + public override bool IsReadOnly { get; set; } + public override System.DateTime LastAccessTime { get; set; } + public override System.DateTime LastAccessTimeUtc { get; set; } + public override System.DateTime LastWriteTime { get; set; } + public override System.DateTime LastWriteTimeUtc { get; set; } + public override long Length { get; } + public override string Name { get; } + public override System.IO.StreamWriter AppendText() { } + public override System.IO.Abstractions.IFileInfo CopyTo(string destFileName) { } + public override System.IO.Abstractions.IFileInfo CopyTo(string destFileName, bool overwrite) { } + public override System.IO.Abstractions.FileSystemStream Create() { } + public override System.IO.StreamWriter CreateText() { } + public override void Decrypt() { } + public override void Delete() { } + public override void Encrypt() { } + public object GetAccessControl() { } + public object GetAccessControl(System.IO.Abstractions.IFileSystemAclSupport.AccessControlSections includeSections) { } + public override void MoveTo(string destFileName) { } + public override System.IO.Abstractions.FileSystemStream Open(System.IO.FileMode mode) { } + public override System.IO.Abstractions.FileSystemStream Open(System.IO.FileMode mode, System.IO.FileAccess access) { } + public override System.IO.Abstractions.FileSystemStream Open(System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share) { } + public override System.IO.Abstractions.FileSystemStream OpenRead() { } + public override System.IO.StreamReader OpenText() { } + public override System.IO.Abstractions.FileSystemStream OpenWrite() { } + public override void Refresh() { } + public override System.IO.Abstractions.IFileInfo Replace(string destinationFileName, string destinationBackupFileName) { } + public override System.IO.Abstractions.IFileInfo Replace(string destinationFileName, string destinationBackupFileName, bool ignoreMetadataErrors) { } + public void SetAccessControl(object value) { } + public override string ToString() { } + } + public static class FileStreamAclExtensions + { + public static System.Security.AccessControl.FileSecurity GetAccessControl(this System.IO.Abstractions.FileSystemStream fileStream) { } + public static void SetAccessControl(this System.IO.Abstractions.FileSystemStream fileStream, System.Security.AccessControl.FileSecurity fileSecurity) { } + } + [System.Serializable] + public class FileSystem : System.IO.Abstractions.FileSystemBase + { + public FileSystem() { } + public override System.IO.Abstractions.IDirectory Directory { get; } + public override System.IO.Abstractions.IDirectoryInfoFactory DirectoryInfo { get; } + public override System.IO.Abstractions.IDriveInfoFactory DriveInfo { get; } + public override System.IO.Abstractions.IFile File { get; } + public override System.IO.Abstractions.IFileInfoFactory FileInfo { get; } + public override System.IO.Abstractions.IFileStreamFactory FileStream { get; } + public override System.IO.Abstractions.IFileSystemWatcherFactory FileSystemWatcher { get; } + public override System.IO.Abstractions.IFileVersionInfoFactory FileVersionInfo { get; } + public override System.IO.Abstractions.IPath Path { get; } + } + [System.Serializable] + public abstract class FileSystemBase : System.IO.Abstractions.IFileSystem + { + protected FileSystemBase() { } + public abstract System.IO.Abstractions.IDirectory Directory { get; } + public abstract System.IO.Abstractions.IDirectoryInfoFactory DirectoryInfo { get; } + public abstract System.IO.Abstractions.IDriveInfoFactory DriveInfo { get; } + public abstract System.IO.Abstractions.IFile File { get; } + public abstract System.IO.Abstractions.IFileInfoFactory FileInfo { get; } + public abstract System.IO.Abstractions.IFileStreamFactory FileStream { get; } + public abstract System.IO.Abstractions.IFileSystemWatcherFactory FileSystemWatcher { get; } + public abstract System.IO.Abstractions.IFileVersionInfoFactory FileVersionInfo { get; } + public abstract System.IO.Abstractions.IPath Path { get; } + } + [System.Serializable] + public abstract class FileSystemInfoBase : System.IO.Abstractions.IFileSystemInfo + { + protected FileSystemInfoBase(System.IO.Abstractions.IFileSystem fileSystem) { } + public abstract System.IO.FileAttributes Attributes { get; set; } + public abstract System.DateTime CreationTime { get; set; } + public abstract System.DateTime CreationTimeUtc { get; set; } + public abstract bool Exists { get; } + public abstract string Extension { get; } + public System.IO.Abstractions.IFileSystem FileSystem { get; } + public abstract string FullName { get; } + public abstract System.DateTime LastAccessTime { get; set; } + public abstract System.DateTime LastAccessTimeUtc { get; set; } + public abstract System.DateTime LastWriteTime { get; set; } + public abstract System.DateTime LastWriteTimeUtc { get; set; } + public abstract string Name { get; } + public abstract void Delete(); + public abstract void Refresh(); + } + [System.Serializable] + public abstract class FileSystemWatcherBase : System.IDisposable, System.IO.Abstractions.IFileSystemEntity, System.IO.Abstractions.IFileSystemWatcher + { + protected FileSystemWatcherBase() { } + public abstract System.ComponentModel.IContainer Container { get; } + public abstract bool EnableRaisingEvents { get; set; } + public abstract System.IO.Abstractions.IFileSystem FileSystem { get; } + public abstract string Filter { get; set; } + public abstract bool IncludeSubdirectories { get; set; } + public abstract int InternalBufferSize { get; set; } + public abstract System.IO.NotifyFilters NotifyFilter { get; set; } + public abstract string Path { get; set; } + public abstract System.ComponentModel.ISite Site { get; set; } + public abstract System.ComponentModel.ISynchronizeInvoke SynchronizingObject { get; set; } + public virtual event System.IO.FileSystemEventHandler Changed; + public virtual event System.IO.FileSystemEventHandler Created; + public virtual event System.IO.FileSystemEventHandler Deleted; + public virtual event System.IO.ErrorEventHandler Error; + public virtual event System.IO.RenamedEventHandler Renamed; + public abstract void BeginInit(); + public void Dispose() { } + public virtual void Dispose(bool disposing) { } + public abstract void EndInit(); + protected void OnChanged(object sender, System.IO.FileSystemEventArgs args) { } + protected void OnCreated(object sender, System.IO.FileSystemEventArgs args) { } + protected void OnDeleted(object sender, System.IO.FileSystemEventArgs args) { } + protected void OnError(object sender, System.IO.ErrorEventArgs args) { } + protected void OnRenamed(object sender, System.IO.RenamedEventArgs args) { } + public abstract System.IO.Abstractions.IWaitForChangedResult WaitForChanged(System.IO.WatcherChangeTypes changeType); + public abstract System.IO.Abstractions.IWaitForChangedResult WaitForChanged(System.IO.WatcherChangeTypes changeType, int timeout); + public static System.IO.Abstractions.FileSystemWatcherBase op_Implicit(System.IO.FileSystemWatcher watcher) { } + } + [System.Serializable] + public class FileSystemWatcherFactory : System.IO.Abstractions.IFileSystemEntity, System.IO.Abstractions.IFileSystemWatcherFactory + { + public FileSystemWatcherFactory(System.IO.Abstractions.IFileSystem fileSystem) { } + public System.IO.Abstractions.IFileSystem FileSystem { get; } + public System.IO.Abstractions.IFileSystemWatcher New() { } + public System.IO.Abstractions.IFileSystemWatcher New(string path) { } + public System.IO.Abstractions.IFileSystemWatcher New(string path, string filter) { } + public System.IO.Abstractions.IFileSystemWatcher Wrap(System.IO.FileSystemWatcher fileSystemWatcher) { } + } + [System.Serializable] + public class FileSystemWatcherWrapper : System.IO.Abstractions.FileSystemWatcherBase + { + public FileSystemWatcherWrapper(System.IO.Abstractions.IFileSystem fileSystem) { } + public FileSystemWatcherWrapper(System.IO.Abstractions.IFileSystem fileSystem, System.IO.FileSystemWatcher watcher) { } + public FileSystemWatcherWrapper(System.IO.Abstractions.IFileSystem fileSystem, string path) { } + public FileSystemWatcherWrapper(System.IO.Abstractions.IFileSystem fileSystem, string path, string filter) { } + public override System.ComponentModel.IContainer Container { get; } + public override bool EnableRaisingEvents { get; set; } + public override System.IO.Abstractions.IFileSystem FileSystem { get; } + public override string Filter { get; set; } + public override bool IncludeSubdirectories { get; set; } + public override int InternalBufferSize { get; set; } + public override System.IO.NotifyFilters NotifyFilter { get; set; } + public override string Path { get; set; } + public override System.ComponentModel.ISite Site { get; set; } + public override System.ComponentModel.ISynchronizeInvoke SynchronizingObject { get; set; } + public override void BeginInit() { } + public override void Dispose(bool disposing) { } + public override void EndInit() { } + public override System.IO.Abstractions.IWaitForChangedResult WaitForChanged(System.IO.WatcherChangeTypes changeType) { } + public override System.IO.Abstractions.IWaitForChangedResult WaitForChanged(System.IO.WatcherChangeTypes changeType, int timeout) { } + } + [System.Serializable] + public abstract class FileVersionInfoBase : System.IO.Abstractions.IFileVersionInfo + { + protected FileVersionInfoBase() { } + public abstract string Comments { get; } + public abstract string CompanyName { get; } + public abstract int FileBuildPart { get; } + public abstract string FileDescription { get; } + public abstract int FileMajorPart { get; } + public abstract int FileMinorPart { get; } + public abstract string FileName { get; } + public abstract int FilePrivatePart { get; } + public abstract string FileVersion { get; } + public abstract string InternalName { get; } + public abstract bool IsDebug { get; } + public abstract bool IsPatched { get; } + public abstract bool IsPreRelease { get; } + public abstract bool IsPrivateBuild { get; } + public abstract bool IsSpecialBuild { get; } + public abstract string Language { get; } + public abstract string LegalCopyright { get; } + public abstract string LegalTrademarks { get; } + public abstract string OriginalFilename { get; } + public abstract string PrivateBuild { get; } + public abstract int ProductBuildPart { get; } + public abstract int ProductMajorPart { get; } + public abstract int ProductMinorPart { get; } + public abstract string ProductName { get; } + public abstract int ProductPrivatePart { get; } + public abstract string ProductVersion { get; } + public abstract string SpecialBuild { get; } + public abstract string ToString(); + public static System.IO.Abstractions.FileVersionInfoBase op_Implicit(System.Diagnostics.FileVersionInfo fileVersionInfo) { } + } + [System.Serializable] + public class FileVersionInfoWrapper : System.IO.Abstractions.FileVersionInfoBase + { + public FileVersionInfoWrapper(System.Diagnostics.FileVersionInfo fileVersionInfo) { } + public override string Comments { get; } + public override string CompanyName { get; } + public override int FileBuildPart { get; } + public override string FileDescription { get; } + public override int FileMajorPart { get; } + public override int FileMinorPart { get; } + public override string FileName { get; } + public override int FilePrivatePart { get; } + public override string FileVersion { get; } + public override string InternalName { get; } + public override bool IsDebug { get; } + public override bool IsPatched { get; } + public override bool IsPreRelease { get; } + public override bool IsPrivateBuild { get; } + public override bool IsSpecialBuild { get; } + public override string Language { get; } + public override string LegalCopyright { get; } + public override string LegalTrademarks { get; } + public override string OriginalFilename { get; } + public override string PrivateBuild { get; } + public override int ProductBuildPart { get; } + public override int ProductMajorPart { get; } + public override int ProductMinorPart { get; } + public override string ProductName { get; } + public override int ProductPrivatePart { get; } + public override string ProductVersion { get; } + public override string SpecialBuild { get; } + public override string ToString() { } + } + [System.Serializable] + public class FileWrapper : System.IO.Abstractions.FileBase + { + public FileWrapper(System.IO.Abstractions.IFileSystem fileSystem) { } + public override void AppendAllLines(string path, System.Collections.Generic.IEnumerable contents) { } + public override void AppendAllLines(string path, System.Collections.Generic.IEnumerable contents, System.Text.Encoding encoding) { } + public override System.Threading.Tasks.Task AppendAllLinesAsync(string path, System.Collections.Generic.IEnumerable contents, System.Threading.CancellationToken cancellationToken = default) { } + public override System.Threading.Tasks.Task AppendAllLinesAsync(string path, System.Collections.Generic.IEnumerable contents, System.Text.Encoding encoding, System.Threading.CancellationToken cancellationToken = default) { } + public override void AppendAllText(string path, string contents) { } + public override void AppendAllText(string path, string contents, System.Text.Encoding encoding) { } + public override System.Threading.Tasks.Task AppendAllTextAsync(string path, string contents, System.Threading.CancellationToken cancellationToken = default) { } + public override System.Threading.Tasks.Task AppendAllTextAsync(string path, string contents, System.Text.Encoding encoding, System.Threading.CancellationToken cancellationToken = default) { } + public override System.IO.StreamWriter AppendText(string path) { } + public override void Copy(string sourceFileName, string destFileName) { } + public override void Copy(string sourceFileName, string destFileName, bool overwrite) { } + public override System.IO.Abstractions.FileSystemStream Create(string path) { } + public override System.IO.Abstractions.FileSystemStream Create(string path, int bufferSize) { } + public override System.IO.Abstractions.FileSystemStream Create(string path, int bufferSize, System.IO.FileOptions options) { } + public override System.IO.StreamWriter CreateText(string path) { } + public override void Decrypt(string path) { } + public override void Delete(string path) { } + public override void Encrypt(string path) { } + public override bool Exists(string path) { } + public override System.IO.FileAttributes GetAttributes(string path) { } + public override System.DateTime GetCreationTime(string path) { } + public override System.DateTime GetCreationTimeUtc(string path) { } + public override System.DateTime GetLastAccessTime(string path) { } + public override System.DateTime GetLastAccessTimeUtc(string path) { } + public override System.DateTime GetLastWriteTime(string path) { } + public override System.DateTime GetLastWriteTimeUtc(string path) { } + public override void Move(string sourceFileName, string destFileName) { } + public override System.IO.Abstractions.FileSystemStream Open(string path, System.IO.FileMode mode) { } + public override System.IO.Abstractions.FileSystemStream Open(string path, System.IO.FileMode mode, System.IO.FileAccess access) { } + public override System.IO.Abstractions.FileSystemStream Open(string path, System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share) { } + public override System.IO.Abstractions.FileSystemStream OpenRead(string path) { } + public override System.IO.StreamReader OpenText(string path) { } + public override System.IO.Abstractions.FileSystemStream OpenWrite(string path) { } + public override byte[] ReadAllBytes(string path) { } + public override System.Threading.Tasks.Task ReadAllBytesAsync(string path, System.Threading.CancellationToken cancellationToken = default) { } + public override string[] ReadAllLines(string path) { } + public override string[] ReadAllLines(string path, System.Text.Encoding encoding) { } + public override System.Threading.Tasks.Task ReadAllLinesAsync(string path, System.Threading.CancellationToken cancellationToken = default) { } + public override System.Threading.Tasks.Task ReadAllLinesAsync(string path, System.Text.Encoding encoding, System.Threading.CancellationToken cancellationToken = default) { } + public override string ReadAllText(string path) { } + public override string ReadAllText(string path, System.Text.Encoding encoding) { } + public override System.Threading.Tasks.Task ReadAllTextAsync(string path, System.Threading.CancellationToken cancellationToken = default) { } + public override System.Threading.Tasks.Task ReadAllTextAsync(string path, System.Text.Encoding encoding, System.Threading.CancellationToken cancellationToken = default) { } + public override System.Collections.Generic.IEnumerable ReadLines(string path) { } + public override System.Collections.Generic.IEnumerable ReadLines(string path, System.Text.Encoding encoding) { } + public override void Replace(string sourceFileName, string destinationFileName, string destinationBackupFileName) { } + public override void Replace(string sourceFileName, string destinationFileName, string destinationBackupFileName, bool ignoreMetadataErrors) { } + public override void SetAttributes(string path, System.IO.FileAttributes fileAttributes) { } + public override void SetCreationTime(string path, System.DateTime creationTime) { } + public override void SetCreationTimeUtc(string path, System.DateTime creationTimeUtc) { } + public override void SetLastAccessTime(string path, System.DateTime lastAccessTime) { } + public override void SetLastAccessTimeUtc(string path, System.DateTime lastAccessTimeUtc) { } + public override void SetLastWriteTime(string path, System.DateTime lastWriteTime) { } + public override void SetLastWriteTimeUtc(string path, System.DateTime lastWriteTimeUtc) { } + public override void WriteAllBytes(string path, byte[] bytes) { } + public override System.Threading.Tasks.Task WriteAllBytesAsync(string path, byte[] bytes, System.Threading.CancellationToken cancellationToken = default) { } + public override void WriteAllLines(string path, System.Collections.Generic.IEnumerable contents) { } + public override void WriteAllLines(string path, string[] contents) { } + public override void WriteAllLines(string path, System.Collections.Generic.IEnumerable contents, System.Text.Encoding encoding) { } + public override void WriteAllLines(string path, string[] contents, System.Text.Encoding encoding) { } + public override System.Threading.Tasks.Task WriteAllLinesAsync(string path, System.Collections.Generic.IEnumerable contents, System.Threading.CancellationToken cancellationToken = default) { } + public override System.Threading.Tasks.Task WriteAllLinesAsync(string path, System.Collections.Generic.IEnumerable contents, System.Text.Encoding encoding, System.Threading.CancellationToken cancellationToken = default) { } + public override void WriteAllText(string path, string contents) { } + public override void WriteAllText(string path, string contents, System.Text.Encoding encoding) { } + public override System.Threading.Tasks.Task WriteAllTextAsync(string path, string contents, System.Threading.CancellationToken cancellationToken = default) { } + public override System.Threading.Tasks.Task WriteAllTextAsync(string path, string contents, System.Text.Encoding encoding, System.Threading.CancellationToken cancellationToken = default) { } + } + [System.Serializable] + public abstract class PathBase : System.IO.Abstractions.IFileSystemEntity, System.IO.Abstractions.IPath + { + protected PathBase(System.IO.Abstractions.IFileSystem fileSystem) { } + public abstract char AltDirectorySeparatorChar { get; } + public abstract char DirectorySeparatorChar { get; } + public System.IO.Abstractions.IFileSystem FileSystem { get; } + [System.Obsolete("Please use GetInvalidPathChars or GetInvalidFileNameChars instead.")] + public abstract char[] InvalidPathChars { get; } + public abstract char PathSeparator { get; } + public abstract char VolumeSeparatorChar { get; } + public abstract string ChangeExtension(string path, string extension); + public abstract string Combine(params string[] paths); + public abstract string Combine(string path1, string path2); + public abstract string Combine(string path1, string path2, string path3); + public abstract string Combine(string path1, string path2, string path3, string path4); + public abstract System.ReadOnlySpan GetDirectoryName(System.ReadOnlySpan path); + public abstract string GetDirectoryName(string path); + public abstract System.ReadOnlySpan GetExtension(System.ReadOnlySpan path); + public abstract string GetExtension(string path); + public abstract System.ReadOnlySpan GetFileName(System.ReadOnlySpan path); + public abstract string GetFileName(string path); + public abstract System.ReadOnlySpan GetFileNameWithoutExtension(System.ReadOnlySpan path); + public abstract string GetFileNameWithoutExtension(string path); + public abstract string GetFullPath(string path); + public abstract string GetFullPath(string path, string basePath); + public abstract char[] GetInvalidFileNameChars(); + public abstract char[] GetInvalidPathChars(); + public abstract System.ReadOnlySpan GetPathRoot(System.ReadOnlySpan path); + public abstract string GetPathRoot(string path); + public abstract string GetRandomFileName(); + public abstract string GetRelativePath(string relativeTo, string path); + public abstract string GetTempFileName(); + public abstract string GetTempPath(); + public abstract bool HasExtension(System.ReadOnlySpan path); + public abstract bool HasExtension(string path); + public abstract bool IsPathFullyQualified(System.ReadOnlySpan path); + public abstract bool IsPathFullyQualified(string path); + public abstract bool IsPathRooted(System.ReadOnlySpan path); + public abstract bool IsPathRooted(string path); + public abstract string Join(System.ReadOnlySpan path1, System.ReadOnlySpan path2); + public abstract string Join(System.ReadOnlySpan path1, System.ReadOnlySpan path2, System.ReadOnlySpan path3); + public abstract bool TryJoin(System.ReadOnlySpan path1, System.ReadOnlySpan path2, System.Span destination, out int charsWritten); + public abstract bool TryJoin(System.ReadOnlySpan path1, System.ReadOnlySpan path2, System.ReadOnlySpan path3, System.Span destination, out int charsWritten); + } + [System.Serializable] + public class PathWrapper : System.IO.Abstractions.PathBase + { + public PathWrapper(System.IO.Abstractions.IFileSystem fileSystem) { } + public override char AltDirectorySeparatorChar { get; } + public override char DirectorySeparatorChar { get; } + [System.Obsolete("Please use GetInvalidPathChars or GetInvalidFileNameChars instead.")] + public override char[] InvalidPathChars { get; } + public override char PathSeparator { get; } + public override char VolumeSeparatorChar { get; } + public override string ChangeExtension(string path, string extension) { } + public override string Combine(params string[] paths) { } + public override string Combine(string path1, string path2) { } + public override string Combine(string path1, string path2, string path3) { } + public override string Combine(string path1, string path2, string path3, string path4) { } + public override System.ReadOnlySpan GetDirectoryName(System.ReadOnlySpan path) { } + public override string GetDirectoryName(string path) { } + public override System.ReadOnlySpan GetExtension(System.ReadOnlySpan path) { } + public override string GetExtension(string path) { } + public override System.ReadOnlySpan GetFileName(System.ReadOnlySpan path) { } + public override string GetFileName(string path) { } + public override System.ReadOnlySpan GetFileNameWithoutExtension(System.ReadOnlySpan path) { } + public override string GetFileNameWithoutExtension(string path) { } + public override string GetFullPath(string path) { } + public override string GetFullPath(string path, string basePath) { } + public override char[] GetInvalidFileNameChars() { } + public override char[] GetInvalidPathChars() { } + public override System.ReadOnlySpan GetPathRoot(System.ReadOnlySpan path) { } + public override string GetPathRoot(string path) { } + public override string GetRandomFileName() { } + public override string GetRelativePath(string relativeTo, string path) { } + public override string GetTempFileName() { } + public override string GetTempPath() { } + public override bool HasExtension(System.ReadOnlySpan path) { } + public override bool HasExtension(string path) { } + public override bool IsPathFullyQualified(System.ReadOnlySpan path) { } + public override bool IsPathFullyQualified(string path) { } + public override bool IsPathRooted(System.ReadOnlySpan path) { } + public override bool IsPathRooted(string path) { } + public override string Join(System.ReadOnlySpan path1, System.ReadOnlySpan path2) { } + public override string Join(System.ReadOnlySpan path1, System.ReadOnlySpan path2, System.ReadOnlySpan path3) { } + public override bool TryJoin(System.ReadOnlySpan path1, System.ReadOnlySpan path2, System.Span destination, out int charsWritten) { } + public override bool TryJoin(System.ReadOnlySpan path1, System.ReadOnlySpan path2, System.ReadOnlySpan path3, System.Span destination, out int charsWritten) { } + } +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.Api.Tests/Helper.cs b/tests/TestableIO.System.IO.Abstractions.Api.Tests/Helper.cs new file mode 100644 index 000000000..d4f27af25 --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.Api.Tests/Helper.cs @@ -0,0 +1,72 @@ +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Xml.Linq; +using System.Xml.XPath; +using PublicApiGenerator; + +namespace TestableIO.System.IO.Abstractions.Api.Tests; + +public static class Helper +{ + public static string CreatePublicApi(string framework, string assemblyName) + { +#if DEBUG + var configuration = "Debug"; +#else + string configuration = "Release"; +#endif + var assemblyFile = + CombinedPaths("src", assemblyName, "bin", configuration, framework, $"{assemblyName}.dll"); + var assembly = Assembly.LoadFile(assemblyFile); + var publicApi = assembly.GeneratePublicApi(new ApiGeneratorOptions + { + AllowNamespacePrefixes = ["System.IO.Abstractions",], + }); + return publicApi.Replace("\r\n", "\n"); + } + + public static string GetExpectedApi(string framework, string assemblyName) + { + var expectedPath = CombinedPaths("tests", "TestableIO.System.IO.Abstractions.Api.Tests", + "Expected", $"{assemblyName}_{framework}.txt"); + try + { + return File.ReadAllText(expectedPath) + .Replace("\r\n", "\n"); + } + catch + { + return string.Empty; + } + } + + public static IEnumerable GetTargetFrameworks() + { + var csproj = CombinedPaths("src", "Directory.Build.props"); + var project = XDocument.Load(csproj); + var targetFrameworks = + project.XPathSelectElement("/Project/PropertyGroup/TargetFrameworks"); + foreach (var targetFramework in targetFrameworks!.Value.Split(';')) yield return targetFramework; + } + + public static void SetExpectedApi(string framework, string assemblyName, string publicApi) + { + var expectedPath = CombinedPaths("tests", "TestableIO.System.IO.Abstractions.Api.Tests", + "Expected", $"{assemblyName}_{framework}.txt"); + Directory.CreateDirectory(Path.GetDirectoryName(expectedPath)!); + File.WriteAllText(expectedPath, publicApi); + } + + private static string CombinedPaths(params string[] paths) + { + return Path.GetFullPath(Path.Combine(paths.Prepend(GetSolutionDirectory()).ToArray())); + } + + private static string GetSolutionDirectory([CallerFilePath] string path = "") + { + return Path.Combine(Path.GetDirectoryName(path)!, "..", ".."); + } +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.Api.Tests/TestableIO.System.IO.Abstractions.Api.Tests.csproj b/tests/TestableIO.System.IO.Abstractions.Api.Tests/TestableIO.System.IO.Abstractions.Api.Tests.csproj new file mode 100644 index 000000000..4fb826fe6 --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.Api.Tests/TestableIO.System.IO.Abstractions.Api.Tests.csproj @@ -0,0 +1,19 @@ + + + + net8.0 + + + + + + + + + + + + + + + diff --git a/tests/TestableIO.System.IO.Abstractions.Api.Tests/Usings.cs b/tests/TestableIO.System.IO.Abstractions.Api.Tests/Usings.cs new file mode 100644 index 000000000..5876408d3 --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.Api.Tests/Usings.cs @@ -0,0 +1,5 @@ +global using System; +global using System.Threading.Tasks; +global using NUnit.Framework; +global using aweXpect; +global using static aweXpect.Expect; diff --git a/tests/TestableIO.System.IO.Abstractions.Parity.Tests/ApiParityTests.cs b/tests/TestableIO.System.IO.Abstractions.Parity.Tests/ApiParityTests.cs new file mode 100644 index 000000000..7462b07b9 --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.Parity.Tests/ApiParityTests.cs @@ -0,0 +1,137 @@ +using System.Collections.Generic; +using System.Linq; +using System.Text.Json; +using System.Threading.Tasks; +using aweXpect; +using static aweXpect.Expect; +using NUnit.Framework; +using static System.Reflection.BindingFlags; + +namespace System.IO.Abstractions.Tests; + +[TestFixture] +public class ApiParityTests +{ + [Test] + public async Task File() => + await AssertParity( + typeof(File), + typeof(FileBase) + ); + + [Test] + public async Task FileInfo() => + await AssertParity( + typeof(FileInfo), + typeof(FileInfoBase) + ); + + [Test] + public async Task FileVersionInfo() => + await AssertParity( + typeof(Diagnostics.FileVersionInfo), + typeof(FileVersionInfoBase) + ); + + [Test] + public async Task Directory() => + await AssertParity( + typeof(Directory), + typeof(DirectoryBase) + ); + + [Test] + public async Task DirectoryInfo() => + await AssertParity( + typeof(DirectoryInfo), + typeof(DirectoryInfoBase) + ); + + [Test] + public async Task DriveInfo() => + await AssertParity( + typeof(DriveInfo), + typeof(DriveInfoBase) + ); + + [Test] + public async Task Path() => + await AssertParity( + typeof(Path), + typeof(PathBase) + ); + + [Test] + public async Task FileSystemWatcher() => + await AssertParity( + typeof(FileSystemWatcher), + typeof(FileSystemWatcherBase) + ); + + private async Task AssertParity(Type referenceType, Type abstractionType) + { + static IEnumerable GetMembers(Type type) => type + .GetMembers(bindingAttr: Instance | Static | Public | FlattenHierarchy) + .Select(x => x.ToString()) + .OrderBy(x => x, StringComparer.Ordinal); + var referenceMembers = GetMembers(referenceType) + .Select(x => x.Replace("System.IO.FileStream", "System.IO.Abstractions.FileSystemStream")) + .Select(x => x.Replace("System.IO.Abstractions.FileSystemStreamOptions", "System.IO.FileStreamOptions")) + .Select(x => x.Replace("System.IO.FileSystemInfo", "System.IO.Abstractions.IFileSystemInfo")) + .Select(x => x.Replace("System.IO.FileInfo", "System.IO.Abstractions.IFileInfo")) + .Select(x => x.Replace("System.IO.DirectoryInfo", "System.IO.Abstractions.IDirectoryInfo")) + .Select(x => x.Replace("System.IO.DriveInfo", "System.IO.Abstractions.IDriveInfo")) + .Select(x => x.Replace("System.IO.WaitForChangedResult", "System.IO.Abstractions.IWaitForChangedResult")) + .Where(x => x != "System.Diagnostics.FileVersionInfo GetVersionInfo(System.String)"); + var abstractionMembers = GetMembers(abstractionType) + .Where(x => !x.Contains("op_Implicit")) + .Where(x => x != "System.IO.Abstractions.IFileSystem get_FileSystem()") + .Where(x => x != "System.IO.Abstractions.IFileSystem FileSystem"); + var diff = new ApiDiff( + extraMembers: abstractionMembers.Except(referenceMembers), + missingMembers: referenceMembers.Except(abstractionMembers) + ); + + var serializedDiff = JsonSerializer.Serialize(diff, SerializerOptions); + + var snapshotPath = IO.Path.GetFullPath("../../../__snapshots__/"); + var fileName = $"ApiParityTests.{referenceType.Name}_{snapshotSuffix}.snap"; + var fileContent = IO.File.ReadAllText(IO.Path.Combine(snapshotPath, fileName)); + + await That(fileContent).IsEqualTo(serializedDiff) + .IgnoringNewlineStyle() + .IgnoringTrailingWhiteSpace(); + } + + private static JsonSerializerOptions SerializerOptions = new() + { + WriteIndented = true + }; + + private readonly struct ApiDiff + { + public ApiDiff(IEnumerable extraMembers, IEnumerable missingMembers) + { + ExtraMembers = extraMembers.ToArray(); + MissingMembers = missingMembers.ToArray(); + + } + + public string[] ExtraMembers { get; } + public string[] MissingMembers { get; } + } + +#if NET472 + private const string snapshotSuffix = ".NET Framework 4.7.2"; +#elif NET6_0 + private const string snapshotSuffix = ".NET 6.0"; +#elif NET8_0 + private const string snapshotSuffix = ".NET 8.0"; +#elif NET9_0 + private const string snapshotSuffix = ".NET 9.0"; +#elif NET10_0 + private const string snapshotSuffix = ".NET 10.0"; +#else +#error Unknown target framework. +#endif +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.Parity.Tests/TestableIO.System.IO.Abstractions.Parity.Tests.csproj b/tests/TestableIO.System.IO.Abstractions.Parity.Tests/TestableIO.System.IO.Abstractions.Parity.Tests.csproj new file mode 100644 index 000000000..83a9487e6 --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.Parity.Tests/TestableIO.System.IO.Abstractions.Parity.Tests.csproj @@ -0,0 +1,17 @@ + + + + The unit tests for our the parity checks + System.IO.Abstractions.Parity.Tests + System.IO.Abstractions.Parity.Tests + + + + + + + + + + + diff --git a/tests/TestableIO.System.IO.Abstractions.Parity.Tests/__snapshots__/ApiParityTests.DirectoryInfo_.NET 10.0.snap b/tests/TestableIO.System.IO.Abstractions.Parity.Tests/__snapshots__/ApiParityTests.DirectoryInfo_.NET 10.0.snap new file mode 100644 index 000000000..38f83a145 --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.Parity.Tests/__snapshots__/ApiParityTests.DirectoryInfo_.NET 10.0.snap @@ -0,0 +1,9 @@ +{ + "ExtraMembers": [], + "MissingMembers": [ + "System.Object GetLifetimeService()", + "System.Object InitializeLifetimeService()", + "Void .ctor(System.String)", + "Void GetObjectData(System.Runtime.Serialization.SerializationInfo, System.Runtime.Serialization.StreamingContext)" + ] +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.Parity.Tests/__snapshots__/ApiParityTests.DirectoryInfo_.NET 6.0.snap b/tests/TestableIO.System.IO.Abstractions.Parity.Tests/__snapshots__/ApiParityTests.DirectoryInfo_.NET 6.0.snap new file mode 100644 index 000000000..c986824b9 --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.Parity.Tests/__snapshots__/ApiParityTests.DirectoryInfo_.NET 6.0.snap @@ -0,0 +1,9 @@ +{ + "ExtraMembers": [], + "MissingMembers": [ + "System.Object GetLifetimeService()", + "System.Object InitializeLifetimeService()", + "Void .ctor(System.String)", + "Void GetObjectData(System.Runtime.Serialization.SerializationInfo, System.Runtime.Serialization.StreamingContext)" + ] +} diff --git a/tests/TestableIO.System.IO.Abstractions.Parity.Tests/__snapshots__/ApiParityTests.DirectoryInfo_.NET 8.0.snap b/tests/TestableIO.System.IO.Abstractions.Parity.Tests/__snapshots__/ApiParityTests.DirectoryInfo_.NET 8.0.snap new file mode 100644 index 000000000..c986824b9 --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.Parity.Tests/__snapshots__/ApiParityTests.DirectoryInfo_.NET 8.0.snap @@ -0,0 +1,9 @@ +{ + "ExtraMembers": [], + "MissingMembers": [ + "System.Object GetLifetimeService()", + "System.Object InitializeLifetimeService()", + "Void .ctor(System.String)", + "Void GetObjectData(System.Runtime.Serialization.SerializationInfo, System.Runtime.Serialization.StreamingContext)" + ] +} diff --git a/tests/TestableIO.System.IO.Abstractions.Parity.Tests/__snapshots__/ApiParityTests.DirectoryInfo_.NET 9.0.snap b/tests/TestableIO.System.IO.Abstractions.Parity.Tests/__snapshots__/ApiParityTests.DirectoryInfo_.NET 9.0.snap new file mode 100644 index 000000000..c986824b9 --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.Parity.Tests/__snapshots__/ApiParityTests.DirectoryInfo_.NET 9.0.snap @@ -0,0 +1,9 @@ +{ + "ExtraMembers": [], + "MissingMembers": [ + "System.Object GetLifetimeService()", + "System.Object InitializeLifetimeService()", + "Void .ctor(System.String)", + "Void GetObjectData(System.Runtime.Serialization.SerializationInfo, System.Runtime.Serialization.StreamingContext)" + ] +} diff --git a/tests/TestableIO.System.IO.Abstractions.Parity.Tests/__snapshots__/ApiParityTests.DirectoryInfo_.NET Framework 4.7.2.snap b/tests/TestableIO.System.IO.Abstractions.Parity.Tests/__snapshots__/ApiParityTests.DirectoryInfo_.NET Framework 4.7.2.snap new file mode 100644 index 000000000..ec21e0f76 --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.Parity.Tests/__snapshots__/ApiParityTests.DirectoryInfo_.NET Framework 4.7.2.snap @@ -0,0 +1,15 @@ +{ + "ExtraMembers": [], + "MissingMembers": [ + "System.IO.Abstractions.IDirectoryInfo CreateSubdirectory(System.String, System.Security.AccessControl.DirectorySecurity)", + "System.Object GetLifetimeService()", + "System.Object InitializeLifetimeService()", + "System.Runtime.Remoting.ObjRef CreateObjRef(System.Type)", + "System.Security.AccessControl.DirectorySecurity GetAccessControl()", + "System.Security.AccessControl.DirectorySecurity GetAccessControl(System.Security.AccessControl.AccessControlSections)", + "Void .ctor(System.String)", + "Void Create(System.Security.AccessControl.DirectorySecurity)", + "Void GetObjectData(System.Runtime.Serialization.SerializationInfo, System.Runtime.Serialization.StreamingContext)", + "Void SetAccessControl(System.Security.AccessControl.DirectorySecurity)" + ] +} diff --git a/tests/TestableIO.System.IO.Abstractions.Parity.Tests/__snapshots__/ApiParityTests.Directory_.NET 10.0.snap b/tests/TestableIO.System.IO.Abstractions.Parity.Tests/__snapshots__/ApiParityTests.Directory_.NET 10.0.snap new file mode 100644 index 000000000..e24afc2f5 --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.Parity.Tests/__snapshots__/ApiParityTests.Directory_.NET 10.0.snap @@ -0,0 +1,4 @@ +{ + "ExtraMembers": [], + "MissingMembers": [] +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.Parity.Tests/__snapshots__/ApiParityTests.Directory_.NET 6.0.snap b/tests/TestableIO.System.IO.Abstractions.Parity.Tests/__snapshots__/ApiParityTests.Directory_.NET 6.0.snap new file mode 100644 index 000000000..7cb3b9523 --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.Parity.Tests/__snapshots__/ApiParityTests.Directory_.NET 6.0.snap @@ -0,0 +1,4 @@ +{ + "ExtraMembers": [], + "MissingMembers": [] +} diff --git a/tests/TestableIO.System.IO.Abstractions.Parity.Tests/__snapshots__/ApiParityTests.Directory_.NET 8.0.snap b/tests/TestableIO.System.IO.Abstractions.Parity.Tests/__snapshots__/ApiParityTests.Directory_.NET 8.0.snap new file mode 100644 index 000000000..7cb3b9523 --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.Parity.Tests/__snapshots__/ApiParityTests.Directory_.NET 8.0.snap @@ -0,0 +1,4 @@ +{ + "ExtraMembers": [], + "MissingMembers": [] +} diff --git a/tests/TestableIO.System.IO.Abstractions.Parity.Tests/__snapshots__/ApiParityTests.Directory_.NET 9.0.snap b/tests/TestableIO.System.IO.Abstractions.Parity.Tests/__snapshots__/ApiParityTests.Directory_.NET 9.0.snap new file mode 100644 index 000000000..7cb3b9523 --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.Parity.Tests/__snapshots__/ApiParityTests.Directory_.NET 9.0.snap @@ -0,0 +1,4 @@ +{ + "ExtraMembers": [], + "MissingMembers": [] +} diff --git a/tests/TestableIO.System.IO.Abstractions.Parity.Tests/__snapshots__/ApiParityTests.Directory_.NET Framework 4.7.2.snap b/tests/TestableIO.System.IO.Abstractions.Parity.Tests/__snapshots__/ApiParityTests.Directory_.NET Framework 4.7.2.snap new file mode 100644 index 000000000..517bd1d06 --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.Parity.Tests/__snapshots__/ApiParityTests.Directory_.NET Framework 4.7.2.snap @@ -0,0 +1,9 @@ +{ + "ExtraMembers": [], + "MissingMembers": [ + "System.IO.Abstractions.IDirectoryInfo CreateDirectory(System.String, System.Security.AccessControl.DirectorySecurity)", + "System.Security.AccessControl.DirectorySecurity GetAccessControl(System.String)", + "System.Security.AccessControl.DirectorySecurity GetAccessControl(System.String, System.Security.AccessControl.AccessControlSections)", + "Void SetAccessControl(System.String, System.Security.AccessControl.DirectorySecurity)" + ] +} diff --git a/tests/TestableIO.System.IO.Abstractions.Parity.Tests/__snapshots__/ApiParityTests.DriveInfo_.NET 10.0.snap b/tests/TestableIO.System.IO.Abstractions.Parity.Tests/__snapshots__/ApiParityTests.DriveInfo_.NET 10.0.snap new file mode 100644 index 000000000..90d7c1c82 --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.Parity.Tests/__snapshots__/ApiParityTests.DriveInfo_.NET 10.0.snap @@ -0,0 +1,7 @@ +{ + "ExtraMembers": [], + "MissingMembers": [ + "System.IO.Abstractions.IDriveInfo[] GetDrives()", + "Void .ctor(System.String)" + ] +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.Parity.Tests/__snapshots__/ApiParityTests.DriveInfo_.NET 6.0.snap b/tests/TestableIO.System.IO.Abstractions.Parity.Tests/__snapshots__/ApiParityTests.DriveInfo_.NET 6.0.snap new file mode 100644 index 000000000..8c885b472 --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.Parity.Tests/__snapshots__/ApiParityTests.DriveInfo_.NET 6.0.snap @@ -0,0 +1,7 @@ +{ + "ExtraMembers": [], + "MissingMembers": [ + "System.IO.Abstractions.IDriveInfo[] GetDrives()", + "Void .ctor(System.String)" + ] +} diff --git a/tests/TestableIO.System.IO.Abstractions.Parity.Tests/__snapshots__/ApiParityTests.DriveInfo_.NET 8.0.snap b/tests/TestableIO.System.IO.Abstractions.Parity.Tests/__snapshots__/ApiParityTests.DriveInfo_.NET 8.0.snap new file mode 100644 index 000000000..8c885b472 --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.Parity.Tests/__snapshots__/ApiParityTests.DriveInfo_.NET 8.0.snap @@ -0,0 +1,7 @@ +{ + "ExtraMembers": [], + "MissingMembers": [ + "System.IO.Abstractions.IDriveInfo[] GetDrives()", + "Void .ctor(System.String)" + ] +} diff --git a/tests/TestableIO.System.IO.Abstractions.Parity.Tests/__snapshots__/ApiParityTests.DriveInfo_.NET 9.0.snap b/tests/TestableIO.System.IO.Abstractions.Parity.Tests/__snapshots__/ApiParityTests.DriveInfo_.NET 9.0.snap new file mode 100644 index 000000000..8c885b472 --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.Parity.Tests/__snapshots__/ApiParityTests.DriveInfo_.NET 9.0.snap @@ -0,0 +1,7 @@ +{ + "ExtraMembers": [], + "MissingMembers": [ + "System.IO.Abstractions.IDriveInfo[] GetDrives()", + "Void .ctor(System.String)" + ] +} diff --git a/tests/TestableIO.System.IO.Abstractions.Parity.Tests/__snapshots__/ApiParityTests.DriveInfo_.NET Framework 4.7.2.snap b/tests/TestableIO.System.IO.Abstractions.Parity.Tests/__snapshots__/ApiParityTests.DriveInfo_.NET Framework 4.7.2.snap new file mode 100644 index 000000000..8c885b472 --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.Parity.Tests/__snapshots__/ApiParityTests.DriveInfo_.NET Framework 4.7.2.snap @@ -0,0 +1,7 @@ +{ + "ExtraMembers": [], + "MissingMembers": [ + "System.IO.Abstractions.IDriveInfo[] GetDrives()", + "Void .ctor(System.String)" + ] +} diff --git a/tests/TestableIO.System.IO.Abstractions.Parity.Tests/__snapshots__/ApiParityTests.FileInfo_.NET 10.0.snap b/tests/TestableIO.System.IO.Abstractions.Parity.Tests/__snapshots__/ApiParityTests.FileInfo_.NET 10.0.snap new file mode 100644 index 000000000..38f83a145 --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.Parity.Tests/__snapshots__/ApiParityTests.FileInfo_.NET 10.0.snap @@ -0,0 +1,9 @@ +{ + "ExtraMembers": [], + "MissingMembers": [ + "System.Object GetLifetimeService()", + "System.Object InitializeLifetimeService()", + "Void .ctor(System.String)", + "Void GetObjectData(System.Runtime.Serialization.SerializationInfo, System.Runtime.Serialization.StreamingContext)" + ] +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.Parity.Tests/__snapshots__/ApiParityTests.FileInfo_.NET 6.0.snap b/tests/TestableIO.System.IO.Abstractions.Parity.Tests/__snapshots__/ApiParityTests.FileInfo_.NET 6.0.snap new file mode 100644 index 000000000..c986824b9 --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.Parity.Tests/__snapshots__/ApiParityTests.FileInfo_.NET 6.0.snap @@ -0,0 +1,9 @@ +{ + "ExtraMembers": [], + "MissingMembers": [ + "System.Object GetLifetimeService()", + "System.Object InitializeLifetimeService()", + "Void .ctor(System.String)", + "Void GetObjectData(System.Runtime.Serialization.SerializationInfo, System.Runtime.Serialization.StreamingContext)" + ] +} diff --git a/tests/TestableIO.System.IO.Abstractions.Parity.Tests/__snapshots__/ApiParityTests.FileInfo_.NET 8.0.snap b/tests/TestableIO.System.IO.Abstractions.Parity.Tests/__snapshots__/ApiParityTests.FileInfo_.NET 8.0.snap new file mode 100644 index 000000000..c986824b9 --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.Parity.Tests/__snapshots__/ApiParityTests.FileInfo_.NET 8.0.snap @@ -0,0 +1,9 @@ +{ + "ExtraMembers": [], + "MissingMembers": [ + "System.Object GetLifetimeService()", + "System.Object InitializeLifetimeService()", + "Void .ctor(System.String)", + "Void GetObjectData(System.Runtime.Serialization.SerializationInfo, System.Runtime.Serialization.StreamingContext)" + ] +} diff --git a/tests/TestableIO.System.IO.Abstractions.Parity.Tests/__snapshots__/ApiParityTests.FileInfo_.NET 9.0.snap b/tests/TestableIO.System.IO.Abstractions.Parity.Tests/__snapshots__/ApiParityTests.FileInfo_.NET 9.0.snap new file mode 100644 index 000000000..c986824b9 --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.Parity.Tests/__snapshots__/ApiParityTests.FileInfo_.NET 9.0.snap @@ -0,0 +1,9 @@ +{ + "ExtraMembers": [], + "MissingMembers": [ + "System.Object GetLifetimeService()", + "System.Object InitializeLifetimeService()", + "Void .ctor(System.String)", + "Void GetObjectData(System.Runtime.Serialization.SerializationInfo, System.Runtime.Serialization.StreamingContext)" + ] +} diff --git a/tests/TestableIO.System.IO.Abstractions.Parity.Tests/__snapshots__/ApiParityTests.FileInfo_.NET Framework 4.7.2.snap b/tests/TestableIO.System.IO.Abstractions.Parity.Tests/__snapshots__/ApiParityTests.FileInfo_.NET Framework 4.7.2.snap new file mode 100644 index 000000000..edd9281da --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.Parity.Tests/__snapshots__/ApiParityTests.FileInfo_.NET Framework 4.7.2.snap @@ -0,0 +1,13 @@ +{ + "ExtraMembers": [], + "MissingMembers": [ + "System.Object GetLifetimeService()", + "System.Object InitializeLifetimeService()", + "System.Runtime.Remoting.ObjRef CreateObjRef(System.Type)", + "System.Security.AccessControl.FileSecurity GetAccessControl()", + "System.Security.AccessControl.FileSecurity GetAccessControl(System.Security.AccessControl.AccessControlSections)", + "Void .ctor(System.String)", + "Void GetObjectData(System.Runtime.Serialization.SerializationInfo, System.Runtime.Serialization.StreamingContext)", + "Void SetAccessControl(System.Security.AccessControl.FileSecurity)" + ] +} diff --git a/tests/TestableIO.System.IO.Abstractions.Parity.Tests/__snapshots__/ApiParityTests.FileSystemWatcher_.NET 10.0.snap b/tests/TestableIO.System.IO.Abstractions.Parity.Tests/__snapshots__/ApiParityTests.FileSystemWatcher_.NET 10.0.snap new file mode 100644 index 000000000..ba0c953e8 --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.Parity.Tests/__snapshots__/ApiParityTests.FileSystemWatcher_.NET 10.0.snap @@ -0,0 +1,15 @@ +{ + "ExtraMembers": [ + "Void Dispose(Boolean)" + ], + "MissingMembers": [ + "System.EventHandler Disposed", + "System.Object GetLifetimeService()", + "System.Object InitializeLifetimeService()", + "Void .ctor()", + "Void .ctor(System.String)", + "Void .ctor(System.String, System.String)", + "Void add_Disposed(System.EventHandler)", + "Void remove_Disposed(System.EventHandler)" + ] +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.Parity.Tests/__snapshots__/ApiParityTests.FileSystemWatcher_.NET 6.0.snap b/tests/TestableIO.System.IO.Abstractions.Parity.Tests/__snapshots__/ApiParityTests.FileSystemWatcher_.NET 6.0.snap new file mode 100644 index 000000000..cfd946350 --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.Parity.Tests/__snapshots__/ApiParityTests.FileSystemWatcher_.NET 6.0.snap @@ -0,0 +1,15 @@ +{ + "ExtraMembers": [ + "Void Dispose(Boolean)" + ], + "MissingMembers": [ + "System.EventHandler Disposed", + "System.Object GetLifetimeService()", + "System.Object InitializeLifetimeService()", + "Void .ctor()", + "Void .ctor(System.String)", + "Void .ctor(System.String, System.String)", + "Void add_Disposed(System.EventHandler)", + "Void remove_Disposed(System.EventHandler)" + ] +} diff --git a/tests/TestableIO.System.IO.Abstractions.Parity.Tests/__snapshots__/ApiParityTests.FileSystemWatcher_.NET 8.0.snap b/tests/TestableIO.System.IO.Abstractions.Parity.Tests/__snapshots__/ApiParityTests.FileSystemWatcher_.NET 8.0.snap new file mode 100644 index 000000000..cfd946350 --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.Parity.Tests/__snapshots__/ApiParityTests.FileSystemWatcher_.NET 8.0.snap @@ -0,0 +1,15 @@ +{ + "ExtraMembers": [ + "Void Dispose(Boolean)" + ], + "MissingMembers": [ + "System.EventHandler Disposed", + "System.Object GetLifetimeService()", + "System.Object InitializeLifetimeService()", + "Void .ctor()", + "Void .ctor(System.String)", + "Void .ctor(System.String, System.String)", + "Void add_Disposed(System.EventHandler)", + "Void remove_Disposed(System.EventHandler)" + ] +} diff --git a/tests/TestableIO.System.IO.Abstractions.Parity.Tests/__snapshots__/ApiParityTests.FileSystemWatcher_.NET 9.0.snap b/tests/TestableIO.System.IO.Abstractions.Parity.Tests/__snapshots__/ApiParityTests.FileSystemWatcher_.NET 9.0.snap new file mode 100644 index 000000000..cfd946350 --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.Parity.Tests/__snapshots__/ApiParityTests.FileSystemWatcher_.NET 9.0.snap @@ -0,0 +1,15 @@ +{ + "ExtraMembers": [ + "Void Dispose(Boolean)" + ], + "MissingMembers": [ + "System.EventHandler Disposed", + "System.Object GetLifetimeService()", + "System.Object InitializeLifetimeService()", + "Void .ctor()", + "Void .ctor(System.String)", + "Void .ctor(System.String, System.String)", + "Void add_Disposed(System.EventHandler)", + "Void remove_Disposed(System.EventHandler)" + ] +} diff --git a/tests/TestableIO.System.IO.Abstractions.Parity.Tests/__snapshots__/ApiParityTests.FileSystemWatcher_.NET Framework 4.7.2.snap b/tests/TestableIO.System.IO.Abstractions.Parity.Tests/__snapshots__/ApiParityTests.FileSystemWatcher_.NET Framework 4.7.2.snap new file mode 100644 index 000000000..e2c85b146 --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.Parity.Tests/__snapshots__/ApiParityTests.FileSystemWatcher_.NET Framework 4.7.2.snap @@ -0,0 +1,16 @@ +{ + "ExtraMembers": [ + "Void Dispose(Boolean)" + ], + "MissingMembers": [ + "System.EventHandler Disposed", + "System.Object GetLifetimeService()", + "System.Object InitializeLifetimeService()", + "System.Runtime.Remoting.ObjRef CreateObjRef(System.Type)", + "Void .ctor()", + "Void .ctor(System.String)", + "Void .ctor(System.String, System.String)", + "Void add_Disposed(System.EventHandler)", + "Void remove_Disposed(System.EventHandler)" + ] +} diff --git a/tests/TestableIO.System.IO.Abstractions.Parity.Tests/__snapshots__/ApiParityTests.FileVersionInfo_.NET 10.0.snap b/tests/TestableIO.System.IO.Abstractions.Parity.Tests/__snapshots__/ApiParityTests.FileVersionInfo_.NET 10.0.snap new file mode 100644 index 000000000..e24afc2f5 --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.Parity.Tests/__snapshots__/ApiParityTests.FileVersionInfo_.NET 10.0.snap @@ -0,0 +1,4 @@ +{ + "ExtraMembers": [], + "MissingMembers": [] +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.Parity.Tests/__snapshots__/ApiParityTests.FileVersionInfo_.NET 6.0.snap b/tests/TestableIO.System.IO.Abstractions.Parity.Tests/__snapshots__/ApiParityTests.FileVersionInfo_.NET 6.0.snap new file mode 100644 index 000000000..7cb3b9523 --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.Parity.Tests/__snapshots__/ApiParityTests.FileVersionInfo_.NET 6.0.snap @@ -0,0 +1,4 @@ +{ + "ExtraMembers": [], + "MissingMembers": [] +} diff --git a/tests/TestableIO.System.IO.Abstractions.Parity.Tests/__snapshots__/ApiParityTests.FileVersionInfo_.NET 8.0.snap b/tests/TestableIO.System.IO.Abstractions.Parity.Tests/__snapshots__/ApiParityTests.FileVersionInfo_.NET 8.0.snap new file mode 100644 index 000000000..7cb3b9523 --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.Parity.Tests/__snapshots__/ApiParityTests.FileVersionInfo_.NET 8.0.snap @@ -0,0 +1,4 @@ +{ + "ExtraMembers": [], + "MissingMembers": [] +} diff --git a/tests/TestableIO.System.IO.Abstractions.Parity.Tests/__snapshots__/ApiParityTests.FileVersionInfo_.NET 9.0.snap b/tests/TestableIO.System.IO.Abstractions.Parity.Tests/__snapshots__/ApiParityTests.FileVersionInfo_.NET 9.0.snap new file mode 100644 index 000000000..7cb3b9523 --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.Parity.Tests/__snapshots__/ApiParityTests.FileVersionInfo_.NET 9.0.snap @@ -0,0 +1,4 @@ +{ + "ExtraMembers": [], + "MissingMembers": [] +} diff --git a/tests/TestableIO.System.IO.Abstractions.Parity.Tests/__snapshots__/ApiParityTests.FileVersionInfo_.NET Framework 4.7.2.snap b/tests/TestableIO.System.IO.Abstractions.Parity.Tests/__snapshots__/ApiParityTests.FileVersionInfo_.NET Framework 4.7.2.snap new file mode 100644 index 000000000..7cb3b9523 --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.Parity.Tests/__snapshots__/ApiParityTests.FileVersionInfo_.NET Framework 4.7.2.snap @@ -0,0 +1,4 @@ +{ + "ExtraMembers": [], + "MissingMembers": [] +} diff --git a/tests/TestableIO.System.IO.Abstractions.Parity.Tests/__snapshots__/ApiParityTests.File_.NET 10.0.snap b/tests/TestableIO.System.IO.Abstractions.Parity.Tests/__snapshots__/ApiParityTests.File_.NET 10.0.snap new file mode 100644 index 000000000..5387b9a98 --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.Parity.Tests/__snapshots__/ApiParityTests.File_.NET 10.0.snap @@ -0,0 +1,6 @@ +{ + "ExtraMembers": [], + "MissingMembers": [ + "Microsoft.Win32.SafeHandles.SafeFileHandle OpenHandle(System.String, System.IO.FileMode, System.IO.FileAccess, System.IO.FileShare, System.IO.FileOptions, Int64)" + ] +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.Parity.Tests/__snapshots__/ApiParityTests.File_.NET 6.0.snap b/tests/TestableIO.System.IO.Abstractions.Parity.Tests/__snapshots__/ApiParityTests.File_.NET 6.0.snap new file mode 100644 index 000000000..ce42363ab --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.Parity.Tests/__snapshots__/ApiParityTests.File_.NET 6.0.snap @@ -0,0 +1,6 @@ +{ + "ExtraMembers": [], + "MissingMembers": [ + "Microsoft.Win32.SafeHandles.SafeFileHandle OpenHandle(System.String, System.IO.FileMode, System.IO.FileAccess, System.IO.FileShare, System.IO.FileOptions, Int64)" + ] +} diff --git a/tests/TestableIO.System.IO.Abstractions.Parity.Tests/__snapshots__/ApiParityTests.File_.NET 8.0.snap b/tests/TestableIO.System.IO.Abstractions.Parity.Tests/__snapshots__/ApiParityTests.File_.NET 8.0.snap new file mode 100644 index 000000000..ce42363ab --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.Parity.Tests/__snapshots__/ApiParityTests.File_.NET 8.0.snap @@ -0,0 +1,6 @@ +{ + "ExtraMembers": [], + "MissingMembers": [ + "Microsoft.Win32.SafeHandles.SafeFileHandle OpenHandle(System.String, System.IO.FileMode, System.IO.FileAccess, System.IO.FileShare, System.IO.FileOptions, Int64)" + ] +} diff --git a/tests/TestableIO.System.IO.Abstractions.Parity.Tests/__snapshots__/ApiParityTests.File_.NET 9.0.snap b/tests/TestableIO.System.IO.Abstractions.Parity.Tests/__snapshots__/ApiParityTests.File_.NET 9.0.snap new file mode 100644 index 000000000..ce42363ab --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.Parity.Tests/__snapshots__/ApiParityTests.File_.NET 9.0.snap @@ -0,0 +1,6 @@ +{ + "ExtraMembers": [], + "MissingMembers": [ + "Microsoft.Win32.SafeHandles.SafeFileHandle OpenHandle(System.String, System.IO.FileMode, System.IO.FileAccess, System.IO.FileShare, System.IO.FileOptions, Int64)" + ] +} diff --git a/tests/TestableIO.System.IO.Abstractions.Parity.Tests/__snapshots__/ApiParityTests.File_.NET Framework 4.7.2.snap b/tests/TestableIO.System.IO.Abstractions.Parity.Tests/__snapshots__/ApiParityTests.File_.NET Framework 4.7.2.snap new file mode 100644 index 000000000..2e2ed8e14 --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.Parity.Tests/__snapshots__/ApiParityTests.File_.NET Framework 4.7.2.snap @@ -0,0 +1,9 @@ +{ + "ExtraMembers": [], + "MissingMembers": [ + "System.IO.Abstractions.FileSystemStream Create(System.String, Int32, System.IO.FileOptions, System.Security.AccessControl.FileSecurity)", + "System.Security.AccessControl.FileSecurity GetAccessControl(System.String)", + "System.Security.AccessControl.FileSecurity GetAccessControl(System.String, System.Security.AccessControl.AccessControlSections)", + "Void SetAccessControl(System.String, System.Security.AccessControl.FileSecurity)" + ] +} diff --git a/tests/TestableIO.System.IO.Abstractions.Parity.Tests/__snapshots__/ApiParityTests.Path_.NET 10.0.snap b/tests/TestableIO.System.IO.Abstractions.Parity.Tests/__snapshots__/ApiParityTests.Path_.NET 10.0.snap new file mode 100644 index 000000000..ea45cb355 --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.Parity.Tests/__snapshots__/ApiParityTests.Path_.NET 10.0.snap @@ -0,0 +1,10 @@ +{ + "ExtraMembers": [ + "Char get_AltDirectorySeparatorChar()", + "Char get_DirectorySeparatorChar()", + "Char get_PathSeparator()", + "Char get_VolumeSeparatorChar()", + "Char[] get_InvalidPathChars()" + ], + "MissingMembers": [] +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.Parity.Tests/__snapshots__/ApiParityTests.Path_.NET 6.0.snap b/tests/TestableIO.System.IO.Abstractions.Parity.Tests/__snapshots__/ApiParityTests.Path_.NET 6.0.snap new file mode 100644 index 000000000..d83d023ac --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.Parity.Tests/__snapshots__/ApiParityTests.Path_.NET 6.0.snap @@ -0,0 +1,10 @@ +{ + "ExtraMembers": [ + "Char get_AltDirectorySeparatorChar()", + "Char get_DirectorySeparatorChar()", + "Char get_PathSeparator()", + "Char get_VolumeSeparatorChar()", + "Char[] get_InvalidPathChars()" + ], + "MissingMembers": [] +} diff --git a/tests/TestableIO.System.IO.Abstractions.Parity.Tests/__snapshots__/ApiParityTests.Path_.NET 8.0.snap b/tests/TestableIO.System.IO.Abstractions.Parity.Tests/__snapshots__/ApiParityTests.Path_.NET 8.0.snap new file mode 100644 index 000000000..d83d023ac --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.Parity.Tests/__snapshots__/ApiParityTests.Path_.NET 8.0.snap @@ -0,0 +1,10 @@ +{ + "ExtraMembers": [ + "Char get_AltDirectorySeparatorChar()", + "Char get_DirectorySeparatorChar()", + "Char get_PathSeparator()", + "Char get_VolumeSeparatorChar()", + "Char[] get_InvalidPathChars()" + ], + "MissingMembers": [] +} diff --git a/tests/TestableIO.System.IO.Abstractions.Parity.Tests/__snapshots__/ApiParityTests.Path_.NET 9.0.snap b/tests/TestableIO.System.IO.Abstractions.Parity.Tests/__snapshots__/ApiParityTests.Path_.NET 9.0.snap new file mode 100644 index 000000000..d83d023ac --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.Parity.Tests/__snapshots__/ApiParityTests.Path_.NET 9.0.snap @@ -0,0 +1,10 @@ +{ + "ExtraMembers": [ + "Char get_AltDirectorySeparatorChar()", + "Char get_DirectorySeparatorChar()", + "Char get_PathSeparator()", + "Char get_VolumeSeparatorChar()", + "Char[] get_InvalidPathChars()" + ], + "MissingMembers": [] +} diff --git a/tests/TestableIO.System.IO.Abstractions.Parity.Tests/__snapshots__/ApiParityTests.Path_.NET Framework 4.7.2.snap b/tests/TestableIO.System.IO.Abstractions.Parity.Tests/__snapshots__/ApiParityTests.Path_.NET Framework 4.7.2.snap new file mode 100644 index 000000000..d83d023ac --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.Parity.Tests/__snapshots__/ApiParityTests.Path_.NET Framework 4.7.2.snap @@ -0,0 +1,10 @@ +{ + "ExtraMembers": [ + "Char get_AltDirectorySeparatorChar()", + "Char get_DirectorySeparatorChar()", + "Char get_PathSeparator()", + "Char get_VolumeSeparatorChar()", + "Char[] get_InvalidPathChars()" + ], + "MissingMembers": [] +} diff --git a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockDirectoryArgumentPathTests.cs b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockDirectoryArgumentPathTests.cs new file mode 100644 index 000000000..6865f153c --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockDirectoryArgumentPathTests.cs @@ -0,0 +1,44 @@ +using System.Collections.Generic; +using System.Security.AccessControl; +using NUnit.Framework; + +namespace System.IO.Abstractions.TestingHelpers.Tests; + +public class MockDirectoryArgumentPathTests +{ + private static IEnumerable> GetFileSystemActionsForArgumentNullException() + { + yield return ds => ds.Delete(null); + yield return ds => ds.Delete(null, true); + yield return ds => ds.CreateDirectory(null); + if (MockUnixSupport.IsWindowsPlatform()) + { +#pragma warning disable CA1416 + yield return ds => ds.CreateDirectory(null, new DirectorySecurity()); +#pragma warning restore CA1416 + } + yield return ds => ds.SetCreationTime(null, DateTime.Now); + yield return ds => ds.SetCreationTimeUtc(null, DateTime.Now); + yield return ds => ds.SetLastAccessTime(null, DateTime.Now); + yield return ds => ds.SetLastAccessTimeUtc(null, DateTime.Now); + yield return ds => ds.SetLastWriteTime(null, DateTime.Now); + yield return ds => ds.SetLastWriteTimeUtc(null, DateTime.Now); + yield return ds => ds.EnumerateDirectories(null); + yield return ds => ds.EnumerateDirectories(null, "foo"); + yield return ds => ds.EnumerateDirectories(null, "foo", SearchOption.AllDirectories); + } + + [TestCaseSource(nameof(GetFileSystemActionsForArgumentNullException))] + public async Task Operations_ShouldThrowArgumentNullExceptionIfPathIsNull(Action action) + { + // Arrange + var fileSystem = new MockFileSystem(); + + // Act + Action wrapped = () => action(fileSystem.Directory); + + // Assert + var exception = await That(wrapped).Throws(); + await That(exception.ParamName).IsEqualTo("path"); + } +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockDirectoryGetAccessControlTests.cs b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockDirectoryGetAccessControlTests.cs new file mode 100644 index 000000000..5e6d1724f --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockDirectoryGetAccessControlTests.cs @@ -0,0 +1,67 @@ +using NUnit.Framework; +using System.Collections.Generic; +using System.Security.AccessControl; +using System.Runtime.Versioning; + +namespace System.IO.Abstractions.TestingHelpers.Tests; + +using XFS = MockUnixSupport; +[TestFixture] +[WindowsOnly(WindowsSpecifics.AccessControlLists)] +[SupportedOSPlatform("windows")] +public class MockDirectoryGetAccessControlTests +{ + [TestCase(" ")] + [TestCase(" ")] + public async Task MockDirectory_GetAccessControl_ShouldThrowArgumentExceptionIfPathContainsOnlyWhitespaces(string path) + { + // Arrange + var fileSystem = new MockFileSystem(); + + // Act + Action action = () => fileSystem.Directory.GetAccessControl(path); + + // Assert + var exception = await That(action).Throws(); + await That(exception.ParamName).IsEqualTo("path"); + } + + [Test] + public async Task MockDirectory_GetAccessControl_ShouldThrowDirectoryNotFoundExceptionIfDirectoryDoesNotExistInMockData() + { + // Arrange + var fileSystem = new MockFileSystem(); + var expectedDirectoryName = XFS.Path(@"c:\a"); + + // Act + Action action = () => fileSystem.Directory.GetAccessControl(expectedDirectoryName); + + // Assert + await That(action).Throws(); + } + + [Test] + public async Task MockDirectory_GetAccessControl_ShouldReturnAccessControlOfDirectoryData() + { + // Arrange + var expectedDirectorySecurity = new DirectorySecurity(); + expectedDirectorySecurity.SetAccessRuleProtection(false, false); + + var filePath = XFS.Path(@"c:\a\"); + var fileData = new MockDirectoryData() + { + AccessControl = expectedDirectorySecurity, + }; + + var fileSystem = new MockFileSystem(new Dictionary() + { + { filePath, fileData } + }); + + // Act + var directorySecurity = fileSystem.Directory.GetAccessControl(filePath); + + // Assert + await That(directorySecurity).IsEqualTo(expectedDirectorySecurity); + } +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockDirectoryInfoAccessControlTests.cs b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockDirectoryInfoAccessControlTests.cs new file mode 100644 index 000000000..f76169d47 --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockDirectoryInfoAccessControlTests.cs @@ -0,0 +1,64 @@ +using NUnit.Framework; +using System.Collections.Generic; +using System.Runtime.Versioning; +using System.Security.AccessControl; +using XFS = System.IO.Abstractions.TestingHelpers.MockUnixSupport; + +namespace System.IO.Abstractions.TestingHelpers.Tests; + +[TestFixture] +[WindowsOnly(WindowsSpecifics.AccessControlLists)] +[SupportedOSPlatform("windows")] +public class MockDirectoryInfoAccessControlTests +{ + [Test] + public async Task MockDirectoryInfo_GetAccessControl_ShouldReturnAccessControlOfDirectoryData() + { + // Arrange + var expectedDirectorySecurity = new DirectorySecurity(); + expectedDirectorySecurity.SetAccessRuleProtection(false, false); + + var filePath = XFS.Path(@"c:\a\"); + var fileData = new MockDirectoryData() + { + AccessControl = expectedDirectorySecurity, + }; + + var fileSystem = new MockFileSystem(new Dictionary() + { + { filePath, fileData } + }); + + var directorInfo = fileSystem.DirectoryInfo.New(filePath); + + // Act + var directorySecurity = directorInfo.GetAccessControl(); + + // Assert + await That(directorySecurity).IsEqualTo(expectedDirectorySecurity); + } + + [Test] + public async Task MockDirectoryInfo_SetAccessControl_ShouldSetAccessControlOfDirectoryData() + { + // Arrange + var filePath = XFS.Path(@"c:\a\"); + var fileData = new MockDirectoryData(); + + var fileSystem = new MockFileSystem(new Dictionary() + { + { filePath, fileData } + }); + + var directorInfo = fileSystem.DirectoryInfo.New(filePath); + + // Act + var expectedAccessControl = new DirectorySecurity(); + expectedAccessControl.SetAccessRuleProtection(false, false); + directorInfo.SetAccessControl(expectedAccessControl); + + // Assert + var accessControl = directorInfo.GetAccessControl(); + await That(accessControl).IsEqualTo(expectedAccessControl); + } +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockDirectoryInfoFactoryTests.cs b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockDirectoryInfoFactoryTests.cs new file mode 100644 index 000000000..58a3aa9ae --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockDirectoryInfoFactoryTests.cs @@ -0,0 +1,28 @@ +using NUnit.Framework; + +namespace System.IO.Abstractions.TestingHelpers.Tests; + +[TestFixture] +public class MockDirectoryInfoFactoryTests +{ + [Test] + public async Task MockDirectoryInfoFactory_Wrap_WithNull_ShouldReturnNull() + { + var fileSystem = new MockFileSystem(); + + var result = fileSystem.DirectoryInfo.Wrap(null); + + await That(result).IsNull(); + } + + [Test] + public async Task MockDirectoryInfoFactory_Wrap_ShouldKeepNameAndFullName() + { + var fs = new MockFileSystem(); + var directoryInfo = new DirectoryInfo(@"C:\subfolder\file"); + var wrappedDirectoryInfo = fs.DirectoryInfo.Wrap(directoryInfo); + + await That(wrappedDirectoryInfo.FullName).IsEqualTo(directoryInfo.FullName); + await That(wrappedDirectoryInfo.Name).IsEqualTo(directoryInfo.Name); + } +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockDirectoryInfoSymlinkTests.cs b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockDirectoryInfoSymlinkTests.cs new file mode 100644 index 000000000..c54dfe471 --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockDirectoryInfoSymlinkTests.cs @@ -0,0 +1,68 @@ +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Versioning; +using System.Security.AccessControl; +using NUnit.Framework; + +namespace System.IO.Abstractions.TestingHelpers.Tests; + +using XFS = MockUnixSupport; + +[TestFixture] +public class MockDirectoryInfoSymlinkTests +{ + +#if FEATURE_CREATE_SYMBOLIC_LINK + + [Test] + public async Task MockDirectoryInfo_ResolveLinkTarget_ShouldReturnPathOfTargetLink() + { + var fileSystem = new MockFileSystem(); + fileSystem.Directory.CreateDirectory("bar"); + fileSystem.Directory.CreateSymbolicLink("foo", "bar"); + + var result = fileSystem.DirectoryInfo.New("foo").ResolveLinkTarget(false); + + await That(result.Name).IsEqualTo("bar"); + } + + [Test] + public async Task MockDirectoryInfo_ResolveLinkTarget_WithFinalTarget_ShouldReturnPathOfTargetLink() + { + var fileSystem = new MockFileSystem(); + fileSystem.Directory.CreateDirectory("bar"); + fileSystem.Directory.CreateSymbolicLink("foo", "bar"); + fileSystem.Directory.CreateSymbolicLink("foo1", "foo"); + + var result = fileSystem.DirectoryInfo.New("foo1").ResolveLinkTarget(true); + + await That(result.Name).IsEqualTo("bar"); + } + + [Test] + public async Task MockDirectoryInfo_ResolveLinkTarget_WithoutFinalTarget_ShouldReturnFirstLink() + { + var fileSystem = new MockFileSystem(); + fileSystem.Directory.CreateDirectory("bar"); + fileSystem.Directory.CreateSymbolicLink("foo", "bar"); + fileSystem.Directory.CreateSymbolicLink("foo1", "foo"); + + var result = fileSystem.DirectoryInfo.New("foo1").ResolveLinkTarget(false); + + await That(result.Name).IsEqualTo("foo"); + } + + [Test] + public async Task MockDirectoryInfo_ResolveLinkTarget_WithoutTargetLink_ShouldThrowIOException() + { + var fileSystem = new MockFileSystem(); + fileSystem.Directory.CreateDirectory("bar"); + fileSystem.Directory.CreateSymbolicLink("foo", "bar"); + + await That(() => + { + fileSystem.DirectoryInfo.New("bar").ResolveLinkTarget(false); + }).Throws(); + } +#endif +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockDirectoryInfoTests.cs b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockDirectoryInfoTests.cs new file mode 100644 index 000000000..bed4d6702 --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockDirectoryInfoTests.cs @@ -0,0 +1,724 @@ +using System.Collections.Generic; +using System.Linq; +using System.Security.AccessControl; +using NUnit.Framework; + +namespace System.IO.Abstractions.TestingHelpers.Tests; + +using XFS = MockUnixSupport; + +[TestFixture] +public class MockDirectoryInfoTests +{ + public static IEnumerable MockDirectoryInfo_GetExtension_Cases + { + get + { + yield return new object[] { XFS.Path(@"c:\temp") }; + yield return new object[] { XFS.Path(@"c:\temp\") }; + } + } + + [TestCaseSource(nameof(MockDirectoryInfo_GetExtension_Cases))] + public async Task MockDirectoryInfo_GetExtension_ShouldReturnEmptyString(string directoryPath) + { + // Arrange + var fileSystem = new MockFileSystem(new Dictionary()); + var directoryInfo = new MockDirectoryInfo(fileSystem, directoryPath); + + // Act + var result = directoryInfo.Extension; + + // Assert + await That(result).IsEmpty(); + } + + public static IEnumerable MockDirectoryInfo_Exists_Cases + { + get + { + yield return new object[] { XFS.Path(@"c:\temp\folder"), true }; + yield return new object[] { XFS.Path(@"c:\temp\folder\notExistant"), false }; + } + } + + [TestCaseSource(nameof(MockDirectoryInfo_Exists_Cases))] + public async Task MockDirectoryInfo_Exists(string path, bool expected) + { + var fileSystem = new MockFileSystem(new Dictionary + { + {XFS.Path(@"c:\temp\folder\file.txt"), new MockFileData("Hello World")} + }); + var directoryInfo = new MockDirectoryInfo(fileSystem, path); + + var result = directoryInfo.Exists; + + await That(result).IsEqualTo(expected); + } + + [Test] + public async Task MockDirectoryInfo_Attributes_ShouldReturnMinusOneForNonExistingFile() + { + var fileSystem = new MockFileSystem(); + var directoryInfo = new MockDirectoryInfo(fileSystem, XFS.Path(@"c:\non\existing\file.txt")); + FileAttributes expected = (FileAttributes)(-1); + + await That(directoryInfo.Attributes).IsEqualTo(expected); + } + + [Test] + public async Task MockDirectoryInfo_Attributes_Clear_ShouldRemainDirectory() + { + var fileSystem = new MockFileSystem(); + var path = XFS.Path(@"c:\existing\directory"); + fileSystem.Directory.CreateDirectory(path); + var directoryInfo = fileSystem.DirectoryInfo.New(path); + directoryInfo.Attributes = 0; + + await That(fileSystem.File.Exists(path)).IsFalse(); + await That(directoryInfo.Attributes).IsEqualTo(FileAttributes.Directory); + } + + [Test] + public async Task MockDirectoryInfo_Attributes_SetterShouldThrowDirectoryNotFoundExceptionOnNonExistingFileOrDirectory() + { + var fileSystem = new MockFileSystem(); + var directoryInfo = new MockDirectoryInfo(fileSystem, XFS.Path(@"c:\non\existing")); + + await That(() => directoryInfo.Attributes = FileAttributes.Hidden).Throws(); + } + + [Test] + [WindowsOnly(WindowsSpecifics.UNCPaths)] + public async Task MockDirectoryInfo_GetFiles_ShouldWorkWithUNCPath() + { + var fileName = XFS.Path(@"\\unc\folder\file.txt"); + var directoryName = XFS.Path(@"\\unc\folder"); + // Arrange + var fileSystem = new MockFileSystem(new Dictionary + { + {fileName, ""} + }); + + var directoryInfo = new MockDirectoryInfo(fileSystem, directoryName); + + // Act + var files = directoryInfo.GetFiles(); + + // Assert + await That(files[0].FullName).IsEqualTo(fileName); + } + + [Test] + [WindowsOnly(WindowsSpecifics.UNCPaths)] + public async Task MockDirectoryInfo_GetFiles_ShouldWorkWithUNCPath_WhenCurrentDirectoryIsUnc() + { + var fileName = XFS.Path(@"\\unc\folder\file.txt"); + var directoryName = XFS.Path(@"\\unc\folder"); + // Arrange + var fileSystem = new MockFileSystem(new Dictionary + { + {fileName, ""} + }); + + fileSystem.Directory.SetCurrentDirectory(directoryName); + + var directoryInfo = new MockDirectoryInfo(fileSystem, directoryName); + + // Act + var files = directoryInfo.GetFiles(); + + // Assert + await That(files[0].FullName).IsEqualTo(fileName); + } + + [Test] + public async Task MockDirectoryInfo_FullName_ShouldReturnFullNameWithoutIncludingTrailingPathDelimiter() + { + var fileSystem = new MockFileSystem(new Dictionary + { + { + XFS.Path(@"c:\temp\folder\file.txt"), + new MockFileData("Hello World") + } + }); + var directoryInfo = new MockDirectoryInfo(fileSystem, XFS.Path(@"c:\temp\folder")); + + var result = directoryInfo.FullName; + + await That(result).IsEqualTo(XFS.Path(@"c:\temp\folder")); + } + + [Test] + public async Task MockDirectoryInfo_GetFileSystemInfos_ShouldReturnBothDirectoriesAndFiles() + { + var fileSystem = new MockFileSystem(new Dictionary + { + { XFS.Path(@"c:\temp\folder\file.txt"), new MockFileData("Hello World") }, + { XFS.Path(@"c:\temp\folder\folder"), new MockDirectoryData() } + }); + + var directoryInfo = new MockDirectoryInfo(fileSystem, XFS.Path(@"c:\temp\folder")); + var result = directoryInfo.GetFileSystemInfos(); + + await That(result.Length).IsEqualTo(2); + } + + [Test] + public async Task MockDirectoryInfo_EnumerateFileSystemInfos_ShouldReturnBothDirectoriesAndFiles() + { + var fileSystem = new MockFileSystem(new Dictionary + { + { XFS.Path(@"c:\temp\folder\file.txt"), new MockFileData("Hello World") }, + { XFS.Path(@"c:\temp\folder\folder"), new MockDirectoryData() } + }); + + var directoryInfo = new MockDirectoryInfo(fileSystem, XFS.Path(@"c:\temp\folder")); + var result = directoryInfo.EnumerateFileSystemInfos().ToArray(); + + await That(result.Length).IsEqualTo(2); + } + + [Test] + public async Task MockDirectoryInfo_GetFileSystemInfos_ShouldReturnDirectoriesAndNamesWithSearchPattern() + { + var fileSystem = new MockFileSystem(new Dictionary + { + { XFS.Path(@"c:\temp\folder\file.txt"), new MockFileData("Hello World") }, + { XFS.Path(@"c:\temp\folder\folder"), new MockDirectoryData() }, + { XFS.Path(@"c:\temp\folder\older"), new MockDirectoryData() } + }); + + var directoryInfo = new MockDirectoryInfo(fileSystem, XFS.Path(@"c:\temp\folder")); + var result = directoryInfo.GetFileSystemInfos("f*"); + + await That(result.Length).IsEqualTo(2); + } + + [Test] + public async Task MockDirectoryInfo_EnumerateFileSystemInfos_ShouldReturnDirectoriesAndNamesWithSearchPattern() + { + var fileSystem = new MockFileSystem(new Dictionary + { + { XFS.Path(@"c:\temp\folder\file.txt"), new MockFileData("Hello World") }, + { XFS.Path(@"c:\temp\folder\folder"), new MockDirectoryData() }, + { XFS.Path(@"c:\temp\folder\older"), new MockDirectoryData() } + }); + + var directoryInfo = new MockDirectoryInfo(fileSystem, XFS.Path(@"c:\temp\folder")); + var result = directoryInfo.EnumerateFileSystemInfos("f*", SearchOption.AllDirectories).ToArray(); + + await That(result.Length).IsEqualTo(2); + } + + [Test] + public async Task MockDirectoryInfo_EnumerateFileSystemInfos_ShouldReturnDirectoriesAndNamesWithSearchPatternRecursive() + { + var fileSystem = new MockFileSystem(new Dictionary + { + { XFS.Path(@"c:\temp\folder\file.txt"), new MockFileData("") }, + { XFS.Path(@"c:\temp\folder\folder"), new MockDirectoryData() }, + { XFS.Path(@"c:\temp\folder\older"), new MockDirectoryData() } + }); + + var directoryInfo = new MockDirectoryInfo(fileSystem, XFS.Path(@"c:\")); + var result = directoryInfo.EnumerateFileSystemInfos("*", SearchOption.AllDirectories).ToArray(); + + await That(result.Length).IsEqualTo(5); + } + +#if FEATURE_ENUMERATION_OPTIONS + [Test] + public async Task MockDirectoryInfo_EnumerateFileSystemInfos_ShouldReturnDirectoriesAndNamesWithSearchPatternRecursiveEnumerateOptions() + { + var fileSystem = new MockFileSystem(new Dictionary + { + { XFS.Path(@"c:\temp\folder\file.txt"), new MockFileData("") }, + { XFS.Path(@"c:\temp\folder\folder"), new MockDirectoryData() }, + { XFS.Path(@"c:\temp\folder\older"), new MockDirectoryData() } + }); + + var directoryInfo = new MockDirectoryInfo(fileSystem, XFS.Path(@"c:\")); + + var enumerationOptions = new EnumerationOptions() + { + RecurseSubdirectories = true, + }; + + var result = directoryInfo.EnumerateFileSystemInfos("*", enumerationOptions).ToArray(); + + await That(result.Length).IsEqualTo(5); + } +#endif + + [Test] + public async Task MockDirectoryInfo_GetParent_ShouldReturnDirectoriesAndNamesWithSearchPattern() + { + // Arrange + var fileSystem = new MockFileSystem(); + fileSystem.AddDirectory(XFS.Path(@"c:\a\b\c")); + var directoryInfo = new MockDirectoryInfo(fileSystem, XFS.Path(@"c:\a\b\c")); + + // Act + var result = directoryInfo.Parent; + + // Assert + await That(result.FullName).IsEqualTo(XFS.Path(@"c:\a\b")); + } + + [Test] + public async Task MockDirectoryInfo_EnumerateFiles_ShouldReturnAllFiles() + { + // Arrange + var fileSystem = new MockFileSystem(new Dictionary + { + //Files "above" in folder we're querying + { XFS.Path(@"c:\temp\a.txt"), "" }, + + //Files in the folder we're querying + { XFS.Path(@"c:\temp\folder\b.txt"), "" }, + { XFS.Path(@"c:\temp\folder\c.txt"), "" }, + + //Files "below" the folder we're querying + { XFS.Path(@"c:\temp\folder\deeper\d.txt"), "" } + }); + + // Act + var directoryInfo = new MockDirectoryInfo(fileSystem, XFS.Path(@"c:\temp\folder")); + + // Assert + await That(directoryInfo.EnumerateFiles().ToList().Select(x => x.Name).ToArray()).IsEqualTo(new[] { "b.txt", "c.txt" }); + } + + [Test] + public async Task MockDirectoryInfo_EnumerateDirectories_ShouldReturnAllDirectories() + { + // Arrange + var fileSystem = new MockFileSystem(new Dictionary + { + //A file we want to ignore entirely + { XFS.Path(@"c:\temp\folder\a.txt"), "" }, + + //Some files in sub folders (which we also want to ignore entirely) + { XFS.Path(@"c:\temp\folder\b\file.txt"), "" }, + { XFS.Path(@"c:\temp\folder\c\other.txt"), "" }, + }); + var directoryInfo = new MockDirectoryInfo(fileSystem, XFS.Path(@"c:\temp\folder")); + + // Act + var directories = directoryInfo.EnumerateDirectories().Select(a => a.Name).ToArray(); + + // Assert + await That(directories).IsEqualTo(new[] { "b", "c" }); + } + + [TestCase(@"\\unc\folder", @"\\unc\folder")] + [TestCase(@"\\unc/folder\\foo", @"\\unc\folder\foo")] + [WindowsOnly(WindowsSpecifics.UNCPaths)] + public async Task MockDirectoryInfo_FullName_ShouldReturnNormalizedUNCPath(string directoryPath, string expectedFullName) + { + // Arrange + directoryPath = XFS.Path(directoryPath); + expectedFullName = XFS.Path(expectedFullName); + var fileSystem = new MockFileSystem(new Dictionary()); + var directoryInfo = new MockDirectoryInfo(fileSystem, directoryPath); + + // Act + var actualFullName = directoryInfo.FullName; + + // Assert + await That(actualFullName).IsEqualTo(expectedFullName); + } + + [TestCase(@"c:\temp\\folder", @"c:\temp\folder")] + [TestCase(@"c:\temp//folder", @"c:\temp\folder")] + [TestCase(@"c:\temp//\\///folder", @"c:\temp\folder")] + public async Task MockDirectoryInfo_FullName_ShouldReturnNormalizedPath(string directoryPath, string expectedFullName) + { + // Arrange + directoryPath = XFS.Path(directoryPath); + expectedFullName = XFS.Path(expectedFullName); + var fileSystem = new MockFileSystem(new Dictionary()); + var directoryInfo = new MockDirectoryInfo(fileSystem, directoryPath); + + // Act + var actualFullName = directoryInfo.FullName; + + // Assert + await That(actualFullName).IsEqualTo(expectedFullName); + } + + [TestCase(@"c:\temp\folder ", @"c:\temp\folder")] + [WindowsOnly(WindowsSpecifics.Drives)] + public async Task MockDirectoryInfo_FullName_ShouldReturnPathWithTrimmedTrailingSpaces(string directoryPath, string expectedFullName) + { + // Arrange + var fileSystem = new MockFileSystem(); + var directoryInfo = new MockDirectoryInfo(fileSystem, directoryPath); + + // Act + var actualFullName = directoryInfo.FullName; + + // Assert + await That(actualFullName).IsEqualTo(expectedFullName); + } + + [Test] + public async Task MockDirectoryInfo_MoveTo_ShouldUpdateFullName() + { + // Arrange + var path = XFS.Path(@"c:\source"); + var destination = XFS.Path(@"c:\destination"); + var fileSystem = new MockFileSystem(); + fileSystem.Directory.CreateDirectory(path); + var directoryInfo = fileSystem.DirectoryInfo.New(path); + + // Act + directoryInfo.MoveTo(destination); + + // Assert + await That(directoryInfo.FullName).IsEqualTo(destination); + } + + [TestCase(@"c:\temp\\folder ", @"folder")] + [WindowsOnly(WindowsSpecifics.Drives)] + public async Task MockDirectoryInfo_Name_ShouldReturnNameWithTrimmedTrailingSpaces(string directoryPath, string expectedName) + { + // Arrange + var fileSystem = new MockFileSystem(); + var directoryInfo = new MockDirectoryInfo(fileSystem, directoryPath); + + // Act + var actualName = directoryInfo.Name; + + // Assert + await That(actualName).IsEqualTo(expectedName); + } + + [TestCase(@"c:\", @"c:\")] + [WindowsOnly(WindowsSpecifics.Drives)] + public async Task MockDirectoryInfo_Name_ShouldReturnPathRoot_IfDirectoryPathIsPathRoot(string directoryPath, string expectedName) + { + // Arrange + var fileSystem = new MockFileSystem(); + var directoryInfo = new MockDirectoryInfo(fileSystem, directoryPath); + + // Act + var actualName = directoryInfo.Name; + + // Assert + await That(actualName).IsEqualTo(expectedName); + } + + [Test] + public async Task MockDirectoryInfo_Constructor_ShouldThrowArgumentNullException_IfArgumentDirectoryIsNull() + { + // Arrange + var fileSystem = new MockFileSystem(); + + // Act + Action action = () => new MockDirectoryInfo(fileSystem, null); + + // Assert + var exception = await That(action).Throws(); + await That(exception.Message).StartsWith("Value cannot be null."); + } + + [Test] + public async Task MockDirectoryInfo_Constructor_ShouldThrowArgumentNullException_IfArgumentFileSystemIsNull() + { + // Arrange + // nothing to do + + // Act + Action action = () => new MockDirectoryInfo(null, XFS.Path(@"c:\foo\bar\folder")); + + // Assert + await That(action).Throws(); + } + + [Test] + public async Task MockDirectoryInfo_Constructor_ShouldThrowArgumentException_IfArgumentDirectoryIsEmpty() + { + // Arrange + var fileSystem = new MockFileSystem(); + + // Act + Action action = () => new MockDirectoryInfo(fileSystem, string.Empty); + + // Assert + var exception = await That(action).Throws(); + await That(exception.Message).StartsWith("The path is not of a legal form."); + } + + [TestCase(@"c:\temp\folder\folder")] + [TestCase(@"..\..\..\Desktop")] + public async Task MockDirectoryInfo_ToString_ShouldReturnDirectoryName(string directoryName) + { + // Arrange + var directoryPath = XFS.Path(directoryName); + + // Act + var mockDirectoryInfo = new MockDirectoryInfo(new MockFileSystem(), directoryPath); + + // Assert + await That(mockDirectoryInfo.ToString()).IsEqualTo(directoryPath); + } + + [Test] + public async Task MockDirectoryInfo_Exists_ShouldReturnCachedData() + { + // Arrange + var fileSystem = new MockFileSystem(); + var path = XFS.Path(@"c:\abc"); + var directoryInfo = fileSystem.DirectoryInfo.New(path); + + // Act + fileSystem.AddDirectory(path); + + // Assert + await That(directoryInfo.Exists).IsFalse(); + } + + [Test] + public async Task MockDirectoryInfo_Exists_ShouldUpdateCachedDataOnRefresh() + { + // Arrange + var fileSystem = new MockFileSystem(); + var path = XFS.Path(@"c:\abc"); + var directoryInfo = fileSystem.DirectoryInfo.New(path); + + // Act + fileSystem.AddDirectory(path); + directoryInfo.Refresh(); + + // Assert + await That(directoryInfo.Exists).IsTrue(); + } + + [Test] + public async Task Directory_exists_after_creation() + { + // Arrange + var fileSystem = new MockFileSystem(); + var directoryInfo = fileSystem.DirectoryInfo.New(XFS.Path(@"c:\abc")); + + // Act + directoryInfo.Create(); + + // Assert + await That(directoryInfo.Exists).IsTrue(); + } + + [Test, WindowsOnly(WindowsSpecifics.AccessControlLists)] + public async Task Directory_exists_after_creation_with_security() + { + // Arrange + var fileSystem = new MockFileSystem(); + var directoryInfo = fileSystem.DirectoryInfo.New(XFS.Path(@"c:\abc")); + + // Act +#pragma warning disable CA1416 + directoryInfo.Create(new DirectorySecurity()); +#pragma warning restore CA1416 + + // Assert + await That(directoryInfo.Exists).IsTrue(); + } + + [Test] + public async Task Directory_does_not_exist_after_delete() + { + // Arrange + var fileSystem = new MockFileSystem(); + var directoryInfo = fileSystem.Directory.CreateDirectory(XFS.Path(@"c:\abc")); + + // Act + directoryInfo.Delete(); + + // Assert + await That(directoryInfo.Exists).IsFalse(); + } + + [Test] + public async Task Directory_does_not_exist_after_recursive_delete() + { + // Arrange + var fileSystem = new MockFileSystem(); + var directoryInfo = fileSystem.Directory.CreateDirectory(XFS.Path(@"c:\abc")); + + // Act + directoryInfo.Delete(true); + + // Assert + await That(directoryInfo.Exists).IsFalse(); + } + + [Test] + public async Task Directory_still_exists_after_move() + { + // Arrange + var fileSystem = new MockFileSystem(); + var directoryInfo = fileSystem.Directory.CreateDirectory(XFS.Path(@"c:\abc")); + + // Act + directoryInfo.MoveTo(XFS.Path(@"c:\abc2")); + + // Assert + await That(directoryInfo.Exists).IsTrue(); + } + + [Test] + public async Task MockDirectoryInfo_LastAccessTime_ShouldReflectChangedValue() + { + // Arrange + var path = XFS.Path(@"c:\abc"); + var fileSystem = new MockFileSystem(new Dictionary + { + { path, new MockDirectoryData() } + }); + var directoryInfo = fileSystem.DirectoryInfo.New(path); + var lastAccessTime = new DateTime(2022, 1, 8); + + // Act + directoryInfo.LastAccessTime = lastAccessTime; + + // Assert + await That(directoryInfo.LastAccessTime).IsEqualTo(lastAccessTime); + } + + [Test] + public async Task MockDirectoryInfo_CreationTime_ShouldReturnDefaultTimeForNonExistingFile() + { + var fileSystem = new MockFileSystem(); + var directoryInfo = new MockDirectoryInfo(fileSystem, XFS.Path(@"c:\non\existing")); + + var result = directoryInfo.CreationTime; + + await That(result).IsEqualTo(MockFileData.DefaultDateTimeOffset.LocalDateTime); + } + + [Test] + public async Task MockDirectoryInfo_LastAccessTime_ShouldReturnDefaultTimeForNonExistingFile() + { + var fileSystem = new MockFileSystem(); + var directoryInfo = new MockDirectoryInfo(fileSystem, XFS.Path(@"c:\non\existing")); + + var result = directoryInfo.LastAccessTime; + + await That(result).IsEqualTo(MockFileData.DefaultDateTimeOffset.LocalDateTime); + } + + [Test] + public async Task MockDirectoryInfo_LastWriteTime_ShouldReturnDefaultTimeForNonExistingFile() + { + var fileSystem = new MockFileSystem(); + var directoryInfo = new MockDirectoryInfo(fileSystem, XFS.Path(@"c:\non\existing")); + + var result = directoryInfo.LastWriteTime; + + await That(result).IsEqualTo(MockFileData.DefaultDateTimeOffset.LocalDateTime); + } + + [Test] + public async Task MockDirectoryInfo_CreationTimeUtc_ShouldReturnDefaultTimeForNonExistingFile() + { + var fileSystem = new MockFileSystem(); + var directoryInfo = new MockDirectoryInfo(fileSystem, XFS.Path(@"c:\non\existing")); + + var result = directoryInfo.CreationTimeUtc; + + await That(result).IsEqualTo(MockFileData.DefaultDateTimeOffset.UtcDateTime); + } + + [Test] + public async Task MockDirectoryInfo_LastAccessTimeUtc_ShouldReturnDefaultTimeForNonExistingFile() + { + var fileSystem = new MockFileSystem(); + var directoryInfo = new MockDirectoryInfo(fileSystem, XFS.Path(@"c:\non\existing")); + + var result = directoryInfo.LastAccessTimeUtc; + + await That(result).IsEqualTo(MockFileData.DefaultDateTimeOffset.UtcDateTime); + } + + [Test] + public async Task MockDirectoryInfo_LastWriteTimeUtc_ShouldReturnDefaultTimeForNonExistingFile() + { + var fileSystem = new MockFileSystem(); + var directoryInfo = new MockDirectoryInfo(fileSystem, XFS.Path(@"c:\non\existing")); + + var result = directoryInfo.LastWriteTimeUtc; + + await That(result).IsEqualTo(MockFileData.DefaultDateTimeOffset.UtcDateTime); + } + + [Test] + public async Task MockDirectoryInfo_Create_WithConflictingFile_ShouldThrowIOException() + { + var fileSystem = new MockFileSystem(); + fileSystem.AddFile(XFS.Path(@"c:\foo\bar.txt"), new MockFileData("Demo text content")); + var sut = fileSystem.DirectoryInfo.New(XFS.Path(@"c:\foo\bar.txt")); + + // Act + Action action = () => sut.Create(); + + // Assert + await That(action).Throws(); + } + + public async Task MockDirectoryInfo_CreationTime_SetterShouldThrowDirectoryNotFoundExceptionForNonExistingDirectory() + { + var newTime = new DateTime(2022, 04, 06); + var fileSystem = new MockFileSystem(); + var directoryInfo = new MockDirectoryInfo(fileSystem, XFS.Path(@"c:\non\existing")); + + await That(() => directoryInfo.CreationTime = newTime).Throws(); + } + + public async Task MockDirectoryInfo_LastAccessTime_SetterShouldThrowDirectoryNotFoundExceptionForNonExistingDirectory() + { + var newTime = new DateTime(2022, 04, 06); + var fileSystem = new MockFileSystem(); + var directoryInfo = new MockDirectoryInfo(fileSystem, XFS.Path(@"c:\non\existing")); + + await That(() => directoryInfo.LastAccessTime = newTime).Throws(); + } + + public async Task MockDirectoryInfo_LastWriteTime_SetterShouldThrowDirectoryNotFoundExceptionForNonExistingDirectory() + { + var newTime = new DateTime(2022, 04, 06); + var fileSystem = new MockFileSystem(); + var directoryInfo = new MockDirectoryInfo(fileSystem, XFS.Path(@"c:\non\existing")); + + await That(() => directoryInfo.LastWriteTime = newTime).Throws(); + } + + public async Task MockDirectoryInfo_CreationTimeUtc_SetterShouldThrowDirectoryNotFoundExceptionForNonExistingDirectory() + { + var newTime = new DateTime(2022, 04, 06); + var fileSystem = new MockFileSystem(); + var directoryInfo = new MockDirectoryInfo(fileSystem, XFS.Path(@"c:\non\existing")); + + await That(() => directoryInfo.CreationTimeUtc = newTime).Throws(); + } + + public async Task MockDirectoryInfo_LastAccessTimeUtc_SetterShouldThrowDirectoryNotFoundExceptionForNonExistingDirectory() + { + var newTime = new DateTime(2022, 04, 06); + var fileSystem = new MockFileSystem(); + var directoryInfo = new MockDirectoryInfo(fileSystem, XFS.Path(@"c:\non\existing")); + + await That(() => directoryInfo.LastAccessTimeUtc = newTime).Throws(); + } + + public async Task MockDirectoryInfo_LastWriteTimeUtc_SetterShouldThrowDirectoryNotFoundExceptionForNonExistingDirectory() + { + var newTime = new DateTime(2022, 04, 06); + var fileSystem = new MockFileSystem(); + var directoryInfo = new MockDirectoryInfo(fileSystem, XFS.Path(@"c:\non\existing")); + + await That(() => directoryInfo.LastWriteTime = newTime).Throws(); + } + +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockDirectorySetAccessControlTests.cs b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockDirectorySetAccessControlTests.cs new file mode 100644 index 000000000..3d18ff9dc --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockDirectorySetAccessControlTests.cs @@ -0,0 +1,67 @@ +using NUnit.Framework; +using System.Collections.Generic; + +namespace System.IO.Abstractions.TestingHelpers.Tests; + +using System.Runtime.Versioning; +using Security.AccessControl; +using XFS = MockUnixSupport; + +[TestFixture] +[SupportedOSPlatform("windows")] +[WindowsOnly(WindowsSpecifics.AccessControlLists)] +public class MockDirectorySetAccessControlTests +{ + [TestCase(" ")] + [TestCase(" ")] + public async Task MockDirectory_SetAccessControl_ShouldThrowArgumentExceptionIfPathContainsOnlyWhitespaces(string path) + { + // Arrange + var fileSystem = new MockFileSystem(); + var directorySecurity = new DirectorySecurity(); + + // Act + Action action = () => fileSystem.Directory.SetAccessControl(path, directorySecurity); + + // Assert + var exception = await That(action).Throws(); + await That(exception.ParamName).IsEqualTo("path"); + } + + [Test] + public async Task MockDirectory_SetAccessControl_ShouldThrowDirectoryNotFoundExceptionIfDirectoryDoesNotExistInMockData() + { + // Arrange + var fileSystem = new MockFileSystem(); + var expectedFileName = XFS.Path(@"c:\a\"); + var directorySecurity = new DirectorySecurity(); + + // Act + Action action = () => fileSystem.Directory.SetAccessControl(expectedFileName, directorySecurity); + + // Assert + await That(action).Throws(); + } + + [Test] + public async Task MockDirectory_SetAccessControl_ShouldSetAccessControlOfDirectoryData() + { + // Arrange + var filePath = XFS.Path(@"c:\a\"); + var fileData = new MockDirectoryData(); + + var fileSystem = new MockFileSystem(new Dictionary() + { + { filePath, fileData } + }); + + // Act + var expectedAccessControl = new DirectorySecurity(); + expectedAccessControl.SetAccessRuleProtection(false, false); + fileSystem.Directory.SetAccessControl(filePath, expectedAccessControl); + + // Assert + var accessControl = fileSystem.Directory.GetAccessControl(filePath); + await That(accessControl).IsEqualTo(expectedAccessControl); + } +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockDirectorySymlinkTests.cs b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockDirectorySymlinkTests.cs new file mode 100644 index 000000000..e0e617b7a --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockDirectorySymlinkTests.cs @@ -0,0 +1,294 @@ +using NUnit.Framework; + +namespace System.IO.Abstractions.TestingHelpers.Tests; + +using XFS = MockUnixSupport; + +[TestFixture] +public class MockDirectorySymlinkTests +{ + +#if FEATURE_CREATE_SYMBOLIC_LINK + + [Test] + public async Task MockDirectory_CreateSymbolicLink_ShouldReturnFileSystemInfo() + { + // Arrange + var fileSystem = new MockFileSystem(); + var pathToTarget = XFS.Path(@"C:\Folder\foo"); + var path = XFS.Path(@"C:\bar"); + fileSystem.AddDirectory(pathToTarget); + + // Act + IFileSystemInfo fileSystemInfo = fileSystem.Directory.CreateSymbolicLink(path, pathToTarget); + + // Assert + await That(fileSystemInfo.FullName).IsEqualTo(path); + await That(fileSystemInfo.LinkTarget).IsEqualTo(pathToTarget); + } + + [Test] + public async Task MockDirectory_CreateSymbolicLink_ShouldSucceedFromDirectoryInfo() + { + // Arrange + var fileSystem = new MockFileSystem(); + var pathToTarget = XFS.Path(@"C:\Folder\foo"); + var path = XFS.Path(@"C:\bar"); + fileSystem.AddDirectory(pathToTarget); + + // Act + fileSystem.Directory.CreateSymbolicLink(path, pathToTarget); + IDirectoryInfo directoryInfo = fileSystem.DirectoryInfo.New(path); + + // Assert + await That(directoryInfo.FullName).IsEqualTo(path); + await That(directoryInfo.LinkTarget).IsEqualTo(pathToTarget); + } + + [Test] + public async Task MockDirectory_CreateSymbolicLink_ShouldFailWithNullPath() + { + // Arrange + var fileSystem = new MockFileSystem(); + var pathToTarget = XFS.Path(@"C:\Folder\foo"); + fileSystem.AddDirectory(pathToTarget); + + // Act + var ex = await That(() => fileSystem.Directory.CreateSymbolicLink(null, pathToTarget)).Throws(); + + // Assert + await That(ex.ParamName).IsEqualTo("path"); + } + + [Test] + public async Task MockDirectory_CreateSymbolicLink_ShouldFailWithNullTarget() + { + // Arrange + var fileSystem = new MockFileSystem(); + var path = XFS.Path(@"C:\Folder\foo"); + fileSystem.AddDirectory(path); + + // Act + var ex = await That(() => fileSystem.Directory.CreateSymbolicLink(path, null)).Throws(); + + // Assert + await That(ex.ParamName).IsEqualTo("pathToTarget"); + } + + [Test] + public async Task MockDirectory_CreateSymbolicLink_ShouldFailWithEmptyPath() + { + // Arrange + var fileSystem = new MockFileSystem(); + var pathToTarget = XFS.Path(@"C:\Folder\foo"); + fileSystem.AddDirectory(pathToTarget); + + // Act + var ex = await That(() => fileSystem.Directory.CreateSymbolicLink("", pathToTarget)).Throws(); + + // Assert + await That(ex.ParamName).IsEqualTo("path"); + } + + [Test] + public async Task MockDirectory_CreateSymbolicLink_ShouldFailWithEmptyTarget() + { + // Arrange + var fileSystem = new MockFileSystem(); + string path = XFS.Path(@"C:\Folder\foo"); + fileSystem.AddDirectory(path); + + // Act + var ex = await That(() => fileSystem.Directory.CreateSymbolicLink(path, "")).Throws(); + + // Assert + await That(ex.ParamName).IsEqualTo("pathToTarget"); + } + + [Test] + public async Task MockDirectory_CreateSymbolicLink_ShouldFailWithIllegalPath() + { + // Arrange + var fileSystem = new MockFileSystem(); + string pathToTarget = XFS.Path(@"C:\Folder\foo"); + fileSystem.AddDirectory(pathToTarget); + + // Act + var ex = await That(() => fileSystem.Directory.CreateSymbolicLink(" ", pathToTarget)).Throws(); + + // Assert + await That(ex.ParamName).IsEqualTo("path"); + } + + [Test] + public async Task MockDirectory_CreateSymbolicLink_ShouldFailWithIllegalTarget() + { + // Arrange + var fileSystem = new MockFileSystem(); + string path = XFS.Path(@"C:\Folder\foo"); + fileSystem.AddDirectory(path); + + // Act + var ex = await That(() => fileSystem.Directory.CreateSymbolicLink(path, " ")).Throws(); + + // Assert + await That(ex.ParamName).IsEqualTo("pathToTarget"); + } + + [Test] + [WindowsOnly(WindowsSpecifics.StrictPathRules)] + public async Task MockDirectory_CreateSymbolicLink_ShouldFailWithIllegalCharactersInPath() + { + // Arrange + var fileSystem = new MockFileSystem(); + string pathToTarget = XFS.Path(@"C:\Folder\foo"); + fileSystem.AddDirectory(pathToTarget); + + // Act + Action ex = () => fileSystem.Directory.CreateSymbolicLink(@"C:\bar_?_", pathToTarget); + + // Assert + await That(ex).Throws(); + } + + [Test] + [WindowsOnly(WindowsSpecifics.StrictPathRules)] + public async Task MockDirectory_CreateSymbolicLink_ShouldFailWithIllegalCharactersInTarget() + { + // Arrange + var fileSystem = new MockFileSystem(); + string path = XFS.Path(@"C:\foo"); + + // Act + Action ex = () => fileSystem.Directory.CreateSymbolicLink(path, @"C:\bar_?_"); + + // Assert + await That(ex).Throws(); + } + + [Test] + public async Task MockDirectory_CreateSymbolicLink_ShouldFailIfPathExists() + { + // Arrange + var fileSystem = new MockFileSystem(); + string pathToTarget = XFS.Path(@"C:\Folder\foo"); + string path = XFS.Path(@"C:\Folder\bar"); + fileSystem.AddDirectory(pathToTarget); + fileSystem.AddDirectory(path); + + // Act + var ex = await That(() => fileSystem.Directory.CreateSymbolicLink(path, pathToTarget)).Throws(); + + // Assert + await That(ex.Message).Contains("path"); + } + + [Test] + public async Task MockDirectory_CreateSymbolicLink_ShouldNotFailIfTargetDoesNotExist() + { + // Arrange + var fileSystem = new MockFileSystem(); + string path = XFS.Path(@"C:\Folder\foo"); + string pathToTarget = XFS.Path(@"C:\Target"); + + // Act + var fileSystemInfo = fileSystem.Directory.CreateSymbolicLink(path, pathToTarget); + + // Assert + await That(fileSystemInfo.Exists).IsTrue(); + } + + [Test] + public async Task MockDirectory_CreateSymbolicLink_ShouldSetReparsePointAttribute() + { + var path = "foo"; + var pathToTarget = "bar"; + var fileSystem = new MockFileSystem(); + fileSystem.Directory.CreateDirectory(pathToTarget); + + fileSystem.Directory.CreateSymbolicLink(path, pathToTarget); + + var attributes = fileSystem.DirectoryInfo.New(path).Attributes; + await That(attributes.HasFlag(FileAttributes.ReparsePoint)).IsTrue(); + } + + [Test] + public async Task MockDirectory_ResolveLinkTarget_ShouldReturnPathOfTargetLink() + { + var fileSystem = new MockFileSystem(); + fileSystem.Directory.CreateDirectory("bar"); + fileSystem.Directory.CreateSymbolicLink("foo", "bar"); + + var result = fileSystem.Directory.ResolveLinkTarget("foo", false); + + await That(result.Name).IsEqualTo("bar"); + } + + [Test] + public async Task MockDirectory_ResolveLinkTarget_WithFinalTarget_ShouldReturnPathOfTargetLink() + { + // The maximum number of symbolic links that are followed: + // https://learn.microsoft.com/en-us/dotnet/api/system.io.directory.resolvelinktarget?view=net-6.0#remarks + var maxResolveLinks = XFS.IsWindowsPlatform() ? 63 : 40; + var fileSystem = new MockFileSystem(); + fileSystem.Directory.CreateDirectory("bar"); + var previousPath = "bar"; + for (int i = 0; i < maxResolveLinks; i++) + { + string newPath = $"foo-{i}"; + fileSystem.Directory.CreateSymbolicLink(newPath, previousPath); + previousPath = newPath; + } + + var result = fileSystem.Directory.ResolveLinkTarget(previousPath, true); + + await That(result.Name).IsEqualTo("bar"); + } + + [Test] + public async Task MockDirectory_ResolveLinkTarget_WithFinalTargetWithTooManyLinks_ShouldThrowIOException() + { + // The maximum number of symbolic links that are followed: + // https://learn.microsoft.com/en-us/dotnet/api/system.io.directory.resolvelinktarget?view=net-6.0#remarks + var maxResolveLinks = XFS.IsWindowsPlatform() ? 63 : 40; + maxResolveLinks++; + var fileSystem = new MockFileSystem(); + fileSystem.Directory.CreateDirectory("bar"); + var previousPath = "bar"; + for (int i = 0; i < maxResolveLinks; i++) + { + string newPath = $"foo-{i}"; + fileSystem.Directory.CreateSymbolicLink(newPath, previousPath); + previousPath = newPath; + } + + await That(() => fileSystem.Directory.ResolveLinkTarget(previousPath, true)).Throws(); + } + + [Test] + public async Task MockDirectory_ResolveLinkTarget_WithoutFinalTarget_ShouldReturnFirstLink() + { + var fileSystem = new MockFileSystem(); + fileSystem.Directory.CreateDirectory("bar"); + fileSystem.Directory.CreateSymbolicLink("foo", "bar"); + fileSystem.Directory.CreateSymbolicLink("foo1", "foo"); + + var result = fileSystem.Directory.ResolveLinkTarget("foo1", false); + + await That(result.Name).IsEqualTo("foo"); + } + + [Test] + public async Task MockDirectory_ResolveLinkTarget_WithoutTargetLink_ShouldThrowIOException() + { + var fileSystem = new MockFileSystem(); + fileSystem.Directory.CreateDirectory("bar"); + fileSystem.Directory.CreateSymbolicLink("foo", "bar"); + + await That(() => + { + fileSystem.Directory.ResolveLinkTarget("bar", false); + }).Throws(); + } +#endif +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockDirectoryTests.cs b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockDirectoryTests.cs new file mode 100644 index 000000000..79b531edc --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockDirectoryTests.cs @@ -0,0 +1,2241 @@ +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Versioning; +using System.Security.AccessControl; +using aweXpect.Equivalency; +using NUnit.Framework; + +namespace System.IO.Abstractions.TestingHelpers.Tests; + +using XFS = MockUnixSupport; + +[TestFixture] +public class MockDirectoryTests +{ + [Test] + public async Task MockDirectory_GetFiles_ShouldReturnAllFilesBelowPathWhenPatternIsEmptyAndSearchOptionIsAllDirectories() + { + // Arrange + var fileSystem = SetupFileSystem(); + var expected = new[] + { + XFS.Path(@"c:\a\a.txt"), + XFS.Path(@"c:\a\b.gif"), + XFS.Path(@"c:\a\c.txt"), + XFS.Path(@"c:\a\d"), + XFS.Path(@"c:\a\a\a.txt"), + XFS.Path(@"c:\a\a\b.txt"), + XFS.Path(@"c:\a\a\c.gif"), + XFS.Path(@"c:\a\a\d") + }; + + // Act + var result = fileSystem.Directory.GetFiles(XFS.Path(@"c:\a"), "", SearchOption.AllDirectories); + + // Assert + await That(result).IsEqualTo(expected).InAnyOrder(); + } + + [Test] + public async Task MockDirectory_GetFiles_ShouldReturnFilesDirectlyBelowPathWhenPatternIsEmptyAndSearchOptionIsTopDirectoryOnly() + { + // Arrange + var fileSystem = SetupFileSystem(); + var expected = new[] + { + XFS.Path(@"c:\a\a.txt"), + XFS.Path(@"c:\a\b.gif"), + XFS.Path(@"c:\a\c.txt"), + XFS.Path(@"c:\a\d") + }; + + // Act + var result = fileSystem.Directory.GetFiles(XFS.Path(@"c:\a"), "", SearchOption.TopDirectoryOnly); + + // Assert + await That(result).IsEqualTo(expected).InAnyOrder(); + } + + [Test] + public async Task MockDirectory_GetFiles_ShouldReturnAllFilesBelowPathWhenPatternIsWildcardAndSearchOptionIsAllDirectories() + { + // Arrange + var fileSystem = SetupFileSystem(); + var expected = new[] + { + XFS.Path(@"c:\a\a.txt"), + XFS.Path(@"c:\a\b.gif"), + XFS.Path(@"c:\a\c.txt"), + XFS.Path(@"c:\a\d"), + XFS.Path(@"c:\a\a\a.txt"), + XFS.Path(@"c:\a\a\b.txt"), + XFS.Path(@"c:\a\a\c.gif"), + XFS.Path(@"c:\a\a\d") + }; + + // Act + var result = fileSystem.Directory.GetFiles(XFS.Path(@"c:\a"), "*", SearchOption.AllDirectories); + + // Assert + await That(result).IsEqualTo(expected).InAnyOrder(); + } + +#if FEATURE_ENUMERATION_OPTIONS + [Test] + public async Task MockDirectory_GetFiles_ShouldReturnAllPatternMatchingFilesWhenEnumerationOptionHasRecurseSubdirectoriesSetToTrue() + { + // Arrange + var fileSystem = SetupFileSystem(); + var expected = new[] + { + XFS.Path(@"c:\b.txt"), + XFS.Path(@"c:\c.txt"), + XFS.Path(@"c:\a\a.txt"), + XFS.Path(@"c:\a\c.txt"), + XFS.Path(@"c:\a\a\a.txt"), + XFS.Path(@"c:\a\a\b.txt") + }; + + // Act + var result = fileSystem.Directory.GetFiles(XFS.Path(@"c:\"), "*.txt", new EnumerationOptions { RecurseSubdirectories = true }); + + // Assert + await That(result).IsEqualTo(expected).InAnyOrder(); + } +#endif + + private MockFileSystem SetupFileSystem() + { + return new MockFileSystem(new Dictionary + { + { XFS.Path(@"c:\a.gif"), new MockFileData("Demo text content") }, + { XFS.Path(@"c:\b.txt"), new MockFileData("Demo text content") }, + { XFS.Path(@"c:\c.txt"), new MockFileData("Demo text content") }, + { XFS.Path(@"c:\d"), new MockFileData("Demo text content") }, + { XFS.Path(@"c:\a\a.txt"), new MockFileData("Demo text content") }, + { XFS.Path(@"c:\a\b.gif"), new MockFileData("Demo text content") }, + { XFS.Path(@"c:\a\c.txt"), new MockFileData("Demo text content") }, + { XFS.Path(@"c:\a\d"), new MockFileData("Demo text content") }, + { XFS.Path(@"c:\a\a\a.txt"), new MockFileData("Demo text content") }, + { XFS.Path(@"c:\a\a\b.txt"), new MockFileData("Demo text content") }, + { XFS.Path(@"c:\a\a\c.gif"), new MockFileData("Demo text content") }, + { XFS.Path(@"c:\a\a\d"), new MockFileData("Demo text content") } + }); + + } + + [Test] + public async Task MockDirectory_GetFiles_ShouldReturnFilesDirectlyBelowPathWhenPatternIsWildcardAndSearchOptionIsTopDirectoryOnly() + { + // Arrange + var fileSystem = SetupFileSystem(); + var expected = new[] + { + XFS.Path(@"c:\a\a.txt"), + XFS.Path(@"c:\a\b.gif"), + XFS.Path(@"c:\a\c.txt"), + XFS.Path(@"c:\a\d") + }; + + // Act + var result = fileSystem.Directory.GetFiles(XFS.Path(@"c:\a"), "*", SearchOption.TopDirectoryOnly); + + // Assert + await That(result).IsEqualTo(expected).InAnyOrder(); + } + + [Test] + public async Task MockDirectory_GetFiles_ShouldFilterByExtensionBasedSearchPattern() + { + // Arrange + var fileSystem = SetupFileSystem(); + var expected = new[] + { + XFS.Path(@"c:\a.gif"), + XFS.Path(@"c:\a\b.gif"), + XFS.Path(@"c:\a\a\c.gif") + }; + + // Act + var result = fileSystem.Directory.GetFiles(XFS.Path(@"c:\"), "*.gif", SearchOption.AllDirectories); + + // Assert + await That(result).IsEqualTo(expected).InAnyOrder(); + } + + [Test] + public async Task MockDirectory_GetFiles_ShouldFilterByExtensionBasedSearchPatternWithThreeCharacterLongFileExtension_RespectingAllDirectorySearchOption() + { + // Arrange + var additionalFilePath = XFS.Path(@"c:\a\a\c.gifx"); + var fileSystem = SetupFileSystem(); + fileSystem.AddFile(additionalFilePath, new MockFileData(string.Empty)); + fileSystem.AddFile(XFS.Path(@"c:\a\a\c.gifx.xyz"), new MockFileData(string.Empty)); + fileSystem.AddFile(XFS.Path(@"c:\a\a\c.gifz\xyz"), new MockFileData(string.Empty)); + var expected = new[] + { + XFS.Path(@"c:\a.gif"), + XFS.Path(@"c:\a\b.gif"), + XFS.Path(@"c:\a\a\c.gif"), + additionalFilePath + }; + + // Act + var result = fileSystem.Directory.GetFiles(XFS.Path(@"c:\"), "*.gif", SearchOption.AllDirectories); + + // Assert + await That(result).IsEqualTo(expected).InAnyOrder(); + } + + [Test] + public async Task MockDirectory_GetFiles_ShouldFilterByExtensionBasedSearchPatternWithThreeCharacterLongFileExtension_RespectingTopDirectorySearchOption() + { + // Arrange + var additionalFilePath = XFS.Path(@"c:\a\c.gifx"); + var fileSystem = SetupFileSystem(); + fileSystem.AddFile(additionalFilePath, new MockFileData(string.Empty)); + fileSystem.AddFile(XFS.Path(@"c:\a\a\c.gifx.xyz"), new MockFileData(string.Empty)); + fileSystem.AddFile(XFS.Path(@"c:\a\a\c.gifx"), new MockFileData(string.Empty)); + var expected = new[] + { + XFS.Path(@"c:\a\b.gif"), + additionalFilePath + }; + + // Act + var result = fileSystem.Directory.GetFiles(XFS.Path(@"c:\a"), "*.gif", SearchOption.TopDirectoryOnly); + + // Assert + await That(result).IsEqualTo(expected).InAnyOrder(); + } + + [Test] + public async Task MockDirectory_GetFiles_ShouldFilterByExtensionBasedSearchPatternOnlyIfTheFileExtensionIsThreeCharacterLong() + { + // Arrange + var additionalFilePath = XFS.Path(@"c:\a\c.gi"); + var fileSystem = SetupFileSystem(); + fileSystem.AddFile(additionalFilePath, new MockFileData(string.Empty)); + fileSystem.AddFile(XFS.Path(@"c:\a\a\c.gifx.xyz"), new MockFileData(string.Empty)); + fileSystem.AddFile(XFS.Path(@"c:\a\a\c.gif"), new MockFileData(string.Empty)); + fileSystem.AddFile(XFS.Path(@"c:\a\a\c.gifx"), new MockFileData(string.Empty)); + var expected = new[] + { + additionalFilePath + }; + + // Act + var result = fileSystem.Directory.GetFiles(XFS.Path(@"c:\a"), "*.gi", SearchOption.AllDirectories); + + // Assert + await That(result).IsEqualTo(expected).InAnyOrder(); + } + + [Test] + public async Task MockDirectory_GetFiles_ShouldFilterByExtensionBasedSearchPatternWithDotsInFilenames() + { + // Arrange + var fileSystem = new MockFileSystem(new Dictionary + { + { XFS.Path(@"c:\a.there.are.dots.in.this.filename.gif"), new MockFileData("Demo text content") }, + { XFS.Path(@"c:\b.txt"), new MockFileData("Demo text content") }, + { XFS.Path(@"c:\c.txt"), new MockFileData("Demo text content") }, + { XFS.Path(@"c:\a\a.txt"), new MockFileData("Demo text content") }, + { XFS.Path(@"c:\a\b.gif"), new MockFileData("Demo text content") }, + { XFS.Path(@"c:\a\c.txt"), new MockFileData("Demo text content") }, + { XFS.Path(@"c:\a\a\a.txt"), new MockFileData("Demo text content") }, + { XFS.Path(@"c:\a\a\b.txt"), new MockFileData("Demo text content") }, + { XFS.Path(@"c:\a\a\c.gif"), new MockFileData("Demo text content") }, + }); + var expected = new[] + { + XFS.Path(@"c:\a.there.are.dots.in.this.filename.gif"), + XFS.Path(@"c:\a\b.gif"), + XFS.Path(@"c:\a\a\c.gif") + }; + + // Act + var result = fileSystem.Directory.GetFiles(XFS.Path(@"c:\"), "*.gif", SearchOption.AllDirectories); + + // Assert + await That(result).IsEqualTo(expected).InAnyOrder(); + } + + [Test] + public async Task MockDirectory_GetFiles_FilterShouldFindFilesWithSpecialChars() + { + // Arrange + var fileSystem = new MockFileSystem(new Dictionary + { + { XFS.Path(@"c:\a.1#.pdf"), new MockFileData("Demo text content") }, + { XFS.Path(@"c:\b\b #1.txt"), new MockFileData("Demo text content") } + }); + var expected = new[] + { + XFS.Path(@"c:\a.1#.pdf"), + XFS.Path(@"c:\b\b #1.txt") + }; + + // Act + var result = fileSystem.Directory.GetFiles(XFS.Path(@"c:\"), "*.*", SearchOption.AllDirectories); + + // Assert + await That(result).IsEqualTo(expected).InAnyOrder(); + } + + [Test] + public async Task MockDirectory_GetFiles_ShouldFilterByExtensionBasedSearchPatternAndSearchOptionTopDirectoryOnly() + { + // Arrange + var fileSystem = SetupFileSystem(); + var expected = new[] { XFS.Path(@"c:\a.gif") }; + + // Act + var result = fileSystem.Directory.GetFiles(XFS.Path(@"c:\"), "*.gif", SearchOption.TopDirectoryOnly); + + // Assert + await That(result).IsEqualTo(expected).InAnyOrder(); + } + + [Test] + public async Task MockDirectory_GetFiles_ShouldFilterForAllFilesWithNoExtensionsAndSearchOptionTopDirectoryOnly() + { + // Arrange + var fileSystem = SetupFileSystem(); + fileSystem.AddFile(XFS.Path(@"C:\mytestfilename"), new MockFileData("some content")); + fileSystem.AddFile(XFS.Path(@"C:\mytestfilename."), new MockFileData("some content")); + fileSystem.AddFile(XFS.Path(@"C:\mytestfile.name"), new MockFileData("some content")); + fileSystem.AddFile(XFS.Path(@"C:\mytestfile.name."), new MockFileData("some content")); + fileSystem.AddFile(XFS.Path(@"C:\mytestfile.name.again"), new MockFileData("some content")); + fileSystem.AddFile(XFS.Path(@"C:\mytestfile.name.again."), new MockFileData("some content")); + + var expected = new[] + { + XFS.Path(@"c:\d"), + XFS.Path(@"C:\mytestfilename"), + XFS.Path(@"C:\mytestfilename."), + XFS.Path(@"C:\mytestfile.name."), + XFS.Path(@"C:\mytestfile.name.again.") + }; + + // Act + var result = fileSystem.Directory.GetFiles(XFS.Path(@"C:\"), "*.", SearchOption.TopDirectoryOnly); + + // Assert + await That(result).IsEqualTo(expected).InAnyOrder(); + } + + [Test] + public async Task MockDirectory_GetFiles_ShouldFilterForAllFilesWithNoExtensionsAndSearchOptionAllDirectories() + { + // Arrange + var fileSystem = SetupFileSystem(); + fileSystem.AddFile(XFS.Path(@"C:\specialNameFormats\mytestfilename"), new MockFileData("some content")); + fileSystem.AddFile(XFS.Path(@"C:\specialNameFormats\mytestfilename."), new MockFileData("some content")); + fileSystem.AddFile(XFS.Path(@"C:\specialNameFormats\mytestfile.name"), new MockFileData("some content")); + fileSystem.AddFile(XFS.Path(@"C:\specialNameFormats\mytestfile.name."), new MockFileData("some content")); + fileSystem.AddFile(XFS.Path(@"C:\specialNameFormats\mytestfile.name.again"), new MockFileData("some content")); + fileSystem.AddFile(XFS.Path(@"C:\specialNameFormats\mytestfile.name.again."), new MockFileData("some content")); + + var expected = new[] + { + XFS.Path(@"c:\d"), + XFS.Path(@"c:\a\d"), + XFS.Path(@"c:\a\a\d"), + XFS.Path(@"C:\specialNameFormats\mytestfilename"), + XFS.Path(@"C:\specialNameFormats\mytestfilename."), + XFS.Path(@"C:\specialNameFormats\mytestfile.name."), + XFS.Path(@"C:\specialNameFormats\mytestfile.name.again.") + }; + + // Act + var result = fileSystem.Directory.GetFiles(XFS.Path(@"c:\"), "*.", SearchOption.AllDirectories); + + // Assert + await That(result).IsEqualTo(expected).InAnyOrder(); + } + + [Test] + public async Task MockDirectory_GetFiles_ShouldFilterForFilesWithNoExtensionsAndNonTrivialFilterAndSearchOptionTopDirectoryOnly() + { + // Arrange + var fileSystem = SetupFileSystem(); + fileSystem.AddFile(XFS.Path(@"C:\mytestfilename"), new MockFileData("some content")); + fileSystem.AddFile(XFS.Path(@"C:\mytestfilename."), new MockFileData("some content")); + fileSystem.AddFile(XFS.Path(@"C:\mytestfile.name"), new MockFileData("some content")); + fileSystem.AddFile(XFS.Path(@"C:\mytestfile.name."), new MockFileData("some content")); + fileSystem.AddFile(XFS.Path(@"C:\mytestfile.name.again"), new MockFileData("some content")); + fileSystem.AddFile(XFS.Path(@"C:\mytestfile.name.again."), new MockFileData("some content")); + + var expected = new[] + { + XFS.Path(@"C:\mytestfilename"), + XFS.Path(@"C:\mytestfilename."), + XFS.Path(@"C:\mytestfile.name."), + XFS.Path(@"C:\mytestfile.name.again.") + + }; + + // Act + var result = fileSystem.Directory.GetFiles(XFS.Path(@"C:\"), "my??s*.", SearchOption.TopDirectoryOnly); + + // Assert + await That(result).IsEqualTo(expected).InAnyOrder(); + } + + [Test] + public async Task MockDirectory_GetFiles_ShouldFilterForFilesWithNoExtensionsAndNonTrivialFilter2AndSearchOptionTopDirectoryOnly() + { + // Arrange + var fileSystem = SetupFileSystem(); + fileSystem.AddFile(XFS.Path(@"C:\mytestfilename"), new MockFileData("some content")); + fileSystem.AddFile(XFS.Path(@"C:\mytestfilename."), new MockFileData("some content")); + fileSystem.AddFile(XFS.Path(@"C:\mytestfile.name"), new MockFileData("some content")); + fileSystem.AddFile(XFS.Path(@"C:\mytestfile.name."), new MockFileData("some content")); + fileSystem.AddFile(XFS.Path(@"C:\mytestfile.name.again"), new MockFileData("some content")); + fileSystem.AddFile(XFS.Path(@"C:\mytestfile.name.again."), new MockFileData("some content")); + + var expected = new[] + { + XFS.Path(@"C:\mytestfile.name"), + XFS.Path(@"C:\mytestfile.name."), + XFS.Path(@"C:\mytestfile.name.again.") + + }; + + // Act + var result = fileSystem.Directory.GetFiles(XFS.Path(@"C:\"), "my*.n*.", SearchOption.TopDirectoryOnly); + + // Assert + await That(result).IsEqualTo(expected).InAnyOrder(); + } + + [Test] + public async Task MockDirectory_GetFiles_ShouldFilterForFilesWithNoExtensionsAndFilterThatIncludesDotAndSearchOptionTopDirectoryOnly() + { + // Arrange + var fileSystem = SetupFileSystem(); + fileSystem.AddFile(XFS.Path(@"C:\mytestfilename"), new MockFileData("some content")); + fileSystem.AddFile(XFS.Path(@"C:\mytestfilename."), new MockFileData("some content")); + fileSystem.AddFile(XFS.Path(@"C:\mytestfile.name"), new MockFileData("some content")); + fileSystem.AddFile(XFS.Path(@"C:\mytestfile.name."), new MockFileData("some content")); + fileSystem.AddFile(XFS.Path(@"C:\mytestfile.name.again"), new MockFileData("some content")); + fileSystem.AddFile(XFS.Path(@"C:\mytestfile.name.again."), new MockFileData("some content")); + + var expected = new[] + { + XFS.Path(@"C:\mytestfile.name"), + XFS.Path(@"C:\mytestfile.name."), + XFS.Path(@"C:\mytestfile.name.again.") + }; + + // Act + var result = fileSystem.Directory.GetFiles(XFS.Path(@"C:\"), "my*.n*.", SearchOption.TopDirectoryOnly); + + // Assert + await That(result).IsEqualTo(expected).InAnyOrder(); + } + + private async Task ExecuteTimeAttributeTest(DateTime time, Action setter, Func getter) + { + string path = XFS.Path(@"c:\something\demo.txt"); + var fileSystem = new MockFileSystem(new Dictionary + { + { path, new MockFileData("Demo text content") } + }); + + // Act + setter(fileSystem, path, time); + var result = getter(fileSystem, path); + + // Assert + await That(result).IsEqualTo(time); + } + + [Test] + public async Task MockDirectory_GetCreationTime_ShouldReturnCreationTimeFromFile() + { + await ExecuteTimeAttributeTest( + new DateTime(2010, 6, 4, 13, 26, 42), + (fs, p, d) => fs.File.SetCreationTime(p, d), + (fs, p) => fs.Directory.GetCreationTime(p)); + } + + [Test] + public async Task MockDirectory_GetCreationTimeUtc_ShouldReturnCreationTimeUtcFromFile() + { + await ExecuteTimeAttributeTest( + new DateTime(2010, 6, 4, 13, 26, 42, DateTimeKind.Utc), + (fs, p, d) => fs.File.SetCreationTimeUtc(p, d), + (fs, p) => fs.Directory.GetCreationTimeUtc(p)); + } + + [Test] + public async Task MockDirectory_GetLastAccessTime_ShouldReturnLastAccessTimeFromFile() + { + await ExecuteTimeAttributeTest( + new DateTime(2010, 6, 4, 13, 26, 42), + (fs, p, d) => fs.File.SetLastAccessTime(p, d), + (fs, p) => fs.Directory.GetLastAccessTime(p)); + } + + [Test] + public async Task MockDirectory_GetLastAccessTimeUtc_ShouldReturnLastAccessTimeUtcFromFile() + { + await ExecuteTimeAttributeTest( + new DateTime(2010, 6, 4, 13, 26, 42, DateTimeKind.Utc), + (fs, p, d) => fs.File.SetLastAccessTimeUtc(p, d), + (fs, p) => fs.Directory.GetLastAccessTimeUtc(p)); + } + + [Test] + public async Task MockDirectory_GetLastWriteTime_ShouldReturnLastWriteTimeFromFile() + { + await ExecuteTimeAttributeTest( + new DateTime(2010, 6, 4, 13, 26, 42), + (fs, p, d) => fs.File.SetLastWriteTime(p, d), + (fs, p) => fs.Directory.GetLastWriteTime(p)); + } + + [Test] + public async Task MockDirectory_GetLastWriteTimeUtc_ShouldReturnLastWriteTimeUtcFromFile() + { + await ExecuteTimeAttributeTest( + new DateTime(2010, 6, 4, 13, 26, 42, DateTimeKind.Utc), + (fs, p, d) => fs.File.SetLastWriteTimeUtc(p, d), + (fs, p) => fs.Directory.GetLastWriteTimeUtc(p)); + } + + [Test] + public async Task MockDirectory_SetCreationTime_ShouldSetCreationTimeOnFile() + { + await ExecuteTimeAttributeTest( + new DateTime(2010, 6, 4, 13, 26, 42), + (fs, p, d) => fs.Directory.SetCreationTime(p, d), + (fs, p) => fs.File.GetCreationTime(p)); + } + + [Test] + public async Task MockDirectory_SetCreationTimeUtc_ShouldSetCreationTimeUtcOnFile() + { + await ExecuteTimeAttributeTest( + new DateTime(2010, 6, 4, 13, 26, 42, DateTimeKind.Utc), + (fs, p, d) => fs.Directory.SetCreationTimeUtc(p, d), + (fs, p) => fs.File.GetCreationTimeUtc(p)); + } + + [Test] + public async Task MockDirectory_SetLastAccessTime_ShouldSetLastAccessTimeOnFile() + { + await ExecuteTimeAttributeTest( + new DateTime(2010, 6, 4, 13, 26, 42), + (fs, p, d) => fs.Directory.SetLastAccessTime(p, d), + (fs, p) => fs.File.GetLastAccessTime(p)); + } + + [Test] + public async Task MockDirectory_SetLastAccessTimeUtc_ShouldSetLastAccessTimeUtcOnFile() + { + await ExecuteTimeAttributeTest( + new DateTime(2010, 6, 4, 13, 26, 42, DateTimeKind.Utc), + (fs, p, d) => fs.Directory.SetLastAccessTimeUtc(p, d), + (fs, p) => fs.File.GetLastAccessTimeUtc(p)); + } + + [Test] + public async Task MockDirectory_SetLastWriteTime_ShouldSetLastWriteTimeOnFile() + { + await ExecuteTimeAttributeTest( + new DateTime(2010, 6, 4, 13, 26, 42), + (fs, p, d) => fs.Directory.SetLastWriteTime(p, d), + (fs, p) => fs.File.GetLastWriteTime(p)); + } + + [Test] + public async Task MockDirectory_SetLastWriteTimeUtc_ShouldSetLastWriteTimeUtcOnFile() + { + await ExecuteTimeAttributeTest( + new DateTime(2010, 6, 4, 13, 26, 42, DateTimeKind.Utc), + (fs, p, d) => fs.Directory.SetLastWriteTimeUtc(p, d), + (fs, p) => fs.File.GetLastWriteTimeUtc(p)); + } + + [Test] + public async Task MockDirectory_Exists_ShouldReturnTrueForDirectoryDefinedInMemoryFileSystemWithoutTrailingSlash() + { + // Arrange + var fileSystem = new MockFileSystem(new Dictionary + { + { XFS.Path(@"c:\foo\bar.txt"), new MockFileData("Demo text content") } + }); + + // Act + var result = fileSystem.Directory.Exists(XFS.Path(@"c:\foo")); + + // Assert + await That(result).IsTrue(); + } + + [Test] + public async Task MockDirectory_Exists_ShouldReturnTrueForDirectoryDefinedInMemoryFileSystemWithTrailingSlash() + { + // Arrange + var fileSystem = new MockFileSystem(new Dictionary + { + { XFS.Path(@"c:\foo\bar.txt"), new MockFileData("Demo text content") } + }); + + // Act + var result = fileSystem.Directory.Exists(XFS.Path(@"c:\foo\")); + + // Assert + await That(result).IsTrue(); + } + + [Test] + public async Task MockDirectory_Exists_ShouldReturnFalseForDirectoryNotDefinedInMemoryFileSystemWithoutTrailingSlash() + { + // Arrange + var fileSystem = new MockFileSystem(new Dictionary + { + { XFS.Path(@"c:\foo\bar.txt"), new MockFileData("Demo text content") } + }); + + // Act + var result = fileSystem.Directory.Exists(XFS.Path(@"c:\baz")); + + // Assert + await That(result).IsFalse(); + } + + [Test] + public async Task MockDirectory_Exists_ShouldReturnFalseForDirectoryNotDefinedInMemoryFileSystemWithTrailingSlash() + { + // Arrange + var fileSystem = new MockFileSystem(new Dictionary + { + { XFS.Path(@"c:\foo\bar.txt"), new MockFileData("Demo text content") } + }); + + // Act + var result = fileSystem.Directory.Exists(XFS.Path(@"c:\baz\")); + + // Assert + await That(result).IsFalse(); + } + + [Test] + public async Task MockDirectory_Exists_ShouldReturnFalseForDirectoryNotDefinedInMemoryFileSystemWithSimilarFileName() + { + // Arrange + var fileSystem = new MockFileSystem(new Dictionary + { + { XFS.Path(@"c:\foo\bar.txt"), new MockFileData("Demo text content") }, + { XFS.Path(@"c:\baz.txt"), new MockFileData("Demo text content") } + }); + + // Act + var result = fileSystem.Directory.Exists(XFS.Path(@"c:\baz")); + + // Assert + await That(result).IsFalse(); + } + + [Test] + public async Task MockDirectory_Exists_ShouldReturnTrueForDirectoryCreatedViaMocks() + { + // Arrange + var fileSystem = new MockFileSystem(new Dictionary + { + { XFS.Path(@"c:\foo\bar.txt"), new MockFileData("Demo text content") } + }); + fileSystem.Directory.CreateDirectory(XFS.Path(@"c:\bar")); + + // Act + var result = fileSystem.Directory.Exists(XFS.Path(@"c:\bar")); + + // Assert + await That(result).IsTrue(); + } + + [Test] + public async Task MockDirectory_Exists_ShouldReturnTrueForFolderContainingFileAddedToMockFileSystem() + { + // Arrange + var fileSystem = new MockFileSystem(); + fileSystem.AddFile(XFS.Path(@"c:\foo\bar.txt"), new MockFileData("Demo text content")); + + // Act + var result = fileSystem.Directory.Exists(XFS.Path(@"c:\foo\")); + + // Assert + await That(result).IsTrue(); + } + + [TestCase(@"\\s")] + [TestCase(@"<")] + [TestCase("\t")] + public async Task MockDirectory_Exists_ShouldReturnFalseForIllegalPath(string path) + { + // Arrange + var fileSystem = new MockFileSystem(); + + // Act + var result = fileSystem.Directory.Exists(path); + + // Assert + await That(result).IsFalse(); + } + + [Test] + public async Task MockDirectory_CreateDirectory_WithConflictingFile_ShouldThrowIOException() + { + var fileSystem = new MockFileSystem(); + fileSystem.AddFile(XFS.Path(@"c:\foo\bar.txt"), new MockFileData("Demo text content")); + + // Act + Action action = () => fileSystem.Directory.CreateDirectory(XFS.Path(@"c:\foo\bar.txt")); + + // Assert + await That(action).Throws(); + } + + [Test] + public async Task MockDirectory_Exists_ShouldReturnFalseForFiles() + { + // Arrange + var fileSystem = new MockFileSystem(); + fileSystem.AddFile(XFS.Path(@"c:\foo\bar.txt"), new MockFileData("Demo text content")); + + // Act + var result = fileSystem.Directory.Exists(XFS.Path(@"c:\foo\bar.txt")); + + // Assert + await That(result).IsFalse(); + } + + [Test] + public async Task MockDirectory_CreateDirectory_ShouldCreateFolderInMemoryFileSystem() + { + // Arrange + var fileSystem = new MockFileSystem(new Dictionary + { + { XFS.Path(@"c:\foo.txt"), new MockFileData("Demo text content") } + }); + + // Act + fileSystem.Directory.CreateDirectory(XFS.Path(@"c:\bar")); + + // Assert + await That(fileSystem.FileExists(XFS.Path(@"c:\bar\"))).IsTrue(); + await That(fileSystem.AllDirectories.Any(d => d == XFS.Path(@"c:\bar"))).IsTrue(); + } + + [Test] + public async Task MockDirectory_CreateDirectory_ShouldThrowIfIllegalCharacterInPath() + { + // Arrange + var fileSystem = new MockFileSystem(new Dictionary + { + { XFS.Path(@"c:\foo.txt"), new MockFileData("Demo text content") } + }); + + // Act + Action createDelegate = () => fileSystem.Directory.CreateDirectory(XFS.Path(@"c:\bar_?_")); + + // Assert + await That(createDelegate).Throws(); + } + + [Test] + [WindowsOnly(WindowsSpecifics.UNCPaths)] + public async Task MockDirectory_CreateDirectory_ShouldSupportExtendedLengthPaths() + { + // Arrange + var fileSystem = new MockFileSystem(); + + // Act + var directoryInfo = fileSystem.Directory.CreateDirectory(XFS.Path(@"\\?\c:\bar")); + fileSystem.File.WriteAllText(@"\\?\c:\bar\grok.txt", "hello world\n"); + + // Assert + await That(fileSystem.Directory.Exists(XFS.Path(@"\\?\c:\bar"))).IsTrue(); + await That(directoryInfo.FullName).IsEqualTo(@"\\?\c:\bar"); + await That(fileSystem.File.ReadAllText(@"\\?\c:\bar\grok.txt")).IsEqualTo("hello world\n"); + await That(fileSystem.Directory.GetFiles(@"\\?\c:\bar")).HasSingle() + .Which.IsEqualTo(@"\\?\c:\bar\grok.txt"); + } + + // Issue #210 + [Test] + public async Task MockDirectory_CreateDirectory_ShouldIgnoreExistingDirectoryRegardlessOfTrailingSlash() + { + // Arrange + var fileSystem = new MockFileSystem(new Dictionary + { + { XFS.Path(@"c:\foo\"), new MockDirectoryData() } + }); + + // Act/Assert + await That(() => fileSystem.Directory.CreateDirectory(XFS.Path(@"c:\foo"))).DoesNotThrow(); + await That(() => fileSystem.Directory.CreateDirectory(XFS.Path(@"c:\foo\"))).DoesNotThrow(); + } + + [Test] + public async Task MockDirectory_CreateDirectory_ShouldReturnDirectoryInfoBase() + { + // Arrange + var fileSystem = new MockFileSystem(new Dictionary + { + { XFS.Path(@"c:\foo.txt"), new MockFileData("Demo text content") } + }); + + // Act + var result = fileSystem.Directory.CreateDirectory(XFS.Path(@"c:\bar")); + + // Assert + await That(result).IsNotNull(); + } + + [Test] + [WindowsOnly(WindowsSpecifics.Drives)] + public async Task MockDirectory_CreateDirectory_ShouldTrimTrailingSpaces() + { + // Arrange + var fileSystem = new MockFileSystem(); + + // Act + fileSystem.Directory.CreateDirectory(XFS.Path(@"c:\temp\folder ")); + + // Assert + await That(fileSystem.Directory.Exists(XFS.Path(@"c:\temp\folder"))).IsTrue(); + } + + [Test] + public async Task MockDirectory_CreMockDirectory_CreateDirectory_ShouldReturnDirectoryInfoBaseWhenDirectoryExists() + { + // Arrange + var fileSystem = new MockFileSystem(new Dictionary + { + { XFS.Path(@"c:\foo\"), new MockDirectoryData() } + }); + + // Act + var result = fileSystem.Directory.CreateDirectory(XFS.Path(@"c:\foo\")); + + // Assert + await That(result).IsNotNull(); + } + + [Test] + [WindowsOnly(WindowsSpecifics.UNCPaths)] + public async Task MockDirectory_CreateDirectory_ShouldWorkWithUNCPath() + { + // Arrange + var fileSystem = new MockFileSystem(); + + // Act + fileSystem.Directory.CreateDirectory(@"\\server\share\path\to\create"); + + // Assert + await That(fileSystem.Directory.Exists(@"\\server\share\path\to\create\")).IsTrue(); + } + + [Test] + [WindowsOnly(WindowsSpecifics.UNCPaths)] + public async Task MockDirectory_CreateDirectory_ShouldFailIfTryingToCreateUNCPathOnlyServer() + { + // Arrange + var fileSystem = new MockFileSystem(); + + // Act + var ex = await That(() => fileSystem.Directory.CreateDirectory(@"\\server")).Throws(); + + // Assert + await That(ex.Message).StartsWith("The UNC path should be of the form \\\\server\\share."); + await That(ex.ParamName).IsEqualTo("path"); + } + + [Test] + [WindowsOnly(WindowsSpecifics.UNCPaths)] + public async Task MockDirectory_CreateDirectory_ShouldSucceedIfTryingToCreateUNCPathShare() + { + // Arrange + var fileSystem = new MockFileSystem(); + + // Act + fileSystem.Directory.CreateDirectory(@"\\server\share"); + + // Assert + await That(fileSystem.Directory.Exists(@"\\server\share\")).IsTrue(); + } + +#if FEATURE_CREATE_TEMP_SUBDIRECTORY + [Test] + public async Task MockDirectory_CreateTempSubdirectory_ShouldCreateSubdirectoryInTempDirectory() + { + // Arrange + var fileSystem = new MockFileSystem(); + + // Act + var result = fileSystem.Directory.CreateTempSubdirectory(); + + // Assert + await That(fileSystem.Directory.Exists(result.FullName)).IsTrue(); + await That(result.FullName).StartsWith(fileSystem.Path.GetTempPath()); + } + + [Test] + public async Task MockDirectory_CreateTempSubdirectoryWithPrefix_ShouldCreateDirectoryWithGivenPrefixInTempDirectory() + { + // Arrange + var fileSystem = new MockFileSystem(); + + // Act + var result = fileSystem.Directory.CreateTempSubdirectory("foo-"); + + // Assert + await That(fileSystem.Directory.Exists(result.FullName)).IsTrue(); + await That(Path.GetFileName(result.FullName).StartsWith("foo-")).IsTrue(); + await That(result.FullName.Contains(fileSystem.Path.GetTempPath())).IsTrue(); + } +#endif + + [Test] + public async Task MockDirectory_Delete_ShouldDeleteDirectory() + { + // Arrange + var fileSystem = new MockFileSystem(new Dictionary + { + { XFS.Path(@"c:\bar\foo.txt"), new MockFileData("Demo text content") } + }); + + // Act + fileSystem.Directory.Delete(XFS.Path(@"c:\bar"), true); + + // Assert + await That(fileSystem.Directory.Exists(XFS.Path(@"c:\bar"))).IsFalse(); + } + + [Test] + public async Task MockDirectory_Delete_ShouldNotDeleteAllDirectories() + { + // Arrange + var folder1Path = XFS.Path(@"D:\Test\Program"); + var folder1SubFolderPath = XFS.Path(@"D:\Test\Program\Subfolder"); + var folder2Path = XFS.Path(@"D:\Test\Program_bak"); + + var fileSystem = new MockFileSystem(); + + fileSystem.AddDirectory(folder1Path); + fileSystem.AddDirectory(folder2Path); + fileSystem.AddDirectory(folder1SubFolderPath); + + // Act + fileSystem.Directory.Delete(folder1Path, recursive: true); + + // Assert + await That(fileSystem.Directory.Exists(folder1Path)).IsFalse(); + await That(fileSystem.Directory.Exists(folder1SubFolderPath)).IsFalse(); + await That(fileSystem.Directory.Exists(folder2Path)).IsTrue(); + } + + [Test] + [WindowsOnly(WindowsSpecifics.CaseInsensitivity)] + public async Task MockDirectory_Delete_ShouldDeleteDirectoryCaseInsensitively() + { + // Arrange + var fileSystem = new MockFileSystem(new Dictionary + { + { XFS.Path(@"c:\bar\foo.txt"), new MockFileData("Demo text content") } + }); + + // Act + fileSystem.Directory.Delete(XFS.Path(@"c:\BAR"), true); + + // Assert + await That(fileSystem.Directory.Exists(XFS.Path(@"c:\bar"))).IsFalse(); + } + + [Test] + [UnixOnly(UnixSpecifics.CaseSensitivity)] + public async Task MockDirectory_Delete_ShouldThrowDirectoryNotFoundException_WhenSpecifiedWithInDifferentCase() + { + // Arrange + var fileSystem = new MockFileSystem(new Dictionary + { + { "/bar/foo.txt", new MockFileData("Demo text content") } + }); + + // Act + Action action = () => fileSystem.Directory.Delete("/BAR", true); + + // Assert + await That(action).Throws(); + } + + [Test] + [UnixOnly(UnixSpecifics.CaseSensitivity)] + public async Task MockDirectory_Delete_ShouldDeleteDirectoryCaseSensitively() + { + // Arrange + var fileSystem = new MockFileSystem(new Dictionary + { + { "/bar/foo.txt", new MockFileData("Demo text content") } + }); + + // Act + fileSystem.Directory.Delete("/bar", true); + + // Assert + await That(fileSystem.Directory.Exists("/bar")).IsFalse(); + } + + [Test] + public async Task MockDirectory_Delete_ShouldThrowDirectoryNotFoundException() + { + // Arrange + var fileSystem = new MockFileSystem(new Dictionary + { + { XFS.Path(@"c:\bar\foo.txt"), new MockFileData("Demo text content") } + }); + + var ex = await That(() => fileSystem.Directory.Delete(XFS.Path(@"c:\baz"))).Throws(); + + await That(ex.Message).IsEqualTo($"'{XFS.Path("c:\\baz")}' does not exist or could not be found."); + } + + [Test] + public async Task MockDirectory_Delete_ShouldThrowIOException() + { + // Arrange + var fileSystem = new MockFileSystem(new Dictionary + { + { XFS.Path(@"c:\bar\foo.txt"), new MockFileData("Demo text content") }, + { XFS.Path(@"c:\bar\baz.txt"), new MockFileData("Demo text content") } + }); + + var ex = await That(() => fileSystem.Directory.Delete(XFS.Path(@"c:\bar"))).Throws(); + + await That(ex.Message).IsEqualTo("The directory specified by " + XFS.Path("c:\\bar") + " is read-only, or recursive is false and " + XFS.Path("c:\\bar") + " is not an empty directory."); + } + + [Test] + public async Task MockDirectory_Delete_ShouldDeleteDirectoryRecursively() + { + // Arrange + var fileSystem = new MockFileSystem(new Dictionary + { + { XFS.Path(@"c:\bar\foo.txt"), new MockFileData("Demo text content") }, + { XFS.Path(@"c:\bar\bar2\foo.txt"), new MockFileData("Demo text content") } + }); + + // Act + fileSystem.DirectoryInfo.New(XFS.Path(@"c:\bar")).Delete(true); + + // Assert + await That(fileSystem.Directory.Exists(XFS.Path(@"c:\bar"))).IsFalse(); + await That(fileSystem.Directory.Exists(XFS.Path(@"c:\bar\bar2"))).IsFalse(); + } + + [Test] + public async Task MockDirectory_Delete_ShouldThrowIOException_WhenPathIsAFile() + { + // Arrange + var fileSystem = new MockFileSystem(new Dictionary + { + { XFS.Path(@"c:\foo.txt"), new MockFileData("Demo text content") }, + }); + + // Act + Action action = () => fileSystem.Directory.Delete(XFS.Path(@"c:\foo.txt")); + + // Assert + await That(action).Throws(); + } + + [Test] + public async Task MockDirectory_GetFileSystemEntries_Returns_Files_And_Directories() + { + string testPath = XFS.Path(@"c:\foo\bar.txt"); + string testDir = XFS.Path(@"c:\foo\bar"); + var fileSystem = new MockFileSystem(new Dictionary + { + { testPath, new MockFileData("Demo text content") }, + { testDir, new MockDirectoryData() } + }); + + var entries = fileSystem.Directory.GetFileSystemEntries(XFS.Path(@"c:\foo")).OrderBy(k => k); + await That(entries.Count()).IsEqualTo(2); + await That(entries.First()).IsEqualTo(testDir); + await That(entries.Last()).IsEqualTo(testPath); + } + + [Test] + public async Task MockDirectory_GetFileSystemEntries_ShouldNotReturnSubDirectory_WithSearchOption() + { + string testPath = XFS.Path(@"c:\foo\bar.txt"); + string testDir = XFS.Path(@"c:\foo\bar"); + string testSubDir = XFS.Path(@"c:\foo\bar\baz"); + var fileSystem = new MockFileSystem(new Dictionary + { + { testPath, new MockFileData("Demo text content") }, + { testSubDir, new MockDirectoryData() }, + }); + + var entries = fileSystem.Directory.GetFileSystemEntries(XFS.Path(@"c:\foo"), "*", SearchOption.TopDirectoryOnly).OrderBy(k => k); + await That(entries.Count()).IsEqualTo(2); + await That(entries.First()).IsEqualTo(testDir); + await That(entries.Last()).IsEqualTo(testPath); + } + + [Test] + public async Task MockDirectory_GetFiles_ShouldThrowArgumentNullException_IfPathParamIsNull() + { + var fileSystem = new MockFileSystem(new Dictionary()); + + Action action = () => fileSystem.Directory.GetFiles(null); + await That(action).Throws(); + } + + [Test] + public async Task MockDirectory_GetFiles_ShouldThrowDirectoryNotFoundException_IfPathDoesNotExists() + { + // Arrange + var fileSystem = new MockFileSystem(); + + // Act + Action action = () => fileSystem.Directory.GetFiles(XFS.Path(@"c:\Foo"), "*a.txt"); + + // Assert + await That(action).Throws(); + } + + [Test] + public async Task MockDirectory_GetFiles_Returns_Files() + { + string testPath = XFS.Path(@"c:\foo\bar.txt"); + string testDir = XFS.Path(@"c:\foo\bar\"); + var fileSystem = new MockFileSystem(new Dictionary + { + { testPath, new MockFileData("Demo text content") }, + { testDir, new MockDirectoryData() } + }); + + var entries = fileSystem.Directory.GetFiles(XFS.Path(@"c:\foo")).OrderBy(k => k); + await That(entries.Count()).IsEqualTo(1); + await That(entries.First()).IsEqualTo(testPath); + } + + [Test] + public async Task MockDirectory_GetFiles_Returns_Files_WithRelativePath() + { + // arrange + var fileSystem = new MockFileSystem(new Dictionary()); + + string directory = XFS.Path(@"C:\foo"); + + fileSystem.Directory.SetCurrentDirectory(directory); + fileSystem.AddFile(XFS.Path(@"C:\test.txt"), new MockFileData("Some ASCII text.")); + + await That(fileSystem.Directory.GetFiles(XFS.Path(@"..\")).Length).IsEqualTo(1); // Assert with relative path + } + + [Test] + public async Task MockDirectory_GetFiles_ShouldThrowAnArgumentNullException_IfSearchPatternIsNull() + { + // Arrange + var directoryPath = XFS.Path(@"c:\Foo"); + var fileSystem = new MockFileSystem(); + fileSystem.AddDirectory(directoryPath); + + // Act + Action action = () => fileSystem.Directory.GetFiles(directoryPath, null); + + // Assert + await That(action).Throws(); + } + + [Test] + public async Task MockDirectory_GetFiles_ShouldThrowAnArgumentException_IfSearchPatternEndsWithTwoDots() + { + // Arrange + var directoryPath = XFS.Path(@"c:\Foo"); + var fileSystem = new MockFileSystem(); + fileSystem.AddDirectory(directoryPath); + + // Act + Action action = () => fileSystem.Directory.GetFiles(directoryPath, "*a.."); + + // Assert + await That(action).Throws(); + } + + [TestCase(@"..\")] + [TestCase(@"aaa\vv..\")] + [TestCase(@"a..\b")] + [WindowsOnly(WindowsSpecifics.StrictPathRules)] + public async Task MockDirectory_GetFiles_ShouldThrowAnArgumentException_IfSearchPatternContainsTwoDotsFollowedByOneBackslash(string searchPattern) + { + // Arrange + var directoryPath = XFS.Path(@"c:\Foo"); + var fileSystem = new MockFileSystem(); + fileSystem.AddDirectory(directoryPath); + + // Act + Action action = () => fileSystem.Directory.GetFiles(directoryPath, searchPattern); + + // Assert + await That(action).Throws(); + } + + [TestCase(@"a../b")] + [TestCase(@"../")] + public async Task MockDirectory_GetFiles_ShouldThrowAnArgumentException_IfSearchPatternContainsTwoDotsFollowedByOneSlash(string searchPattern) + { + // Arrange + var directoryPath = XFS.Path(@"c:\Foo"); + var fileSystem = new MockFileSystem(); + fileSystem.AddDirectory(directoryPath); + + // Act + Action action = () => fileSystem.Directory.GetFiles(directoryPath, searchPattern); + + // Assert + await That(action).Throws(); + } + + [Test] + public async Task MockDirectory_GetFiles_ShouldFindFilesContainingTwoOrMoreDots() + { + // Arrange + string testPath = XFS.Path(@"c:\foo..r\bar.txt"); + var fileSystem = new MockFileSystem(new Dictionary + { + { testPath, new MockFileData(string.Empty) } + }); + + // Act + var actualResult = fileSystem.Directory.GetFiles(XFS.Path(@"c:\"), XFS.Path(@"foo..r\*")); + + // Assert + await That(actualResult).IsEquivalentTo(new[] { testPath }); + } + + [TestCase("aa\t")] + [WindowsOnly(WindowsSpecifics.StrictPathRules)] + public async Task MockDirectory_GetFiles_ShouldThrowAnArgumentException_IfSearchPatternHasIllegalCharacters(string searchPattern) + { + // Arrange + var directoryPath = XFS.Path(@"c:\Foo"); + var fileSystem = new MockFileSystem(); + fileSystem.AddDirectory(directoryPath); + + // Act + Action action = () => fileSystem.Directory.GetFiles(directoryPath, searchPattern); + + // Assert + await That(action).Throws(); + } + + [Test] + public async Task MockDirectory_GetRoot_Returns_Root() + { + string testDir = XFS.Path(@"c:\foo\bar\"); + var fileSystem = new MockFileSystem(new Dictionary + { + { testDir, new MockDirectoryData() } + }); + + await That(fileSystem.Directory.GetDirectoryRoot(XFS.Path(@"C:\foo\bar"))).IsEqualTo(XFS.Path("C:\\")); + } + + [Test] + public async Task MockDirectory_GetLogicalDrives_Returns_LogicalDrives() + { + var fileSystem = new MockFileSystem(new Dictionary + { + {XFS.Path(@"c:\foo\bar\"), new MockDirectoryData()}, + {XFS.Path(@"c:\foo\baz\"), new MockDirectoryData()}, + {XFS.Path(@"d:\bash\"), new MockDirectoryData()}, + }); + + var drives = fileSystem.Directory.GetLogicalDrives(); + + if (XFS.IsUnixPlatform()) + { + await That(drives.Length).IsEqualTo(1); + await That(drives.Contains("/")).IsTrue(); + } + else + { + await That(drives.Length).IsEqualTo(2); + await That(drives.Contains(@"C:\")).IsTrue(); + await That(drives.Contains(@"D:\")).IsTrue(); + } + } + + [Test] + public async Task MockDirectory_GetDirectories_Returns_Child_Directories() + { + var fileSystem = new MockFileSystem(new Dictionary + { + { XFS.Path(@"A:\folder1\folder2\folder3\file.txt"), new MockFileData("Demo text content") }, + { XFS.Path(@"A:\folder1\folder4\file2.txt"), new MockFileData("Demo text content 2") }, + }); + + var directories = fileSystem.Directory.GetDirectories(XFS.Path(@"A:\folder1")).ToArray(); + + //Check that it does not returns itself + await That(directories.Contains(XFS.Path(@"A:\folder1"))).IsFalse(); + + //Check that it correctly returns all child directories + await That(directories.Count()).IsEqualTo(2); + await That(directories.Contains(XFS.Path(@"A:\folder1\folder2"))).IsTrue(); + await That(directories.Contains(XFS.Path(@"A:\folder1\folder4"))).IsTrue(); + } + + [Test] + public async Task MockDirectory_GetDirectories_WithTopDirectories_ShouldOnlyReturnTopDirectories() + { + // Arrange + var fileSystem = new MockFileSystem(); + fileSystem.AddDirectory(XFS.Path(@"C:\Folder\.foo\")); + fileSystem.AddDirectory(XFS.Path(@"C:\Folder\foo")); + fileSystem.AddDirectory(XFS.Path(@"C:\Folder\foo.foo")); + fileSystem.AddDirectory(XFS.Path(@"C:\Folder\.foo\.foo")); + fileSystem.AddFile(XFS.Path(@"C:\Folder\.foo\bar"), new MockFileData(string.Empty)); + + // Act + var actualResult = fileSystem.Directory.GetDirectories(XFS.Path(@"C:\Folder\"), "*.foo"); + + // Assert + await That(actualResult).IsEquivalentTo(new[] { XFS.Path(@"C:\Folder\.foo"), XFS.Path(@"C:\Folder\foo.foo") }); + } + + [Test] + public async Task MockDirectory_GetDirectories_RelativeWithNoSubDirectories_ShouldReturnDirectories() + { + // Arrange + var fileSystem = new MockFileSystem(); + fileSystem.Directory.CreateDirectory("Folder"); + + // Act + var actualResult = fileSystem.Directory.GetDirectories("Folder"); + + // Assert + await That(actualResult).IsEmpty(); + } + + [TestCase(@"Folder\SubFolder")] + [TestCase(@"Folder")] + public async Task MockDirectory_GetDirectories_RelativeDirectory_WithoutChildren_ShouldReturnNoChildDirectories(string relativeDirPath) + { + // Arrange + var fileSystem = new MockFileSystem(); + fileSystem.Directory.CreateDirectory(relativeDirPath); + + // Act + var actualResult = fileSystem.Directory.GetDirectories(relativeDirPath); + + // Assert + await That(actualResult).IsEmpty(); + } + + [TestCase(@"Folder\SubFolder")] + [TestCase(@"Folder")] + public async Task MockDirectory_GetDirectories_RelativeDirectory_WithChildren_ShouldReturnChildDirectories(string relativeDirPath) + { + // Arrange + var currentDirectory = XFS.Path(@"T:\foo"); + var fileSystem = new MockFileSystem(null, currentDirectory: currentDirectory); + fileSystem.Directory.CreateDirectory(XFS.Path(relativeDirPath)); + fileSystem.Directory.CreateDirectory(XFS.Path(relativeDirPath + @"\child")); + + // Act + var actualResult = fileSystem.Directory.GetDirectories(XFS.Path(relativeDirPath)); + + // Assert + await That(actualResult).IsEqualTo(new[] { XFS.Path(relativeDirPath + @"\child") }); + } + + [Test] + public async Task MockDirectory_GetDirectories_AbsoluteWithNoSubDirectories_ShouldReturnDirectories() + { + // Arrange + var fileSystem = new MockFileSystem(); + fileSystem.Directory.CreateDirectory("Folder"); + + // Act + var fullPath = fileSystem.Path.GetFullPath("Folder"); + var actualResult = fileSystem.Directory.GetDirectories(fullPath); + + // Assert + await That(actualResult).IsEmpty(); + } + + [Test] + public async Task MockDirectory_GetDirectories_WithAllDirectories_ShouldReturnsAllMatchingSubFolders() + { + // Arrange + var fileSystem = new MockFileSystem(); + fileSystem.AddDirectory(XFS.Path(@"C:\Folder\.foo\")); + fileSystem.AddDirectory(XFS.Path(@"C:\Folder\foo")); + fileSystem.AddDirectory(XFS.Path(@"C:\Folder\foo.foo")); + fileSystem.AddDirectory(XFS.Path(@"C:\Folder\.foo\.foo")); + fileSystem.AddFile(XFS.Path(@"C:\Folder\.foo\bar"), new MockFileData(string.Empty)); + + // Act + var actualResult = fileSystem.Directory.GetDirectories(XFS.Path(@"C:\Folder\"), "*.foo", SearchOption.AllDirectories); + + // Assert + await That(actualResult).IsEquivalentTo(new[] { XFS.Path(@"C:\Folder\.foo"), XFS.Path(@"C:\Folder\foo.foo"), XFS.Path(@"C:\Folder\.foo\.foo") }); + } + + [Test] + public async Task MockDirectory_GetDirectories_ShouldThrowWhenPathIsNotMocked() + { + // Arrange + var fileSystem = new MockFileSystem(new Dictionary + { + { XFS.Path(@"c:\a.gif"), new MockFileData("Demo text content") }, + { XFS.Path(@"c:\b.txt"), new MockFileData("Demo text content") }, + { XFS.Path(@"c:\c.txt"), new MockFileData("Demo text content") }, + { XFS.Path(@"c:\a\a.txt"), new MockFileData("Demo text content") }, + { XFS.Path(@"c:\a\b.gif"), new MockFileData("Demo text content") }, + { XFS.Path(@"c:\a\c.txt"), new MockFileData("Demo text content") }, + { XFS.Path(@"c:\a\a\a.txt"), new MockFileData("Demo text content") }, + { XFS.Path(@"c:\a\a\b.txt"), new MockFileData("Demo text content") }, + { XFS.Path(@"c:\a\a\c.gif"), new MockFileData("Demo text content") }, + }); + + // Act + Action action = () => fileSystem.Directory.GetDirectories(XFS.Path(@"c:\d")); + + // Assert + await That(action).Throws(); + } + + [Test] + public async Task MockDirectory_EnumerateDirectories_Returns_Child_Directories() + { + var fileSystem = new MockFileSystem(new Dictionary + { + { XFS.Path(@"A:\folder1\folder2\folder3\file.txt"), new MockFileData("Demo text content") }, + { XFS.Path(@"A:\folder1\folder4\file2.txt"), new MockFileData("Demo text content 2") }, + }); + + var directories = fileSystem.Directory.EnumerateDirectories(XFS.Path(@"A:\folder1")).ToArray(); + + //Check that it does not returns itself + await That(directories.Contains(XFS.Path(@"A:\folder1"))).IsFalse(); + + //Check that it correctly returns all child directories + await That(directories.Count()).IsEqualTo(2); + await That(directories.Contains(XFS.Path(@"A:\folder1\folder2"))).IsTrue(); + await That(directories.Contains(XFS.Path(@"A:\folder1\folder4"))).IsTrue(); + } + + [Test] + public async Task MockDirectory_EnumerateDirectories_WithTopDirectories_ShouldOnlyReturnTopDirectories() + { + // Arrange + var fileSystem = new MockFileSystem(); + fileSystem.AddDirectory(XFS.Path(@"C:\Folder\.foo\")); + fileSystem.AddDirectory(XFS.Path(@"C:\Folder\foo")); + fileSystem.AddDirectory(XFS.Path(@"C:\Folder\foo.foo")); + fileSystem.AddDirectory(XFS.Path(@"C:\Folder\.foo\.foo")); + fileSystem.AddFile(XFS.Path(@"C:\Folder\.foo\bar"), new MockFileData(string.Empty)); + + // Act + var actualResult = fileSystem.Directory.EnumerateDirectories(XFS.Path(@"C:\Folder\"), "*.foo"); + + // Assert + await That(actualResult).IsEquivalentTo(new[] { XFS.Path(@"C:\Folder\.foo"), XFS.Path(@"C:\Folder\foo.foo") }); + } + +#if FEATURE_ENUMERATION_OPTIONS + [Test] + public async Task MockDirectory_EnumerateDirectories_WithEnumerationOptionsTopDirectories_ShouldOnlyReturnTopDirectories() + { + // Arrange + var fileSystem = new MockFileSystem(); + fileSystem.AddDirectory(XFS.Path(@"C:\Folder\.foo\")); + fileSystem.AddDirectory(XFS.Path(@"C:\Folder\foo")); + fileSystem.AddDirectory(XFS.Path(@"C:\Folder\foo.foo")); + fileSystem.AddDirectory(XFS.Path(@"C:\Folder\.foo\.foo")); + fileSystem.AddFile(XFS.Path(@"C:\Folder\.foo\bar"), new MockFileData(string.Empty)); + + var enumerationOptions = new EnumerationOptions + { + RecurseSubdirectories = false + }; + + // Act + var actualResult = fileSystem.Directory.EnumerateDirectories(XFS.Path(@"C:\Folder\"), "*.foo", enumerationOptions); + + // Assert + await That(actualResult).IsEquivalentTo(new[] { XFS.Path(@"C:\Folder\.foo"), XFS.Path(@"C:\Folder\foo.foo") }); + } +#endif + [Test] + public async Task MockDirectory_EnumerateDirectories_WithAllDirectories_ShouldReturnsAllMatchingSubFolders() + { + // Arrange + var fileSystem = new MockFileSystem(); + fileSystem.AddDirectory(XFS.Path(@"C:\Folder\.foo\")); + fileSystem.AddDirectory(XFS.Path(@"C:\Folder\foo")); + fileSystem.AddDirectory(XFS.Path(@"C:\Folder\foo.foo")); + fileSystem.AddDirectory(XFS.Path(@"C:\Folder\.foo\.foo")); + fileSystem.AddFile(XFS.Path(@"C:\Folder\.foo\bar"), new MockFileData(string.Empty)); + + // Act + var actualResult = fileSystem.Directory.EnumerateDirectories(XFS.Path(@"C:\Folder\"), "*.foo", SearchOption.AllDirectories); + + // Assert + await That(actualResult).IsEquivalentTo(new[] { XFS.Path(@"C:\Folder\.foo"), XFS.Path(@"C:\Folder\foo.foo"), XFS.Path(@"C:\Folder\.foo\.foo") }); + } + + [Test] + public async Task MockDirectory_EnumerateDirectories_ShouldThrowWhenPathIsNotMocked() + { + // Arrange + var fileSystem = new MockFileSystem(new Dictionary + { + { XFS.Path(@"c:\a.gif"), new MockFileData("Demo text content") }, + { XFS.Path(@"c:\b.txt"), new MockFileData("Demo text content") }, + { XFS.Path(@"c:\c.txt"), new MockFileData("Demo text content") }, + { XFS.Path(@"c:\a\a.txt"), new MockFileData("Demo text content") }, + { XFS.Path(@"c:\a\b.gif"), new MockFileData("Demo text content") }, + { XFS.Path(@"c:\a\c.txt"), new MockFileData("Demo text content") }, + { XFS.Path(@"c:\a\a\a.txt"), new MockFileData("Demo text content") }, + { XFS.Path(@"c:\a\a\b.txt"), new MockFileData("Demo text content") }, + { XFS.Path(@"c:\a\a\c.gif"), new MockFileData("Demo text content") }, + }); + + // Act + Action action = () => fileSystem.Directory.EnumerateDirectories(XFS.Path(@"c:\d")); + + // Assert + await That(action).Throws(); + } + + [TestCaseSource(nameof(GetPrefixTestPaths))] + public async Task MockDirectory_EnumerateDirectories_ShouldReturnPathsPrefixedWithQueryPath( + string queryPath, string expectedPath) + { + var fileSystem = new MockFileSystem(); + fileSystem.Directory.CreateDirectory("Folder/SubFolder"); + + var actualResult = fileSystem.Directory.EnumerateDirectories(queryPath); + + await That(actualResult).IsEqualTo(new[] { expectedPath }); + } + + private static IEnumerable GetPrefixTestPaths() + { + var sep = Path.DirectorySeparatorChar; + yield return new object[] { "Folder", $"Folder{sep}SubFolder" }; + yield return new object[] { $"Folder{sep}", $"Folder{sep}SubFolder" }; + yield return new object[] { $"Folder{sep}..{sep}.{sep}Folder", $"Folder{sep}..{sep}.{sep}Folder{sep}SubFolder" }; + } + + public static IEnumerable GetPathsForMoving() + { + yield return new object[] { XFS.Path(@"a:\folder1\"), XFS.Path(@"A:\folder3\"), XFS.Path("file.txt"), XFS.Path(@"folder2\file2.txt") }; + yield return new object[] { XFS.Path(@"A:\folder1\"), XFS.Path(@"A:\folder3\"), XFS.Path("file.txt"), XFS.Path(@"folder2\file2.txt") }; + yield return new object[] { XFS.Path(@"a:\folder1\"), XFS.Path(@"a:\folder3\"), XFS.Path("file.txt"), XFS.Path(@"folder2\file2.txt") }; + yield return new object[] { XFS.Path(@"A:\folder1\"), XFS.Path(@"a:\folder3\"), XFS.Path("file.txt"), XFS.Path(@"folder2\file2.txt") }; + yield return new object[] { XFS.Path(@"A:\folder1\"), XFS.Path(@"a:\folder3\"), XFS.Path("file.txt"), XFS.Path(@"Folder2\file2.txt") }; + yield return new object[] { XFS.Path(@"A:\folder1\"), XFS.Path(@"a:\folder3\"), XFS.Path("file.txt"), XFS.Path(@"Folder2\fiLe2.txt") }; + yield return new object[] { XFS.Path(@"A:\folder1\"), XFS.Path(@"a:\folder3\"), XFS.Path("folder444\\file.txt"), XFS.Path(@"Folder2\fiLe2.txt") }; + } + + [Test] + public async Task Move_DirectoryExistsWithDifferentCase_DirectorySuccessfullyMoved() + { + // Arrange + var fileSystem = new MockFileSystem(); + fileSystem.AddDirectory(XFS.Path(@"C:\OLD_LOCATION\Data")); + fileSystem.AddFile(XFS.Path(@"C:\old_location\Data\someFile.txt"), new MockFileData("abc")); + + // Act + fileSystem.Directory.Move(XFS.Path(@"C:\old_location"), XFS.Path(@"C:\NewLocation\")); + + // Assert + await That(fileSystem.File.Exists(XFS.Path(@"C:\NewLocation\Data\someFile.txt"))).IsTrue(); + } + + [TestCaseSource(nameof(GetPathsForMoving))] + public async Task MockDirectory_Move_ShouldMoveDirectories(string sourceDirName, string destDirName, string filePathOne, string filePathTwo) + { + // Arrange + var fileSystem = new MockFileSystem(new Dictionary + { + { XFS.Path(sourceDirName + filePathOne) , new MockFileData("aaa") }, + { XFS.Path(sourceDirName + filePathTwo) , new MockFileData("bbb") }, + }); + + // Act + fileSystem.DirectoryInfo.New(sourceDirName).MoveTo(destDirName); + + // Assert + await That(fileSystem.Directory.Exists(sourceDirName)).IsFalse(); + await That(fileSystem.File.Exists(XFS.Path(destDirName + filePathOne))).IsTrue(); + await That(fileSystem.File.Exists(XFS.Path(destDirName + filePathTwo))).IsTrue(); + } + + [Test] + public async Task MockDirectory_Move_ShouldMoveFiles() + { + string sourceFilePath = XFS.Path(@"c:\demo.txt"); + string sourceFileContent = "this is some content"; + + var fileSystem = new MockFileSystem(new Dictionary + { + { sourceFilePath, new MockFileData(sourceFileContent) } + }); + + string destFilePath = XFS.Path(@"c:\demo1.txt"); + + fileSystem.Directory.Move(sourceFilePath, destFilePath); + + await That(fileSystem.FileExists(destFilePath)).IsTrue(); + await That(fileSystem.FileExists(sourceFilePath)).IsFalse(); + await That(fileSystem.GetFile(destFilePath).TextContents).IsEqualTo(sourceFileContent); + } + + [Test] + public async Task MockDirectory_Move_ShouldMoveDirectoryAttributes() + { + // Arrange + var sourceDirName = XFS.Path(@"a:\folder1\"); + var destDirName = XFS.Path(@"a:\folder2\"); + const string filePathOne = "file1.txt"; + const string filePathTwo = "file2.txt"; + var fileSystem = new MockFileSystem(new Dictionary + { + { XFS.Path(sourceDirName + filePathOne) , new MockFileData("aaa") }, + { XFS.Path(sourceDirName + filePathTwo) , new MockFileData("bbb") }, + }); + + var sourceDirectoryInfo = fileSystem.DirectoryInfo.New(sourceDirName); + sourceDirectoryInfo.Attributes |= FileAttributes.System; + + // Act + fileSystem.DirectoryInfo.New(sourceDirName).MoveTo(destDirName); + + // Assert + var destDirectoryInfo = fileSystem.DirectoryInfo.New(destDirName); + await That(destDirectoryInfo.Attributes.HasFlag(FileAttributes.System)).IsTrue(); + } + + [Test] + public async Task MockDirectory_Move_ShouldMoveDirectoryWithReadOnlySubDirectory() + { + // Arrange + var sourceDirName = XFS.Path(@"a:\folder1\"); + var sourceSubDirName = XFS.Path(@"a:\folder1\sub\"); + + var destDirName = XFS.Path(@"a:\folder2\"); + var destSubDirName = XFS.Path(@"a:\folder2\sub\"); + + var fileSystem = new MockFileSystem(); + fileSystem.AddDirectory(sourceSubDirName); + + var subDirectoryInfo = fileSystem.DirectoryInfo.New(sourceSubDirName); + subDirectoryInfo.Attributes |= FileAttributes.ReadOnly; + + var sourceDirectoryInfo = fileSystem.DirectoryInfo.New(sourceDirName); + + // Act + fileSystem.DirectoryInfo.New(sourceDirName).MoveTo(destDirName); + + // Assert + await That(fileSystem.Directory.Exists(sourceSubDirName)).IsFalse(); + await That(fileSystem.FileExists(destSubDirName)).IsTrue(); + } + + [Test] + public async Task MockDirectory_Move_ShouldOnlyMoveDirAndFilesWithinDir() + { + // Arrange + var fileSystem = new MockFileSystem(new Dictionary + { + {XFS.Path(@"c:\source\dummy"), new MockDirectoryData()}, + {XFS.Path(@"c:\source\dummy\content.txt"), new MockFileData(new byte[] {0})}, + {XFS.Path(@"c:\source\dummy.txt"), new MockFileData(new byte[] {0})}, + {XFS.Path(@"c:\source\dummy2"), new MockDirectoryData()}, + {XFS.Path(@"c:\destination"), new MockDirectoryData()}, + }); + + // Act + fileSystem.Directory.Move(XFS.Path(@"c:\source\dummy"), XFS.Path(@"c:\destination\dummy")); + + // Assert + await That(fileSystem.FileExists(XFS.Path(@"c:\source\dummy.txt"))).IsTrue(); + await That(fileSystem.Directory.Exists(XFS.Path(@"c:\source\dummy2"))).IsTrue(); + } + + [Test] + public async Task MockDirectory_GetCurrentDirectory_ShouldReturnValueFromFileSystemConstructor() + { + string directory = XFS.Path(@"D:\folder1\folder2"); + var fileSystem = new MockFileSystem(new Dictionary(), directory); + + var actual = fileSystem.Directory.GetCurrentDirectory(); + + await That(actual).IsEqualTo(directory); + } + + [Test] + public async Task MockDirectory_GetCurrentDirectory_ShouldReturnDefaultPathWhenNotSet() + { + string directory = XFS.Path(@"C:\"); + + var fileSystem = new MockFileSystem(); + + var actual = fileSystem.Directory.GetCurrentDirectory(); + + await That(actual).IsEqualTo(directory); + } + + [Test] + public async Task MockDirectory_SetCurrentDirectory_ShouldChangeCurrentDirectory() + { + string directory = XFS.Path(@"D:\folder1\folder2"); + var fileSystem = new MockFileSystem(); + + // Precondition + await That(fileSystem.Directory.GetCurrentDirectory()).IsNotEqualTo(directory); + + fileSystem.Directory.SetCurrentDirectory(directory); + + await That(fileSystem.Directory.GetCurrentDirectory()).IsEqualTo(directory); + } + + [Test] + public async Task MockDirectory_SetCurrentDirectory_WithRelativePath_ShouldUseFullPath() + { + var fileSystem = new MockFileSystem(); + fileSystem.Directory.SetCurrentDirectory("."); + + var result = fileSystem.Directory.GetCurrentDirectory(); + + await That(fileSystem.Path.IsPathRooted(result)).IsTrue(); + } + + [Test] + public async Task MockDirectory_GetParent_ShouldThrowArgumentNullExceptionIfPathIsNull() + { + // Arrange + var fileSystem = new MockFileSystem(); + + // Act + Action act = () => fileSystem.Directory.GetParent(null); + + // Assert + await That(act).Throws(); + } + + [Test] + public async Task MockDirectory_GetParent_ShouldThrowArgumentExceptionIfPathIsEmpty() + { + // Arrange + var fileSystem = new MockFileSystem(); + + // Act + Action act = () => fileSystem.Directory.GetParent(string.Empty); + + // Assert + await That(act).Throws(); + } + + [Test] + public async Task MockDirectory_GetParent_ShouldReturnADirectoryInfoIfPathDoesNotExist() + { + // Arrange + var fileSystem = new MockFileSystem(); + + // Act + var actualResult = fileSystem.Directory.GetParent(XFS.Path(@"c:\directory\does\not\exist")); + + // Assert + await That(actualResult).IsNotNull(); + } + + [Test] + [WindowsOnly(WindowsSpecifics.StrictPathRules)] + public async Task MockDirectory_GetParent_ShouldThrowArgumentExceptionIfPathHasIllegalCharacters() + { + // Arrange + var fileSystem = new MockFileSystem(); + + // Act + Action act = () => fileSystem.Directory.GetParent(XFS.Path("c:\\director\ty\\has\\illegal\\character")); + + // Assert + await That(act).Throws(); + } + + [Test] + public async Task MockDirectory_GetParent_ShouldReturnNullIfPathIsRoot() + { + // Arrange + var fileSystem = new MockFileSystem(); + fileSystem.AddDirectory(XFS.Path(@"c:\")); + + // Act + var actualResult = fileSystem.Directory.GetParent(XFS.Path(@"c:\")); + + // Assert + await That(actualResult).IsNull(); + } + + [Test] + [UnixOnly(UnixSpecifics.SlashRoot)] + public async Task MockDirectory_GetParent_ShouldReturnRootIfDirectoryIsInRoot() + { + // Arrange + var fileSystem = new MockFileSystem(); + fileSystem.AddDirectory("/bar"); + + // Act + var parent = fileSystem.Directory.GetParent("/bar"); + + // Assert + await That(parent.FullName).IsEqualTo("/"); + } + + public static IEnumerable MockDirectory_GetParent_Cases + { + get + { + yield return new[] { XFS.Path(@"c:\a"), XFS.Path(@"c:\") }; + yield return new[] { XFS.Path(@"c:\a\b\c\d"), XFS.Path(@"c:\a\b\c") }; + yield return new[] { XFS.Path(@"c:\a\b\c\d\"), XFS.Path(@"c:\a\b\c") }; + } + } + + public async Task MockDirectory_GetParent_ShouldReturnTheParentWithoutTrailingDirectorySeparatorChar(string path, string expectedResult) + { + // Arrange + var fileSystem = new MockFileSystem(); + fileSystem.AddDirectory(path); + + // Act + var actualResult = fileSystem.Directory.GetParent(path); + + // Assert + await That(actualResult.FullName).IsEqualTo(expectedResult); + } + + [Test] + public async Task MockDirectory_Move_ShouldThrowAnIOExceptionIfBothPathAreIdentical() + { + // Arrange + string path = XFS.Path(@"c:\a"); + var fileSystem = new MockFileSystem(); + fileSystem.AddDirectory(path); + + // Act + Action action = () => fileSystem.Directory.Move(path, path); + + // Assert + await That(action, "Source and destination path must be different.").Throws(); + } + + [Test] + [WindowsOnly(WindowsSpecifics.Drives)] + public async Task MockDirectory_Move_ShouldThrowAnIOExceptionIfDirectoriesAreOnDifferentVolumes() + { + // Arrange + string sourcePath = XFS.Path(@"c:\a"); + string destPath = XFS.Path(@"d:\v"); + var fileSystem = new MockFileSystem(); + fileSystem.AddDirectory(sourcePath); + + // Act + Action action = () => fileSystem.Directory.Move(sourcePath, destPath); + + // Assert + await That(action, "Source and destination path must have identical roots. Move will not work across volumes.").Throws(); + } + + [Test] + public async Task MockDirectory_Move_ShouldThrowADirectoryNotFoundExceptionIfDestinationDirectoryDoesNotExist() + { + // Arrange + string sourcePath = XFS.Path(@"c:\a"); + string destPath = XFS.Path(@"c:\b"); + var fileSystem = new MockFileSystem(); + + // Act + Action action = () => fileSystem.Directory.Move(sourcePath, destPath); + + // Assert + await That(action, "Could not find a part of the path 'c:\a'.").Throws(); + } + + [Test] + public async Task MockDirectory_Move_ShouldThrowAnIOExceptionIfDestinationDirectoryExists() + { + // Arrange + string sourcePath = XFS.Path(@"c:\a"); + string destPath = XFS.Path(@"c:\b"); + var fileSystem = new MockFileSystem(); + fileSystem.AddDirectory(sourcePath); + fileSystem.AddDirectory(destPath); + + // Act + Action action = () => fileSystem.Directory.Move(sourcePath, destPath); + + // Assert + await That(action, "Cannot create 'c:\b\' because a file or directory with the same name already exists.'").Throws(); + } + + [Test] + public async Task MockDirectory_EnumerateFiles_ShouldReturnAllFilesBelowPathWhenPatternIsWildcardAndSearchOptionIsAllDirectories() + { + // Arrange + var fileSystem = SetupFileSystem(); + IEnumerable expected = new[] + { + XFS.Path(@"c:\a\a.txt"), + XFS.Path(@"c:\a\b.gif"), + XFS.Path(@"c:\a\c.txt"), + XFS.Path(@"c:\a\d"), + XFS.Path(@"c:\a\a\a.txt"), + XFS.Path(@"c:\a\a\b.txt"), + XFS.Path(@"c:\a\a\c.gif"), + XFS.Path(@"c:\a\a\d") + }; + + // Act + var result = fileSystem.Directory.EnumerateFiles(XFS.Path(@"c:\a"), "*", SearchOption.AllDirectories); + + // Assert + await That(result).IsEqualTo(expected).InAnyOrder(); + } + +#if FEATURE_ENUMERATION_OPTIONS + [Test] + public async Task MockDirectory_EnumerateFiles_ShouldReturnAllFilesBelowPathWhenPatternIsWildcardAndEnumerationOptionsIsAllDirectories() + { + // Arrange + var fileSystem = SetupFileSystem(); + IEnumerable expected = new[] + { + XFS.Path(@"c:\a\a.txt"), + XFS.Path(@"c:\a\b.gif"), + XFS.Path(@"c:\a\c.txt"), + XFS.Path(@"c:\a\d"), + XFS.Path(@"c:\a\a\a.txt"), + XFS.Path(@"c:\a\a\b.txt"), + XFS.Path(@"c:\a\a\c.gif"), + XFS.Path(@"c:\a\a\d") + }; + + var enumerationOptions = new EnumerationOptions + { + RecurseSubdirectories = true + }; + + // Act + var result = fileSystem.Directory.EnumerateFiles(XFS.Path(@"c:\a"), "*", enumerationOptions); + + // Assert + await That(result).IsEqualTo(expected).InAnyOrder(); + } + +#endif + + [Test] + public async Task MockDirectory_EnumerateFiles_ShouldFilterByExtensionBasedSearchPattern() + { + // Arrange + var fileSystem = SetupFileSystem(); + var expected = new[] + { + XFS.Path(@"c:\a.gif"), + XFS.Path(@"c:\a\b.gif"), + XFS.Path(@"c:\a\a\c.gif") + }; + + // Act + var result = fileSystem.Directory.EnumerateFiles(XFS.Path(@"c:\"), "*.gif", SearchOption.AllDirectories); + + // Assert + await That(result).IsEqualTo(expected).InAnyOrder(); + } + + [Test] + public async Task MockDirectory_EnumerateFiles_WhenFilterIsUnRooted_ShouldFindFilesInCurrentDirectory() + { + // Arrange + var someContent = new MockFileData(String.Empty); + var fileSystem = new MockFileSystem(new Dictionary + { + { XFS.Path(@"c:\a.txt"), someContent }, + { XFS.Path(@"c:\a\a.txt"), someContent }, + { XFS.Path(@"c:\a\b\b.txt"), someContent }, + { XFS.Path(@"c:\a\c\c.txt"), someContent }, + }); + + var expected = new[] + { + XFS.Path(@"c:\a\b\b.txt"), + }; + + fileSystem.Directory.SetCurrentDirectory(XFS.Path(@"c:\a")); + + // Act + var result = fileSystem.Directory.EnumerateFiles(XFS.Path("b")); + + // Assert + await That(result).IsEqualTo(expected).InAnyOrder(); + } + + [Test] + public async Task MockDirectory_EnumerateFiles_WhenFilterIsUnRooted_ShouldNotFindFilesInPathOutsideCurrentDirectory() + { + // Arrange + var someContent = new MockFileData(String.Empty); + var fileSystem = new MockFileSystem(new Dictionary + { + { XFS.Path(@"c:\a.txt"), someContent }, + { XFS.Path(@"c:\a\b\b.txt"), someContent }, + { XFS.Path(@"c:\c\b\b.txt"), someContent }, + }); + + var expected = new[] + { + XFS.Path(@"c:\a\b\b.txt"), + }; + + fileSystem.Directory.SetCurrentDirectory(XFS.Path(@"c:\a")); + + // Act + var result = fileSystem.Directory.EnumerateFiles(XFS.Path("b")); + + // Assert + await That(result).IsEqualTo(expected).InAnyOrder(); + } + + [Test] + public async Task MockDirectory_EnumerateFileSystemEntries_ShouldReturnAllFilesBelowPathWhenPatternIsWildcardAndSearchOptionIsAllDirectories() + { + // Arrange + var fileSystem = SetupFileSystem(); + IEnumerable expected = new[] + { + XFS.Path(@"c:\a\a.txt"), + XFS.Path(@"c:\a\b.gif"), + XFS.Path(@"c:\a\c.txt"), + XFS.Path(@"c:\a\d"), + XFS.Path(@"c:\a\a\a.txt"), + XFS.Path(@"c:\a\a\b.txt"), + XFS.Path(@"c:\a\a\c.gif"), + XFS.Path(@"c:\a\a\d"), + XFS.Path(@"c:\a\a") + }; + + // Act + var result = fileSystem.Directory.EnumerateFileSystemEntries(XFS.Path(@"c:\a"), "*", SearchOption.AllDirectories); + + // Assert + await That(result).IsEqualTo(expected).InAnyOrder(); + } + + [Test] + public async Task MockDirectory_EnumerateFileSystemEntries_ShouldFilterByExtensionBasedSearchPattern() + { + // Arrange + var fileSystem = SetupFileSystem(); + var expected = new[] + { + XFS.Path(@"c:\a.gif"), + XFS.Path(@"c:\a\b.gif"), + XFS.Path(@"c:\a\a\c.gif") + }; + + // Act + var result = fileSystem.Directory.EnumerateFileSystemEntries(XFS.Path(@"c:\"), "*.gif", SearchOption.AllDirectories); + + // Assert + await That(result).IsEqualTo(expected).InAnyOrder(); + } + +#if FEATURE_ENUMERATION_OPTIONS + [Test] + public async Task MockDirectory_EnumerateFileSystemEntries_ShouldReturnAllFilesBelowPathWhenPatternIsWildcardAndEnumerationOptionsIsAllDirectories() + { + // Arrange + var fileSystem = SetupFileSystem(); + IEnumerable expected = new[] + { + XFS.Path(@"c:\a\a.txt"), + XFS.Path(@"c:\a\b.gif"), + XFS.Path(@"c:\a\c.txt"), + XFS.Path(@"c:\a\d"), + XFS.Path(@"c:\a\a\a.txt"), + XFS.Path(@"c:\a\a\b.txt"), + XFS.Path(@"c:\a\a\c.gif"), + XFS.Path(@"c:\a\a\d"), + XFS.Path(@"c:\a\a") + }; + + var enumerationOptions = new EnumerationOptions + { + RecurseSubdirectories = true + }; + + // Act + var result = fileSystem.Directory.EnumerateFileSystemEntries(XFS.Path(@"c:\a"), "*", enumerationOptions); + + // Assert + await That(result).IsEqualTo(expected).InAnyOrder(); + } +#endif + + [Test] + public async Task MockDirectory_GetAccessControl_ShouldThrowExceptionOnDirectoryNotFound() + { + // Arrange + var fileSystem = new MockFileSystem(); + + // Act +#pragma warning disable CA1416 + await That(() => fileSystem.Directory.GetAccessControl(XFS.Path(@"c:\foo"))).Throws(); +#pragma warning restore CA1416 + } + + [Test] + [WindowsOnly(WindowsSpecifics.AccessControlLists)] + [SupportedOSPlatform("windows")] + public async Task MockDirectory_GetAccessControl_ShouldReturnNewDirectorySecurity() + { + // Arrange + var fileSystem = new MockFileSystem(); + fileSystem.Directory.CreateDirectory(XFS.Path(@"c:\foo\")); + + // Act + DirectorySecurity result = fileSystem.Directory.GetAccessControl(XFS.Path(@"c:\foo\")); + + // Assert + await That(result).IsNotNull(); + } + + [Test] + public async Task MockDirectory_SetCreationTime_ShouldNotThrowWithoutTrailingBackslash() + { + var path = XFS.Path(@"C:\NoTrailingBackslash"); + var fs = new MockFileSystem(); + fs.Directory.CreateDirectory(path); + await That(()=> fs.Directory.SetCreationTime(path, DateTime.Now)).DoesNotThrow(); + fs.Directory.Delete(path); + } + + private static IEnumerable Failing_DirectoryMoveFromToPaths + { + get + { + var testTargetDirs = new[] + { + @"c:\temp2\fd\df", @"c:\temp2\fd\", @"c:\temp2\fd\..\fd", @"c:\temp2\fd", @".\..\temp2\fd\df", + @".\..\temp2\fd\df\..", @".\..\temp2\fd\df\..\", @"..\temp2\fd\", @".\temp2\fd", @"temp2\fd", + @"c:\temp3\exists2\d3", @"c:\temp4\exists" + }; + + var testSourceDirs = new[] { @"c:\temp\exists\foldertomove", @"c:\temp3\exists", @"c:\temp3" }; + + return + from s in testSourceDirs + from t in testTargetDirs + select new TestCaseData(XFS.Path(s), XFS.Path(t)); + } + } + + [Test] + [TestCaseSource(nameof(Failing_DirectoryMoveFromToPaths))] + public async Task Move_Directory_Throws_When_Target_Directory_Parent_Does_Not_Exist( + string sourceDirName, + string targetDirName) + { + // Arange + var fileSystem = new MockFileSystem(); + fileSystem.Directory.CreateDirectory(sourceDirName); + + // Act + await That(() => fileSystem.Directory.Move(sourceDirName, targetDirName)) + .Throws(); + + // Assert + await That(fileSystem.Directory.Exists(targetDirName)).IsFalse(); + await That(fileSystem.Directory.Exists(sourceDirName)).IsTrue(); + } + + private static IEnumerable Success_DirectoryMoveFromToPaths + { + get + { + var testTargetDirs = new[] + { + @"c:\temp2\", @"c:\temp2", @"c:\temp2\..\temp2", @".\..\temp2", @".\..\temp2\..\temp2", + @".\..\temp2\fd\df\..\..", @".\..\temp2\fd\df\..\..\", @"..\temp2", @".\temp2", @"\temp2", @"temp2", + }; + + var testSourceDirs = new[] { @"c:\temp3\exists\foldertomove", @"c:\temp3\exists", @"c:\temp4" }; + + return + from s in testSourceDirs + from t in testTargetDirs + select new TestCaseData(XFS.Path(s), XFS.Path(t)); + } + } + + [Test] + [TestCaseSource(nameof(Success_DirectoryMoveFromToPaths))] + public async Task Move_Directory_DoesNotThrow_When_Target_Directory_Parent_Exists( + string sourceDirName, + string targetDirName) + { + // Arrange + var fileSystem = new MockFileSystem(); + fileSystem.Directory.CreateDirectory(sourceDirName); + + // Act + await That(() => fileSystem.Directory.Move(sourceDirName, targetDirName)).DoesNotThrow(); + + // Assert + await That(fileSystem.Directory.Exists(targetDirName)).IsTrue(); + await That(fileSystem.Directory.Exists(sourceDirName)).IsFalse(); + } + + [Test] + public async Task MockDirectory_Exists_ShouldReturnTrue_IfArgIsFrontSlashAndRootDirExists() + { + string testDir = XFS.Path(@"c:\foo\bar\"); + var fileSystem = new MockFileSystem(new Dictionary + { + { testDir, new MockDirectoryData() } + }); + + await That(fileSystem.Directory.Exists("/")).IsEqualTo(true); + } + + [Test] + public static void MockDirectory_Move_ShouldNotThrowException_InWindows_When_SourceAndDestinationDifferOnlyInCasing() + { + // Arrange + MockFileSystem mockFs = new MockFileSystem(); + string tempDir = mockFs.Path.GetTempPath(); + string src = mockFs.Path.Combine(tempDir, "src"); + string dest = mockFs.Path.Combine(tempDir, "SRC"); + IDirectoryInfo srcDir = mockFs.DirectoryInfo.New(src); + srcDir.Create(); + + // Act & Assert + Assert.DoesNotThrow(() => mockFs.Directory.Move(src, dest)); + } +} diff --git a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockDriveInfoFactoryTests.cs b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockDriveInfoFactoryTests.cs new file mode 100644 index 000000000..cf36bb17b --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockDriveInfoFactoryTests.cs @@ -0,0 +1,110 @@ +using System; +using System.Linq; +using NUnit.Framework; + +namespace System.IO.Abstractions.TestingHelpers.Tests; + +using XFS = MockUnixSupport; + +[TestFixture] +[WindowsOnly(WindowsSpecifics.Drives)] +public class MockDriveInfoFactoryTests +{ + [Test] + public async Task MockDriveInfoFactory_GetDrives_ShouldReturnDrives() + { + // Arrange + var fileSystem = new MockFileSystem(); + fileSystem.AddDirectory(XFS.Path(@"C:\Test")); + fileSystem.AddDirectory(XFS.Path(@"Z:\Test")); + fileSystem.AddDirectory(XFS.Path(@"d:\Test")); + var factory = new MockDriveInfoFactory(fileSystem); + + // Act + var actualResults = factory.GetDrives(); + + var actualNames = actualResults.Select(d => d.Name); + + // Assert + await That(actualNames).IsEquivalentTo(new[] { @"C:\", @"Z:\", @"d:\" }); + } + + [Test] + public async Task MockDriveInfoFactory_GetDrives_ShouldReturnDrivesWithNoDuplicates() + { + // Arrange + var fileSystem = new MockFileSystem(); + fileSystem.AddDirectory(XFS.Path(@"C:\Test")); + fileSystem.AddDirectory(XFS.Path(@"c:\Test2")); + fileSystem.AddDirectory(XFS.Path(@"Z:\Test")); + fileSystem.AddDirectory(XFS.Path(@"d:\Test")); + fileSystem.AddDirectory(XFS.Path(@"d:\Test2")); + var factory = new MockDriveInfoFactory(fileSystem); + + // Act + var actualResults = factory.GetDrives(); + + var actualNames = actualResults.Select(d => d.Name); + + // Assert + await That(actualNames).IsEquivalentTo(new[] { @"C:\", @"Z:\", @"d:\" }); + } + + [Test] + public async Task MockDriveInfoFactory_GetDrives_ShouldReturnOnlyLocalDrives() + { + // Arrange + var fileSystem = new MockFileSystem(); + fileSystem.AddDirectory(XFS.Path(@"C:\Test")); + fileSystem.AddDirectory(XFS.Path(@"Z:\Test")); + fileSystem.AddDirectory(XFS.Path(@"d:\Test")); + fileSystem.AddDirectory(XFS.Path(@"\\anunc\share\Zzz")); + var factory = new MockDriveInfoFactory(fileSystem); + + // Act + var actualResults = factory.GetDrives(); + + var actualNames = actualResults.Select(d => d.Name); + + // Assert + await That(actualNames).IsEquivalentTo(new[] { @"C:\", @"Z:\", @"d:\" }); + } + + [Test] + public async Task MockDriveInfoFactory_New_WithDriveShouldReturnDrive() + { + // Arrange + var fileSystem = new MockFileSystem(); + var factory = new MockDriveInfoFactory(fileSystem); + + // Act + var actualResult = factory.New(@"Z:\"); + + // Assert + await That(actualResult.Name).IsEquivalentTo(@"Z:\"); + } + + [Test] + public async Task MockDriveInfoFactory_New_WithPathShouldReturnDrive() + { + // Arrange + var fileSystem = new MockFileSystem(); + var factory = new MockDriveInfoFactory(fileSystem); + + // Act + var actualResult = factory.New(@"Z:\foo\bar\"); + + // Assert + await That(actualResult.Name).IsEquivalentTo(@"Z:\"); + } + + [Test] + public async Task MockDriveInfoFactory_Wrap_WithNull_ShouldReturnNull() + { + var fileSystem = new MockFileSystem(); + + var result = fileSystem.DriveInfo.Wrap(null); + + await That(result).IsNull(); + } +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockDriveInfoTests.cs b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockDriveInfoTests.cs new file mode 100644 index 000000000..4946b34bb --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockDriveInfoTests.cs @@ -0,0 +1,221 @@ +using NUnit.Framework; +using System.Linq; + +namespace System.IO.Abstractions.TestingHelpers.Tests; + +using XFS = MockUnixSupport; + +[TestFixture] +[WindowsOnly(WindowsSpecifics.Drives)] +public class MockDriveInfoTests +{ + [TestCase(@"c:")] + [TestCase(@"c:\")] + public async Task MockDriveInfo_Constructor_ShouldInitializeLocalWindowsDrives(string driveName) + { + // Arrange + var fileSystem = new MockFileSystem(); + fileSystem.AddDirectory(XFS.Path(@"c:\Test")); + var path = XFS.Path(driveName); + + // Act + var driveInfo = new MockDriveInfo(fileSystem, path); + + // Assert + await That(driveInfo.Name).IsEqualTo(@"c:\"); + } + + [Test] + public async Task MockDriveInfo_Constructor_ShouldInitializeLocalWindowsDrives_SpecialForWindows() + { + // Arrange + var fileSystem = new MockFileSystem(); + fileSystem.AddDirectory(XFS.Path(@"c:\Test")); + + // Act + var driveInfo = new MockDriveInfo(fileSystem, "c"); + + // Assert + await That(driveInfo.Name).IsEqualTo(@"c:\"); + } + + [TestCase(@"\\unc\share")] + [TestCase(@"\\unctoo")] + public async Task MockDriveInfo_Constructor_ShouldThrowExceptionIfUncPath(string driveName) + { + // Arrange + var fileSystem = new MockFileSystem(); + + // Act + Action action = () => new MockDriveInfo(fileSystem, XFS.Path(driveName)); + + // Assert + await That(action).Throws(); + } + + [Test] + public async Task MockDriveInfo_RootDirectory_ShouldReturnTheDirectoryBase() + { + // Arrange + var fileSystem = new MockFileSystem(); + fileSystem.AddDirectory(XFS.Path(@"c:\Test")); + var driveInfo = new MockDriveInfo(fileSystem, "c:"); + var expectedDirectory = XFS.Path(@"c:\"); + + // Act + var actualDirectory = driveInfo.RootDirectory; + + // Assert + await That(actualDirectory.FullName).IsEqualTo(expectedDirectory); + } + + [TestCase("c:", "c:\\")] + [TestCase("C:", "C:\\")] + [TestCase("d:", "d:\\")] + [TestCase("e:", "e:\\")] + [TestCase("f:", "f:\\")] + public async Task MockDriveInfo_ToString_ShouldReturnTheDrivePath(string path, string expectedPath) + { + // Arrange + var directoryPath = XFS.Path(path); + + // Act + var mockDriveInfo = new MockDriveInfo(new MockFileSystem(), directoryPath); + + // Assert + await That(mockDriveInfo.ToString()).IsEqualTo(expectedPath); + } + + [Test] + public async Task MockDriveInfo_AvailableFreeSpace_ShouldReturnAvailableFreeSpaceOfDriveInMemoryFileSystem() + { + // Arrange + var availableFreeSpace = 1024L; + var driveData = new MockDriveData { AvailableFreeSpace = availableFreeSpace }; + var fileSystem = new MockFileSystem(); + fileSystem.AddDrive("C:", driveData); + var driveInfo = fileSystem.DriveInfo + .GetDrives() + .Single(x => x.Name == @"C:\"); + + // Act + var result = driveInfo.AvailableFreeSpace; + + // Assert + await That(result).IsEqualTo(availableFreeSpace); + } + + [Test] + public async Task MockDriveInfo_DriveFormat_ShouldReturnDriveFormatOfDriveInMemoryFileSystem() + { + // Arrange + var driveFormat = "NTFS"; + var driveData = new MockDriveData { DriveFormat = driveFormat }; + var fileSystem = new MockFileSystem(); + fileSystem.AddDrive("C:", driveData); + var driveInfo = fileSystem.DriveInfo + .GetDrives() + .Single(x => x.Name == @"C:\"); + + // Act + var result = driveInfo.DriveFormat; + + // Assert + await That(result).IsEqualTo(driveFormat); + } + + [Test] + public async Task MockDriveInfo_DriveType_ShouldReturnDriveTypeOfDriveInMemoryFileSystem() + { + // Arrange + var driveType = DriveType.Fixed; + var driveData = new MockDriveData { DriveType = driveType }; + var fileSystem = new MockFileSystem(); + fileSystem.AddDrive("C:", driveData); + var driveInfo = fileSystem.DriveInfo + .GetDrives() + .Single(x => x.Name == @"C:\"); + + // Act + var result = driveInfo.DriveType; + + // Assert + await That(result).IsEqualTo(driveType); + } + + [TestCase(true)] + [TestCase(false)] + public async Task MockDriveInfo_IsReady_ShouldReturnIsReadyOfDriveInMemoryFileSystem(bool isReady) + { + // Arrange + var driveData = new MockDriveData { IsReady = isReady }; + var fileSystem = new MockFileSystem(); + fileSystem.AddDrive("C:", driveData); + var driveInfo = fileSystem.DriveInfo + .GetDrives() + .Single(x => x.Name == @"C:\"); + + // Act + var result = driveInfo.IsReady; + + // Assert + await That(result).IsEqualTo(isReady); + } + + [Test] + public async Task MockDriveInfo_TotalFreeSpace_ShouldReturnTotalFreeSpaceOfDriveInMemoryFileSystem() + { + // Arrange + var totalFreeSpace = 4096L; + var driveData = new MockDriveData { TotalFreeSpace = totalFreeSpace }; + var fileSystem = new MockFileSystem(); + fileSystem.AddDrive("C:", driveData); + var driveInfo = fileSystem.DriveInfo + .GetDrives() + .Single(x => x.Name == @"C:\"); + + // Act + var result = driveInfo.TotalFreeSpace; + + // Assert + await That(result).IsEqualTo(totalFreeSpace); + } + + [Test] + public async Task MockDriveInfo_TotalSize_ShouldReturnTotalSizeOfDriveInMemoryFileSystem() + { + // Arrange + var totalSize = 8192L; + var driveData = new MockDriveData { TotalSize = totalSize }; + var fileSystem = new MockFileSystem(); + fileSystem.AddDrive("C:", driveData); + var driveInfo = fileSystem.DriveInfo + .GetDrives() + .Single(x => x.Name == @"C:\"); + + // Act + var result = driveInfo.TotalSize; + + // Assert + await That(result).IsEqualTo(totalSize); + } + + [Test] + public async Task MockDriveInfo_VolumeLabel_ShouldReturnVolumeLabelOfDriveInMemoryFileSystem() + { + // Arrange + var volumeLabel = "Windows"; + var driveData = new MockDriveData { VolumeLabel = volumeLabel }; + var fileSystem = new MockFileSystem(); + fileSystem.AddDrive("C:", driveData); + var driveInfo = fileSystem.DriveInfo + .GetDrives() + .Single(x => x.Name == @"C:\"); + + // Act + var result = driveInfo.VolumeLabel; + + // Assert + await That(result).IsEqualTo(volumeLabel); + } +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileAdjustTimesTest.cs b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileAdjustTimesTest.cs new file mode 100644 index 000000000..89d270c1a --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileAdjustTimesTest.cs @@ -0,0 +1,301 @@ +using System.Runtime.Versioning; +using System.Security.AccessControl; +using System.Text; +using NUnit.Framework; + +namespace System.IO.Abstractions.TestingHelpers.Tests; + +[TestFixture] +public class MockFileAdjustTimesTest +{ + [Test] + public async Task MockFile_AfterAppendAllText_ShouldUpdateLastAccessAndLastWriteTime() + { + var creationTime = DateTime.UtcNow.AddDays(10); + var updateTime = creationTime.AddDays(10); + var fileSystem = new MockFileSystem() + .MockTime(() => creationTime); + fileSystem.File.WriteAllText("foo.txt", "abc"); + fileSystem.MockTime(() => updateTime); + fileSystem.File.AppendAllText("foo.txt", "xyz"); + + var actualCreationTime = fileSystem.File.GetCreationTimeUtc("foo.txt"); + var actualLastAccessTime = fileSystem.File.GetLastAccessTimeUtc("foo.txt"); + var actualLastWriteTime = fileSystem.File.GetLastWriteTimeUtc("foo.txt"); + + await That(actualCreationTime).IsEqualTo(creationTime); + await That(actualLastAccessTime).IsEqualTo(updateTime); + await That(actualLastWriteTime).IsEqualTo(updateTime); + } + + [Test] + public async Task MockFile_AfterCopy_ShouldUpdateCreationAndLastAccessTimeOfDestination() + { + var creationTime = DateTime.UtcNow.AddDays(10); + var updateTime = creationTime.AddDays(10); + var fileSystem = new MockFileSystem() + .MockTime(() => creationTime); + fileSystem.File.WriteAllText("foo.txt", "abc"); + fileSystem.MockTime(() => updateTime); + fileSystem.File.Copy("foo.txt", "bar.txt"); + + var actualSourceCreationTime = fileSystem.File.GetCreationTimeUtc("foo.txt"); + var actualDestinationCreationTime = fileSystem.File.GetCreationTimeUtc("bar.txt"); + var actualSourceLastAccessTime = fileSystem.File.GetLastAccessTimeUtc("foo.txt"); + var actualDestinationLastAccessTime = fileSystem.File.GetLastAccessTimeUtc("bar.txt"); + var actualSourceLastWriteTime = fileSystem.File.GetLastWriteTimeUtc("foo.txt"); + var actualDestinationLastWriteTime = fileSystem.File.GetLastWriteTimeUtc("bar.txt"); + + await That(actualSourceCreationTime).IsEqualTo(creationTime); + await That(actualDestinationCreationTime).IsEqualTo(updateTime); + await That(actualSourceLastAccessTime).IsEqualTo(creationTime); + await That(actualDestinationLastAccessTime).IsEqualTo(updateTime); + await That(actualSourceLastWriteTime).IsEqualTo(creationTime); + await That(actualDestinationLastWriteTime).IsEqualTo(creationTime); + } + + [Test] + public async Task MockFile_AfterMove_ShouldUpdateLastAccessTime() + { + var creationTime = DateTime.UtcNow.AddDays(10); + var updateTime = creationTime.AddDays(10); + var fileSystem = new MockFileSystem() + .MockTime(() => creationTime); + fileSystem.File.WriteAllText("foo.txt", "abc"); + fileSystem.MockTime(() => updateTime); + fileSystem.File.Move("foo.txt", "bar.txt"); + + var actualCreationTime = fileSystem.File.GetCreationTimeUtc("bar.txt"); + var actualLastAccessTime = fileSystem.File.GetLastAccessTimeUtc("bar.txt"); + var actualLastWriteTime = fileSystem.File.GetLastWriteTimeUtc("bar.txt"); + + await That(actualCreationTime).IsEqualTo(creationTime); + await That(actualLastAccessTime).IsEqualTo(updateTime); + await That(actualLastWriteTime).IsEqualTo(creationTime); + } + + [TestCase(FileMode.Open, FileAccess.ReadWrite)] + [TestCase(FileMode.OpenOrCreate, FileAccess.Write)] + [TestCase(FileMode.Append, FileAccess.Write)] + public async Task MockFile_AfterOpen_WithWriteAccess_ShouldUpdateLastAccessAndLastWriteTime(FileMode fileMode, FileAccess fileAccess) + { + var creationTime = DateTime.UtcNow.AddDays(10); + var updateTime = creationTime.AddDays(10); + var fileSystem = new MockFileSystem() + .MockTime(() => creationTime); + fileSystem.File.WriteAllText("foo.txt", "abc"); + fileSystem.MockTime(() => updateTime); + fileSystem.File.Open("foo.txt", fileMode, fileAccess); + + var actualCreationTime = fileSystem.File.GetCreationTimeUtc("foo.txt"); + var actualLastAccessTime = fileSystem.File.GetLastAccessTimeUtc("foo.txt"); + var actualLastWriteTime = fileSystem.File.GetLastWriteTimeUtc("foo.txt"); + + await That(actualCreationTime).IsEqualTo(creationTime); + await That(actualLastAccessTime).IsEqualTo(updateTime); + await That(actualLastWriteTime).IsEqualTo(updateTime); + } + + [TestCase(FileMode.Open, FileAccess.Read)] + [TestCase(FileMode.OpenOrCreate, FileAccess.Read)] + public async Task MockFile_AfterOpen_WithReadOnlyAccess_ShouldUpdateLastAccessTime(FileMode fileMode, FileAccess fileAccess) + { + var creationTime = DateTime.UtcNow.AddDays(10); + var updateTime = creationTime.AddDays(10); + var fileSystem = new MockFileSystem() + .MockTime(() => creationTime); + fileSystem.File.WriteAllText("foo.txt", "abc"); + fileSystem.MockTime(() => updateTime); + fileSystem.File.Open("foo.txt", fileMode, fileAccess); + + var actualCreationTime = fileSystem.File.GetCreationTimeUtc("foo.txt"); + var actualLastAccessTime = fileSystem.File.GetLastAccessTimeUtc("foo.txt"); + var actualLastWriteTime = fileSystem.File.GetLastWriteTimeUtc("foo.txt"); + + await That(actualCreationTime).IsEqualTo(creationTime); + await That(actualLastAccessTime).IsEqualTo(updateTime); + await That(actualLastWriteTime).IsEqualTo(creationTime); + } + + [Test] + public async Task MockFile_AfterReadAllBytes_ShouldUpdateLastAccessTime() + { + var creationTime = DateTime.UtcNow.AddDays(10); + var updateTime = creationTime.AddDays(10); + var fileSystem = new MockFileSystem() + .MockTime(() => creationTime); + fileSystem.File.WriteAllText("foo.txt", "abc"); + fileSystem.MockTime(() => updateTime); + fileSystem.File.ReadAllBytes("foo.txt"); + + var actualCreationTime = fileSystem.File.GetCreationTimeUtc("foo.txt"); + var actualLastAccessTime = fileSystem.File.GetLastAccessTimeUtc("foo.txt"); + var actualLastWriteTime = fileSystem.File.GetLastWriteTimeUtc("foo.txt"); + + await That(actualCreationTime).IsEqualTo(creationTime); + await That(actualLastAccessTime).IsEqualTo(updateTime); + await That(actualLastWriteTime).IsEqualTo(creationTime); + } + + [Test] + public async Task MockFile_AfterReadAllLines_ShouldUpdateLastAccessTime() + { + var creationTime = DateTime.UtcNow.AddDays(10); + var updateTime = creationTime.AddDays(10); + var fileSystem = new MockFileSystem() + .MockTime(() => creationTime); + fileSystem.File.WriteAllText("foo.txt", "abc"); + fileSystem.MockTime(() => updateTime); + fileSystem.File.ReadAllLines("foo.txt"); + + var actualCreationTime = fileSystem.File.GetCreationTimeUtc("foo.txt"); + var actualLastAccessTime = fileSystem.File.GetLastAccessTimeUtc("foo.txt"); + var actualLastWriteTime = fileSystem.File.GetLastWriteTimeUtc("foo.txt"); + + await That(actualCreationTime).IsEqualTo(creationTime); + await That(actualLastAccessTime).IsEqualTo(updateTime); + await That(actualLastWriteTime).IsEqualTo(creationTime); + } + + [Test] + public async Task MockFile_AfterReadAllText_ShouldUpdateLastAccessTime() + { + var creationTime = DateTime.UtcNow.AddDays(10); + var updateTime = creationTime.AddDays(10); + var fileSystem = new MockFileSystem() + .MockTime(() => creationTime); + fileSystem.File.WriteAllText("foo.txt", "abc"); + fileSystem.MockTime(() => updateTime); + fileSystem.File.ReadAllText("foo.txt"); + + var actualCreationTime = fileSystem.File.GetCreationTimeUtc("foo.txt"); + var actualLastAccessTime = fileSystem.File.GetLastAccessTimeUtc("foo.txt"); + var actualLastWriteTime = fileSystem.File.GetLastWriteTimeUtc("foo.txt"); + + await That(actualCreationTime).IsEqualTo(creationTime); + await That(actualLastAccessTime).IsEqualTo(updateTime); + await That(actualLastWriteTime).IsEqualTo(creationTime); + } + + [Test] + public async Task MockFile_AfterSetAttributes_ShouldUpdateLastAccessTime() + { + var creationTime = DateTime.UtcNow.AddDays(10); + var updateTime = creationTime.AddDays(10); + var fileSystem = new MockFileSystem() + .MockTime(() => creationTime); + fileSystem.File.WriteAllText("foo.txt", "abc"); + fileSystem.MockTime(() => updateTime); + fileSystem.File.SetAttributes("foo.txt", FileAttributes.Hidden); + + var actualCreationTime = fileSystem.File.GetCreationTimeUtc("foo.txt"); + var actualLastAccessTime = fileSystem.File.GetLastAccessTimeUtc("foo.txt"); + var actualLastWriteTime = fileSystem.File.GetLastWriteTimeUtc("foo.txt"); + + await That(actualCreationTime).IsEqualTo(creationTime); + await That(actualLastAccessTime).IsEqualTo(updateTime); + await That(actualLastWriteTime).IsEqualTo(creationTime); + } + + [Test] + [SupportedOSPlatform("windows")] + [WindowsOnly(WindowsSpecifics.AccessControlLists)] + public async Task MockFile_AfterSetAccessControl_ShouldUpdateLastAccessTime() + { + var creationTime = DateTime.UtcNow.AddDays(10); + var updateTime = creationTime.AddDays(10); + var fileSystem = new MockFileSystem() + .MockTime(() => creationTime); + fileSystem.File.WriteAllText("foo.txt", "abc"); + fileSystem.MockTime(() => updateTime); + fileSystem.File.SetAccessControl("foo.txt", new FileSecurity()); + + var actualCreationTime = fileSystem.File.GetCreationTimeUtc("foo.txt"); + var actualLastAccessTime = fileSystem.File.GetLastAccessTimeUtc("foo.txt"); + var actualLastWriteTime = fileSystem.File.GetLastWriteTimeUtc("foo.txt"); + + await That(actualCreationTime).IsEqualTo(creationTime); + await That(actualLastAccessTime).IsEqualTo(creationTime); + await That(actualLastWriteTime).IsEqualTo(creationTime); + } + + [Test] + public async Task MockFile_AfterWriteAllBytes_ShouldUpdateLastAccessAndLastWriteTime() + { + var creationTime = DateTime.UtcNow.AddDays(10); + var updateTime = creationTime.AddDays(10); + var fileSystem = new MockFileSystem() + .MockTime(() => creationTime); + fileSystem.File.WriteAllText("foo.txt", "abc"); + fileSystem.MockTime(() => updateTime); + fileSystem.File.WriteAllBytes("foo.txt", Encoding.UTF8.GetBytes("xyz")); + + var actualCreationTime = fileSystem.File.GetCreationTimeUtc("foo.txt"); + var actualLastAccessTime = fileSystem.File.GetLastAccessTimeUtc("foo.txt"); + var actualLastWriteTime = fileSystem.File.GetLastWriteTimeUtc("foo.txt"); + + await That(actualCreationTime).IsEqualTo(creationTime); + await That(actualLastAccessTime).IsEqualTo(updateTime); + await That(actualLastWriteTime).IsEqualTo(updateTime); + } + + [Test] + public async Task MockFile_AfterWriteAllText_ShouldUpdateLastAccessAndLastWriteTime() + { + var creationTime = DateTime.UtcNow.AddDays(10); + var updateTime = creationTime.AddDays(10); + var fileSystem = new MockFileSystem() + .MockTime(() => creationTime); + fileSystem.File.WriteAllText("foo.txt", "abc"); + fileSystem.MockTime(() => updateTime); + fileSystem.File.WriteAllText("foo.txt", "xyz"); + + var actualCreationTime = fileSystem.File.GetCreationTimeUtc("foo.txt"); + var actualLastAccessTime = fileSystem.File.GetLastAccessTimeUtc("foo.txt"); + var actualLastWriteTime = fileSystem.File.GetLastWriteTimeUtc("foo.txt"); + + await That(actualCreationTime).IsEqualTo(creationTime); + await That(actualLastAccessTime).IsEqualTo(updateTime); + await That(actualLastWriteTime).IsEqualTo(updateTime); + } + + [Test] + public async Task MockFileStream_OpenRead_ShouldUpdateLastAccessTime() + { + var creationTime = DateTime.UtcNow.AddDays(10); + var updateTime = creationTime.AddDays(10); + var fileSystem = new MockFileSystem() + .MockTime(() => creationTime); + fileSystem.File.WriteAllText("foo.txt", "abc"); + fileSystem.MockTime(() => updateTime); + _ = fileSystem.File.OpenRead("foo.txt"); + + var actualCreationTime = fileSystem.File.GetCreationTimeUtc("foo.txt"); + var actualLastAccessTime = fileSystem.File.GetLastAccessTimeUtc("foo.txt"); + var actualLastWriteTime = fileSystem.File.GetLastWriteTimeUtc("foo.txt"); + + await That(actualCreationTime).IsEqualTo(creationTime); + await That(actualLastAccessTime).IsEqualTo(updateTime); + await That(actualLastWriteTime).IsEqualTo(creationTime); + } + + [Test] + public async Task MockFileStream_OpenWrite_ShouldUpdateLastAccessAndLastWriteTime() + { + var creationTime = DateTime.UtcNow.AddDays(10); + var updateTime = creationTime.AddDays(10); + var fileSystem = new MockFileSystem() + .MockTime(() => creationTime); + fileSystem.File.WriteAllText("foo.txt", "abc"); + fileSystem.MockTime(() => updateTime); + _ = fileSystem.File.OpenWrite("foo.txt"); + + var actualCreationTime = fileSystem.File.GetCreationTimeUtc("foo.txt"); + var actualLastAccessTime = fileSystem.File.GetLastAccessTimeUtc("foo.txt"); + var actualLastWriteTime = fileSystem.File.GetLastWriteTimeUtc("foo.txt"); + + await That(actualCreationTime).IsEqualTo(creationTime); + await That(actualLastAccessTime).IsEqualTo(updateTime); + await That(actualLastWriteTime).IsEqualTo(updateTime); + } +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileAppendAllLinesTests.cs b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileAppendAllLinesTests.cs new file mode 100644 index 000000000..f67ed4c76 --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileAppendAllLinesTests.cs @@ -0,0 +1,256 @@ +using System.Collections.Generic; +using NUnit.Framework; +using XFS = System.IO.Abstractions.TestingHelpers.MockUnixSupport; +using System.Threading.Tasks; +using System.Threading; + +namespace System.IO.Abstractions.TestingHelpers.Tests; + +public class MockFileAppendAllLinesTests +{ + [Test] + public async Task MockFile_AppendAllLines_ShouldPersistNewLinesToExistingFile() + { + // Arrange + string path = XFS.Path(@"c:\something\demo.txt"); + var fileSystem = new MockFileSystem(new Dictionary + { + { path, new MockFileData("Demo text content") } + }); + + var file = new MockFile(fileSystem); + + // Act + file.AppendAllLines(path, new[] { "line 1", "line 2", "line 3" }); + + // Assert + await That(file.ReadAllText(path)) + .IsEqualTo("Demo text contentline 1" + Environment.NewLine + "line 2" + Environment.NewLine + "line 3" + Environment.NewLine); + } + + [Test] + public async Task MockFile_AppendAllLines_ShouldPersistNewLinesToNewFile() + { + // Arrange + string path = XFS.Path(@"c:\something\demo.txt"); + var fileSystem = new MockFileSystem(new Dictionary + { + { XFS.Path(@"c:\something\"), new MockDirectoryData() } + }); + var file = new MockFile(fileSystem); + + // Act + file.AppendAllLines(path, new[] { "line 1", "line 2", "line 3" }); + + // Assert + await That(file.ReadAllText(path)) + .IsEqualTo("line 1" + Environment.NewLine + "line 2" + Environment.NewLine + "line 3" + Environment.NewLine); + } + + [Test] + public async Task MockFile_AppendAllLines_ShouldThrowArgumentExceptionIfPathIsZeroLength() + { + // Arrange + var fileSystem = new MockFileSystem(); + + // Act + Action action = () => fileSystem.File.AppendAllLines(string.Empty, new[] { "does not matter" }); + + // Assert + await That(action).Throws(); + } + + [TestCase(" ")] + [TestCase(" ")] + public async Task MockFile_AppendAllLines_ShouldThrowArgumentExceptionIfPathContainsOnlyWhitespaces(string path) + { + // Arrange + var fileSystem = new MockFileSystem(); + + // Act + Action action = () => fileSystem.File.AppendAllLines(path, new[] { "does not matter" }); + + // Assert + await That(action).Throws(); + } + + [TestCase("\"")] + [TestCase("<")] + [TestCase(">")] + [TestCase("|")] + [WindowsOnly(WindowsSpecifics.StrictPathRules)] + public async Task MockFile_AppendAllLines_ShouldThrowArgumentExceptionIfPathContainsInvalidChar(string path) + { + // Arrange + var fileSystem = new MockFileSystem(); + + // Act + Action action = () => fileSystem.File.AppendAllLines(path, new[] { "does not matter" }); + + // Assert + await That(action).Throws(); + } + + [Test] + public async Task MockFile_AppendAllLines_ShouldThrowArgumentNullExceptionIfContentIsNull() + { + // Arrange + var fileSystem = new MockFileSystem(); + + // Act + Action action = () => fileSystem.File.AppendAllLines("foo", null); + + // Assert + var exception = await That(action).Throws(); + await That(exception.ParamName).IsEqualTo("contents"); + } + + [Test] + public async Task MockFile_AppendAllLines_ShouldThrowArgumentNullExceptionIfEncodingIsNull() + { + // Arrange + var fileSystem = new MockFileSystem(); + + // Act + Action action = () => fileSystem.File.AppendAllLines("foo.txt", new[] { "bar" }, null); + + // Assert + var exception = await That(action).Throws(); + await That(exception.ParamName).IsEqualTo("encoding"); + } + +#if FEATURE_ASYNC_FILE + [Test] + public async Task MockFile_AppendAllLinesAsync_ShouldPersistNewLinesToExistingFile() + { + // Arrange + string path = XFS.Path(@"c:\something\demo.txt"); + var fileSystem = new MockFileSystem(new Dictionary + { + { path, new MockFileData("Demo text content") } + }); + + var file = new MockFile(fileSystem); + + // Act + await file.AppendAllLinesAsync(path, new[] { "line 1", "line 2", "line 3" }); + + // Assert + await That(file.ReadAllText(path)) + .IsEqualTo("Demo text contentline 1" + Environment.NewLine + "line 2" + Environment.NewLine + "line 3" + Environment.NewLine); + } + + [Test] + public async Task MockFile_AppendAllLinesAsync_ShouldPersistNewLinesToNewFile() + { + // Arrange + string path = XFS.Path(@"c:\something\demo.txt"); + var fileSystem = new MockFileSystem(new Dictionary + { + { XFS.Path(@"c:\something\"), new MockDirectoryData() } + }); + var file = new MockFile(fileSystem); + + // Act + await file.AppendAllLinesAsync(path, new[] { "line 1", "line 2", "line 3" }); + + // Assert + await That(file.ReadAllText(path)) + .IsEqualTo("line 1" + Environment.NewLine + "line 2" + Environment.NewLine + "line 3" + Environment.NewLine); + } + + [Test] + public async Task MockFile_AppendAllLinesAsync_ShouldThrowOperationCanceledExceptionIfCancelled() + { + // Arrange + const string path = "test.txt"; + var fileSystem = new MockFileSystem(new Dictionary + { + { path, new MockFileData("line 1") } + }); + + // Act + async Task Act() => + await fileSystem.File.AppendAllLinesAsync( + path, + new[] { "line 2" }, + new CancellationToken(canceled: true)); + await That(Act).Throws(); + + // Assert + await That(fileSystem.File.ReadAllText(path)).IsEqualTo("line 1"); + } + + [Test] + public async Task MockFile_AppendAllLinesAsync_ShouldThrowArgumentExceptionIfPathIsZeroLength() + { + // Arrange + var fileSystem = new MockFileSystem(); + + // Act + Func action = async () => await fileSystem.File.AppendAllLinesAsync(string.Empty, new[] { "does not matter" }); + + // Assert + await That(action).Throws(); + } + + [TestCase(" ")] + [TestCase(" ")] + public async Task MockFile_AppendAllLinesAsync_ShouldThrowArgumentExceptionIfPathContainsOnlyWhitespaces(string path) + { + // Arrange + var fileSystem = new MockFileSystem(); + + // Act + Func action = async () => await fileSystem.File.AppendAllLinesAsync(path, new[] { "does not matter" }); + + // Assert + await That(action).Throws(); + } + + [TestCase("\"")] + [TestCase("<")] + [TestCase(">")] + [TestCase("|")] + [WindowsOnly(WindowsSpecifics.StrictPathRules)] + public async Task MockFile_AppendAllLinesAsync_ShouldThrowArgumentExceptionIfPathContainsInvalidChar(string path) + { + // Arrange + var fileSystem = new MockFileSystem(); + + // Act + Func action = async () => await fileSystem.File.AppendAllLinesAsync(path, new[] { "does not matter" }); + + // Assert + await That(action).Throws(); + } + + [Test] + public async Task MockFile_AppendAllLinesAsync_ShouldThrowArgumentNullExceptionIfContentIsNull() + { + // Arrange + var fileSystem = new MockFileSystem(); + + // Act + Func action = async () => await fileSystem.File.AppendAllLinesAsync("foo", null); + + // Assert + var exception = await That(action).Throws(); + await That(exception.ParamName).IsEqualTo("contents"); + } + + [Test] + public async Task MockFile_AppendAllLinesAsync_ShouldThrowArgumentNullExceptionIfEncodingIsNull() + { + // Arrange + var fileSystem = new MockFileSystem(); + + // Act + Func action = async () => await fileSystem.File.AppendAllLinesAsync("foo.txt", new[] { "bar" }, null); + + // Assert + var exception = await That(action).Throws(); + await That(exception.ParamName).IsEqualTo("encoding"); + } +#endif +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileAppendAllTextTests.cs b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileAppendAllTextTests.cs new file mode 100644 index 000000000..8a8f280e8 --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileAppendAllTextTests.cs @@ -0,0 +1,314 @@ +namespace System.IO.Abstractions.TestingHelpers.Tests; + +using Collections.Generic; + +using Globalization; + +using NUnit.Framework; +using Text; + +using XFS = MockUnixSupport; + +using System.Threading.Tasks; +using System.Threading; + +public class MockFileAppendAllTextTests +{ + [Test] + public async Task MockFile_AppendAllText_ShouldPersistNewText() + { + // Arrange + string path = XFS.Path(@"c:\something\demo.txt"); + var fileSystem = new MockFileSystem(new Dictionary + { + {path, new MockFileData("Demo text content")} + }); + + var file = new MockFile(fileSystem); + + // Act + file.AppendAllText(path, "+ some text"); + + // Assert + await That(file.ReadAllText(path)) + .IsEqualTo("Demo text content+ some text"); + } + + [Test] + public async Task MockFile_AppendAllText_ShouldPersistNewTextWithDifferentEncoding() + { + // Arrange + const string Path = @"c:\something\demo.txt"; + var fileSystem = new MockFileSystem(new Dictionary + { + {Path, new MockFileData("AA", Encoding.UTF32)} + }); + + var file = new MockFile(fileSystem); + + // Act + file.AppendAllText(Path, "BB", Encoding.UTF8); + + // Assert + await That(fileSystem.GetFile(Path).Contents) + .IsEqualTo(new byte[] { 255, 254, 0, 0, 65, 0, 0, 0, 65, 0, 0, 0, 66, 66 }); + } + + [Test] + public async Task MockFile_AppendAllText_ShouldCreateIfNotExist() + { + // Arrange + string path = XFS.Path(@"c:\something\demo.txt"); + var fileSystem = new MockFileSystem(new Dictionary + { + {path, new MockFileData("Demo text content")} + }); + + // Act + fileSystem.File.AppendAllText(path, " some text"); + + // Assert + await That(fileSystem.File.ReadAllText(path)) + .IsEqualTo("Demo text content some text"); + } + + [Test] + public async Task MockFile_AppendAllText_ShouldCreateIfNotExistWithBom() + { + // Arrange + var fileSystem = new MockFileSystem(new Dictionary()); + var path = XFS.Path(@"c:\something\demo3.txt"); + fileSystem.AddDirectory(XFS.Path(@"c:\something\")); + + // Act + fileSystem.File.AppendAllText(path, "AA", Encoding.UTF32); + + // Assert + await That(fileSystem.GetFile(path).Contents) + .IsEqualTo(new byte[] { 255, 254, 0, 0, 65, 0, 0, 0, 65, 0, 0, 0 }); + } + + [Test] + public async Task MockFile_AppendAllText_ShouldFailIfNotExistButDirectoryAlsoNotExist() + { + // Arrange + string path = XFS.Path(@"c:\something\demo.txt"); + var fileSystem = new MockFileSystem(new Dictionary + { + {path, new MockFileData("Demo text content")} + }); + + // Act + path = XFS.Path(@"c:\something2\demo.txt"); + + // Assert + Exception ex; + ex = await That(() => fileSystem.File.AppendAllText(path, "some text")).Throws(); + await That(ex.Message) + .IsEqualTo(String.Format(CultureInfo.InvariantCulture, "Could not find a part of the path '{0}'.", path)); + + ex = + await That( + () => fileSystem.File.AppendAllText(path, "some text", Encoding.Unicode)).Throws(); + await That(ex.Message) + .IsEqualTo(String.Format(CultureInfo.InvariantCulture, "Could not find a part of the path '{0}'.", path)); + } + + [Test] + public async Task MockFile_AppendAllText_ShouldPersistNewTextWithCustomEncoding() + { + // Arrange + string path = XFS.Path(@"c:\something\demo.txt"); + var fileSystem = new MockFileSystem(new Dictionary + { + {path, new MockFileData("Demo text content")} + }); + + var file = new MockFile(fileSystem); + + // Act + file.AppendAllText(path, "+ some text", Encoding.BigEndianUnicode); + + // Assert + var expected = new byte[] + { + 68, 101, 109, 111, 32, 116, 101, 120, 116, 32, 99, 111, 110, 116, + 101, 110, 116, 0, 43, 0, 32, 0, 115, 0, 111, 0, 109, 0, 101, + 0, 32, 0, 116, 0, 101, 0, 120, 0, 116 + }; + + await That(file.ReadAllBytes(path)).IsEqualTo(expected); + } + + [Test] + public async Task MockFile_AppendAllText_ShouldWorkWithRelativePath() + { + var file = "file.txt"; + var fileSystem = new MockFileSystem(); + + fileSystem.File.AppendAllText(file, "Foo"); + + await That(fileSystem.File.Exists(file)).IsTrue(); + } + +#if FEATURE_ASYNC_FILE + [Test] + public async Task MockFile_AppendAllTextAsync_ShouldPersistNewText() + { + // Arrange + string path = XFS.Path(@"c:\something\demo.txt"); + var fileSystem = new MockFileSystem(new Dictionary + { + {path, new MockFileData("Demo text content")} + }); + + var file = new MockFile(fileSystem); + + // Act + await file.AppendAllTextAsync(path, "+ some text"); + + // Assert + await That(file.ReadAllText(path)) + .IsEqualTo("Demo text content+ some text"); + } + + [Test] + public async Task MockFile_AppendAllTextAsync_ShouldThrowOperationCanceledExceptionIfCancelled() + { + // Arrange + const string path = "test.txt"; + var fileSystem = new MockFileSystem(new Dictionary + { + { path, new MockFileData("line 1") } + }); + + // Act + async Task Act() => + await fileSystem.File.AppendAllTextAsync( + path, + "line 2", + new CancellationToken(canceled: true)); + await That(Act).Throws(); + + // Assert + await That(fileSystem.File.ReadAllText(path)).IsEqualTo("line 1"); + } + + [Test] + public async Task MockFile_AppendAllTextAsync_ShouldPersistNewTextWithDifferentEncoding() + { + // Arrange + const string Path = @"c:\something\demo.txt"; + var fileSystem = new MockFileSystem(new Dictionary + { + {Path, new MockFileData("AA", Encoding.UTF32)} + }); + + var file = new MockFile(fileSystem); + + // Act + await file.AppendAllTextAsync(Path, "BB", Encoding.UTF8); + + // Assert + await That(fileSystem.GetFile(Path).Contents) + .IsEqualTo(new byte[] { 255, 254, 0, 0, 65, 0, 0, 0, 65, 0, 0, 0, 66, 66 }); + } + + [Test] + public async Task MockFile_AppendAllTextAsync_ShouldCreateIfNotExist() + { + // Arrange + string path = XFS.Path(@"c:\something\demo.txt"); + var fileSystem = new MockFileSystem(new Dictionary + { + {path, new MockFileData("Demo text content")} + }); + + // Act + await fileSystem.File.AppendAllTextAsync(path, " some text"); + + // Assert + await That(fileSystem.File.ReadAllText(path)) + .IsEqualTo("Demo text content some text"); + } + + [Test] + public async Task MockFile_AppendAllTextAsync_ShouldCreateIfNotExistWithBom() + { + // Arrange + var fileSystem = new MockFileSystem(new Dictionary()); + var path = XFS.Path(@"c:\something\demo3.txt"); + fileSystem.AddDirectory(XFS.Path(@"c:\something\")); + + // Act + await fileSystem.File.AppendAllTextAsync(path, "AA", Encoding.UTF32); + + // Assert + await That(fileSystem.GetFile(path).Contents) + .IsEqualTo(new byte[] { 255, 254, 0, 0, 65, 0, 0, 0, 65, 0, 0, 0 }); + } + + [Test] + public async Task MockFile_AppendAllTextAsync_ShouldFailIfNotExistButDirectoryAlsoNotExist() + { + // Arrange + string path = XFS.Path(@"c:\something\demo.txt"); + var fileSystem = new MockFileSystem(new Dictionary + { + {path, new MockFileData("Demo text content")} + }); + + // Act + path = XFS.Path(@"c:\something2\demo.txt"); + + // Assert + Exception ex; + Func action = async () => await fileSystem.File.AppendAllTextAsync(path, "some text"); + ex = await That(action).Throws(); + await That(ex.Message) + .IsEqualTo(String.Format(CultureInfo.InvariantCulture, "Could not find a part of the path '{0}'.", path)); + + async Task Act() => await fileSystem.File.AppendAllTextAsync(path, "some text", Encoding.Unicode); + ex = await That(Act).Throws(); + await That(ex.Message) + .IsEqualTo(String.Format(CultureInfo.InvariantCulture, "Could not find a part of the path '{0}'.", path)); + } + + [Test] + public async Task MockFile_AppendAllTextAsync_ShouldPersistNewTextWithCustomEncoding() + { + // Arrange + string path = XFS.Path(@"c:\something\demo.txt"); + var fileSystem = new MockFileSystem(new Dictionary + { + {path, new MockFileData("Demo text content")} + }); + + var file = new MockFile(fileSystem); + + // Act + await file.AppendAllTextAsync(path, "+ some text", Encoding.BigEndianUnicode); + + // Assert + var expected = new byte[] + { + 68, 101, 109, 111, 32, 116, 101, 120, 116, 32, 99, 111, 110, 116, + 101, 110, 116, 0, 43, 0, 32, 0, 115, 0, 111, 0, 109, 0, 101, + 0, 32, 0, 116, 0, 101, 0, 120, 0, 116 + }; + + await That(file.ReadAllBytes(path)).IsEqualTo(expected); + } + + [Test] + public async Task MockFile_AppendAllTextAsync_ShouldWorkWithRelativePath() + { + var file = "file.txt"; + var fileSystem = new MockFileSystem(); + + await fileSystem.File.AppendAllTextAsync(file, "Foo"); + + await That(fileSystem.File.Exists(file)).IsTrue(); + } +#endif +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileArgumentPathTests.cs b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileArgumentPathTests.cs new file mode 100644 index 000000000..5015a6d30 --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileArgumentPathTests.cs @@ -0,0 +1,73 @@ +using System.Collections.Generic; +using System.Linq; +using System.Text; +using Microsoft.Win32.SafeHandles; +using NUnit.Framework; + +namespace System.IO.Abstractions.TestingHelpers.Tests; + +public class MockFileArgumentPathTests +{ + private static IEnumerable> GetFileSystemActionsForArgumentNullException() + { + yield return fs => fs.AppendAllLines(null, new[] { "does not matter" }); + yield return fs => fs.AppendAllLines(null, new[] { "does not matter" }, Encoding.ASCII); + yield return fs => fs.AppendAllText(null, "does not matter"); + yield return fs => fs.AppendAllText(null, "does not matter", Encoding.ASCII); + yield return fs => fs.AppendText(null); + yield return fs => fs.WriteAllBytes(null, new byte[] { 0 }); + yield return fs => fs.WriteAllLines(null, new[] { "does not matter" }); + yield return fs => fs.WriteAllLines(null, new[] { "does not matter" }, Encoding.ASCII); + yield return fs => fs.WriteAllLines(null, new[] { "does not matter" }.ToArray()); + yield return fs => fs.WriteAllLines(null, new[] { "does not matter" }.ToArray(), Encoding.ASCII); + yield return fs => fs.Create(null); + yield return fs => fs.Delete(null); + yield return fs => fs.GetCreationTime((string)null); + yield return fs => fs.GetCreationTimeUtc((string)null); + yield return fs => fs.GetLastAccessTime((string)null); + yield return fs => fs.GetLastAccessTimeUtc((string)null); + yield return fs => fs.GetLastWriteTime((string)null); + yield return fs => fs.GetLastWriteTimeUtc((string)null); + yield return fs => fs.WriteAllText(null, "does not matter"); + yield return fs => fs.WriteAllText(null, "does not matter", Encoding.ASCII); + yield return fs => fs.Open(null, FileMode.OpenOrCreate); + yield return fs => fs.Open(null, FileMode.OpenOrCreate, FileAccess.Read); + yield return fs => fs.Open(null, FileMode.OpenOrCreate, FileAccess.Read, FileShare.Inheritable); + yield return fs => fs.OpenRead(null); + yield return fs => fs.OpenText(null); + yield return fs => fs.OpenWrite(null); + yield return fs => fs.ReadAllBytes(null); + yield return fs => fs.ReadAllLines(null); + yield return fs => fs.ReadAllLines(null, Encoding.ASCII); + yield return fs => fs.ReadAllText(null); + yield return fs => fs.ReadAllText(null, Encoding.ASCII); + yield return fs => fs.ReadLines(null); + yield return fs => fs.ReadLines(null, Encoding.ASCII); + yield return fs => fs.SetAttributes((string)null, FileAttributes.Archive); + yield return fs => fs.GetAttributes((string)null); + yield return fs => fs.SetCreationTime((string)null, DateTime.Now); + yield return fs => fs.SetCreationTimeUtc((string)null, DateTime.Now); + yield return fs => fs.SetLastAccessTime((string)null, DateTime.Now); + yield return fs => fs.SetLastAccessTimeUtc((string)null, DateTime.Now); + yield return fs => fs.SetLastWriteTime((string)null, DateTime.Now); + yield return fs => fs.SetLastWriteTimeUtc((string)null, DateTime.Now); +#pragma warning disable CA1416 + yield return fs => fs.Decrypt(null); + yield return fs => fs.Encrypt(null); +#pragma warning restore CA1416 + } + + [TestCaseSource(nameof(GetFileSystemActionsForArgumentNullException))] + public async Task Operations_ShouldThrowArgumentNullExceptionIfPathIsNull(Action action) + { + // Arrange + var fileSystem = new MockFileSystem(); + + // Act + Action wrapped = () => action(fileSystem.File); + + // Assert + var exception = await That(wrapped).Throws(); + await That(exception.ParamName).IsEqualTo("path"); + } +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileCopyTests.cs b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileCopyTests.cs new file mode 100644 index 000000000..7ffca2a0b --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileCopyTests.cs @@ -0,0 +1,436 @@ +namespace System.IO.Abstractions.TestingHelpers.Tests; + +using Collections.Generic; +using Globalization; +using Linq; +using NUnit.Framework; +using XFS = MockUnixSupport; + +public class MockFileCopyTests +{ + + [Test] + public async Task MockFile_Copy_ShouldOverwriteFileWhenOverwriteFlagIsTrue() + { + string sourceFileName = XFS.Path(@"c:\source\demo.txt"); + var sourceContents = new MockFileData("Source content"); + string destFileName = XFS.Path(@"c:\destination\demo.txt"); + var fileSystem = new MockFileSystem(new Dictionary + { + {sourceFileName, sourceContents}, + {destFileName, new MockFileData("Destination content")} + }); + + fileSystem.File.Copy(sourceFileName, destFileName, true); + + var copyResult = fileSystem.GetFile(destFileName); + await That(sourceContents.Contents).IsEqualTo(copyResult.Contents); + } + + [Test] + public async Task MockFile_Copy_ShouldAdjustTimestampsOnDestination() + { + var sourceFileName = XFS.Path(@"c:\source\demo.txt"); + var destFileName = XFS.Path(@"c:\source\demo_copy.txt"); + + var mockFileSystem = new MockFileSystem(); + mockFileSystem.AddFile(sourceFileName, "Original"); + mockFileSystem.File.Copy(sourceFileName, destFileName); + + var sourceFileInfo = mockFileSystem.FileInfo.New(sourceFileName); + var destFileInfo = mockFileSystem.FileInfo.New(destFileName); + await That(destFileInfo.LastWriteTime).IsEqualTo(sourceFileInfo.LastWriteTime); + await That(DateTime.Now - destFileInfo.CreationTime).IsLessThanOrEqualTo( TimeSpan.FromSeconds(1)); + await That(destFileInfo.LastAccessTime).IsEqualTo(destFileInfo.CreationTime); + } + + [Test] + public async Task MockFile_Copy_ShouldCloneContents() + { + var sourceFileName = XFS.Path(@"c:\source\demo.txt"); + var destFileName = XFS.Path(@"c:\source\demo_copy.txt"); + + var mockFileSystem = new MockFileSystem(); + mockFileSystem.AddFile(sourceFileName, "Original"); + mockFileSystem.File.Copy(sourceFileName, destFileName); + + using (var stream = mockFileSystem.File.Open(sourceFileName, FileMode.Open, FileAccess.ReadWrite)) + { + var binaryWriter = new System.IO.BinaryWriter(stream); + + binaryWriter.Seek(0, SeekOrigin.Begin); + binaryWriter.Write("Modified"); + } + + await That(mockFileSystem.File.ReadAllText(destFileName)).IsEqualTo("Original"); + } + + [Test] + public async Task MockFile_Copy_ShouldCloneBinaryContents() + { + var sourceFileName = XFS.Path(@"c:\source\demo.bin"); + var destFileName = XFS.Path(@"c:\source\demo_copy.bin"); + + byte[] original = new byte[] { 0xC0 }; + var mockFileSystem = new MockFileSystem(); + mockFileSystem.AddFile(sourceFileName, new MockFileData(original)); + mockFileSystem.File.Copy(sourceFileName, destFileName); + + using (var stream = mockFileSystem.File.Open(sourceFileName, FileMode.Open, FileAccess.ReadWrite)) + { + var binaryWriter = new System.IO.BinaryWriter(stream); + + binaryWriter.Seek(0, SeekOrigin.Begin); + binaryWriter.Write("Modified"); + } + + await That(mockFileSystem.File.ReadAllBytes(destFileName)).IsEqualTo(original); + } + + [Test] + public async Task MockFile_Copy_ShouldCreateFileAtNewDestination() + { + string sourceFileName = XFS.Path(@"c:\source\demo.txt"); + var sourceContents = new MockFileData("Source content"); + string destFileName = XFS.Path(@"c:\source\demo_copy.txt"); + var fileSystem = new MockFileSystem(new Dictionary + { + {sourceFileName, sourceContents} + }); + + fileSystem.File.Copy(sourceFileName, destFileName, false); + + var copyResult = fileSystem.GetFile(destFileName); + await That(sourceContents.Contents).IsEqualTo(copyResult.Contents); + } + + [Test] + public async Task MockFile_Copy_ShouldThrowExceptionWhenFileExistsAtDestination() + { + string sourceFileName = XFS.Path(@"c:\source\demo.txt"); + var sourceContents = new MockFileData("Source content"); + string destFileName = XFS.Path(@"c:\destination\demo.txt"); + var fileSystem = new MockFileSystem(new Dictionary + { + {sourceFileName, sourceContents}, + {destFileName, new MockFileData("Destination content")} + }); + + await That(() => fileSystem.File.Copy(sourceFileName, destFileName), XFS.Path(@"The file c:\destination\demo.txt already exists.")).Throws(); + } + + [TestCase(@"c:\source\demo.txt", @"c:\source\doesnotexist\demo.txt")] + [TestCase(@"c:\source\demo.txt", @"c:\doesnotexist\demo.txt")] + public async Task MockFile_Copy_ShouldThrowExceptionWhenFolderInDestinationDoesNotExist(string sourceFilePath, string destFilePath) + { + string sourceFileName = XFS.Path(sourceFilePath); + string destFileName = XFS.Path(destFilePath); + var fileSystem = new MockFileSystem(new Dictionary + { + {sourceFileName, string.Empty} + }); + + await That(() => fileSystem.File.Copy(sourceFileName, destFileName), string.Format(CultureInfo.InvariantCulture, @"Could not find a part of the path '{0}'.", destFilePath)).Throws(); + } + + [Test] + public async Task MockFile_Copy_ShouldThrowArgumentNullExceptionWhenSourceIsNull_Message() + { + string destFilePath = XFS.Path(@"c:\something\demo.txt"); + var fileSystem = new MockFileSystem(); + + var exception = await That(() => fileSystem.File.Copy(null, destFilePath)).Throws(); + + await That(exception.Message).StartsWith("File name cannot be null."); + } + + [Test] + public async Task MockFile_Copy_ShouldThrowArgumentNullExceptionWhenSourceIsNull_ParamName() + { + string destFilePath = XFS.Path(@"c:\something\demo.txt"); + var fileSystem = new MockFileSystem(); + + var exception = await That(() => fileSystem.File.Copy(null, destFilePath)).Throws(); + + await That(exception.ParamName).IsEqualTo("sourceFileName"); + } + + [Test] + [WindowsOnly(WindowsSpecifics.StrictPathRules)] + public async Task MockFile_Copy_ShouldThrowArgumentExceptionWhenSourceFileNameContainsInvalidChars_Message() + { + var destFilePath = @"c:\something\demo.txt"; + var fileSystem = new MockFileSystem(); + var excludeChars = Shared.SpecialInvalidPathChars(fileSystem); + + foreach (var invalidChar in fileSystem.Path.GetInvalidFileNameChars().Except(excludeChars)) + { + var sourceFilePath = @"c:\something\demo.txt" + invalidChar; + + var exception = + await That(() => fileSystem.File.Copy(sourceFilePath, destFilePath)).Throws(); + + await That(exception.Message).IsEqualTo("Illegal characters in path.") + .Because(string.Format("Testing char: [{0:c}] \\{1:X4}", invalidChar, (int)invalidChar)); + } + } + + [Test] + [WindowsOnly(WindowsSpecifics.StrictPathRules)] + public async Task MockFile_Copy_ShouldThrowArgumentExceptionWhenSourcePathContainsInvalidChars_Message() + { + var destFilePath = @"c:\something\demo.txt"; + var fileSystem = new MockFileSystem(); + + foreach (var invalidChar in fileSystem.Path.GetInvalidPathChars()) + { + var sourceFilePath = @"c:\some" + invalidChar + @"thing\demo.txt"; + + var exception = + await That(() => fileSystem.File.Copy(sourceFilePath, destFilePath)).Throws(); + + await That(exception.Message).IsEqualTo("Illegal characters in path.") + .Because(string.Format("Testing char: [{0:c}] \\{1:X4}", invalidChar, (int)invalidChar)); + } + } + + [Test] + [WindowsOnly(WindowsSpecifics.StrictPathRules)] + public async Task MockFile_Copy_ShouldThrowArgumentExceptionWhenTargetPathContainsInvalidChars_Message() + { + var sourceFilePath = @"c:\something\demo.txt"; + var fileSystem = new MockFileSystem(); + + foreach (var invalidChar in fileSystem.Path.GetInvalidPathChars()) + { + var destFilePath = @"c:\some" + invalidChar + @"thing\demo.txt"; + + var exception = + await That(() => fileSystem.File.Copy(sourceFilePath, destFilePath)).Throws(); + + await That(exception.Message).IsEqualTo("Illegal characters in path.") + .Because(string.Format("Testing char: [{0:c}] \\{1:X4}", invalidChar, (int)invalidChar)); + } + } + + [Test] + [WindowsOnly(WindowsSpecifics.StrictPathRules)] + public async Task MockFile_Copy_ShouldThrowArgumentExceptionWhenTargetFileNameContainsInvalidChars_Message() + { + var sourceFilePath = @"c:\something\demo.txt"; + var fileSystem = new MockFileSystem(); + var excludeChars = Shared.SpecialInvalidPathChars(fileSystem); + + foreach (var invalidChar in fileSystem.Path.GetInvalidFileNameChars().Except(excludeChars)) + { + var destFilePath = @"c:\something\demo.txt" + invalidChar; + + var exception = + await That(() => fileSystem.File.Copy(sourceFilePath, destFilePath)).Throws(); + + await That(exception.Message).IsEqualTo("Illegal characters in path.") + .Because(string.Format("Testing char: [{0:c}] \\{1:X4}", invalidChar, (int)invalidChar)); + } + } + + [Test] + [WindowsOnly(WindowsSpecifics.Drives)] + public async Task MockFile_Copy_ShouldThrowNotSupportedExceptionWhenSourcePathContainsInvalidUseOfDriveSeparator() + { + var badSourcePath = @"C::\something\demo.txt"; + var destinationPath = @"C:\elsewhere\demo.txt"; + var fileSystem = new MockFileSystem(); + + Action action = () => fileSystem.File.Copy(badSourcePath, destinationPath); + + await That(action).Throws(); + } + + [Test] + [WindowsOnly(WindowsSpecifics.Drives)] + public async Task MockFile_Copy_ShouldThrowIOExceptionWhenOverwritingWithSameNameDifferentCase() + { + var fileSystem = new MockFileSystem(); + string path = @"C:\Temp\file.txt"; + string pathUpper = @"C:\Temp\FILE.TXT"; + + fileSystem.File.WriteAllText(path, "Hello"); + + void Act() => fileSystem.File.Copy(path, pathUpper, true); + + await That(Act).Throws() + .WithMessage($"The process cannot access the file '{pathUpper}' because it is being used by another process."); + } + + [Test] + [WindowsOnly(WindowsSpecifics.Drives)] + public async Task MockFile_Copy_ShouldThrowNotSupportedExceptionWhenSourcePathContainsInvalidDriveLetter() + { + var badSourcePath = @"0:\something\demo.txt"; + var destinationPath = @"C:\elsewhere\demo.txt"; + var fileSystem = new MockFileSystem(); + + Action action = () => fileSystem.File.Copy(badSourcePath, destinationPath); + + await That(action).Throws(); + } + + [Test] + [WindowsOnly(WindowsSpecifics.Drives)] + public async Task MockFile_Copy_ShouldThrowNotSupportedExceptionWhenDestinationPathContainsInvalidUseOfDriveSeparator() + { + var sourcePath = @"C:\something\demo.txt"; + var badDestinationPath = @"C:\elsewhere:\demo.txt"; + var fileSystem = new MockFileSystem(); + + Action action = () => fileSystem.File.Copy(sourcePath, badDestinationPath); + + await That(action).Throws(); + } + + [Test] + [WindowsOnly(WindowsSpecifics.Drives)] + public async Task MockFile_Copy_ShouldThrowNotSupportedExceptionWhenDestinationPathContainsInvalidDriveLetter() + { + var sourcePath = @"C:\something\demo.txt"; + var badDestinationPath = @"^:\elsewhere\demo.txt"; + var fileSystem = new MockFileSystem(); + + Action action = () => fileSystem.File.Copy(sourcePath, badDestinationPath); + + await That(action).Throws(); + } + + [Test] + public async Task MockFile_Copy_ShouldThrowArgumentExceptionWhenSourceIsEmpty_Message() + { + string destFilePath = XFS.Path(@"c:\something\demo.txt"); + var fileSystem = new MockFileSystem(); + + var exception = await That(() => fileSystem.File.Copy(string.Empty, destFilePath)).Throws(); + + await That(exception.Message).StartsWith("Empty file name is not legal."); + } + + [Test] + public async Task MockFile_Copy_ShouldThrowArgumentExceptionWhenSourceIsEmpty_ParamName() + { + string destFilePath = XFS.Path(@"c:\something\demo.txt"); + var fileSystem = new MockFileSystem(); + + var exception = await That(() => fileSystem.File.Copy(string.Empty, destFilePath)).Throws(); + + await That(exception.ParamName).IsEqualTo("sourceFileName"); + } + + [Test] + public async Task MockFile_Copy_ShouldThrowArgumentExceptionWhenSourceIsStringOfBlanks() + { + string sourceFilePath = " "; + string destFilePath = XFS.Path(@"c:\something\demo.txt"); + var fileSystem = new MockFileSystem(); + + var exception = await That(() => fileSystem.File.Copy(sourceFilePath, destFilePath)).Throws(); + + await That(exception.Message).StartsWith("The path is not of a legal form."); + } + + [Test] + public async Task MockFile_Copy_ShouldThrowArgumentNullExceptionWhenTargetIsNull_Message() + { + string sourceFilePath = XFS.Path(@"c:\something\demo.txt"); + var fileSystem = new MockFileSystem(); + + var exception = await That(() => fileSystem.File.Copy(sourceFilePath, null)).Throws(); + + await That(exception.Message).StartsWith("File name cannot be null."); + } + + [Test] + public async Task MockFile_Copy_ShouldThrowArgumentNullExceptionWhenTargetIsNull_ParamName() + { + string sourceFilePath = XFS.Path(@"c:\something\demo.txt"); + var fileSystem = new MockFileSystem(); + + var exception = await That(() => fileSystem.File.Copy(sourceFilePath, null)).Throws(); + + await That(exception.ParamName).IsEqualTo("destFileName"); + } + + [Test] + public async Task MockFile_Copy_ShouldThrowArgumentExceptionWhenTargetIsStringOfBlanks() + { + string sourceFilePath = XFS.Path(@"c:\something\demo.txt"); + string destFilePath = " "; + var fileSystem = new MockFileSystem(); + + var exception = await That(() => fileSystem.File.Copy(sourceFilePath, destFilePath)).Throws(); + + await That(exception.Message).StartsWith("The path is not of a legal form."); + } + + [Test] + public async Task MockFile_Copy_ShouldThrowArgumentExceptionWhenTargetIsEmpty_Message() + { + string sourceFilePath = XFS.Path(@"c:\something\demo.txt"); + var fileSystem = new MockFileSystem(); + + var exception = await That(() => fileSystem.File.Copy(sourceFilePath, string.Empty)).Throws(); + + await That(exception.Message).StartsWith("Empty file name is not legal."); + } + + [Test] + public async Task MockFile_Copy_ShouldThrowFileNotFoundExceptionWhenSourceDoesNotExist() + { + string sourceFilePath = XFS.Path(@"c:\something\demo.txt"); + var fileSystem = new MockFileSystem(); + + Action action = () => fileSystem.File.Copy(sourceFilePath, XFS.Path(@"c:\something\demo2.txt")); + + await That(action).Throws(); + } + + [Test] + public async Task MockFile_Copy_ShouldThrowFileNotFoundExceptionWhenSourceDoesNotExist_EvenWhenCopyingToItself() + { + string sourceFilePath = XFS.Path(@"c:\something\demo.txt"); + var fileSystem = new MockFileSystem(); + + Action action = () => fileSystem.File.Copy(sourceFilePath, XFS.Path(@"c:\something\demo.txt")); + + await That(action).Throws(); + } + + [Test] + public async Task MockFile_Copy_ShouldWorkWithRelativePaths() + { + var sourceFile = "source_file.txt"; + var destinationFile = "destination_file.txt"; + var fileSystem = new MockFileSystem(); + + fileSystem.File.Create(sourceFile).Close(); + fileSystem.File.Copy(sourceFile, destinationFile); + + await That(fileSystem.File.Exists(destinationFile)).IsTrue(); + } + + [Test] + public async Task MockFile_Copy_ShouldThrowIOExceptionForInvalidFileShare() + { + string sourceFileName = XFS.Path(@"c:\source\demo.txt"); + var sourceContents = new MockFileData("Source content") + { + AllowedFileShare = FileShare.None + }; + var fileSystem = new MockFileSystem(new Dictionary + { + {sourceFileName, sourceContents} + }); + fileSystem.AddDirectory(XFS.Path(@"c:\something")); + + Action action = () => fileSystem.File.Copy(sourceFileName, XFS.Path(@"c:\something\demo.txt")); + + await That(action).Throws(); + } +} diff --git a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileCreateTests.cs b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileCreateTests.cs new file mode 100644 index 000000000..e63005dde --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileCreateTests.cs @@ -0,0 +1,304 @@ +namespace System.IO.Abstractions.TestingHelpers.Tests; + +using Collections.Generic; + +using Globalization; + +using NUnit.Framework; + +using Text; + +using XFS = MockUnixSupport; + +public class MockFileCreateTests +{ + [Test] + public async Task Mockfile_Create_ShouldCreateNewStream() + { + string fullPath = XFS.Path(@"c:\something\demo.txt"); + var fileSystem = new MockFileSystem(); + fileSystem.AddDirectory(XFS.Path(@"c:\something")); + + var sut = new MockFile(fileSystem); + + await That(fileSystem.FileExists(fullPath)).IsFalse(); + + sut.Create(fullPath).Dispose(); + + await That(fileSystem.FileExists(fullPath)).IsTrue(); + } + + [Test] + public async Task Mockfile_Create_CanWriteToNewStream() + { + string fullPath = XFS.Path(@"c:\something\demo.txt"); + var fileSystem = new MockFileSystem(); + fileSystem.AddDirectory(XFS.Path(@"c:\something")); + var data = new UTF8Encoding(false).GetBytes("Test string"); + + var sut = new MockFile(fileSystem); + using (var stream = sut.Create(fullPath)) + { + stream.Write(data, 0, data.Length); + } + + var mockFileData = fileSystem.GetFile(fullPath); + var fileData = mockFileData.Contents; + + await That(fileData).IsEqualTo(data); + } + + [Test] + public async Task Mockfile_Create_OverwritesExistingFile() + { + string path = XFS.Path(@"c:\some\file.txt"); + var fileSystem = new MockFileSystem(); + fileSystem.AddDirectory(XFS.Path(@"c:\some")); + + var mockFile = new MockFile(fileSystem); + + // Create a file + using (var stream = mockFile.Create(path)) + { + var contents = new UTF8Encoding(false).GetBytes("Test 1"); + stream.Write(contents, 0, contents.Length); + } + + // Create new file that should overwrite existing file + var expectedContents = new UTF8Encoding(false).GetBytes("Test 2"); + using (var stream = mockFile.Create(path)) + { + stream.Write(expectedContents, 0, expectedContents.Length); + } + + var actualContents = fileSystem.GetFile(path).Contents; + + await That(actualContents).IsEqualTo(expectedContents); + } + + [Test] + public async Task Mockfile_Create_ShouldThrowUnauthorizedAccessExceptionIfPathIsReadOnly() + { + // Arrange + string path = XFS.Path(@"c:\something\read-only.txt"); + var fileSystem = new MockFileSystem(new Dictionary { { path, new MockFileData("Content") } }); + var mockFile = new MockFile(fileSystem); + + // Act + mockFile.SetAttributes(path, FileAttributes.ReadOnly); + + // Assert + var exception = await That(() => mockFile.Create(path).Dispose()).Throws(); + await That(exception.Message).IsEqualTo(string.Format(CultureInfo.InvariantCulture, "Access to the path '{0}' is denied.", path)); + } + + [Test] + public async Task Mockfile_Create_ShouldThrowArgumentExceptionIfPathIsZeroLength() + { + // Arrange + var fileSystem = new MockFileSystem(); + + // Act + Action action = () => fileSystem.File.Create(""); + + // Assert + await That(action).Throws(); + } + + [TestCase("\"")] + [TestCase("<")] + [TestCase(">")] + [TestCase("|")] + [WindowsOnly(WindowsSpecifics.StrictPathRules)] + public async Task MockFile_Create_ShouldThrowArgumentNullExceptionIfPathIsNull1(string path) + { + // Arrange + var fileSystem = new MockFileSystem(); + + // Act + Action action = () => fileSystem.File.Create(path); + + // Assert + await That(action).Throws(); + } + + [TestCase(" ")] + [TestCase(" ")] + public async Task MockFile_Create_ShouldThrowArgumentExceptionIfPathContainsOnlyWhitespaces(string path) + { + // Arrange + var fileSystem = new MockFileSystem(); + + // Act + Action action = () => fileSystem.File.Create(path); + + // Assert + await That(action).Throws(); + } + + [Test] + public async Task MockFile_Create_ShouldThrowArgumentNullExceptionIfPathIsNull() + { + // Arrange + var fileSystem = new MockFileSystem(); + + // Act + Action action = () => fileSystem.File.Create(null); + + // Assert + var exception = await That(action).Throws(); + await That(exception.Message).StartsWith("Path cannot be null."); + } + + [Test] + public async Task MockFile_Create_ShouldThrowDirectoryNotFoundExceptionIfCreatingAndParentPathDoesNotExist() + { + // Arrange + var fileSystem = new MockFileSystem(); + var file = XFS.Path("C:\\path\\NotFound.ext"); + + // Act + Action action = () => fileSystem.File.Create(file); + + // Assert + var exception = await That(action).Throws(); + await That(exception.Message).StartsWith("Could not find a part of the path"); + } + + [Test] + public async Task MockFile_Create_TruncateShouldWriteNewContents() + { + // Arrange + string testFileName = XFS.Path(@"c:\someFile.txt"); + var fileSystem = new MockFileSystem(); + + using (var stream = fileSystem.FileStream.New(testFileName, FileMode.Create, FileAccess.Write)) + { + using (var writer = new StreamWriter(stream)) + { + writer.Write("original_text"); + } + } + + // Act + using (var stream = fileSystem.FileStream.New(testFileName, FileMode.Truncate, FileAccess.Write)) + { + using (var writer = new StreamWriter(stream)) + { + writer.Write("new_text"); + } + } + + // Assert + await That(fileSystem.File.ReadAllText(testFileName)).IsEqualTo("new_text"); + } + + [Test] + public async Task MockFile_Create_TruncateShouldClearFileContentsOnOpen() + { + // Arrange + string testFileName = XFS.Path(@"c:\someFile.txt"); + var fileSystem = new MockFileSystem(); + + using (var stream = fileSystem.FileStream.New(testFileName, FileMode.Create, FileAccess.Write)) + { + using (var writer = new StreamWriter(stream)) + { + writer.Write("original_text"); + } + } + + // Act + using (var stream = fileSystem.FileStream.New(testFileName, FileMode.Truncate, FileAccess.Write)) + { + // Opening the stream is enough to reset the contents + } + + // Assert + await That(fileSystem.File.ReadAllText(testFileName)).IsEqualTo(string.Empty); + } + + [Test] + public async Task MockFile_Create_DeleteOnCloseOption_FileExistsWhileStreamIsOpen() + { + var root = XFS.Path(@"C:\"); + var filePath = XFS.Path(@"C:\test.txt"); + var fileSystem = new MockFileSystem(); + fileSystem.Directory.CreateDirectory(root); + + using (fileSystem.File.Create(filePath, 4096, FileOptions.DeleteOnClose)) + { + await That(fileSystem.File.Exists(filePath)).IsTrue(); + } + } + + [Test] + public async Task MockFile_Create_DeleteOnCloseOption_FileDeletedWhenStreamIsClosed() + { + var root = XFS.Path(@"C:\"); + var filePath = XFS.Path(@"C:\test.txt"); + var fileSystem = new MockFileSystem(); + fileSystem.Directory.CreateDirectory(root); + + using (fileSystem.File.Create(filePath, 4096, FileOptions.DeleteOnClose)) + { + } + + await That(fileSystem.File.Exists(filePath)).IsFalse(); + } + + [Test] + public async Task MockFile_Create_EncryptedOption_FileNotYetEncryptedWhenStreamIsOpen() + { + var root = XFS.Path(@"C:\"); + var filePath = XFS.Path(@"C:\test.txt"); + var fileSystem = new MockFileSystem(); + fileSystem.Directory.CreateDirectory(root); + + using (var stream = fileSystem.File.Create(filePath, 4096, FileOptions.Encrypted)) + { + var fileInfo = fileSystem.FileInfo.New(filePath); + await That(fileInfo.Attributes.HasFlag(FileAttributes.Encrypted)).IsFalse(); + } + } + + [Test] + public async Task MockFile_Create_EncryptedOption_EncryptsFileWhenStreamIsClose() + { + var root = XFS.Path(@"C:\"); + var filePath = XFS.Path(@"C:\test.txt"); + var fileSystem = new MockFileSystem(); + fileSystem.Directory.CreateDirectory(root); + + using (var stream = fileSystem.File.Create(filePath, 4096, FileOptions.Encrypted)) + { + } + + var fileInfo = fileSystem.FileInfo.New(filePath); + await That(fileInfo.Attributes.HasFlag(FileAttributes.Encrypted)).IsTrue(); + } + + [Test] + public async Task MockFile_Create_ShouldWorkWithRelativePath() + { + var relativeFile = "file.txt"; + var fileSystem = new MockFileSystem(); + + fileSystem.File.Create(relativeFile).Close(); + + await That(fileSystem.File.Exists(relativeFile)).IsTrue(); + } + + [Test] + public async Task MockFile_Create_CanReadFromNewStream() + { + string fullPath = XFS.Path(@"c:\something\demo.txt"); + var fileSystem = new MockFileSystem(); + fileSystem.AddDirectory(XFS.Path(@"c:\something")); + + using (var stream = fileSystem.File.Create(fullPath)) + { + await That(stream.CanRead).IsTrue(); + } + } +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileDeleteTests.cs b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileDeleteTests.cs new file mode 100644 index 000000000..9012b04e3 --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileDeleteTests.cs @@ -0,0 +1,62 @@ +namespace System.IO.Abstractions.TestingHelpers.Tests; + +using System.Collections.Generic; +using NUnit.Framework; + +using XFS = MockUnixSupport; + +public class MockFileDeleteTests +{ + [Test] + public async Task MockFile_Delete_ShouldDeleteFile() + { + var fileSystem = new MockFileSystem(); + var path = XFS.Path("C:\\some_folder\\test"); + var directory = fileSystem.Path.GetDirectoryName(path); + fileSystem.AddFile(path, new MockFileData("Bla")); + + var fileCount1 = fileSystem.Directory.GetFiles(directory, "*").Length; + fileSystem.File.Delete(path); + var fileCount2 = fileSystem.Directory.GetFiles(directory, "*").Length; + + await That(fileCount1).IsEqualTo(1).Because("File should have existed"); + await That(fileCount2).IsEqualTo(0).Because("File should have been deleted"); + } + + [TestCase(" ")] + [TestCase(" ")] + public async Task MockFile_Delete_ShouldThrowArgumentExceptionIfPathContainsOnlyWhitespaces(string path) + { + // Arrange + var fileSystem = new MockFileSystem(); + + // Act + Action action = () => fileSystem.File.Delete(path); + + // Assert + await That(action).Throws(); + } + + [Test] + public async Task MockFile_Delete_ShouldThrowDirectoryNotFoundExceptionIfParentFolderAbsent() + { + var fileSystem = new MockFileSystem(); + var path = XFS.Path("C:\\test\\somefile.txt"); + + await That(() => fileSystem.File.Delete(path)).Throws(); + } + + [Test] + public async Task MockFile_Delete_ShouldSilentlyReturnIfNonExistingFileInExistingFolder() + { + var fileSystem = new MockFileSystem(new Dictionary() + { + { XFS.Path("C:\\temp\\exist.txt"), new MockFileData("foobar") }, + }); + + string filePath = XFS.Path("C:\\temp\\somefile.txt"); + + // Delete() returns void, so there is nothing to check here beside absense of an exception + await That(() => fileSystem.File.Delete(filePath)).DoesNotThrow(); + } +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileExistsTests.cs b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileExistsTests.cs new file mode 100644 index 000000000..bc064c8d9 --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileExistsTests.cs @@ -0,0 +1,133 @@ +namespace System.IO.Abstractions.TestingHelpers.Tests; + +using Collections.Generic; + +using NUnit.Framework; + +using XFS = MockUnixSupport; + +public class MockFileExistsTests +{ + [Test] + public async Task MockFile_Exists_ShouldReturnTrueForSamePath() + { + // Arrange + var fileSystem = new MockFileSystem(new Dictionary + { + { XFS.Path(@"C:\something\other.gif"), new MockFileData("gif content") } + }); + + // Act + var result = fileSystem.File.Exists(XFS.Path(@"C:\something\other.gif")); + + // Assert + await That(result).IsTrue(); + } + + [Test] + [WindowsOnly(WindowsSpecifics.CaseInsensitivity)] + public async Task MockFile_Exists_ShouldReturnTrueForPathVaryingByCase() + { + // Arrange + var fileSystem = new MockFileSystem(new Dictionary + { + { @"C:\something\demo.txt", new MockFileData("Demo text content") } + }); + + // Act + var result = fileSystem.File.Exists(@"C:\SomeThing\DEMO.txt"); + + // Assert + await That(result).IsTrue(); + } + + [Test] + [UnixOnly(UnixSpecifics.CaseSensitivity)] + public async Task MockFile_Exists_ShouldReturnFalseForPathVaryingByCase() + { + // Arrange + var fileSystem = new MockFileSystem(new Dictionary + { + { "/something/demo.txt", new MockFileData("Demo text content") } + }); + + // Act + var result = fileSystem.File.Exists("/SomeThing/DEMO.txt"); + + // Assert + await That(result).IsFalse(); + } + + [Test] + public async Task MockFile_Exists_ShouldReturnFalseForEntirelyDifferentPath() + { + // Arrange + var fileSystem = new MockFileSystem(new Dictionary + { + { XFS.Path(@"C:\something\demo.txt"), new MockFileData("Demo text content") }, + { XFS.Path(@"C:\something\other.gif"), new MockFileData("gif content") } + }); + + // Act + var result = fileSystem.File.Exists(XFS.Path(@"C:\SomeThing\DoesNotExist.gif")); + + // Assert + await That(result).IsFalse(); + } + + [Test] + public async Task MockFile_Exists_ShouldReturnFalseForNullPath() + { + // Arrange + var fileSystem = new MockFileSystem(); + + // Act + var result = fileSystem.File.Exists(null); + + // Assert + await That(result).IsFalse(); + } + + [Test] + public async Task MockFile_Exists_ShouldReturnFalseForEmptyStringPath() + { + // Arrange + var fileSystem = new MockFileSystem(); + + // Act + var result = fileSystem.File.Exists(string.Empty); + + // Assert + await That(result).IsFalse(); + } + + [Test] + public async Task MockFile_Exists_ShouldReturnFalseForInvalidCharactersInPath() + { + // Arrange + var fileSystem = new MockFileSystem(); + + // Act + var result = fileSystem.File.Exists(@"C:""*/:<>?|abc"); + + // Assert + await That(result).IsFalse(); + } + + [Test] + public async Task MockFile_Exists_ShouldReturnFalseForDirectories() + { + // Arrange + var fileSystem = new MockFileSystem(new Dictionary + { + { XFS.Path(@"C:\something\demo.txt"), new MockFileData("Demo text content") }, + { XFS.Path(@"C:\something\other.gif"), new MockFileData("gif content") } + }); + + // Act + var result = fileSystem.File.Exists(XFS.Path(@"C:\something\")); + + // Assert + await That(result).IsFalse(); + } +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileGetAccessControlTests.cs b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileGetAccessControlTests.cs new file mode 100644 index 000000000..4550a81c5 --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileGetAccessControlTests.cs @@ -0,0 +1,67 @@ +using NUnit.Framework; +using System.Collections.Generic; +using System.Security.AccessControl; +using System.Runtime.Versioning; + +namespace System.IO.Abstractions.TestingHelpers.Tests; + +using XFS = MockUnixSupport; +[TestFixture] +[WindowsOnly(WindowsSpecifics.AccessControlLists)] +[SupportedOSPlatform("windows")] +public class MockFileGetAccessControlTests +{ + [TestCase(" ")] + [TestCase(" ")] + public async Task MockFile_GetAccessControl_ShouldThrowArgumentExceptionIfPathContainsOnlyWhitespaces(string path) + { + // Arrange + var fileSystem = new MockFileSystem(); + + // Act + Action action = () => fileSystem.File.GetAccessControl(path); + + // Assert + var exception = await That(action).Throws(); + await That(exception.ParamName).IsEqualTo("path"); + } + + [Test] + public async Task MockFile_GetAccessControl_ShouldThrowFileNotFoundExceptionIfFileDoesNotExistInMockData() + { + // Arrange + var fileSystem = new MockFileSystem(); + var expectedFileName = XFS.Path(@"c:\a.txt"); + + // Act + Action action = () => fileSystem.File.GetAccessControl(expectedFileName); + + // Assert + await That(action).Throws(); + } + + [Test] + public async Task MockFile_GetAccessControl_ShouldReturnAccessControlOfFileData() + { + // Arrange + var expectedFileSecurity = new FileSecurity(); + expectedFileSecurity.SetAccessRuleProtection(false, false); + + var filePath = XFS.Path(@"c:\a.txt"); + var fileData = new MockFileData("Test content") + { + AccessControl = expectedFileSecurity, + }; + + var fileSystem = new MockFileSystem(new Dictionary() + { + { filePath, fileData } + }); + + // Act + var fileSecurity = fileSystem.File.GetAccessControl(filePath); + + // Assert + await That(fileSecurity).IsEqualTo(expectedFileSecurity); + } +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileGetCreationTimeTests.cs b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileGetCreationTimeTests.cs new file mode 100644 index 000000000..7a6a86d6d --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileGetCreationTimeTests.cs @@ -0,0 +1,49 @@ +using NUnit.Framework; + +namespace System.IO.Abstractions.TestingHelpers.Tests; + +[TestFixture] +public class MockFileGetCreationTimeTests +{ + [TestCase(" ")] + [TestCase(" ")] + public async Task MockFile_GetCreationTime_ShouldThrowArgumentExceptionIfPathContainsOnlyWhitespaces(string path) + { + // Arrange + var fileSystem = new MockFileSystem(); + + // Act + Action action = () => fileSystem.File.GetCreationTime(path); + + // Assert + var exception = await That(action).Throws(); + await That(exception.ParamName).IsEqualTo("path"); + } + + [Test] + public async Task MockFile_GetCreationTime_ShouldReturnDefaultTimeIfFileDoesNotExist() + { + // Arrange + var fileSystem = new MockFileSystem(); + + // Act + var actualCreationTime = fileSystem.File.GetCreationTime(@"c:\does\not\exist.txt"); + + // Assert + await That(actualCreationTime).IsEqualTo(new DateTime(1601, 01, 01, 00, 00, 00, DateTimeKind.Utc).ToLocalTime()); + } + + [Test] + public async Task MockFile_GetCreationTime_ShouldBeSet() + { + var now = DateTime.Now.AddDays(10); + var fileSystem = new MockFileSystem() + .MockTime(() => now); + fileSystem.File.WriteAllText("foo.txt", "xyz"); + + var result = fileSystem.File.GetCreationTime("foo.txt"); + + await That(result.Kind).IsEqualTo(DateTimeKind.Local); + await That(result).IsEqualTo(now.ToLocalTime()); + } +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileGetCreationTimeUtcTests.cs b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileGetCreationTimeUtcTests.cs new file mode 100644 index 000000000..d351291ab --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileGetCreationTimeUtcTests.cs @@ -0,0 +1,49 @@ +using NUnit.Framework; + +namespace System.IO.Abstractions.TestingHelpers.Tests; + +[TestFixture] +public class MockFileGetCreationTimeUtcTests +{ + [TestCase(" ")] + [TestCase(" ")] + public async Task MockFile_GetCreationTimeUtc_ShouldThrowArgumentExceptionIfPathContainsOnlyWhitespaces(string path) + { + // Arrange + var fileSystem = new MockFileSystem(); + + // Act + Action action = () => fileSystem.File.GetCreationTimeUtc(path); + + // Assert + var exception = await That(action).Throws(); + await That(exception.ParamName).IsEqualTo("path"); + } + + [Test] + public async Task MockFile_GetCreationTimeUtc_ShouldReturnDefaultTimeIfFileDoesNotExist() + { + // Arrange + var fileSystem = new MockFileSystem(); + + // Act + var actualCreationTime = fileSystem.File.GetCreationTimeUtc(@"c:\does\not\exist.txt"); + + // Assert + await That(actualCreationTime).IsEqualTo(new DateTime(1601, 01, 01, 00, 00, 00, DateTimeKind.Utc)); + } + + [Test] + public async Task MockFile_GetCreationTimeUtc_ShouldBeSet() + { + var now = DateTime.Now.AddDays(10); + var fileSystem = new MockFileSystem() + .MockTime(() => now); + fileSystem.File.WriteAllText("foo.txt", "xyz"); + + var result = fileSystem.File.GetCreationTimeUtc("foo.txt"); + + await That(result.Kind).IsEqualTo(DateTimeKind.Utc); + await That(result).IsEqualTo(now.ToUniversalTime()); + } +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileGetLastAccessTimeTests.cs b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileGetLastAccessTimeTests.cs new file mode 100644 index 000000000..fc6a71b27 --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileGetLastAccessTimeTests.cs @@ -0,0 +1,49 @@ +using NUnit.Framework; + +namespace System.IO.Abstractions.TestingHelpers.Tests; + +[TestFixture] +public class MockFileGetLastAccessTimeTests +{ + [TestCase(" ")] + [TestCase(" ")] + public async Task MockFile_GetLastAccessTime_ShouldThrowArgumentExceptionIfPathContainsOnlyWhitespaces(string path) + { + // Arrange + var fileSystem = new MockFileSystem(); + + // Act + Action action = () => fileSystem.File.GetLastAccessTime(path); + + // Assert + var exception = await That(action).Throws(); + await That(exception.ParamName).IsEqualTo("path"); + } + + [Test] + public async Task MockFile_GetLastAccessTime_ShouldReturnDefaultTimeIfFileDoesNotExist() + { + // Arrange + var fileSystem = new MockFileSystem(); + + // Act + var actualLastAccessTime = fileSystem.File.GetLastAccessTime(@"c:\does\not\exist.txt"); + + // Assert + await That(actualLastAccessTime).IsEqualTo(new DateTime(1601, 01, 01, 00, 00, 00, DateTimeKind.Utc).ToLocalTime()); + } + + [Test] + public async Task MockFile_GetLastAccessTime_ShouldBeSet() + { + var now = DateTime.Now.AddDays(10); + var fileSystem = new MockFileSystem() + .MockTime(() => now); + fileSystem.File.WriteAllText("foo.txt", "xyz"); + + var result = fileSystem.File.GetLastAccessTime("foo.txt"); + + await That(result.Kind).IsEqualTo(DateTimeKind.Local); + await That(result).IsEqualTo(now.ToLocalTime()); + } +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileGetLastAccessTimeUtcTests.cs b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileGetLastAccessTimeUtcTests.cs new file mode 100644 index 000000000..7d0c97f33 --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileGetLastAccessTimeUtcTests.cs @@ -0,0 +1,49 @@ +using NUnit.Framework; + +namespace System.IO.Abstractions.TestingHelpers.Tests; + +[TestFixture] +public class MockFileGetLastAccessTimeUtcTests +{ + [TestCase(" ")] + [TestCase(" ")] + public async Task MockFile_GetLastAccessTimeUtc_ShouldThrowArgumentExceptionIfPathContainsOnlyWhitespaces(string path) + { + // Arrange + var fileSystem = new MockFileSystem(); + + // Act + Action action = () => fileSystem.File.GetLastAccessTimeUtc(path); + + // Assert + var exception = await That(action).Throws(); + await That(exception.ParamName).IsEqualTo("path"); + } + + [Test] + public async Task MockFile_GetLastAccessTimeUtc_ShouldReturnDefaultTimeIfFileDoesNotExist() + { + // Arrange + var fileSystem = new MockFileSystem(); + + // Act + var actualLastAccessTime = fileSystem.File.GetLastAccessTimeUtc(@"c:\does\not\exist.txt"); + + // Assert + await That(actualLastAccessTime).IsEqualTo(new DateTime(1601, 01, 01, 00, 00, 00, DateTimeKind.Utc)); + } + + [Test] + public async Task MockFile_GetLastAccessTimeUtc_ShouldBeSet() + { + var now = DateTime.Now.AddDays(10); + var fileSystem = new MockFileSystem() + .MockTime(() => now); + fileSystem.File.WriteAllText("foo.txt", "xyz"); + + var result = fileSystem.File.GetLastAccessTimeUtc("foo.txt"); + + await That(result.Kind).IsEqualTo(DateTimeKind.Utc); + await That(result).IsEqualTo(now.ToUniversalTime()); + } +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileGetLastWriteTimeTests.cs b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileGetLastWriteTimeTests.cs new file mode 100644 index 000000000..bc8ec5a65 --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileGetLastWriteTimeTests.cs @@ -0,0 +1,49 @@ +using NUnit.Framework; + +namespace System.IO.Abstractions.TestingHelpers.Tests; + +[TestFixture] +public class MockFileGetLastWriteTimeTests +{ + [TestCase(" ")] + [TestCase(" ")] + public async Task MockFile_GetLastWriteTime_ShouldThrowArgumentExceptionIfPathContainsOnlyWhitespaces(string path) + { + // Arrange + var fileSystem = new MockFileSystem(); + + // Act + Action action = () => fileSystem.File.GetLastWriteTime(path); + + // Assert + var exception = await That(action).Throws(); + await That(exception.ParamName).IsEqualTo("path"); + } + + [Test] + public async Task MockFile_GetLastWriteTime_ShouldReturnDefaultTimeIfFileDoesNotExist() + { + // Arrange + var fileSystem = new MockFileSystem(); + + // Act + var actualLastWriteTime = fileSystem.File.GetLastWriteTime(@"c:\does\not\exist.txt"); + + // Assert + await That(actualLastWriteTime).IsEqualTo(new DateTime(1601, 01, 01, 00, 00, 00, DateTimeKind.Utc).ToLocalTime()); + } + + [Test] + public async Task MockFile_GetLastWriteTime_ShouldBeSet() + { + var now = DateTime.Now.AddDays(10); + var fileSystem = new MockFileSystem() + .MockTime(() => now); + fileSystem.File.WriteAllText("foo.txt", "xyz"); + + var result = fileSystem.File.GetLastWriteTime("foo.txt"); + + await That(result.Kind).IsEqualTo(DateTimeKind.Local); + await That(result).IsEqualTo(now.ToLocalTime()); + } +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileGetLastWriteTimeUtcTests.cs b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileGetLastWriteTimeUtcTests.cs new file mode 100644 index 000000000..5be530a15 --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileGetLastWriteTimeUtcTests.cs @@ -0,0 +1,48 @@ +using NUnit.Framework; + +namespace System.IO.Abstractions.TestingHelpers.Tests; + +public class MockFileGetLastWriteTimeUtcTests +{ + [TestCase(" ")] + [TestCase(" ")] + public async Task MockFile_GetLastWriteTimeUtc_ShouldThrowArgumentExceptionIfPathContainsOnlyWhitespaces(string path) + { + // Arrange + var fileSystem = new MockFileSystem(); + + // Act + Action action = () => fileSystem.File.GetLastWriteTimeUtc(path); + + // Assert + var exception = await That(action).Throws(); + await That(exception.ParamName).IsEqualTo("path"); + } + + [Test] + public async Task MockFile_GetLastWriteTimeUtc_ShouldReturnDefaultTimeIfFileDoesNotExist() + { + // Arrange + var fileSystem = new MockFileSystem(); + + // Act + var actualLastWriteTime = fileSystem.File.GetLastWriteTimeUtc(@"c:\does\not\exist.txt"); + + // Assert + await That(actualLastWriteTime).IsEqualTo(new DateTime(1601, 01, 01, 00, 00, 00, DateTimeKind.Utc)); + } + + [Test] + public async Task MockFile_GetLastWriteTimeUtc_ShouldBeSet() + { + var now = DateTime.Now.AddDays(10); + var fileSystem = new MockFileSystem() + .MockTime(() => now); + fileSystem.File.WriteAllText("foo.txt", "xyz"); + + var result = fileSystem.File.GetLastWriteTimeUtc("foo.txt"); + + await That(result.Kind).IsEqualTo(DateTimeKind.Utc); + await That(result).IsEqualTo(now.ToUniversalTime()); + } +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileGetUnixFileModeTests.cs b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileGetUnixFileModeTests.cs new file mode 100644 index 000000000..351130bb6 --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileGetUnixFileModeTests.cs @@ -0,0 +1,59 @@ +#if FEATURE_UNIX_FILE_MODE +using System.Runtime.Versioning; + +namespace System.IO.Abstractions.TestingHelpers.Tests +{ + using Collections.Generic; + + using NUnit.Framework; + + using XFS = MockUnixSupport; + + [UnsupportedOSPlatform("windows")] + [UnixOnly("This feature is not supported on Windows.")] + public class MockFileGetUnixFileModeTests + { + [Test] + public async Task MockFile_GetUnixFileMode_ShouldReturnDefaultAccessMode() + { + // Arrange + var expected = UnixFileMode.UserRead | + UnixFileMode.GroupRead | + UnixFileMode.OtherRead | + UnixFileMode.UserWrite; + + var fileSystem = new MockFileSystem(new Dictionary + { + { XFS.Path(@"C:\something\some.txt"), new MockFileData("Demo text content") } + }); + + // Act + var result = fileSystem.File.GetUnixFileMode(XFS.Path(@"C:\something\some.txt")); + + // Assert + await That(result).IsEqualTo(expected); + } + + [Test] + public async Task MockFile_GetUnixFileMode_ShouldReturnSpecifiedAccessMode([Values] UnixFileMode unixFileMode) + { + // Arrange + var mockFileData = new MockFileData("Demo text content") + { + UnixMode = unixFileMode + }; + + var fileSystem = new MockFileSystem(new Dictionary + { + { XFS.Path(@"C:\something\some.txt"), mockFileData } + }); + + // Act + var result = fileSystem.File.GetUnixFileMode(XFS.Path(@"C:\something\some.txt")); + + // Assert + await That(result).IsEqualTo(unixFileMode); + } + } +} +#endif \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileInfoAccessControlTests.cs b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileInfoAccessControlTests.cs new file mode 100644 index 000000000..889d4bd3b --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileInfoAccessControlTests.cs @@ -0,0 +1,64 @@ +using NUnit.Framework; +using System.Collections.Generic; +using System.Runtime.Versioning; +using System.Security.AccessControl; +using XFS = System.IO.Abstractions.TestingHelpers.MockUnixSupport; + +namespace System.IO.Abstractions.TestingHelpers.Tests; + +[TestFixture] +[WindowsOnly(WindowsSpecifics.AccessControlLists)] +[SupportedOSPlatform("windows")] +public class MockFileInfoAccessControlTests +{ + [Test] + public async Task MockFileInfo_GetAccessControl_ShouldReturnAccessControlOfFileData() + { + // Arrange + var expectedFileSecurity = new FileSecurity(); + expectedFileSecurity.SetAccessRuleProtection(false, false); + + var filePath = XFS.Path(@"c:\a.txt"); + var fileData = new MockFileData("Test content") + { + AccessControl = expectedFileSecurity, + }; + + var fileSystem = new MockFileSystem(new Dictionary() + { + { filePath, fileData } + }); + + var fileInfo = fileSystem.FileInfo.New(filePath); + + // Act + var fileSecurity = fileInfo.GetAccessControl(); + + // Assert + await That(fileSecurity).IsEqualTo(expectedFileSecurity); + } + + [Test] + public async Task MockFile_SetAccessControl_ShouldSetAccessControlOfFileData() + { + // Arrange + var filePath = XFS.Path(@"c:\a.txt"); + var fileData = new MockFileData("Test content"); + + var fileSystem = new MockFileSystem(new Dictionary() + { + { filePath, fileData } + }); + + var fileInfo = fileSystem.FileInfo.New(filePath); + + // Act + var expectedAccessControl = new FileSecurity(); + expectedAccessControl.SetAccessRuleProtection(false, false); + fileInfo.SetAccessControl(expectedAccessControl); + + // Assert + var accessControl = fileInfo.GetAccessControl(); + await That(accessControl).IsEqualTo(expectedAccessControl); + } +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileInfoFactoryTests.cs b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileInfoFactoryTests.cs new file mode 100644 index 000000000..b08e166ac --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileInfoFactoryTests.cs @@ -0,0 +1,65 @@ +using System.Collections.Generic; +using NUnit.Framework; + +namespace System.IO.Abstractions.TestingHelpers.Tests; + +[TestFixture] +public class MockFileInfoFactoryTests +{ + [Test] + public async Task MockFileInfoFactory_New_ShouldReturnFileInfoForExistingFile() + { + // Arrange + var fileSystem = new MockFileSystem(new Dictionary + { + { @"c:\a.txt", new MockFileData("Demo text content") }, + { @"c:\a\b\c.txt", new MockFileData("Demo text content") }, + }); + var fileInfoFactory = new MockFileInfoFactory(fileSystem); + + // Act + var result = fileInfoFactory.New(@"c:\a.txt"); + + // Assert + await That(result).IsNotNull(); + } + + [Test] + public async Task MockFileInfoFactory_New_ShouldReturnFileInfoForNonExistentFile() + { + // Arrange + var fileSystem = new MockFileSystem(new Dictionary + { + { @"c:\a.txt", new MockFileData("Demo text content") }, + { @"c:\a\b\c.txt", new MockFileData("Demo text content") }, + }); + var fileInfoFactory = new MockFileInfoFactory(fileSystem); + + // Act + var result = fileInfoFactory.New(@"c:\foo.txt"); + + // Assert + await That(result).IsNotNull(); + } + + [Test] + public async Task MockFileInfoFactory_Wrap_WithNull_ShouldReturnNull() + { + var fileSystem = new MockFileSystem(); + + var result = fileSystem.FileInfo.Wrap(null); + + await That(result).IsNull(); + } + + [Test] + public async Task MockFileInfoFactory_Wrap_ShouldKeepNameAndFullName() + { + var fs = new MockFileSystem(); + var fileInfo = new FileInfo(@"C:\subfolder\file"); + var wrappedFileInfo = fs.FileInfo.Wrap(fileInfo); + + await That(wrappedFileInfo.FullName).IsEqualTo(fileInfo.FullName); + await That(wrappedFileInfo.Name).IsEqualTo(fileInfo.Name); + } +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileInfoSymlinkTests.cs b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileInfoSymlinkTests.cs new file mode 100644 index 000000000..185439633 --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileInfoSymlinkTests.cs @@ -0,0 +1,68 @@ +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Versioning; +using System.Security.AccessControl; +using NUnit.Framework; + +namespace System.IO.Abstractions.TestingHelpers.Tests; + +using XFS = MockUnixSupport; + +[TestFixture] +public class MockFileInfoSymlinkTests +{ + +#if FEATURE_CREATE_SYMBOLIC_LINK + + [Test] + public async Task MockFileInfo_ResolveLinkTarget_ShouldReturnPathOfTargetLink() + { + var fileSystem = new MockFileSystem(); + fileSystem.File.WriteAllText("bar", "some content"); + fileSystem.File.CreateSymbolicLink("foo", "bar"); + + var result = fileSystem.FileInfo.New("foo").ResolveLinkTarget(false); + + await That(result.Name).IsEqualTo("bar"); + } + + [Test] + public async Task MockFileInfo_ResolveLinkTarget_WithFinalTarget_ShouldReturnPathOfTargetLink() + { + var fileSystem = new MockFileSystem(); + fileSystem.File.WriteAllText("bar", "some content"); + fileSystem.File.CreateSymbolicLink("foo", "bar"); + fileSystem.File.CreateSymbolicLink("foo1", "foo"); + + var result = fileSystem.FileInfo.New("foo1").ResolveLinkTarget(true); + + await That(result.Name).IsEqualTo("bar"); + } + + [Test] + public async Task MockFileInfo_ResolveLinkTarget_WithoutFinalTarget_ShouldReturnFirstLink() + { + var fileSystem = new MockFileSystem(); + fileSystem.File.WriteAllText("bar", "some content"); + fileSystem.File.CreateSymbolicLink("foo", "bar"); + fileSystem.File.CreateSymbolicLink("foo1", "foo"); + + var result = fileSystem.FileInfo.New("foo1").ResolveLinkTarget(false); + + await That(result.Name).IsEqualTo("foo"); + } + + [Test] + public async Task MockFileInfo_ResolveLinkTarget_WithoutTargetLink_ShouldThrowIOException() + { + var fileSystem = new MockFileSystem(); + fileSystem.File.WriteAllText("bar", "some content"); + fileSystem.File.CreateSymbolicLink("foo", "bar"); + + await That(() => + { + fileSystem.FileInfo.New("bar").ResolveLinkTarget(false); + }).Throws(); + } +#endif +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileInfoTests.cs b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileInfoTests.cs new file mode 100644 index 000000000..751b259e1 --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileInfoTests.cs @@ -0,0 +1,981 @@ +using System.Collections.Generic; +using System.Globalization; +using NUnit.Framework; + +namespace System.IO.Abstractions.TestingHelpers.Tests; + +using XFS = MockUnixSupport; + +[TestFixture] +public class MockFileInfoTests +{ + [Test] + public async Task MockFileInfo_NullPath_ThrowArgumentNullException() + { + var fileSystem = new MockFileSystem(); + + Action action = () => new MockFileInfo(fileSystem, null); + + await That(action).Throws(); + + } + + [Test] + public async Task MockFileInfo_Exists_ShouldReturnTrueIfFileExistsInMemoryFileSystem() + { + var fileSystem = new MockFileSystem(new Dictionary + { + { XFS.Path(@"c:\a.txt"), new MockFileData("Demo text content") }, + { XFS.Path(@"c:\a\b\c.txt"), new MockFileData("Demo text content") }, + }); + var fileInfo = new MockFileInfo(fileSystem, XFS.Path(@"c:\a.txt")); + + var result = fileInfo.Exists; + + await That(result).IsTrue(); + } + + [Test] + public async Task MockFileInfo_Exists_ShouldReturnFalseIfFileDoesNotExistInMemoryFileSystem() + { + var fileSystem = new MockFileSystem(new Dictionary + { + { XFS.Path(@"c:\a.txt"), new MockFileData("Demo text content") }, + { XFS.Path(@"c:\a\b\c.txt"), new MockFileData("Demo text content") }, + }); + var fileInfo = new MockFileInfo(fileSystem, XFS.Path(@"c:\foo.txt")); + + var result = fileInfo.Exists; + + await That(result).IsFalse(); + } + + [Test] + public async Task MockFileInfo_Exists_ShouldReturnFalseIfPathLeadsToDirectory() + { + var fileSystem = new MockFileSystem(new Dictionary + { + { XFS.Path(@"c:\a\b\c.txt"), new MockFileData("Demo text content") }, + }); + var fileInfo = new MockFileInfo(fileSystem, XFS.Path(@"c:\a\b")); + + var result = fileInfo.Exists; + + await That(result).IsFalse(); + } + + [Test] + public async Task MockFileInfo_Length_ShouldReturnLengthOfFileInMemoryFileSystem() + { + const string fileContent = "Demo text content"; + var fileSystem = new MockFileSystem(new Dictionary + { + { XFS.Path(@"c:\a.txt"), new MockFileData(fileContent) }, + { XFS.Path(@"c:\a\b\c.txt"), new MockFileData(fileContent) }, + }); + var fileInfo = new MockFileInfo(fileSystem, XFS.Path(@"c:\a.txt")); + + var result = fileInfo.Length; + + await That(result).IsEqualTo(fileContent.Length); + } + + [Test] + public async Task MockFileInfo_Length_ShouldThrowFileNotFoundExceptionIfFileDoesNotExistInMemoryFileSystem() + { + const string fileContent = "Demo text content"; + var fileSystem = new MockFileSystem(new Dictionary + { + { XFS.Path(@"c:\a.txt"), new MockFileData(fileContent) }, + { XFS.Path(@"c:\a\b\c.txt"), new MockFileData(fileContent) }, + }); + var fileInfo = new MockFileInfo(fileSystem, XFS.Path(@"c:\foo.txt")); + + var ex = await That(() => fileInfo.Length.ToString(CultureInfo.InvariantCulture)).Throws(); + + await That(ex.FileName).IsEqualTo(XFS.Path(@"c:\foo.txt")); + } + + [Test] + public async Task MockFileInfo_Length_ShouldThrowFileNotFoundExceptionIfPathLeadsToDirectory() + { + const string fileContent = "Demo text content"; + var fileSystem = new MockFileSystem(new Dictionary + { + { XFS.Path(@"c:\a\b\c.txt"), new MockFileData(fileContent) }, + }); + var fileInfo = new MockFileInfo(fileSystem, XFS.Path(@"c:\a\b")); + + var ex = await That(() => fileInfo.Length.ToString(CultureInfo.InvariantCulture)).Throws(); + + await That(ex.FileName).IsEqualTo(XFS.Path(@"c:\a\b")); + } + + [Test] + public async Task MockFileInfo_CreationTimeUtc_ShouldReturnCreationTimeUtcOfFileInMemoryFileSystem() + { + var creationTime = DateTime.Now.AddHours(-4); + var fileData = new MockFileData("Demo text content") { CreationTime = creationTime }; + var fileSystem = new MockFileSystem(new Dictionary + { + { XFS.Path(@"c:\a.txt"), fileData } + }); + var fileInfo = new MockFileInfo(fileSystem, XFS.Path(@"c:\a.txt")); + + var result = fileInfo.CreationTimeUtc; + + await That(result).IsEqualTo(creationTime.ToUniversalTime()); + } + + [Test] + public async Task MockFileInfo_CreationTimeUtc_ShouldReturnDefaultTimeForNonExistingFile() + { + var fileSystem = new MockFileSystem(); + var fileInfo = new MockFileInfo(fileSystem, XFS.Path(@"c:\non\existing\file.txt")); + + var result = fileInfo.CreationTimeUtc; + + await That(result).IsEqualTo(MockFileData.DefaultDateTimeOffset.UtcDateTime); + } + + [Test] + public async Task MockFileInfo_CreationTimeUtc_ShouldSetCreationTimeUtcOfFileInMemoryFileSystem() + { + var creationTime = DateTime.Now.AddHours(-4); + var fileData = new MockFileData("Demo text content") { CreationTime = creationTime }; + var fileSystem = new MockFileSystem(new Dictionary + { + { XFS.Path(@"c:\a.txt"), fileData } + }); + var fileInfo = new MockFileInfo(fileSystem, XFS.Path(@"c:\a.txt")); + + var newUtcTime = DateTime.UtcNow; + fileInfo.CreationTimeUtc = newUtcTime; + + await That(fileInfo.CreationTimeUtc).IsEqualTo(newUtcTime); + } + + + [Test] + public async Task MockFileInfo_CreationTime_ShouldReturnCreationTimeOfFileInMemoryFileSystem() + { + var creationTime = DateTime.Now.AddHours(-4); + var fileData = new MockFileData("Demo text content") { CreationTime = creationTime }; + var fileSystem = new MockFileSystem(new Dictionary + { + { XFS.Path(@"c:\a.txt"), fileData } + }); + var fileInfo = new MockFileInfo(fileSystem, XFS.Path(@"c:\a.txt")); + + var result = fileInfo.CreationTime; + + await That(result).IsEqualTo(creationTime); + } + + [Test] + public async Task MockFileInfo_CreationTime_ShouldReturnDefaultTimeForNonExistingFile() + { + var fileSystem = new MockFileSystem(); + var fileInfo = new MockFileInfo(fileSystem, XFS.Path(@"c:\non\existing\file.txt")); + + var result = fileInfo.CreationTime; + + await That(result).IsEqualTo(MockFileData.DefaultDateTimeOffset.LocalDateTime); + } + + [Test] + public async Task MockFileInfo_CreationTime_ShouldSetCreationTimeOfFileInMemoryFileSystem() + { + var creationTime = DateTime.Now.AddHours(-4); + var fileData = new MockFileData("Demo text content") { CreationTime = creationTime }; + var fileSystem = new MockFileSystem(new Dictionary + { + { XFS.Path(@"c:\a.txt"), fileData } + }); + var fileInfo = new MockFileInfo(fileSystem, XFS.Path(@"c:\a.txt")); + var newTime = DateTime.Now; + + fileInfo.CreationTime = newTime; + + await That(fileInfo.CreationTime).IsEqualTo(newTime); + } + + [Test] + public async Task MockFileInfo_Attributes_ShouldReturnMinusOneForNonExistingFile() + { + var fileSystem = new MockFileSystem(); + var fileInfo = new MockFileInfo(fileSystem, XFS.Path(@"c:\a.txt")); + FileAttributes expected = (FileAttributes)(-1); + + await That(fileInfo.Attributes).IsEqualTo(expected); + } + + [Test] + public async Task MockFileInfo_Attributes_SetterShouldThrowFileNotFoundExceptionOnNonExistingFileOrDirectory() + { + var fileSystem = new MockFileSystem(); + var fileInfo = new MockFileInfo(fileSystem, XFS.Path(@"c:\non\existing\file.txt")); + + await That(() => fileInfo.Attributes = FileAttributes.Hidden).Throws(); + } + + [Test] + public async Task MockFileInfo_IsReadOnly_ShouldSetReadOnlyAttributeOfFileInMemoryFileSystem() + { + var fileData = new MockFileData("Demo text content"); + var fileSystem = new MockFileSystem(new Dictionary + { + { XFS.Path(@"c:\a.txt"), fileData } + }); + var fileInfo = new MockFileInfo(fileSystem, XFS.Path(@"c:\a.txt")); + + fileInfo.IsReadOnly = true; + + await That(fileData.Attributes & FileAttributes.ReadOnly).IsEqualTo(FileAttributes.ReadOnly); + } + + [Test] + public async Task MockFileInfo_IsReadOnly_ShouldSetNotReadOnlyAttributeOfFileInMemoryFileSystem() + { + var fileData = new MockFileData("Demo text content") { Attributes = FileAttributes.ReadOnly }; + var fileSystem = new MockFileSystem(new Dictionary + { + { XFS.Path(@"c:\a.txt"), fileData } + }); + var fileInfo = new MockFileInfo(fileSystem, XFS.Path(@"c:\a.txt")); + + fileInfo.IsReadOnly = false; + + await That(fileData.Attributes & FileAttributes.ReadOnly).IsNotEqualTo(FileAttributes.ReadOnly); + } + + [Test] + public async Task MockFileInfo_AppendText_ShouldAddTextToFileInMemoryFileSystem() + { + var fileData = new MockFileData("Demo text content"); + var fileSystem = new MockFileSystem(new Dictionary + { + { XFS.Path(@"c:\a.txt"), fileData } + }); + var fileInfo = new MockFileInfo(fileSystem, XFS.Path(@"c:\a.txt")); + + using (var file = fileInfo.AppendText()) + file.WriteLine("This should be at the end"); + + string newcontents; + using (var newfile = fileInfo.OpenText()) + { + newcontents = newfile.ReadToEnd(); + } + + await That(newcontents).IsEqualTo($"Demo text contentThis should be at the end{Environment.NewLine}"); + } + + [Test] + public async Task MockFileInfo_AppendText_ShouldCreateFileIfMissing() + { + var fileSystem = new MockFileSystem(); + var targetFile = XFS.Path(@"c:\a.txt"); + var fileInfo = new MockFileInfo(fileSystem, targetFile); + + using (var file = fileInfo.AppendText()) + file.WriteLine("This should be the contents"); + + string newcontents; + using (var newfile = fileInfo.OpenText()) + { + newcontents = newfile.ReadToEnd(); + } + + await That(fileSystem.File.Exists(targetFile)).IsTrue(); + await That(newcontents).IsEqualTo($"This should be the contents{Environment.NewLine}"); + } + + [Test] + public async Task MockFileInfo_OpenWrite_ShouldAddDataToFileInMemoryFileSystem() + { + var fileData = new MockFileData("Demo text content"); + var fileSystem = new MockFileSystem(new Dictionary + { + { XFS.Path(@"c:\a.txt"), fileData } + }); + var fileInfo = new MockFileInfo(fileSystem, XFS.Path(@"c:\a.txt")); + var bytesToAdd = new byte[] { 65, 66, 67, 68, 69 }; + + + using (var file = fileInfo.OpenWrite()) + { + file.Write(bytesToAdd, 0, bytesToAdd.Length); + } + + string newcontents; + using (var newfile = fileInfo.OpenText()) + { + newcontents = newfile.ReadToEnd(); + } + + await That(newcontents).IsEqualTo("ABCDEtext content"); + } + + [Test] + public async Task MockFileInfo_Encrypt_ShouldSetEncryptedAttributeOfFileInMemoryFileSystem() + { + var fileData = new MockFileData("Demo text content"); + var fileSystem = new MockFileSystem(new Dictionary + { + { XFS.Path(@"c:\a.txt"), fileData } + }); + var fileInfo = new MockFileInfo(fileSystem, XFS.Path(@"c:\a.txt")); + + fileInfo.Encrypt(); + + await That(fileData.Attributes & FileAttributes.Encrypted).IsEqualTo(FileAttributes.Encrypted); + } + + [Test] + public async Task MockFileInfo_Decrypt_ShouldUnsetEncryptedAttributeOfFileInMemoryFileSystem() + { + var fileData = new MockFileData("Demo text content"); + var fileSystem = new MockFileSystem(new Dictionary + { + { XFS.Path(@"c:\a.txt"), fileData } + }); + var fileInfo = new MockFileInfo(fileSystem, XFS.Path(@"c:\a.txt")); + fileInfo.Encrypt(); + + fileInfo.Decrypt(); + + await That(fileData.Attributes & FileAttributes.Encrypted).IsNotEqualTo(FileAttributes.Encrypted); + } + + [Test] + public async Task MockFileInfo_LastAccessTimeUtc_ShouldReturnLastAccessTimeUtcOfFileInMemoryFileSystem() + { + var lastAccessTime = DateTime.Now.AddHours(-4); + var fileData = new MockFileData("Demo text content") { LastAccessTime = lastAccessTime }; + var fileSystem = new MockFileSystem(new Dictionary + { + { XFS.Path(@"c:\a.txt"), fileData } + }); + var fileInfo = new MockFileInfo(fileSystem, XFS.Path(@"c:\a.txt")); + + var result = fileInfo.LastAccessTimeUtc; + + await That(result).IsEqualTo(lastAccessTime.ToUniversalTime()); + } + + [Test] + public async Task MockFileInfo_LastAccessTimeUtc_ShouldReturnDefaultTimeForNonExistingFile() + { + var fileSystem = new MockFileSystem(); + var fileInfo = new MockFileInfo(fileSystem, XFS.Path(@"c:\non\existing\file.txt")); + + var result = fileInfo.LastAccessTimeUtc; + + await That(result).IsEqualTo(MockFileData.DefaultDateTimeOffset.UtcDateTime); + } + + [Test] + public async Task MockFileInfo_LastAccessTimeUtc_ShouldSetCreationTimeUtcOfFileInMemoryFileSystem() + { + var lastAccessTime = DateTime.Now.AddHours(-4); + var fileData = new MockFileData("Demo text content") { LastAccessTime = lastAccessTime }; + var fileSystem = new MockFileSystem(new Dictionary + { + { XFS.Path(@"c:\a.txt"), fileData } + }); + var fileInfo = new MockFileInfo(fileSystem, XFS.Path(@"c:\a.txt")); + + var newUtcTime = DateTime.UtcNow; + fileInfo.LastAccessTimeUtc = newUtcTime; + + await That(fileInfo.LastAccessTimeUtc).IsEqualTo(newUtcTime); + } + + [Test] + public async Task MockFileInfo_LastWriteTime_ShouldReturnDefaultTimeForNonExistingFile() + { + var fileSystem = new MockFileSystem(); + var fileInfo = new MockFileInfo(fileSystem, XFS.Path(@"c:\non\existing\file.txt")); + + var result = fileInfo.LastWriteTime; + + await That(result).IsEqualTo(MockFileData.DefaultDateTimeOffset.LocalDateTime); + } + + [Test] + public async Task MockFileInfo_LastWriteTimeUtc_ShouldReturnLastWriteTimeUtcOfFileInMemoryFileSystem() + { + var lastWriteTime = DateTime.Now.AddHours(-4); + var fileData = new MockFileData("Demo text content") { LastWriteTime = lastWriteTime }; + var fileSystem = new MockFileSystem(new Dictionary + { + { XFS.Path(@"c:\a.txt"), fileData } + }); + var fileInfo = new MockFileInfo(fileSystem, XFS.Path(@"c:\a.txt")); + + var result = fileInfo.LastWriteTimeUtc; + + await That(result).IsEqualTo(lastWriteTime.ToUniversalTime()); + } + + [Test] + public async Task MockFileInfo_LastWriteTimeUtc_ShouldReturnDefaultTimeForNonExistingFile() + { + var fileSystem = new MockFileSystem(); + var fileInfo = new MockFileInfo(fileSystem, XFS.Path(@"c:\non\existing\file.txt")); + + var result = fileInfo.LastWriteTimeUtc; + + await That(result).IsEqualTo(MockFileData.DefaultDateTimeOffset.UtcDateTime); + } + + [Test] + public async Task MockFileInfo_LastWriteTimeUtc_ShouldSetLastWriteTimeUtcOfFileInMemoryFileSystem() + { + var lastWriteTime = DateTime.Now.AddHours(-4); + var fileData = new MockFileData("Demo text content") { LastWriteTime = lastWriteTime }; + var fileSystem = new MockFileSystem(new Dictionary + { + { XFS.Path(@"c:\a.txt"), fileData } + }); + var fileInfo = new MockFileInfo(fileSystem, XFS.Path(@"c:\a.txt")); + + var newUtcTime = DateTime.UtcNow; + fileInfo.LastWriteTimeUtc = newUtcTime; + + await That(fileInfo.LastWriteTimeUtc).IsEqualTo(newUtcTime); + } + + [Test] + public async Task MockFileInfo_GetExtension_ShouldReturnExtension() + { + var fileSystem = new MockFileSystem(new Dictionary()); + var fileInfo = new MockFileInfo(fileSystem, XFS.Path(@"c:\a.txt")); + + var result = fileInfo.Extension; + + await That(result).IsEqualTo(".txt"); + } + + [Test] + public async Task MockFileInfo_GetExtensionWithoutExtension_ShouldReturnEmptyString() + { + var fileSystem = new MockFileSystem(new Dictionary()); + var fileInfo = new MockFileInfo(fileSystem, XFS.Path(@"c:\a")); + + var result = fileInfo.Extension; + + await That(result).IsEmpty(); + } + + [Test] + public async Task MockFileInfo_GetDirectoryName_ShouldReturnCompleteDirectoryPath() + { + var fileInfo = new MockFileInfo(new MockFileSystem(), XFS.Path(@"c:\temp\level1\level2\file.txt")); + + var result = fileInfo.DirectoryName; + + await That(result).IsEqualTo(XFS.Path(@"c:\temp\level1\level2")); + } + + [Test] + public async Task MockFileInfo_GetDirectory_ShouldReturnDirectoryInfoWithCorrectPath() + { + var fileInfo = new MockFileInfo(new MockFileSystem(), XFS.Path(@"c:\temp\level1\level2\file.txt")); + + var result = fileInfo.Directory; + + await That(result.FullName).IsEqualTo(XFS.Path(@"c:\temp\level1\level2")); + } + + [Test] + public async Task MockFileInfo_OpenRead_ShouldReturnByteContentOfFile() + { + var fileSystem = new MockFileSystem(); + fileSystem.AddFile(XFS.Path(@"c:\temp\file.txt"), new MockFileData(new byte[] { 1, 2 })); + var fileInfo = fileSystem.FileInfo.New(XFS.Path(@"c:\temp\file.txt")); + + byte[] result = new byte[2]; + using (var stream = fileInfo.OpenRead()) + { +#pragma warning disable CA2022 + // ReSharper disable once MustUseReturnValue + stream.Read(result, 0, 2); +#pragma warning restore CA2022 + } + + await That(result).IsEqualTo(new byte[] { 1, 2 }); + } + + [Test] + public async Task MockFileInfo_OpenText_ShouldReturnStringContentOfFile() + { + var fileSystem = new MockFileSystem(); + fileSystem.AddFile(XFS.Path(@"c:\temp\file.txt"), new MockFileData(@"line 1\r\nline 2")); + var fileInfo = fileSystem.FileInfo.New(XFS.Path(@"c:\temp\file.txt")); + + string result; + using (var streamReader = fileInfo.OpenText()) + { + result = streamReader.ReadToEnd(); + } + + await That(result).IsEqualTo(@"line 1\r\nline 2"); + } + + [Test] + public async Task MockFileInfo_MoveTo_NonExistentDestination_ShouldUpdateFileInfoDirectoryAndFullName() + { + var fileSystem = new MockFileSystem(); + var sourcePath = XFS.Path(@"c:\temp\file.txt"); + var destinationFolder = XFS.Path(@"c:\temp2"); + var destinationPath = XFS.Path(destinationFolder + @"\file.txt"); + fileSystem.AddFile(sourcePath, new MockFileData("1")); + var fileInfo = fileSystem.FileInfo.New(sourcePath); + fileSystem.AddDirectory(destinationFolder); + + fileInfo.MoveTo(destinationPath); + + await That(fileInfo.DirectoryName).IsEqualTo(destinationFolder); + await That(fileInfo.FullName).IsEqualTo(destinationPath); + } + + [Test] + public async Task MockFileInfo_MoveTo_NonExistentDestinationFolder_ShouldThrowDirectoryNotFoundException() + { + var fileSystem = new MockFileSystem(); + var sourcePath = XFS.Path(@"c:\temp\file.txt"); + var destinationPath = XFS.Path(@"c:\temp2\file.txt"); + fileSystem.AddFile(sourcePath, new MockFileData("1")); + var fileInfo = fileSystem.FileInfo.New(sourcePath); + + await That(() => fileInfo.MoveTo(destinationPath)).Throws(); + } + + [Test] + public async Task MockFileInfo_MoveTo_ExistingDestination_ShouldThrowExceptionAboutFileAlreadyExisting() + { + var fileSystem = new MockFileSystem(); + var sourcePath = XFS.Path(@"c:\temp\file.txt"); + var destinationPath = XFS.Path(@"c:\temp2\file.txt"); + fileSystem.AddFile(sourcePath, new MockFileData("1")); + var fileInfo = fileSystem.FileInfo.New(sourcePath); + fileSystem.AddFile(destinationPath, new MockFileData("2")); + + await That(() => fileInfo.MoveTo(destinationPath)).Throws(); + } + + [Test] + public async Task MockFileInfo_MoveTo_SameSourceAndTargetIsANoOp() + { + var fileSystem = new MockFileSystem(); + fileSystem.AddFile(XFS.Path(@"c:\temp\file.txt"), new MockFileData(@"line 1\r\nline 2")); + var fileInfo = fileSystem.FileInfo.New(XFS.Path(@"c:\temp\file.txt")); + string destination = XFS.Path(XFS.Path(@"c:\temp\file.txt")); + + fileInfo.MoveTo(destination); + + await That(fileInfo.FullName).IsEqualTo(destination); + await That(fileInfo.Exists).IsTrue(); + } + + [Test] + public async Task MockFileInfo_MoveTo_SameSourceAndTargetThrowsExceptionIfSourceDoesNotExist() + { + var fileSystem = new MockFileSystem(); + var fileInfo = fileSystem.FileInfo.New(XFS.Path(@"c:\temp\file.txt")); + string destination = XFS.Path(XFS.Path(@"c:\temp\file.txt")); + + Action action = () => fileInfo.MoveTo(destination); + + await That(action).Throws(); + } + + [Test] + public async Task MockFileInfo_MoveTo_ThrowsExceptionIfSourceDoesNotExist() + { + var fileSystem = new MockFileSystem(); + var fileInfo = fileSystem.FileInfo.New(XFS.Path(@"c:\temp\file.txt")); + string destination = XFS.Path(XFS.Path(@"c:\temp\file2.txt")); + + Action action = () => fileInfo.MoveTo(destination); + + await That(action).Throws(); + } + + + +#if FEATURE_FILE_MOVE_WITH_OVERWRITE + [Test] + public async Task MockFileInfo_MoveToWithOverwrite_ShouldSucceedWhenTargetAlreadyExists() + { + string sourceFilePath = XFS.Path(@"c:\something\demo.txt"); + string sourceFileContent = "this is some content"; + string destFilePath = XFS.Path(@"c:\somethingelse\demo1.txt"); + var fileSystem = new MockFileSystem(new Dictionary + { + {sourceFilePath, new MockFileData(sourceFileContent)}, + {destFilePath, new MockFileData(sourceFileContent)} + }); + + fileSystem.FileInfo.New(sourceFilePath).MoveTo(destFilePath, overwrite: true); + + await That(fileSystem.File.ReadAllText(destFilePath)).IsEqualTo(sourceFileContent); + } +#endif + + [Test] + public async Task MockFileInfo_MoveToOnlyCaseChanging_ShouldSucceed() + { + string sourceFilePath = XFS.Path(@"c:\temp\file.txt"); + string destFilePath = XFS.Path(@"c:\temp\FILE.txt"); + var fileSystem = new MockFileSystem(new Dictionary + { + {sourceFilePath, new MockFileData("1")}, + }); + + var fileInfo = fileSystem.FileInfo.New(sourceFilePath); + fileInfo.MoveTo(destFilePath); + + await That(fileInfo.FullName).IsEqualTo(destFilePath); + await That(fileInfo.Exists).IsTrue(); + } + + [Test] + public async Task MockFileInfo_CopyTo_ThrowsExceptionIfSourceDoesNotExist() + { + var fileSystem = new MockFileSystem(); + var fileInfo = fileSystem.FileInfo.New(XFS.Path(@"c:\temp\file.txt")); + string destination = XFS.Path(XFS.Path(@"c:\temp\file2.txt")); + + Action action = () => fileInfo.CopyTo(destination); + + await That(action).Throws(); + } + + [TestCase(@"..\..\..\c.txt")] + [TestCase(@"c:\a\b\c.txt")] + [TestCase(@"c:\a\c.txt")] + [TestCase(@"c:\c.txt")] + public async Task MockFileInfo_ToString_ShouldReturnOriginalFilePath(string path) + { + //Arrange + var filePath = XFS.Path(path); + + //Act + var mockFileInfo = new MockFileInfo(new MockFileSystem(), filePath); + + //Assert + await That(mockFileInfo.ToString()).IsEqualTo(filePath); + } + + + /// + /// Normalize, tested with Path.GetFullPath and new FileInfo().FullName; + /// + [TestCaseSource(nameof(New_Paths_NormalizePaths_Cases))] + public async Task New_Paths_NormalizePaths(string input, string expected) + { + // Arrange + var mockFs = new MockFileSystem(); + + // Act + var mockFileInfo = mockFs.FileInfo.New(input); + var result = mockFileInfo.FullName; + + // Assert + await That(result).IsEqualTo(expected); + } + + public static IEnumerable New_Paths_NormalizePaths_Cases + { + get + { + yield return new[] { XFS.Path(@"c:\top\..\most\file"), XFS.Path(@"c:\most\file") }; + yield return new[] { XFS.Path(@"c:\top\..\most\..\dir\file"), XFS.Path(@"c:\dir\file") }; + yield return new[] { XFS.Path(@"\file"), XFS.Path(@"C:\file") }; + yield return new[] { XFS.Path(@"c:\top\../..\most\file"), XFS.Path(@"c:\most\file") }; + } + } + + [Test] + public async Task MockFileInfo_Replace_ShouldReplaceFileContents() + { + // Arrange + var fileSystem = new MockFileSystem(); + var path1 = XFS.Path(@"c:\temp\file1.txt"); + var path2 = XFS.Path(@"c:\temp\file2.txt"); + fileSystem.AddFile(path1, new MockFileData("1")); + fileSystem.AddFile(path2, new MockFileData("2")); + var fileInfo1 = fileSystem.FileInfo.New(path1); + var fileInfo2 = fileSystem.FileInfo.New(path2); + + // Act + fileInfo1.Replace(path2, null); + + await That(fileInfo2.OpenText().ReadToEnd()).IsEqualTo("1"); + } + + [Test] + public async Task MockFileInfo_Replace_ShouldCreateBackup() + { + // Arrange + var fileSystem = new MockFileSystem(); + var path1 = XFS.Path(@"c:\temp\file1.txt"); + var path2 = XFS.Path(@"c:\temp\file2.txt"); + var path3 = XFS.Path(@"c:\temp\file3.txt"); + fileSystem.AddFile(path1, new MockFileData("1")); + fileSystem.AddFile(path2, new MockFileData("2")); + var fileInfo1 = fileSystem.FileInfo.New(path1); + var fileInfo3 = fileSystem.FileInfo.New(path3); + + // Act + fileInfo1.Replace(path2, path3); + + await That(fileInfo3.OpenText().ReadToEnd()).IsEqualTo("2"); + } + + [Test] + public async Task MockFileInfo_Replace_ShouldThrowIfDirectoryOfBackupPathDoesNotExist() + { + // Arrange + var fileSystem = new MockFileSystem(); + var path1 = XFS.Path(@"c:\temp\file1.txt"); + var path2 = XFS.Path(@"c:\temp\file2.txt"); + var path3 = XFS.Path(@"c:\temp\subdirectory\file3.txt"); + fileSystem.AddFile(path1, new MockFileData("1")); + fileSystem.AddFile(path2, new MockFileData("2")); + var fileInfo1 = fileSystem.FileInfo.New(path1); + + // Act + await That(() => fileInfo1.Replace(path2, path3)).Throws(); + } + + [Test] + public async Task MockFileInfo_Replace_ShouldReturnDestinationFileInfo() + { + // Arrange + var fileSystem = new MockFileSystem(); + var path1 = XFS.Path(@"c:\temp\file1.txt"); + var path2 = XFS.Path(@"c:\temp\file2.txt"); + fileSystem.AddFile(path1, new MockFileData("1")); + fileSystem.AddFile(path2, new MockFileData("2")); + var fileInfo1 = fileSystem.FileInfo.New(path1); + var fileInfo2 = fileSystem.FileInfo.New(path2); + + // Act + var result = fileInfo1.Replace(path2, null); + + await That(result.FullName).IsEqualTo(fileInfo2.FullName); + } + + [Test] + public async Task MockFileInfo_Replace_ShouldThrowIfSourceFileDoesNotExist() + { + // Arrange + var fileSystem = new MockFileSystem(); + var path1 = XFS.Path(@"c:\temp\file1.txt"); + var path2 = XFS.Path(@"c:\temp\file2.txt"); + fileSystem.AddFile(path2, new MockFileData("1")); + var fileInfo = fileSystem.FileInfo.New(path1); + + await That(() => fileInfo.Replace(path2, null)).Throws(); + } + + [Test] + public async Task MockFileInfo_Replace_ShouldThrowIfDestinationFileDoesNotExist() + { + // Arrange + var fileSystem = new MockFileSystem(); + var path1 = XFS.Path(@"c:\temp\file1.txt"); + var path2 = XFS.Path(@"c:\temp\file2.txt"); + fileSystem.AddFile(path1, new MockFileData("1")); + var fileInfo = fileSystem.FileInfo.New(path1); + + await That(() => fileInfo.Replace(path2, null)).Throws(); + } + + [Test] + public async Task MockFileInfo_Exists_ShouldReturnCachedData() + { + // Arrange + var fileSystem = new MockFileSystem(); + var path1 = XFS.Path(@"c:\temp\file1.txt"); + var fileInfo = fileSystem.FileInfo.New(path1); + + // Act + fileSystem.AddFile(path1, new MockFileData("1")); + + // Assert + await That(fileInfo.Exists).IsFalse(); + } + + [Test] + public async Task MockFileInfo_Exists_ShouldUpdateCachedDataOnRefresh() + { + // Arrange + var fileSystem = new MockFileSystem(); + var path1 = XFS.Path(@"c:\temp\file1.txt"); + var fileInfo = fileSystem.FileInfo.New(path1); + + // Act + fileSystem.AddFile(path1, new MockFileData("1")); + fileInfo.Refresh(); + + // Assert + await That(fileInfo.Exists).IsTrue(); + } + + [Test] + public async Task MockFileInfo_Create_ShouldUpdateCachedDataAndReturnTrueForExists() + { + IFileSystem fileSystem = new MockFileSystem(); + var path = XFS.Path(@"c:\temp\file1.txt"); + IFileInfo fileInfo = fileSystem.FileInfo.New(path); + + // Act + fileInfo.Create().Dispose(); + + // Assert + var result = fileInfo.Exists; + await That(result).IsTrue(); + } + + [Test] + public async Task MockFileInfo_CreateText_ShouldUpdateCachedDataAndReturnTrueForExists() + { + IFileSystem fileSystem = new MockFileSystem(); + var path = XFS.Path(@"c:\temp\file1.txt"); + IFileInfo fileInfo = fileSystem.FileInfo.New(path); + + // Act + fileInfo.CreateText().Dispose(); + + // Assert + await That(fileInfo.Exists).IsTrue(); + } + + [Test] + public async Task MockFileInfo_Delete_ShouldUpdateCachedDataAndReturnFalseForExists() + { + var fileSystem = new MockFileSystem(); + var path = XFS.Path(@"c:\temp\file1.txt"); + IFileInfo fileInfo = fileSystem.FileInfo.New(path); + + // Act + fileInfo.Delete(); + + // Assert + await That(fileInfo.Exists).IsFalse(); + } + + [Test] + public async Task MockFileInfo_Delete_ShouldThrowIfFileAccessShareHasNoWriteOrDeleteAccess() + { + var fileSystem = new MockFileSystem(); + fileSystem.AddFile( + @"c:\bar\foo.txt", + new MockFileData("text contents") { AllowedFileShare = FileShare.None }); + + var fi = fileSystem.FileInfo.New(@"c:\bar\foo.txt"); + + await That(() => fi.Delete()).Throws(); + } + + [Test] + public async Task MockFileInfo_LastAccessTimeUtcWithUnspecifiedDateTimeKind_ShouldSetLastAccessTimeUtcOfFileInFileSystem() + { + var date = DateTime.SpecifyKind(DateTime.Now.AddHours(-4), DateTimeKind.Unspecified); + var fileSystem = new MockFileSystem(); + fileSystem.Directory.CreateDirectory(@"c:\test"); + fileSystem.File.WriteAllText(@"c:\test\a.txt", "Demo text content"); + var fileInfo = new MockFileInfo(fileSystem, @"c:\test\a.txt") + { + LastAccessTimeUtc = date + }; + + await That(fileInfo.LastAccessTimeUtc).IsEqualTo(date); + await That(fileInfo.LastAccessTimeUtc.Kind).IsNotEqualTo(DateTimeKind.Unspecified); + } + + [Test] + public async Task MockFileInfo_LastAccessTimeWithUnspecifiedDateTimeKind_ShouldSetLastAccessTimeOfFileInFileSystem() + { + var date = DateTime.SpecifyKind(DateTime.Now.AddHours(-4), DateTimeKind.Unspecified); + var fileSystem = new MockFileSystem(); + fileSystem.Directory.CreateDirectory(@"c:\test"); + fileSystem.File.WriteAllText(@"c:\test\a.txt", "Demo text content"); + var fileInfo = new MockFileInfo(fileSystem, @"c:\test\a.txt") + { + LastAccessTime = date + }; + + await That(fileInfo.LastAccessTime).IsEqualTo(date); + await That(fileInfo.LastAccessTime.Kind).IsNotEqualTo(DateTimeKind.Unspecified); + } + + [Test] + public async Task MockFileInfo_CreationTimeUtcWithUnspecifiedDateTimeKind_ShouldSetCreationTimeUtcOfFileInFileSystem() + { + var date = DateTime.SpecifyKind(DateTime.Now.AddHours(-4), DateTimeKind.Unspecified); + var fileSystem = new MockFileSystem(); + fileSystem.Directory.CreateDirectory(@"c:\test"); + fileSystem.File.WriteAllText(@"c:\test\a.txt", "Demo text content"); + var fileInfo = new MockFileInfo(fileSystem, @"c:\test\a.txt") + { + CreationTimeUtc = date + }; + + await That(fileInfo.CreationTimeUtc).IsEqualTo(date); + await That(fileInfo.CreationTimeUtc.Kind).IsNotEqualTo(DateTimeKind.Unspecified); + } + + [Test] + public async Task MockFileInfo_CreationTimeWithUnspecifiedDateTimeKind_ShouldSetCreationTimeOfFileInFileSystem() + { + var date = DateTime.SpecifyKind(DateTime.Now.AddHours(-4), DateTimeKind.Unspecified); + var fileSystem = new MockFileSystem(); + fileSystem.Directory.CreateDirectory(@"c:\test"); + fileSystem.File.WriteAllText(@"c:\test\a.txt", "Demo text content"); + var fileInfo = new MockFileInfo(fileSystem, @"c:\test\a.txt") + { + CreationTime = date + }; + + await That(fileInfo.CreationTime).IsEqualTo(date); + await That(fileInfo.CreationTime.Kind).IsNotEqualTo(DateTimeKind.Unspecified); + } + + [Test] + public async Task MockFileInfo_LastWriteTimeUtcWithUnspecifiedDateTimeKind_ShouldSetLastWriteTimeUtcOfFileInFileSystem() + { + var date = DateTime.SpecifyKind(DateTime.Now.AddHours(-4), DateTimeKind.Unspecified); + var fileSystem = new MockFileSystem(); + fileSystem.Directory.CreateDirectory(@"c:\test"); + fileSystem.File.WriteAllText(@"c:\test\a.txt", "Demo text content"); + var fileInfo = new MockFileInfo(fileSystem, @"c:\test\a.txt") + { + LastWriteTimeUtc = date + }; + + await That(fileInfo.LastWriteTimeUtc).IsEqualTo(date); + await That(fileInfo.LastWriteTimeUtc.Kind).IsNotEqualTo(DateTimeKind.Unspecified); + } + + [Test] + public async Task MockFileInfo_LastWriteTimeWithUnspecifiedDateTimeKind_ShouldSetLastWriteTimeOfFileInFileSystem() + { + var date = DateTime.SpecifyKind(DateTime.Now.AddHours(-4), DateTimeKind.Unspecified); + var fileSystem = new MockFileSystem(); + fileSystem.Directory.CreateDirectory(@"c:\test"); + fileSystem.File.WriteAllText(@"c:\test\a.txt", "Demo text content"); + var fileInfo = new MockFileInfo(fileSystem, @"c:\test\a.txt") + { + LastWriteTime = date + }; + + await That(fileInfo.LastWriteTime).IsEqualTo(date); + await That(fileInfo.LastWriteTime.Kind).IsNotEqualTo(DateTimeKind.Unspecified); + } +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileLockTests.cs b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileLockTests.cs new file mode 100644 index 000000000..f54d74274 --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileLockTests.cs @@ -0,0 +1,190 @@ +namespace System.IO.Abstractions.TestingHelpers.Tests; + +using Collections.Generic; + +using NUnit.Framework; +using NUnit.Framework.Constraints; +using XFS = MockUnixSupport; +class MockFileLockTests +{ + [Test] + public async Task MockFile_Lock_FileShareNoneThrows() + { + string filepath = XFS.Path(@"c:\something\does\exist.txt"); + var filesystem = new MockFileSystem(new Dictionary + { + { filepath, new MockFileData("I'm here") { AllowedFileShare = FileShare.None }} + }); + + await That(() => filesystem.File.Open(filepath, FileMode.Open, FileAccess.Read, FileShare.Read)).Throws(); + } + [Test] + public async Task MockFile_Lock_FileShareReadDoesNotThrowOnRead() + { + string filepath = XFS.Path(@"c:\something\does\exist.txt"); + var filesystem = new MockFileSystem(new Dictionary + { + { filepath, new MockFileData("I'm here") { AllowedFileShare = FileShare.Read }} + }); + + await That(() => filesystem.File.Open(filepath, FileMode.Open, FileAccess.Read, FileShare.Read)).DoesNotThrow(); + } + [Test] + public async Task MockFile_Lock_FileShareReadThrowsOnWrite() + { + string filepath = XFS.Path(@"c:\something\does\exist.txt"); + var filesystem = new MockFileSystem(new Dictionary + { + { filepath, new MockFileData("I'm here") { AllowedFileShare = FileShare.Read }} + }); + + await That(() => filesystem.File.Open(filepath, FileMode.Open, FileAccess.Write, FileShare.Read)).Throws(); + } + [Test] + public async Task MockFile_Lock_FileShareWriteThrowsOnRead() + { + string filepath = XFS.Path(@"c:\something\does\exist.txt"); + var filesystem = new MockFileSystem(new Dictionary + { + { filepath, new MockFileData("I'm here") { AllowedFileShare = FileShare.Write }} + }); + + await That(() => filesystem.File.Open(filepath, FileMode.Open, FileAccess.Read, FileShare.Read)).Throws(); + } + [Test] + public async Task MockFile_Lock_FileShareWriteDoesNotThrowOnWrite() + { + string filepath = XFS.Path(@"c:\something\does\exist.txt"); + var filesystem = new MockFileSystem(new Dictionary + { + { filepath, new MockFileData("I'm here") { AllowedFileShare = FileShare.Write }} + }); + + await That(() => filesystem.File.Open(filepath, FileMode.Open, FileAccess.Write, FileShare.Read)).DoesNotThrow(); + } + + + [Test] + public async Task MockFile_Lock_FileShareNoneThrowsOnOpenRead() + { + string filepath = XFS.Path(@"c:\something\does\exist.txt"); + var filesystem = new MockFileSystem(new Dictionary + { + { filepath, new MockFileData("I'm here") { AllowedFileShare = FileShare.None }} + }); + + var exception = await That(() => filesystem.File.OpenRead(filepath)).Throws(); + await That(exception.Message).IsEqualTo($"The process cannot access the file '{filepath}' because it is being used by another process."); + } + [Test] + public async Task MockFile_Lock_FileShareNoneThrowsOnWriteAllLines() + { + string filepath = XFS.Path(@"c:\something\does\exist.txt"); + var filesystem = new MockFileSystem(new Dictionary + { + { filepath, new MockFileData("I'm here") { AllowedFileShare = FileShare.None }} + }); + + var exception = await That(() => filesystem.File.WriteAllLines(filepath, new string[] { "hello", "world" })).Throws(); + await That(exception.Message).IsEqualTo($"The process cannot access the file '{filepath}' because it is being used by another process."); + } + [Test] + public async Task MockFile_Lock_FileShareNoneThrowsOnReadAllLines() + { + string filepath = XFS.Path(@"c:\something\does\exist.txt"); + var filesystem = new MockFileSystem(new Dictionary + { + { filepath, new MockFileData("I'm here") { AllowedFileShare = FileShare.None }} + }); + + var exception = await That(() => filesystem.File.ReadAllLines(filepath)).Throws(); + await That(exception.Message).IsEqualTo($"The process cannot access the file '{filepath}' because it is being used by another process."); + } + [Test] + public async Task MockFile_Lock_FileShareNoneThrowsOnReadAllText() + { + string filepath = XFS.Path(@"c:\something\does\exist.txt"); + var filesystem = new MockFileSystem(new Dictionary + { + { filepath, new MockFileData("I'm here") { AllowedFileShare = FileShare.None }} + }); + + var exception = await That(() => filesystem.File.ReadAllText(filepath)).Throws(); + await That(exception.Message).IsEqualTo($"The process cannot access the file '{filepath}' because it is being used by another process."); + } + [Test] + public async Task MockFile_Lock_FileShareNoneThrowsOnReadAllBytes() + { + string filepath = XFS.Path(@"c:\something\does\exist.txt"); + var filesystem = new MockFileSystem(new Dictionary + { + { filepath, new MockFileData("I'm here") { AllowedFileShare = FileShare.None }} + }); + + var exception = await That(() => filesystem.File.ReadAllBytes(filepath)).Throws(); + await That(exception.Message).IsEqualTo($"The process cannot access the file '{filepath}' because it is being used by another process."); + } + [Test] + public async Task MockFile_Lock_FileShareNoneThrowsOnAppendLines() + { + string filepath = XFS.Path(@"c:\something\does\exist.txt"); + var filesystem = new MockFileSystem(new Dictionary + { + { filepath, new MockFileData("I'm here") { AllowedFileShare = FileShare.None }} + }); + + var exception = await That(() => filesystem.File.AppendAllLines(filepath, new string[] { "hello", "world" })).Throws(); + await That(exception.Message).IsEqualTo($"The process cannot access the file '{filepath}' because it is being used by another process."); + } + + [Test] + public async Task MockFile_Lock_FileShareNoneThrowsFileMove() + { + string filepath = XFS.Path(@"c:\something\does\exist.txt"); + string target = XFS.Path(@"c:\something\does\notexist.txt"); + var filesystem = new MockFileSystem(new Dictionary + { + { filepath, new MockFileData("I'm here") { AllowedFileShare = FileShare.None }} + }); + + var exception = await That(() => filesystem.File.Move(filepath, target)).Throws(); + await That(exception.Message).IsEqualTo("The process cannot access the file because it is being used by another process."); + } + [Test] + public async Task MockFile_Lock_FileShareDeleteDoesNotThrowFileMove() + { + string filepath = XFS.Path(@"c:\something\does\exist.txt"); + string target = XFS.Path(@"c:\something\does\notexist.txt"); + var filesystem = new MockFileSystem(new Dictionary + { + { filepath, new MockFileData("I'm here") { AllowedFileShare = FileShare.Delete }} + }); + + await That(() => filesystem.File.Move(filepath, target)).DoesNotThrow(); + } + [Test] + public async Task MockFile_Lock_FileShareNoneThrowsDelete() + { + string filepath = XFS.Path(@"c:\something\does\exist.txt"); + var filesystem = new MockFileSystem(new Dictionary + { + { filepath, new MockFileData("I'm here") { AllowedFileShare = FileShare.None }} + }); + + var exception = await That(() => filesystem.File.Delete(filepath)).Throws(); + await That(exception.Message).IsEqualTo($"The process cannot access the file '{filepath}' because it is being used by another process."); + } + [Test] + public async Task MockFile_Lock_FileShareDeleteDoesNotThrowDelete() + { + string filepath = XFS.Path(@"c:\something\does\exist.txt"); + var filesystem = new MockFileSystem(new Dictionary + { + { filepath, new MockFileData("I'm here") { AllowedFileShare = FileShare.Delete }} + }); + + await That(() => filesystem.File.Delete(filepath)).DoesNotThrow(); + } + + private static IResolveConstraint IOException() => Is.TypeOf().And.Property("HResult").EqualTo(unchecked((int)0x80070020)); +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileMoveTests.cs b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileMoveTests.cs new file mode 100644 index 000000000..8032d3ad0 --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileMoveTests.cs @@ -0,0 +1,471 @@ +namespace System.IO.Abstractions.TestingHelpers.Tests; + +using Collections.Generic; +using Linq; +using NUnit.Framework; +using XFS = MockUnixSupport; + +public class MockFileMoveTests +{ + [Test] + public async Task MockFile_Move_ShouldMoveFileWithinMemoryFileSystem() + { + string sourceFilePath = XFS.Path(@"c:\something\demo.txt"); + string sourceFileContent = "this is some content"; + var fileSystem = new MockFileSystem(new Dictionary + { + {sourceFilePath, new MockFileData(sourceFileContent)}, + {XFS.Path(@"c:\somethingelse\dummy.txt"), new MockFileData(new byte[] {0})} + }); + + string destFilePath = XFS.Path(@"c:\somethingelse\demo1.txt"); + + fileSystem.File.Move(sourceFilePath, destFilePath); + + await That(fileSystem.FileExists(destFilePath)).IsTrue(); + await That(fileSystem.GetFile(destFilePath).TextContents).IsEqualTo(sourceFileContent); + await That(fileSystem.FileExists(sourceFilePath)).IsFalse(); + } + + [Test] + public async Task MockFile_Move_WithReadOnlyAttribute_ShouldMoveFile() + { + var sourceFilePath = @"c:\foo.txt"; + var destFilePath = @"c:\bar.txt"; + var fileSystem = new MockFileSystem(); + fileSystem.File.WriteAllText(sourceFilePath, "this is some content"); + fileSystem.File.SetAttributes(sourceFilePath, FileAttributes.ReadOnly); + + fileSystem.File.Move(sourceFilePath, destFilePath); + + await That(fileSystem.File.Exists(destFilePath)).IsTrue(); + await That(fileSystem.File.Exists(sourceFilePath)).IsFalse(); + } + + [Test] + public async Task MockFile_Move_SameSourceAndTargetIsANoOp() + { + string sourceFilePath = XFS.Path(@"c:\something\demo.txt"); + string sourceFileContent = "this is some content"; + var fileSystem = new MockFileSystem(new Dictionary + { + {sourceFilePath, new MockFileData(sourceFileContent)}, + {XFS.Path(@"c:\somethingelse\dummy.txt"), new MockFileData(new byte[] {0})} + }); + + string destFilePath = XFS.Path(@"c:\somethingelse\demo.txt"); + + fileSystem.File.Move(sourceFilePath, destFilePath); + + await That(fileSystem.FileExists(destFilePath)).IsTrue(); + await That(fileSystem.GetFile(destFilePath).TextContents).IsEqualTo(sourceFileContent); + } + + [Test] + public async Task MockFile_Move_ShouldThrowIOExceptionWhenTargetAlreadyExists() + { + string sourceFilePath = XFS.Path(@"c:\something\demo.txt"); + string sourceFileContent = "this is some content"; + string destFilePath = XFS.Path(@"c:\somethingelse\demo1.txt"); + var fileSystem = new MockFileSystem(new Dictionary + { + {sourceFilePath, new MockFileData(sourceFileContent)}, + {destFilePath, new MockFileData(sourceFileContent)} + }); + + var exception = await That(() => fileSystem.File.Move(sourceFilePath, destFilePath)).Throws(); + + await That(exception.Message).IsEqualTo("A file can not be created if it already exists."); + } + +#if FEATURE_FILE_MOVE_WITH_OVERWRITE + [Test] + public async Task MockFile_MoveWithOverwrite_ShouldSucceedWhenTargetAlreadyExists() + { + string sourceFilePath = XFS.Path(@"c:\something\demo.txt"); + string sourceFileContent = "this is some content"; + string destFilePath = XFS.Path(@"c:\somethingelse\demo1.txt"); + var fileSystem = new MockFileSystem(new Dictionary + { + {sourceFilePath, new MockFileData(sourceFileContent)}, + {destFilePath, new MockFileData(sourceFileContent)} + }); + + fileSystem.File.Move(sourceFilePath, destFilePath, overwrite: true); + + await That(fileSystem.File.ReadAllText(destFilePath)).IsEqualTo(sourceFileContent); + } +#endif + + [Test] + public async Task MockFile_Move_ShouldThrowArgumentNullExceptionWhenSourceIsNull_Message() + { + string destFilePath = XFS.Path(@"c:\something\demo.txt"); + var fileSystem = new MockFileSystem(); + + var exception = await That(() => fileSystem.File.Move(null, destFilePath)).Throws(); + + await That(exception.Message).StartsWith("File name cannot be null."); + } + + [Test] + public async Task MockFile_Move_ShouldThrowArgumentNullExceptionWhenSourceIsNull_ParamName() + { + string destFilePath = XFS.Path(@"c:\something\demo.txt"); + var fileSystem = new MockFileSystem(); + + var exception = await That(() => fileSystem.File.Move(null, destFilePath)).Throws(); + + await That(exception.ParamName).IsEqualTo("sourceFileName"); + } + + [Test] + [WindowsOnly(WindowsSpecifics.StrictPathRules)] + public async Task MockFile_Move_ShouldThrowArgumentExceptionWhenSourceFileNameContainsInvalidChars_Message() + { + var destFilePath = @"c:\something\demo.txt"; + var fileSystem = new MockFileSystem(); + var excludeChars = Shared.SpecialInvalidPathChars(fileSystem); + + foreach (var invalidChar in fileSystem.Path.GetInvalidFileNameChars().Except(excludeChars)) + { + var sourceFilePath = @"c:\something\demo.txt" + invalidChar; + + var exception = + await That(() => fileSystem.File.Move(sourceFilePath, destFilePath)).Throws(); + + await That(exception.Message).IsEqualTo("Illegal characters in path.") + .Because(string.Format("Testing char: [{0:c}] \\{1:X4}", invalidChar, (int)invalidChar)); + } + } + + [Test] + [WindowsOnly(WindowsSpecifics.StrictPathRules)] + public async Task MockFile_Move_ShouldThrowArgumentExceptionWhenSourcePathContainsInvalidChars_Message() + { + var destFilePath = @"c:\something\demo.txt"; + var fileSystem = new MockFileSystem(); + + foreach (var invalidChar in fileSystem.Path.GetInvalidPathChars()) + { + var sourceFilePath = @"c:\some" + invalidChar + @"thing\demo.txt"; + + var exception = + await That(() => fileSystem.File.Move(sourceFilePath, destFilePath)).Throws(); + + await That(exception.Message).IsEqualTo("Illegal characters in path.") + .Because(string.Format("Testing char: [{0:c}] \\{1:X4}", invalidChar, (int)invalidChar)); + } + } + + [Test] + [WindowsOnly(WindowsSpecifics.StrictPathRules)] + public async Task MockFile_Move_ShouldThrowArgumentExceptionWhenTargetPathContainsInvalidChars_Message() + { + var sourceFilePath = @"c:\something\demo.txt"; + var fileSystem = new MockFileSystem(); + + foreach (var invalidChar in fileSystem.Path.GetInvalidPathChars()) + { + var destFilePath = @"c:\some" + invalidChar + @"thing\demo.txt"; + + var exception = + await That(() => fileSystem.File.Move(sourceFilePath, destFilePath)).Throws(); + + await That(exception.Message).IsEqualTo("Illegal characters in path.") + .Because(string.Format("Testing char: [{0:c}] \\{1:X4}", invalidChar, (int)invalidChar)); + } + } + + [Test] + [WindowsOnly(WindowsSpecifics.StrictPathRules)] + public async Task MockFile_Move_ShouldThrowArgumentExceptionWhenTargetFileNameContainsInvalidChars_Message() + { + var sourceFilePath = @"c:\something\demo.txt"; + var fileSystem = new MockFileSystem(); + var excludeChars = Shared.SpecialInvalidPathChars(fileSystem); + + foreach (var invalidChar in fileSystem.Path.GetInvalidFileNameChars().Except(excludeChars)) + { + var destFilePath = @"c:\something\demo.txt" + invalidChar; + + var exception = + await That(() => fileSystem.File.Move(sourceFilePath, destFilePath)).Throws(); + + await That(exception.Message).IsEqualTo("Illegal characters in path.") + .Because(string.Format("Testing char: [{0:c}] \\{1:X4}", invalidChar, (int)invalidChar)); + } + } + + [Test] + [WindowsOnly(WindowsSpecifics.Drives)] + public async Task MockFile_Move_ShouldThrowNotSupportedExceptionWhenSourcePathContainsInvalidUseOfDriveSeparator() + { + var badSourcePath = @"C::\something\demo.txt"; + var destinationPath = @"C:\elsewhere\demo.txt"; + var fileSystem = new MockFileSystem(); + + Action action = () => fileSystem.File.Move(badSourcePath, destinationPath); + + await That(action).Throws(); + } + + [Test] + [WindowsOnly(WindowsSpecifics.Drives)] + public async Task MockFile_Move_ShouldThrowNotSupportedExceptionWhenSourcePathContainsInvalidDriveLetter() + { + var badSourcePath = @"0:\something\demo.txt"; + var destinationPath = @"C:\elsewhere\demo.txt"; + var fileSystem = new MockFileSystem(); + + Action action = () => fileSystem.File.Move(badSourcePath, destinationPath); + + await That(action).Throws(); + } + + [Test] + [WindowsOnly(WindowsSpecifics.Drives)] + public async Task MockFile_Move_ShouldThrowNotSupportedExceptionWhenDestinationPathContainsInvalidUseOfDriveSeparator() + { + var sourcePath = @"C:\something\demo.txt"; + var badDestinationPath = @"C:\elsewhere:\demo.txt"; + var fileSystem = new MockFileSystem(); + + Action action = () => fileSystem.File.Move(sourcePath, badDestinationPath); + + await That(action).Throws(); + } + + [Test] + [WindowsOnly(WindowsSpecifics.Drives)] + public async Task MockFile_Move_ShouldThrowNotSupportedExceptionWhenDestinationPathContainsInvalidDriveLetter() + { + var sourcePath = @"C:\something\demo.txt"; + var badDestinationPath = @"^:\elsewhere\demo.txt"; + var fileSystem = new MockFileSystem(); + + Action action = () => fileSystem.File.Move(sourcePath, badDestinationPath); + + await That(action).Throws(); + } + + [Test] + [WindowsOnly(WindowsSpecifics.Drives)] + public async Task MockFile_Move_CaseOnlyRename_ShouldChangeCase() + { + var fileSystem = new MockFileSystem(); + string sourceFilePath = @"c:\temp\demo.txt"; + string destFilePath = @"c:\temp\DEMO.TXT"; + string sourceFileContent = "content"; + fileSystem.File.WriteAllText(sourceFilePath, sourceFileContent); + + fileSystem.File.Move(sourceFilePath, destFilePath); + + await That(fileSystem.File.Exists(destFilePath)).IsTrue(); + await That(fileSystem.File.ReadAllText(destFilePath)).IsEqualTo(sourceFileContent); + } + + [Test] + public async Task MockFile_Move_ShouldThrowArgumentExceptionWhenSourceIsEmpty_Message() + { + string destFilePath = XFS.Path(@"c:\something\demo.txt"); + var fileSystem = new MockFileSystem(); + + var exception = await That(() => fileSystem.File.Move(string.Empty, destFilePath)).Throws(); + + await That(exception.Message).StartsWith("Empty file name is not legal."); + } + + [Test] + public async Task MockFile_Move_ShouldThrowArgumentExceptionWhenSourceIsEmpty_ParamName() + { + string destFilePath = XFS.Path(@"c:\something\demo.txt"); + var fileSystem = new MockFileSystem(); + + var exception = await That(() => fileSystem.File.Move(string.Empty, destFilePath)).Throws(); + + await That(exception.ParamName).IsEqualTo("sourceFileName"); + } + + [Test] + public async Task MockFile_Move_ShouldThrowArgumentExceptionWhenSourceIsStringOfBlanks() + { + string sourceFilePath = " "; + string destFilePath = XFS.Path(@"c:\something\demo.txt"); + var fileSystem = new MockFileSystem(); + + var exception = await That(() => fileSystem.File.Move(sourceFilePath, destFilePath)).Throws(); + + await That(exception.Message).StartsWith("The path is not of a legal form."); + } + + [Test] + public async Task MockFile_Move_ShouldThrowArgumentNullExceptionWhenTargetIsNull_Message() + { + string sourceFilePath = XFS.Path(@"c:\something\demo.txt"); + var fileSystem = new MockFileSystem(); + + var exception = await That(() => fileSystem.File.Move(sourceFilePath, null)).Throws(); + + await That(exception.Message).StartsWith("File name cannot be null."); + } + + [Test] + public async Task MockFile_Move_ShouldThrowArgumentNullExceptionWhenTargetIsNull_ParamName() + { + string sourceFilePath = XFS.Path(@"c:\something\demo.txt"); + var fileSystem = new MockFileSystem(); + + var exception = await That(() => fileSystem.File.Move(sourceFilePath, null)).Throws(); + + await That(exception.ParamName).IsEqualTo("destFileName"); + } + + [Test] + public async Task MockFile_Move_ShouldThrowArgumentExceptionWhenTargetIsStringOfBlanks() + { + string sourceFilePath = XFS.Path(@"c:\something\demo.txt"); + string destFilePath = " "; + var fileSystem = new MockFileSystem(); + + var exception = await That(() => fileSystem.File.Move(sourceFilePath, destFilePath)).Throws(); + + await That(exception.Message).StartsWith("The path is not of a legal form."); + } + + [Test] + public async Task MockFile_Move_ShouldThrowArgumentExceptionWhenTargetIsEmpty_Message() + { + string sourceFilePath = XFS.Path(@"c:\something\demo.txt"); + var fileSystem = new MockFileSystem(); + + var exception = await That(() => fileSystem.File.Move(sourceFilePath, string.Empty)).Throws(); + + await That(exception.Message).StartsWith("Empty file name is not legal."); + } + + [Test] + public async Task MockFile_Move_ShouldThrowArgumentExceptionWhenTargetIsEmpty_ParamName() + { + string sourceFilePath = XFS.Path(@"c:\something\demo.txt"); + var fileSystem = new MockFileSystem(); + + var exception = await That(() => fileSystem.File.Move(sourceFilePath, string.Empty)).Throws(); + + await That(exception.ParamName).IsEqualTo("destFileName"); + } + + [Test] + public async Task MockFile_Move_ShouldThrowFileNotFoundExceptionWhenSourceDoesNotExist_Message() + { + string sourceFilePath = XFS.Path(@"c:\something\demo.txt"); + string destFilePath = XFS.Path(@"c:\something\demo1.txt"); + var fileSystem = new MockFileSystem(); + + var exception = await That(() => fileSystem.File.Move(sourceFilePath, destFilePath)).Throws(); + + await That(exception.Message).IsEqualTo("Could not find file '" + XFS.Path("c:\\something\\demo.txt") + "'."); + } + + [Test] + public async Task MockFile_Move_ShouldThrowFileNotFoundExceptionWhenSourceDoesNotExist_FileName() + { + string sourceFilePath = XFS.Path(@"c:\something\demo.txt"); + string destFilePath = XFS.Path(@"c:\something\demo1.txt"); + var fileSystem = new MockFileSystem(); + + var exception = await That(() => fileSystem.File.Move(sourceFilePath, destFilePath)).Throws(); + + await That(exception.FileName).IsEqualTo(XFS.Path(@"c:\something\demo.txt")); + } + + [Test] + public async Task MockFile_Move_ShouldThrowDirectoryNotFoundExceptionWhenSourcePathDoesNotExist_Message() + { + string sourceFilePath = XFS.Path(@"c:\something\demo.txt"); + string destFilePath = XFS.Path(@"c:\somethingelse\demo.txt"); + var fileSystem = new MockFileSystem(new Dictionary + { + {sourceFilePath, new MockFileData(new byte[] {0})} + }); + + await That(() => fileSystem.File.Move(sourceFilePath, destFilePath)) + .Throws() + .WithMessage(@"Could not find a part of the path*").AsWildcard(); + } + + [Test] + public async Task MockFile_Move_ShouldThrowExceptionWhenSourceDoesNotExist() + { + string sourceFilePath = XFS.Path(@"c:\something\demo.txt"); + var fileSystem = new MockFileSystem(); + + Action action = () => fileSystem.File.Move(sourceFilePath, XFS.Path(@"c:\something\demo2.txt")); + + await That(action).Throws(); + } + + [Test] + public async Task MockFile_Move_ShouldThrowExceptionWhenSourceDoesNotExist_EvenWhenCopyingToItself() + { + string sourceFilePath = XFS.Path(@"c:\something\demo.txt"); + var fileSystem = new MockFileSystem(); + + Action action = () => fileSystem.File.Move(sourceFilePath, XFS.Path(@"c:\something\demo.txt")); + + await That(action).Throws(); + } + + [Test] + public async Task MockFile_Move_ShouldRetainMetadata() + { + string sourceFilePath = XFS.Path(@"c:\something\demo.txt"); + string sourceFileContent = "this is some content"; + DateTimeOffset creationTime = DateTimeOffset.Now; + var fileSystem = new MockFileSystem(new Dictionary + { + {sourceFilePath, new MockFileData(sourceFileContent){CreationTime = creationTime}}, + {XFS.Path(@"c:\somethingelse\dummy.txt"), new MockFileData(new byte[] {0})} + }); + + string destFilePath = XFS.Path(@"c:\somethingelse\demo1.txt"); + + fileSystem.File.Move(sourceFilePath, destFilePath); + + await That(fileSystem.File.GetCreationTimeUtc(destFilePath)).IsEqualTo(creationTime.UtcDateTime); + } + + [Test] + public async Task MockFile_Move_ShouldThrowExceptionWhenSourceFileShare_Is_Not_Delete() + { + string sourceFileReadDelete = XFS.Path(@"c:\something\IHaveReadDelete.txt"); + string sourceFileDelete = XFS.Path(@"c:\something\IHaveDelete.txt"); + string sourceFileRead = XFS.Path(@"c:\something\IHaveRead.txt"); + string sourceFileNone = XFS.Path(@"c:\something\IHaveNone.txt"); + var fileSystem = new MockFileSystem(new Dictionary + { + { sourceFileDelete, new MockFileData("") { AllowedFileShare = FileShare.Delete } }, + { sourceFileRead, new MockFileData("") { AllowedFileShare = FileShare.Read } }, + { sourceFileReadDelete, new MockFileData("") { AllowedFileShare = FileShare.Delete | FileShare.Read } }, + { sourceFileNone, new MockFileData("") { AllowedFileShare = FileShare.None } }, + }); + + await AssertMoveSuccess(sourceFileReadDelete); + await AssertMoveSuccess(sourceFileDelete); + await AssertMoveThrowsIOException(sourceFileRead); + await AssertMoveThrowsIOException(sourceFileNone); + + async Task AssertMoveThrowsIOException(string sourceFile) + { + var target = sourceFile + ".moved"; + await That(() => fileSystem.File.Move(sourceFile, target)).Throws(); + } + + async Task AssertMoveSuccess(string sourceFile) + { + var target = sourceFile + ".moved"; + fileSystem.File.Move(sourceFile, target); + await That(fileSystem.File.Exists(target)).IsTrue(); + } + } +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileOpenTests.cs b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileOpenTests.cs new file mode 100644 index 000000000..ec1896ad9 --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileOpenTests.cs @@ -0,0 +1,381 @@ +using System.Threading.Tasks; + +namespace System.IO.Abstractions.TestingHelpers.Tests; + +using Collections.Generic; + +using NUnit.Framework; + +using XFS = MockUnixSupport; + +public class MockFileOpenTests +{ + [Test] + public async Task MockFile_Open_ThrowsOnCreateNewWithExistingFile() + { + string filepath = XFS.Path(@"c:\something\already\exists.txt"); + var filesystem = new MockFileSystem(new Dictionary + { + { filepath, new MockFileData("I'm here") } + }); + + await That(() => filesystem.File.Open(filepath, FileMode.CreateNew)).Throws(); + } + + [Test] + public async Task MockFile_Open_ThrowsOnOpenWithMissingFile() + { + string filepath = XFS.Path(@"c:\something\doesnt\exist.txt"); + var filesystem = new MockFileSystem(new Dictionary()); + + await That(() => filesystem.File.Open(filepath, FileMode.Open)).Throws(); + } + + [Test] + public async Task MockFile_Open_ThrowsOnTruncateWithMissingFile() + { + string filepath = XFS.Path(@"c:\something\doesnt\exist.txt"); + var filesystem = new MockFileSystem(new Dictionary()); + + await That(() => filesystem.File.Open(filepath, FileMode.Truncate)).Throws(); + } + + [Test] + public async Task MockFile_Open_CreatesNewFileFileOnCreate() + { + string filepath = XFS.Path(@"c:\something\doesnt\exist.txt"); + var filesystem = new MockFileSystem(new Dictionary()); + filesystem.AddDirectory(XFS.Path(@"c:\something\doesnt")); + + var stream = filesystem.File.Open(filepath, FileMode.Create); + + await That(filesystem.File.Exists(filepath)).IsTrue(); + await That(stream.Position).IsEqualTo(0); + await That(stream.Length).IsEqualTo(0); + } + + [Test] + public async Task MockFile_Open_AllowsReadWriteOnCreate() + { + string filepath = XFS.Path(@"c:\something\doesnt\exist.txt"); + var filesystem = new MockFileSystem(new Dictionary()); + filesystem.AddDirectory(XFS.Path(@"c:\something\doesnt")); + + var stream = filesystem.File.Open(filepath, FileMode.Create); + + await That(stream.CanRead).IsTrue(); + await That(stream.CanWrite).IsTrue(); + } + + [Test] + public async Task MockFile_Open_CreatesNewFileFileOnCreateNew() + { + string filepath = XFS.Path(@"c:\something\doesnt\exist.txt"); + var filesystem = new MockFileSystem(new Dictionary()); + filesystem.AddDirectory(XFS.Path(@"c:\something\doesnt")); + + var stream = filesystem.File.Open(filepath, FileMode.CreateNew); + + await That(filesystem.File.Exists(filepath)).IsTrue(); + await That(stream.Position).IsEqualTo(0); + await That(stream.Length).IsEqualTo(0); + } + + [Test] + public async Task MockFile_Open_OpensExistingFileOnAppend() + { + string filepath = XFS.Path(@"c:\something\does\exist.txt"); + var filesystem = new MockFileSystem(new Dictionary + { + { filepath, new MockFileData("I'm here") } + }); + + var stream = filesystem.File.Open(filepath, FileMode.Append); + var file = filesystem.GetFile(filepath); + + await That(stream.Position).IsEqualTo(file.Contents.Length); + await That(stream.Length).IsEqualTo(file.Contents.Length); + } + + [Test] + public async Task MockFile_Open_OpensExistingFileOnTruncate() + { + string filepath = XFS.Path(@"c:\something\does\exist.txt"); + var filesystem = new MockFileSystem(new Dictionary + { + { filepath, new MockFileData("I'm here") } + }); + + var stream = filesystem.File.Open(filepath, FileMode.Truncate); + var file = filesystem.GetFile(filepath); + + await That(stream.Position).IsEqualTo(0); + await That(stream.Length).IsEqualTo(0); + await That(file.Contents.Length).IsEqualTo(0); + } + + [Test] + public async Task MockFile_Open_OpensExistingFileOnOpen() + { + string filepath = XFS.Path(@"c:\something\does\exist.txt"); + var filesystem = new MockFileSystem(new Dictionary + { + { filepath, new MockFileData("I'm here") } + }); + + var stream = filesystem.File.Open(filepath, FileMode.Open); + var file = filesystem.GetFile(filepath); + + await That(stream.Position).IsEqualTo(0); + await That(stream.Length).IsEqualTo(file.Contents.Length); + + byte[] data; + using (var br = new BinaryReader(stream)) + data = br.ReadBytes((int)stream.Length); + + await That(data).IsEqualTo(file.Contents); + } + + [Test] + public async Task MockFile_Open_OpensExistingFileOnOpenOrCreate() + { + string filepath = XFS.Path(@"c:\something\does\exist.txt"); + var filesystem = new MockFileSystem(new Dictionary + { + { filepath, new MockFileData("I'm here") } + }); + + var stream = filesystem.File.Open(filepath, FileMode.OpenOrCreate); + var file = filesystem.GetFile(filepath); + + await That(stream.Position).IsEqualTo(0); + await That(stream.Length).IsEqualTo(file.Contents.Length); + + byte[] data; + using (var br = new BinaryReader(stream)) + data = br.ReadBytes((int)stream.Length); + + await That(data).IsEqualTo(file.Contents); + } + + [Test] + public async Task MockFile_Open_CreatesNewFileOnOpenOrCreate() + { + string filepath = XFS.Path(@"c:\something\doesnt\exist.txt"); + var filesystem = new MockFileSystem(new Dictionary()); + filesystem.AddDirectory(XFS.Path(@"c:\something\doesnt")); + + var stream = filesystem.File.Open(filepath, FileMode.OpenOrCreate); + + await That(filesystem.File.Exists(filepath)).IsTrue(); + await That(stream.Position).IsEqualTo(0); + await That(stream.Length).IsEqualTo(0); + } + + [Test] + public async Task MockFile_Open_OverwritesExistingFileOnCreate() + { + string filepath = XFS.Path(@"c:\something\doesnt\exist.txt"); + var filesystem = new MockFileSystem(new Dictionary + { + { filepath, new MockFileData("I'm here") } + }); + + var stream = filesystem.File.Open(filepath, FileMode.Create); + var file = filesystem.GetFile(filepath); + + await That(stream.Position).IsEqualTo(0); + await That(stream.Length).IsEqualTo(0); + await That(file.Contents.Length).IsEqualTo(0); + } + + [Test] + public async Task MockFile_OpenText_ShouldRetainLastWriteTime() + { + // Arrange + var fs = new MockFileSystem(); + string filepath = XFS.Path(@"C:\TestData\test.txt"); + var file = new MockFileData(@"I'm here"); + var lastWriteTime = new DateTime(2012, 03, 21); + file.LastWriteTime = lastWriteTime; + fs.AddFile(filepath, file); + + // Act + using (var reader = fs.File.OpenText(filepath)) + { + reader.ReadLine(); + } + + // Assert + await That(fs.FileInfo.New(filepath).LastWriteTime).IsEqualTo(lastWriteTime); + } + + [Test] + public async Task MockFile_OpenText_ShouldUpdateLastAccessTime() + { + // Arrange + var fs = new MockFileSystem(); + string filepath = XFS.Path(@"C:\TestData\test.txt"); + var file = new MockFileData(@"I'm here"); + var lastAccessTime = new DateTime(2012, 03, 21); + file.LastAccessTime = lastAccessTime; + fs.AddFile(filepath, file); + + // Act + using (var reader = fs.File.OpenText(filepath)) + { + reader.ReadLine(); + } + + // Assert + await That(DateTime.Now - fs.FileInfo.New(filepath).LastAccessTime).IsLessThanOrEqualTo(TimeSpan.FromSeconds(1)); + } + + [Test] + public async Task MockFile_Read_ShouldRetainCreationTimeAndUpdateLastAccessTime() + { + // Arrange + var fs = new MockFileSystem(); + var filepath = XFS.Path(@"C:\TestData\test.txt"); + var file = new MockFileData(new byte[] { 1, 2, 3 }); + var lastAccessTime = new DateTime(2012, 03, 21); + file.LastAccessTime = lastAccessTime; + var creationTime = new DateTime(2012, 03, 20); + file.CreationTime = creationTime; + fs.AddFile(filepath, file); + + var fi = fs.FileInfo.New(filepath); + var stream = fi.OpenRead(); + var buffer = new byte[16]; +#pragma warning disable CA2022 + stream.Read(buffer, 0, buffer.Length); +#pragma warning restore CA2022 + fi.Refresh(); + // Assert + await That(fi.CreationTime).IsEqualTo(creationTime); + await That(DateTime.Now - fi.LastAccessTime).IsLessThanOrEqualTo(TimeSpan.FromSeconds(1)); + } + + [Test] + public async Task MockFile_ReadAsync_ShouldRetainCreationTimeAndUpdateLastAccessTime() + { + // Arrange + var fs = new MockFileSystem(); + var filepath = XFS.Path(@"C:\TestData\test.txt"); + var file = new MockFileData(new byte[] { 1, 2, 3 }); + var lastAccessTime = new DateTime(2012, 03, 21); + file.LastAccessTime = lastAccessTime; + var creationTime = new DateTime(2012, 03, 20); + file.CreationTime = creationTime; + fs.AddFile(filepath, file); + + var fi = fs.FileInfo.New(filepath); + var stream = fi.OpenRead(); + var buffer = new byte[16]; +#pragma warning disable CA1835 +#pragma warning disable CA2022 + // ReSharper disable once MustUseReturnValue + await stream.ReadAsync(buffer, 0, buffer.Length); +#pragma warning restore CA2022 +#pragma warning restore CA1835 + fi.Refresh(); + // Assert + await That(fi.CreationTime).IsEqualTo(creationTime); + await That(DateTime.Now - fi.LastAccessTime).IsLessThanOrEqualTo(TimeSpan.FromSeconds(1)); + } + + [Test] + public async Task MockFile_Write_ShouldRetainCreationTimeAndUpdateLastAccessTimeAndLastWriteTime() + { + // Arrange + var fs = new MockFileSystem(); + var filepath = XFS.Path(@"C:\TestData\test.txt"); + var file = new MockFileData(new byte[] { 1, 2, 3 }); + var lastAccessTime = new DateTime(2012, 03, 21); + file.LastAccessTime = lastAccessTime; + var creationTime = new DateTime(2012, 03, 20); + file.CreationTime = creationTime; + fs.AddFile(filepath, file); + + var fi = fs.FileInfo.New(filepath); + var stream = fi.OpenWrite(); + var buffer = new byte[16]; + stream.Write(buffer, 0, buffer.Length); + fi.Refresh(); + // Assert + await That(fi.CreationTime).IsEqualTo(creationTime); + await That(DateTime.Now - fi.LastAccessTime).IsLessThanOrEqualTo(TimeSpan.FromSeconds(1)); + await That(DateTime.Now - fi.LastWriteTime).IsLessThanOrEqualTo(TimeSpan.FromSeconds(1)); + } + + [Test] + public async Task MockFile_WriteAsync_ShouldRetainCreationTimeAndUpdateLastAccessTimeAndLastWriteTime() + { + // Arrange + var fs = new MockFileSystem(); + var filepath = XFS.Path(@"C:\TestData\test.txt"); + var file = new MockFileData(new byte[] { 1, 2, 3 }); + var lastAccessTime = new DateTime(2012, 03, 21); + file.LastAccessTime = lastAccessTime; + var creationTime = new DateTime(2012, 03, 20); + file.CreationTime = creationTime; + fs.AddFile(filepath, file); + + var fi = fs.FileInfo.New(filepath); + var stream = fi.OpenWrite(); + var buffer = new byte[16]; + await stream.WriteAsync(buffer, 0, buffer.Length); + fi.Refresh(); + // Assert + await That(fi.CreationTime).IsEqualTo(creationTime); + await That(DateTime.Now - fi.LastAccessTime).IsLessThanOrEqualTo(TimeSpan.FromSeconds(1)); + await That(DateTime.Now - fi.LastWriteTime).IsLessThanOrEqualTo(TimeSpan.FromSeconds(1)); + } + + [Test] + public async Task MockFile_OpenText_ShouldRetainCreationTime() + { + // Arrange + var fs = new MockFileSystem(); + string filepath = XFS.Path(@"C:\TestData\test.txt"); + var file = new MockFileData(@"I'm here"); + var creationTime = new DateTime(2012, 03, 21); + file.CreationTime = creationTime; + fs.AddFile(filepath, file); + + // Act + using (var reader = fs.File.OpenText(filepath)) + { + reader.ReadLine(); + } + + // Assert + await That(fs.FileInfo.New(filepath).CreationTime).IsEqualTo(creationTime); + } + + [Test] + public async Task MockFile_Open_ShouldThrowDirectoryNotFoundExceptionIfFileModeCreateAndParentPathDoesNotExist() + { + // Arrange + var fileSystem = new MockFileSystem(); + var file = XFS.Path("C:\\path\\NotFound.ext"); + + // Act + Action action = () => fileSystem.File.Open(file, FileMode.Create); + + // Assert + var exception = await That(action).Throws(); + await That(exception.Message).StartsWith("Could not find a part of the path"); + } + + [Test] + public async Task MockFile_OpenWrite_ShouldWorkWithRelativePath() + { + var file = "file.txt"; + var fileSystem = new MockFileSystem(); + + fileSystem.File.OpenWrite(file).Close(); + + await That(fileSystem.File.Exists(file)).IsTrue(); + } +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileReadAllBytesTests.cs b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileReadAllBytesTests.cs new file mode 100644 index 000000000..f0df4969a --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileReadAllBytesTests.cs @@ -0,0 +1,152 @@ +using System.Collections.Generic; +using NUnit.Framework; +using XFS = System.IO.Abstractions.TestingHelpers.MockUnixSupport; +using System.Threading.Tasks; +using System.Threading; + +namespace System.IO.Abstractions.TestingHelpers.Tests; + +public class MockFileReadAllBytesTests +{ + [Test] + public async Task MockFile_ReadAllBytes_ShouldReturnOriginalByteData() + { + var fileSystem = new MockFileSystem(new Dictionary + { + { XFS.Path(@"c:\something\demo.txt"), new MockFileData("Demo text content") }, + { XFS.Path(@"c:\something\other.gif"), new MockFileData(new byte[] { 0x21, 0x58, 0x3f, 0xa9 }) } + }); + + var file = new MockFile(fileSystem); + + var result = file.ReadAllBytes(XFS.Path(@"c:\something\other.gif")); + + await That(result) + .IsEqualTo(new byte[] { 0x21, 0x58, 0x3f, 0xa9 }); + } + + [Test] + public async Task MockFile_ReadAllBytes_ShouldReturnDataSavedByWriteAllBytes() + { + string path = XFS.Path(@"c:\something\demo.txt"); + var fileSystem = new MockFileSystem(); + var fileContent = new byte[] { 1, 2, 3, 4 }; + fileSystem.AddDirectory(XFS.Path(@"c:\something")); + + fileSystem.File.WriteAllBytes(path, fileContent); + + await That(fileSystem.File.ReadAllBytes(path)).IsEqualTo(fileContent); + } + + [Test] + public async Task MockFile_ReadAllBytes_ShouldThrowFileNotFoundExceptionIfFileDoesNotExist() + { + var fileSystem = new MockFileSystem(); + var file = new MockFile(fileSystem); + + Action action = () => file.ReadAllBytes(@"C:\a.txt"); + + await That(action).Throws(); + } + + [Test] + public async Task MockFile_ReadAllBytes_ShouldTolerateAltDirectorySeparatorInPath() + { + var fileSystem = new MockFileSystem(); + var path = XFS.Path("C:" + fileSystem.Path.DirectorySeparatorChar + "test.dat"); + var altPath = XFS.Path("C:" + fileSystem.Path.AltDirectorySeparatorChar + "test.dat"); + var data = new byte[] { 0x12, 0x34, 0x56, 0x78 }; + + fileSystem.AddFile(path, new MockFileData(data)); + + await That(fileSystem.File.ReadAllBytes(altPath)).IsEqualTo(data); + } + + [Test] + public async Task MockFile_ReadAllBytes_ShouldReturnANewCopyOfTheFileContents() + { + var path = XFS.Path(@"c:\something\demo.bin"); + var fileSystem = new MockFileSystem(new Dictionary + { + { path, new MockFileData(new byte[] { 1, 2, 3, 4 }) } + }); + + var firstRead = fileSystem.File.ReadAllBytes(path); + + var secondRead = fileSystem.File.ReadAllBytes(path); + + for (int i = 0; i < firstRead.Length; i++) + { + firstRead[i] += 1; + } + + await That(firstRead).IsNotEqualTo(secondRead); + } + +#if FEATURE_ASYNC_FILE + [Test] + public async Task MockFile_ReadAllBytesAsync_ShouldReturnOriginalByteData() + { + var fileSystem = new MockFileSystem(new Dictionary + { + { XFS.Path(@"c:\something\demo.txt"), new MockFileData("Demo text content") }, + { XFS.Path(@"c:\something\other.gif"), new MockFileData(new byte[] { 0x21, 0x58, 0x3f, 0xa9 }) } + }); + + var file = new MockFile(fileSystem); + + var result = await file.ReadAllBytesAsync(XFS.Path(@"c:\something\other.gif")); + + await That(result) + .IsEqualTo(new byte[] { 0x21, 0x58, 0x3f, 0xa9 }); + } + + [Test] + public async Task MockFile_ReadAllBytesAsync_ShouldReturnDataSavedByWriteAllBytes() + { + string path = XFS.Path(@"c:\something\demo.txt"); + var fileSystem = new MockFileSystem(); + var fileContent = new byte[] { 1, 2, 3, 4 }; + fileSystem.AddDirectory(XFS.Path(@"c:\something")); + + fileSystem.File.WriteAllBytes(path, fileContent); + + await That(await fileSystem.File.ReadAllBytesAsync(path)).IsEqualTo(fileContent); + } + + [Test] + public async Task MockFile_ReadAllBytesAsync_ShouldThrowFileNotFoundExceptionIfFileDoesNotExist() + { + var fileSystem = new MockFileSystem(); + var file = new MockFile(fileSystem); + + Func action = async () => await file.ReadAllBytesAsync(@"C:\a.txt"); + + await That(action).Throws(); + } + + [Test] + public async Task MockFile_ReadAllBytesAsync_ShouldThrowOperationCanceledExceptionIfCanceled() + { + var fileSystem = new MockFileSystem(); + + Func action = async () => + await fileSystem.File.ReadAllBytesAsync(@"C:\a.txt", new CancellationToken(canceled: true)); + + await That(action).Throws(); + } + + [Test] + public async Task MockFile_ReadAllBytesAsync_ShouldTolerateAltDirectorySeparatorInPath() + { + var fileSystem = new MockFileSystem(); + var path = XFS.Path("C:" + fileSystem.Path.DirectorySeparatorChar + "test.dat"); + var altPath = XFS.Path("C:" + fileSystem.Path.AltDirectorySeparatorChar + "test.dat"); + var data = new byte[] { 0x12, 0x34, 0x56, 0x78 }; + + fileSystem.AddFile(path, new MockFileData(data)); + + await That(await fileSystem.File.ReadAllBytesAsync(altPath)).IsEqualTo(data); + } +#endif +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileReadAllLinesTests.cs b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileReadAllLinesTests.cs new file mode 100644 index 000000000..3c6e1b294 --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileReadAllLinesTests.cs @@ -0,0 +1,232 @@ +namespace System.IO.Abstractions.TestingHelpers.Tests; + +using Collections.Generic; +using Collections.Specialized; +using Threading; +using Threading.Tasks; + +using NUnit.Framework; + +using Text; + +using XFS = MockUnixSupport; + +public class MockFileReadAllLinesTests +{ + [Test] + public async Task MockFile_ReadAllLines_ShouldReturnOriginalTextData() + { + // Arrange + var fileSystem = new MockFileSystem(new Dictionary + { + { XFS.Path(@"c:\something\demo.txt"), new MockFileData("Demo\r\ntext\ncontent\rvalue") }, + { XFS.Path(@"c:\something\other.gif"), new MockFileData(new byte[] { 0x21, 0x58, 0x3f, 0xa9 }) } + }); + + var file = new MockFile(fileSystem); + + // Act + var result = file.ReadAllLines(XFS.Path(@"c:\something\demo.txt")); + + // Assert + await That(result) + .IsEqualTo(new[] { "Demo", "text", "content", "value" }); + } + + [Test] + public async Task MockFile_ReadAllLines_ShouldReturnOriginalDataWithCustomEncoding() + { + // Arrange + string text = "Hello\r\nthere\rBob\nBob!"; + var encodedText = Encoding.BigEndianUnicode.GetBytes(text); + var fileSystem = new MockFileSystem(new Dictionary + { + { XFS.Path(@"c:\something\demo.txt"), new MockFileData(encodedText) } + }); + + var file = new MockFile(fileSystem); + + // Act + var result = file.ReadAllLines(XFS.Path(@"c:\something\demo.txt"), Encoding.BigEndianUnicode); + + // Assert + await That(result) + .IsEqualTo(new[] { "Hello", "there", "Bob", "Bob!" }); + } + + [Test] + public async Task MockFile_ReadAllLines_NotExistingFile_ThrowsCorrectFileNotFoundException() + { + var absentFileNameFullPath = XFS.Path(@"c:\you surely don't have such file.hope-so"); + var mockFileSystem = new MockFileSystem(); + + var act = new Action(() => + mockFileSystem.File.ReadAllLines(absentFileNameFullPath) + ); + + var exception = await That(act).Throws(); + await That(exception.FileName).IsEqualTo(absentFileNameFullPath); + await That(exception.Message).IsEqualTo("Could not find file '" + absentFileNameFullPath + "'."); + } + + [Test] + public async Task MockFile_ReadAllLines_ShouldNotReturnBom() + { + // Arrange + var testFilePath = XFS.Path(@"c:\a test file.txt"); + const string testText = "Hello World"; + var fileSystem = new MockFileSystem(); + fileSystem.File.WriteAllLines(testFilePath, new[] { testText }, Encoding.UTF8); + + // Act + var result = fileSystem.File.ReadAllLines(testFilePath, Encoding.UTF8); + + // Assert + await That(result.Length).IsEqualTo(1); + await That(result[0]).IsEqualTo(testText); + } +#if FEATURE_ASYNC_FILE + [Test] + public async Task MockFile_ReadAllLinesAsync_ShouldReturnOriginalTextData() + { + // Arrange + var fileSystem = new MockFileSystem(new Dictionary + { + { XFS.Path(@"c:\something\demo.txt"), new MockFileData("Demo\r\ntext\ncontent\rvalue") }, + { XFS.Path(@"c:\something\other.gif"), new MockFileData(new byte[] { 0x21, 0x58, 0x3f, 0xa9 }) } + }); + + var file = new MockFile(fileSystem); + + // Act + var result = await file.ReadAllLinesAsync(XFS.Path(@"c:\something\demo.txt")); + + // Assert + await That(result).IsEqualTo(new[] { "Demo", "text", "content", "value" }); + } + + [Test] + public async Task MockFile_ReadAllLinesAsync_ShouldReturnOriginalDataWithCustomEncoding() + { + // Arrange + string text = "Hello\r\nthere\rBob\nBob!"; + var encodedText = Encoding.BigEndianUnicode.GetBytes(text); + var fileSystem = new MockFileSystem(new Dictionary + { + { XFS.Path(@"c:\something\demo.txt"), new MockFileData(encodedText) } + }); + + var file = new MockFile(fileSystem); + + // Act + var result = await file.ReadAllLinesAsync(XFS.Path(@"c:\something\demo.txt"), Encoding.BigEndianUnicode); + + // Assert + await That(result).IsEqualTo(new[] { "Hello", "there", "Bob", "Bob!" }); + } + + [Test] + public async Task MockFile_ReadAllLinesAsync_ShouldThrowOperationCanceledExceptionIfCanceled() + { + var fileSystem = new MockFileSystem(); + + Func action = async () => + await fileSystem.File.ReadAllLinesAsync(@"C:\a.txt", new CancellationToken(canceled: true)); + + await That(action).Throws(); + } + + [Test] + public async Task MockFile_ReadAllLinesAsync_NotExistingFile_ThrowsCorrectFileNotFoundException() + { + var absentFileNameFullPath = XFS.Path(@"c:\you surely don't have such file.hope-so"); + var mockFileSystem = new MockFileSystem(); + + var act = new Func(async () => + await mockFileSystem.File.ReadAllLinesAsync(absentFileNameFullPath) + ); + + var exception = await That(act).Throws(); + await That(exception.FileName).IsEqualTo(absentFileNameFullPath); + await That(exception.Message).IsEqualTo("Could not find file '" + absentFileNameFullPath + "'."); + } + +#if FEATURE_READ_LINES_ASYNC + [Test] + public async Task MockFile_ReadLinesAsync_ShouldReturnOriginalTextData() + { + // Arrange + var fileSystem = new MockFileSystem(new Dictionary + { + { XFS.Path(@"c:\something\demo.txt"), new MockFileData("Demo\r\ntext\ncontent\rvalue") }, + { XFS.Path(@"c:\something\other.gif"), new MockFileData(new byte[] { 0x21, 0x58, 0x3f, 0xa9 }) } + }); + + var file = new MockFile(fileSystem); + + // Act + var enumerable = file.ReadLinesAsync(XFS.Path(@"c:\something\demo.txt")); + List result = new(); + await foreach (var line in enumerable) + result.Add(line); + + // Assert + await That(result).IsEqualTo(new[] { "Demo", "text", "content", "value" }); + } + + [Test] + public async Task MockFile_ReadLinesAsync_ShouldReturnOriginalDataWithCustomEncoding() + { + // Arrange + string text = "Hello\r\nthere\rBob\nBob!"; + var encodedText = Encoding.BigEndianUnicode.GetBytes(text); + var fileSystem = new MockFileSystem(new Dictionary + { + { XFS.Path(@"c:\something\demo.txt"), new MockFileData(encodedText) } + }); + + var file = new MockFile(fileSystem); + + // Act + var enumerable = file.ReadLinesAsync(XFS.Path(@"c:\something\demo.txt"), Encoding.BigEndianUnicode); + List result = new(); + await foreach (var line in enumerable) + result.Add(line); + + // Assert + await That(result).IsEqualTo(new[] { "Hello", "there", "Bob", "Bob!" }); + } + + [Test] + public async Task MockFile_ReadLinesAsync_ShouldThrowOperationCanceledExceptionIfCanceled() + { + var fileSystem = new MockFileSystem(); + + Func action = async () => + { + var enumerable = fileSystem.File.ReadLinesAsync(@"C:\a.txt", new CancellationToken(canceled: true)); + await foreach (var line in enumerable); + }; + + await That(action).Throws(); + } + + [Test] + public async Task MockFile_ReadLinesAsync_NotExistingFile_ThrowsCorrectFileNotFoundException() + { + var absentFileNameFullPath = XFS.Path(@"c:\you surely don't have such file.hope-so"); + var mockFileSystem = new MockFileSystem(); + + Func action = async () => + { + var enumerable = mockFileSystem.File.ReadLinesAsync(absentFileNameFullPath); + await foreach (var line in enumerable) ; + }; + + var exception = await That(action).Throws(); + await That(exception.FileName).IsEqualTo(absentFileNameFullPath); + await That(exception.Message).IsEqualTo("Could not find file '" + absentFileNameFullPath + "'."); + } +#endif +#endif +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileReadLinesTests.cs b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileReadLinesTests.cs new file mode 100644 index 000000000..7f477b2a2 --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileReadLinesTests.cs @@ -0,0 +1,51 @@ +namespace System.IO.Abstractions.TestingHelpers.Tests; + +using Collections.Generic; + +using NUnit.Framework; + +using Text; + +using XFS = MockUnixSupport; + +public class MockFileReadLinesTests +{ + [Test] + public async Task MockFile_ReadLines_ShouldReturnOriginalTextData() + { + // Arrange + var fileSystem = new MockFileSystem(new Dictionary + { + { XFS.Path(@"c:\something\demo.txt"), new MockFileData("Demo\r\ntext\ncontent\rvalue") }, + { XFS.Path(@"c:\something\other.gif"), new MockFileData(new byte[] { 0x21, 0x58, 0x3f, 0xa9 }) } + }); + + var file = new MockFile(fileSystem); + + // Act + var result = file.ReadLines(XFS.Path(@"c:\something\demo.txt")); + + // Assert + await That(result).IsEqualTo(new[] { "Demo", "text", "content", "value" }); + } + + [Test] + public async Task MockFile_ReadLines_ShouldReturnOriginalDataWithCustomEncoding() + { + // Arrange + string text = "Hello\r\nthere\rBob\nBob!"; + var encodedText = Encoding.BigEndianUnicode.GetBytes(text); + var fileSystem = new MockFileSystem(new Dictionary + { + { XFS.Path(@"c:\something\demo.txt"), new MockFileData(encodedText) } + }); + + var file = new MockFile(fileSystem); + + // Act + var result = file.ReadLines(XFS.Path(@"c:\something\demo.txt"), Encoding.BigEndianUnicode); + + // Assert + await That(result).IsEqualTo(new[] { "Hello", "there", "Bob", "Bob!" }); + } +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileSetAccessControlTests.cs b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileSetAccessControlTests.cs new file mode 100644 index 000000000..d1e8523bd --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileSetAccessControlTests.cs @@ -0,0 +1,67 @@ +using NUnit.Framework; +using System.Collections.Generic; +using System.Runtime.Versioning; +using System.Security.AccessControl; +using XFS = System.IO.Abstractions.TestingHelpers.MockUnixSupport; + +namespace System.IO.Abstractions.TestingHelpers.Tests; + +[TestFixture] +[WindowsOnly(WindowsSpecifics.AccessControlLists)] +[SupportedOSPlatform("windows")] +public class MockFileSetAccessControlTests +{ + [TestCase(" ")] + [TestCase(" ")] + public async Task MockFile_SetAccessControl_ShouldThrowArgumentExceptionIfPathContainsOnlyWhitespaces(string path) + { + // Arrange + var fileSystem = new MockFileSystem(); + var fileSecurity = new FileSecurity(); + + // Act + Action action = () => fileSystem.File.SetAccessControl(path, fileSecurity); + + // Assert + var exception = await That(action).Throws(); + await That(exception.ParamName).IsEqualTo("path"); + } + + [Test] + public async Task MockFile_SetAccessControl_ShouldThrowFileNotFoundExceptionIfFileDoesNotExistInMockData() + { + // Arrange + var fileSystem = new MockFileSystem(); + var expectedFileName = XFS.Path(@"c:\a.txt"); + var fileSecurity = new FileSecurity(); + + // Act + Action action = () => fileSystem.File.SetAccessControl(expectedFileName, fileSecurity); + + // Assert + var exception = await That(action).Throws(); + await That(exception.FileName).IsEqualTo(expectedFileName); + } + + [Test] + public async Task MockFile_SetAccessControl_ShouldSetAccessControlOfFileData() + { + // Arrange + var filePath = XFS.Path(@"c:\a.txt"); + var fileData = new MockFileData("Test content"); + + var fileSystem = new MockFileSystem(new Dictionary() + { + { filePath, fileData } + }); + + // Act + var expectedAccessControl = new FileSecurity(); + expectedAccessControl.SetAccessRuleProtection(false, false); + fileSystem.File.SetAccessControl(filePath, expectedAccessControl); + + // Assert + var accessControl = fileSystem.File.GetAccessControl(filePath); + await That(accessControl).IsEqualTo(expectedAccessControl); + } +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileSetAttributesTests.cs b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileSetAttributesTests.cs new file mode 100644 index 000000000..ef597c6d5 --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileSetAttributesTests.cs @@ -0,0 +1,65 @@ +using System.Collections.Generic; +using NUnit.Framework; +using XFS = System.IO.Abstractions.TestingHelpers.MockUnixSupport; + +namespace System.IO.Abstractions.TestingHelpers.Tests; + +[TestFixture] +public class MockFileSetAttributesTests +{ + [Test] + public async Task MockFile_SetAttributes_ShouldSetAttributesOnFile() + { + var path = XFS.Path(@"c:\something\demo.txt"); + var filedata = new MockFileData("test"); + var fileSystem = new MockFileSystem(new Dictionary + { + {path, filedata}, + }); + + fileSystem.File.SetAttributes(path, FileAttributes.Hidden); + + var attributes = fileSystem.File.GetAttributes(path); + await That(attributes).IsEqualTo(FileAttributes.Hidden); + } + + [Test] + public async Task MockFile_SetAttributes_ShouldSetAttributesOnDirectory() + { + var fileSystem = new MockFileSystem(); + var path = XFS.Path(@"c:\something"); + fileSystem.AddDirectory(path); + var directoryInfo = fileSystem.DirectoryInfo.New(path); + directoryInfo.Attributes = FileAttributes.Directory | FileAttributes.Normal; + + fileSystem.File.SetAttributes(path, FileAttributes.Directory | FileAttributes.Hidden); + + var attributes = fileSystem.File.GetAttributes(path); + await That(attributes).IsEqualTo(FileAttributes.Directory | FileAttributes.Hidden); + } + + [Test] + [TestCase("", FileAttributes.Normal)] + [TestCase(" ", FileAttributes.Normal)] + public async Task MockFile_SetAttributes_ShouldThrowArgumentExceptionIfPathContainsOnlyWhitespaces(string path, FileAttributes attributes) + { + var fileSystem = new MockFileSystem(); + + Action action = () => fileSystem.File.SetAttributes(path, attributes); + + await That(action).Throws(); + } + + [Test] + public async Task MockFile_SetAttributes_ShouldThrowFileNotFoundExceptionIfMissingDirectory() + { + var path = XFS.Path(@"C:\something"); + var attributes = FileAttributes.Normal; + var fileSystem = new MockFileSystem(); + + Action action = () => fileSystem.File.SetAttributes(path, attributes); + + var exception = await That(action).Throws(); + await That(exception.FileName).IsEqualTo(path); + } +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileSetUnixFileModeTests.cs b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileSetUnixFileModeTests.cs new file mode 100644 index 000000000..4a152723d --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileSetUnixFileModeTests.cs @@ -0,0 +1,53 @@ +#if FEATURE_UNIX_FILE_MODE +using System.Runtime.Versioning; + +namespace System.IO.Abstractions.TestingHelpers.Tests +{ + using Collections.Generic; + + using NUnit.Framework; + + using XFS = MockUnixSupport; + + [UnsupportedOSPlatform("windows")] + [UnixOnly("This feature is not supported on Windows.")] + public class MockFileSetUnixFileModeTests + { + [Test] + public async Task MockFile_SetUnixFileMode_ShouldSetSpecifiedAccessMode([Values] UnixFileMode unixFileMode) + { + // Arrange + var mockFileData = new MockFileData("Demo text content"); + var fileSystem = new MockFileSystem(new Dictionary + { + { XFS.Path(@"C:\something\some.txt"), mockFileData } + }); + + // Act + fileSystem.File.SetUnixFileMode(XFS.Path(@"C:\something\some.txt"), unixFileMode); + + // Assert + await That(mockFileData.UnixMode).IsEqualTo(unixFileMode); + } + + [TestCase(UnixFileMode.UserRead | UnixFileMode.GroupRead | UnixFileMode.OtherRead)] + [TestCase(UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute)] + [TestCase(UnixFileMode.UserExecute | UnixFileMode.OtherWrite | UnixFileMode.GroupRead)] + public async Task MockFile_SetUnixFileMode_ShouldSetSpecifiedAccessModeFlags(UnixFileMode unixFileMode) + { + // Arrange + var mockFileData = new MockFileData("Demo text content"); + var fileSystem = new MockFileSystem(new Dictionary + { + { XFS.Path(@"C:\something\some.txt"), mockFileData } + }); + + // Act + fileSystem.File.SetUnixFileMode(XFS.Path(@"C:\something\some.txt"), unixFileMode); + + // Assert + await That(mockFileData.UnixMode).IsEqualTo(unixFileMode); + } + } +} +#endif \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileStreamFactoryTests.cs b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileStreamFactoryTests.cs new file mode 100644 index 000000000..316c61526 --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileStreamFactoryTests.cs @@ -0,0 +1,177 @@ +using System.Collections.Generic; +using NUnit.Framework; +using System.Text; + +namespace System.IO.Abstractions.TestingHelpers.Tests; + +using XFS = MockUnixSupport; + +[TestFixture] +public class MockFileStreamFactoryTests +{ + [Test] + [TestCase(FileMode.Create)] + [TestCase(FileMode.Append)] + public async Task MockFileStreamFactory_CreateForExistingFile_ShouldReturnStream(FileMode fileMode) + { + // Arrange + var fileSystem = new MockFileSystem(new Dictionary + { + { @"c:\existing.txt", string.Empty } + }); + + var fileStreamFactory = new MockFileStreamFactory(fileSystem); + + // Act + var result = fileStreamFactory.New(@"c:\existing.txt", fileMode, FileAccess.Write); + + // Assert + await That(result).IsNotNull(); + } + + [Test] + [TestCase(FileMode.Create)] + [TestCase(FileMode.Append)] + public async Task MockFileStreamFactory_CreateForNonExistingFile_ShouldReturnStream(FileMode fileMode) + { + // Arrange + var fileSystem = new MockFileSystem(); + var fileStreamFactory = new MockFileStreamFactory(fileSystem); + + // Act + var result = fileStreamFactory.New(XFS.Path(@"c:\not_existing.txt"), fileMode, FileAccess.Write); + + // Assert + await That(result).IsNotNull(); + } + + [Test] + [TestCase(FileMode.Create)] + public async Task MockFileStreamFactory_CreateForAnExistingFile_ShouldReplaceFileContents(FileMode fileMode) + { + var fileSystem = new MockFileSystem(); + string FilePath = XFS.Path("C:\\File.txt"); + + using (var stream = fileSystem.FileStream.New(FilePath, fileMode, System.IO.FileAccess.Write)) + { + var data = Encoding.UTF8.GetBytes("1234567890"); + stream.Write(data, 0, data.Length); + } + + using (var stream = fileSystem.FileStream.New(FilePath, fileMode, System.IO.FileAccess.Write)) + { + var data = Encoding.UTF8.GetBytes("AAAAA"); + stream.Write(data, 0, data.Length); + } + + var text = fileSystem.File.ReadAllText(FilePath); + await That(text).IsEqualTo("AAAAA"); + } + + [Test] + [TestCase(FileMode.Create)] + [TestCase(FileMode.Open)] + [TestCase(FileMode.CreateNew)] + public async Task MockFileStreamFactory_CreateInNonExistingDirectory_ShouldThrowDirectoryNotFoundException(FileMode fileMode) + { + // Arrange + var fileSystem = new MockFileSystem(); + fileSystem.AddDirectory(XFS.Path(@"C:\Test")); + + // Act + var fileStreamFactory = new MockFileStreamFactory(fileSystem); + + // Assert + await That(() => fileStreamFactory.New(XFS.Path(@"C:\Test\NonExistingDirectory\some_random_file.txt"), fileMode)).Throws(); + } + + [Test] + public async Task MockFileStreamFactory_AppendAccessWithReadWriteMode_ShouldThrowArgumentException() + { + var fileSystem = new MockFileSystem(); + + await That(() => + { + fileSystem.FileStream.New(XFS.Path(@"c:\path.txt"), FileMode.Append, FileAccess.ReadWrite); + }).Throws(); + } + + [Test] + [TestCase(FileMode.Append)] + [TestCase(FileMode.Truncate)] + [TestCase(FileMode.Create)] + [TestCase(FileMode.CreateNew)] + [TestCase(FileMode.Append)] + public async Task MockFileStreamFactory_InvalidModeForReadAccess_ShouldThrowArgumentException(FileMode fileMode) + { + var fileSystem = new MockFileSystem(); + + await That(() => + { + fileSystem.FileStream.New(XFS.Path(@"c:\path.txt"), fileMode, FileAccess.Read); + }).Throws(); + } + + [Test] + [TestCase(FileMode.Open)] + [TestCase(FileMode.Truncate)] + public async Task MockFileStreamFactory_OpenNonExistingFile_ShouldThrowFileNotFoundException(FileMode fileMode) + { + // Arrange + var fileSystem = new MockFileSystem(); + fileSystem.AddDirectory(XFS.Path(@"C:\Test")); + + // Act + var fileStreamFactory = new MockFileStreamFactory(fileSystem); + + // Assert + await That(() => fileStreamFactory.New(XFS.Path(@"C:\Test\some_random_file.txt"), fileMode)).Throws(); + } + + [Test] + [TestCase(FileMode.CreateNew)] + public async Task MockFileStreamFactory_CreateExistingFile_Should_Throw_IOException(FileMode fileMode) + { + // Arrange + var fileSystem = new MockFileSystem(); + var path = XFS.Path(@"C:\Test\some_random_file.txt"); + fileSystem.AddFile(path, string.Empty); + + // Act + var fileStreamFactory = new MockFileStreamFactory(fileSystem); + + // Assert + await That(() => fileStreamFactory.New(path, fileMode)).Throws(); + + } + + [Test] + [TestCase(FileMode.Create)] + [TestCase(FileMode.CreateNew)] + [TestCase(FileMode.OpenOrCreate)] + public async Task MockFileStreamFactory_CreateWithRelativePath_CreatesFileInCurrentDirectory(FileMode fileMode) + { + // Arrange + var fileSystem = new MockFileSystem(); + + // Act + var fileStreamFactory = new MockFileStreamFactory(fileSystem); + fileStreamFactory.New("some_random_file.txt", fileMode); + + // Assert + await That(fileSystem.File.Exists(XFS.Path("./some_random_file.txt"))).IsTrue(); + } + + [Test] + public async Task MockFileStream_CanRead_ReturnsFalseForAWriteOnlyStream() + { + // Arrange + var fileSystem = new MockFileSystem(); + + // Act + var fileStream = fileSystem.FileStream.New("file.txt", FileMode.CreateNew, FileAccess.Write); + + // Assert + await That(fileStream.CanRead).IsFalse(); + } +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileStreamTests.cs b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileStreamTests.cs new file mode 100644 index 000000000..a8f815a15 --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileStreamTests.cs @@ -0,0 +1,432 @@ +namespace System.IO.Abstractions.TestingHelpers.Tests; + +using System.Collections.Generic; +using System.Threading.Tasks; + +using NUnit.Framework; + +using XFS = MockUnixSupport; + +[TestFixture] +public class MockFileStreamTests +{ + [Test] + public async Task MockFileStream_Flush_WritesByteToFile() + { + // Arrange + var filepath = XFS.Path(@"C:\something\foo.txt"); + var fileSystem = new MockFileSystem(new Dictionary()); + fileSystem.AddDirectory(XFS.Path(@"C:\something")); + + var cut = new MockFileStream(fileSystem, filepath, FileMode.Create); + + // Act + cut.WriteByte(255); + cut.Flush(); + + // Assert + await That(fileSystem.GetFile(filepath).Contents) + .IsEqualTo(new byte[] { 255 }); + } + + [Test] + public async Task MockFileStream_FlushAsync_WritesByteToFile() + { + // bug replication test for issue + // https://github.com/TestableIO/System.IO.Abstractions/issues/959 + + // Arrange + var filepath = XFS.Path(@"C:\something\foo.txt"); + var fileSystem = new MockFileSystem(new Dictionary()); + fileSystem.AddDirectory(XFS.Path(@"C:\something")); + + var cut = new MockFileStream(fileSystem, filepath, FileMode.Create); + + // Act + await cut.WriteAsync(new byte[] { 255 }, 0, 1); + await cut.FlushAsync(); + + // Assert + await That(fileSystem.GetFile(filepath).Contents) + .IsEqualTo(new byte[] { 255 }); + } + + [Test] + public async Task MockFileStream_Dispose_ShouldNotResurrectFile() + { + // path in this test case is a subject to Directory.GetParent(path) Linux issue + // https://github.com/TestableIO/System.IO.Abstractions/issues/395 + var fileSystem = new MockFileSystem(); + var path = XFS.Path("C:\\some_folder\\test"); + var directory = fileSystem.Path.GetDirectoryName(path); + fileSystem.AddFile(path, new MockFileData("Bla")); + var stream = fileSystem.File.Open(path, FileMode.Open, FileAccess.ReadWrite, FileShare.Delete); + + var fileCount1 = fileSystem.Directory.GetFiles(directory, "*").Length; + fileSystem.File.Delete(path); + var fileCount2 = fileSystem.Directory.GetFiles(directory, "*").Length; + stream.Dispose(); + var fileCount3 = fileSystem.Directory.GetFiles(directory, "*").Length; + + await That(fileCount1).IsEqualTo(1).Because("File should have existed"); + await That(fileCount2).IsEqualTo(0).Because("File should have been deleted"); + await That(fileCount3).IsEqualTo(0).Because("Disposing stream should not have resurrected the file"); + } + + [Test] + public async Task MockFileStream_Constructor_Reading_Nonexistent_File_Throws_Exception() + { + // Arrange + var nonexistentFilePath = XFS.Path(@"c:\something\foo.txt"); + var fileSystem = new MockFileSystem(new Dictionary()); + fileSystem.AddDirectory(XFS.Path(@"C:\something")); + + // Act + await That(() => new MockFileStream(fileSystem, nonexistentFilePath, FileMode.Open)).Throws(); + + // Assert - expect an exception + } + + [Test] + public async Task MockFileStream_Constructor_ReadTypeNotWritable() + { + // Arrange + var filePath = @"C:\test.txt"; + var fileSystem = new MockFileSystem(new Dictionary + { + { filePath, new MockFileData("hi") } + }); + + // Act + var stream = new MockFileStream(fileSystem, filePath, FileMode.Open, FileAccess.Read); + + await That(stream.CanWrite).IsFalse(); + await That(() => stream.WriteByte(1)).Throws(); + } + + [Test] + [TestCase(FileAccess.Write)] + [TestCase(FileAccess.ReadWrite)] + public async Task MockFileStream_Constructor_WriteAccessOnReadOnlyFile_Throws_Exception( + FileAccess fileAccess) + { + // Arrange + var filePath = @"C:\test.txt"; + var fileSystem = new MockFileSystem(new Dictionary + { + { filePath, new MockFileData("hi") { Attributes = FileAttributes.ReadOnly } } + }); + + // Act + await That(() => new MockFileStream(fileSystem, filePath, FileMode.Open, fileAccess)).Throws(); + } + + [Test] + public async Task MockFileStream_Constructor_ReadAccessOnReadOnlyFile_Does_Not_Throw_Exception() + { + // Arrange + var filePath = @"C:\test.txt"; + var fileSystem = new MockFileSystem(new Dictionary + { + { filePath, new MockFileData("hi") { Attributes = FileAttributes.ReadOnly } } + }); + + // Act + await That(() => new MockFileStream(fileSystem, filePath, FileMode.Open, FileAccess.Read)).DoesNotThrow(); + } + + + [Test] + public async Task MockFileStream_Constructor_WriteAccessOnNonReadOnlyFile_Does_Not_Throw_Exception() + { + // Arrange + var filePath = @"C:\test.txt"; + var fileSystem = new MockFileSystem(new Dictionary + { + { filePath, new MockFileData("hi") { Attributes = FileAttributes.Normal } } + }); + + // Act + await That(() => new MockFileStream(fileSystem, filePath, FileMode.Open, FileAccess.Write)).DoesNotThrow(); + } + + [Test] + [TestCase(FileShare.None, FileAccess.Read)] + [TestCase(FileShare.None, FileAccess.ReadWrite)] + [TestCase(FileShare.None, FileAccess.Write)] + [TestCase(FileShare.Read, FileAccess.Write)] + [TestCase(FileShare.Read, FileAccess.ReadWrite)] + [TestCase(FileShare.Write, FileAccess.Read)] + public async Task MockFileStream_Constructor_Insufficient_FileShare_Throws_Exception( + FileShare allowedFileShare, + FileAccess fileAccess) + { + var filePath = @"C:\locked.txt"; + var fileSystem = new MockFileSystem(new Dictionary + { + { filePath, new MockFileData("cannot access") { AllowedFileShare = allowedFileShare } } + }); + + await That(() => new MockFileStream(fileSystem, filePath, FileMode.Open, fileAccess)).Throws(); + } + + [Test] + [TestCase(FileShare.Read, FileAccess.Read)] + [TestCase(FileShare.Read | FileShare.Write, FileAccess.Read)] + [TestCase(FileShare.Read | FileShare.Write, FileAccess.ReadWrite)] + [TestCase(FileShare.ReadWrite, FileAccess.Read)] + [TestCase(FileShare.ReadWrite, FileAccess.ReadWrite)] + [TestCase(FileShare.ReadWrite, FileAccess.Write)] + public async Task MockFileStream_Constructor_Sufficient_FileShare_Does_Not_Throw_Exception( + FileShare allowedFileShare, + FileAccess fileAccess) + { + var filePath = @"C:\locked.txt"; + var fileSystem = new MockFileSystem(new Dictionary + { + { filePath, new MockFileData("cannot access") { AllowedFileShare = allowedFileShare } } + }); + + await That(() => new MockFileStream(fileSystem, filePath, FileMode.Open, fileAccess)).DoesNotThrow(); + } + + [Test] + public async Task MockFileStream_Close_MultipleCallsDoNotThrow() + { + var fileSystem = new MockFileSystem(); + var path = XFS.Path("C:\\test"); + fileSystem.AddFile(path, new MockFileData("Bla")); + var stream = fileSystem.File.OpenRead(path); + + // Act + stream.Close(); + + // Assert + await That(() => stream.Close()).DoesNotThrow(); + } + + [Test] + public async Task MockFileStream_Dispose_MultipleCallsDoNotThrow() + { + var fileSystem = new MockFileSystem(); + var path = XFS.Path("C:\\test"); + fileSystem.AddFile(path, new MockFileData("Bla")); + var stream = fileSystem.File.OpenRead(path); + + // Act + stream.Dispose(); + + // Assert + await That(() => stream.Dispose()).DoesNotThrow(); + } + + [Test] + public async Task MockFileStream_Dispose_OperationsAfterDisposeThrow() + { + var fileSystem = new MockFileSystem(); + var path = XFS.Path("C:\\test"); + fileSystem.AddFile(path, new MockFileData(new byte[0])); + var stream = fileSystem.FileInfo.New(path).OpenWrite(); + + // Act + stream.Dispose(); + + // Assert + await That(() => stream.WriteByte(0)).Throws(); + } + + [Test] + public async Task MockFileStream_Flush_ShouldNotChangePosition() + { + // Arrange + var fileSystem = new MockFileSystem(); + var path = XFS.Path("C:\\test"); + fileSystem.AddFile(path, new MockFileData(new byte[0])); + + using (var stream = fileSystem.FileInfo.New(path).OpenWrite()) + { + // Act + stream.Write(new byte[400], 0, 400); + stream.Seek(200, SeekOrigin.Begin); + stream.Flush(); + + // Assert + await That(stream.Position).IsEqualTo(200); + } + } + + [Test] + public async Task MockFileStream_FlushBool_ShouldNotChangePosition([Values] bool flushToDisk) + { + // Arrange + var fileSystem = new MockFileSystem(); + var path = XFS.Path("C:\\test"); + fileSystem.AddFile(path, new MockFileData(new byte[0])); + + using (var stream = fileSystem.FileInfo.New(path).OpenWrite()) + { + // Act + stream.Write(new byte[400], 0, 400); + stream.Seek(200, SeekOrigin.Begin); + stream.Flush(flushToDisk); + + // Assert + await That(stream.Position).IsEqualTo(200); + } + } + + [Test] + public async Task MockFileStream_Null_ShouldReturnSingletonObject() + { + var result1 = MockFileStream.Null; + var result2 = MockFileStream.Null; + + await That(result1).IsSameAs(result2); + } + +#if FEATURE_ASYNC_FILE + [Test] + public async Task MockFileStream_DisposeAsync_ShouldNotThrow() + { + var fileSystem = new MockFileSystem(); + fileSystem.File.WriteAllText("foo.txt", ""); + { + await using var reportStream = fileSystem.File.OpenRead("foo.txt"); + } + } +#endif + + [Test] + public async Task MockFileStream_Null_ShouldHaveExpectedProperties() + { + var result = MockFileStream.Null; + + await That(result.Name).IsEqualTo("."); + await That(result.Length).IsEqualTo(0); + await That(result.IsAsync).IsTrue(); + } + + [Test] + [TestCase(0)] + [TestCase(-1)] + public async Task MockFileStream_WhenBufferSizeIsNotPositive_ShouldThrowArgumentNullException(int bufferSize) + { + var fileSystem = new MockFileSystem(); + fileSystem.File.WriteAllText("foo.txt", ""); + fileSystem.File.WriteAllText("bar.txt", ""); + using var source = fileSystem.FileInfo.New(@"foo.txt").OpenRead(); + using var destination = fileSystem.FileInfo.New(@"bar.txt").OpenWrite(); + + async Task Act() => + await source.CopyToAsync(destination, bufferSize); + await That(Act).Throws(); + } + + [Test] + public async Task MockFileStream_WhenDestinationIsClosed_ShouldThrowObjectDisposedException() + { + var fileSystem = new MockFileSystem(); + fileSystem.File.WriteAllText("foo.txt", ""); + using var source = fileSystem.FileInfo.New(@"foo.txt").OpenRead(); + using var destination = new MemoryStream(); + destination.Close(); + + async Task Act() => + await source.CopyToAsync(destination); + await That(Act).Throws(); + } + + [Test] + public async Task MockFileStream_WhenDestinationIsNull_ShouldThrowArgumentNullException() + { + var fileSystem = new MockFileSystem(); + fileSystem.File.WriteAllText("foo.txt", ""); + using var source = fileSystem.FileInfo.New(@"foo.txt").OpenRead(); + + async Task Act() => + await source.CopyToAsync(null); + await That(Act).Throws(); + } + + [Test] + public async Task MockFileStream_WhenDestinationIsReadOnly_ShouldThrowNotSupportedException() + { + var fileSystem = new MockFileSystem(); + fileSystem.File.WriteAllText("foo.txt", ""); + fileSystem.File.WriteAllText("bar.txt", ""); + using var source = fileSystem.FileInfo.New(@"foo.txt").OpenRead(); + using var destination = fileSystem.FileInfo.New(@"bar.txt").OpenRead(); + + async Task Act() => + await source.CopyToAsync(destination); + await That(Act).Throws(); + } + + [Test] + public async Task MockFileStream_WhenSourceIsClosed_ShouldThrowObjectDisposedException() + { + var fileSystem = new MockFileSystem(); + fileSystem.File.WriteAllText("foo.txt", ""); + fileSystem.File.WriteAllText("bar.txt", ""); + using var source = fileSystem.FileInfo.New(@"foo.txt").OpenRead(); + using var destination = fileSystem.FileInfo.New(@"bar.txt").OpenWrite(); + source.Close(); + + async Task Act() => + await source.CopyToAsync(destination); + await That(Act).Throws(); + } + + [Test] + public async Task MockFileStream_WhenSourceIsWriteOnly_ShouldThrowNotSupportedException() + { + var fileSystem = new MockFileSystem(); + fileSystem.File.WriteAllText("foo.txt", ""); + fileSystem.File.WriteAllText("bar.txt", ""); + using var source = fileSystem.FileInfo.New(@"foo.txt").OpenWrite(); + using var destination = fileSystem.FileInfo.New(@"bar.txt").OpenWrite(); + + async Task Act() => + await source.CopyToAsync(destination); + await That(Act).Throws(); + } + + [Test] + [TestCase(FileShare.None, FileAccess.Read)] + [TestCase(FileShare.None, FileAccess.ReadWrite)] + [TestCase(FileShare.None, FileAccess.Write)] + [TestCase(FileShare.Read, FileAccess.Write)] + [TestCase(FileShare.Read, FileAccess.ReadWrite)] + [TestCase(FileShare.Write, FileAccess.Read)] + public async Task MockFileStream_ConflictingShareOrAccess_ShouldThrowUntilHandleReleased( + FileShare share, + FileAccess access) + { + var fileSystem = new MockFileSystem(); + fileSystem.File.WriteAllText("foo.txt", ""); + using (new MockFileStream(fileSystem, "foo.txt", FileMode.Open, FileAccess.Read, share)) + { + await That(() => new MockFileStream(fileSystem, "foo.txt", FileMode.Open, access)).Throws(); + } + await That(() => new MockFileStream(fileSystem, "foo.txt", FileMode.Open, access)).DoesNotThrow(); + } + + [Test] + [TestCase(FileShare.Read, FileAccess.Read)] + [TestCase(FileShare.Read | FileShare.Write, FileAccess.Read)] + [TestCase(FileShare.Read | FileShare.Write, FileAccess.ReadWrite)] + [TestCase(FileShare.ReadWrite, FileAccess.Read)] + [TestCase(FileShare.ReadWrite, FileAccess.ReadWrite)] + [TestCase(FileShare.ReadWrite, FileAccess.Write)] + public async Task MockFileStream_CompatibleShareOrAccess_ShouldNotThrow( + FileShare share, + FileAccess access) + { + var fileSystem = new MockFileSystem(); + fileSystem.File.WriteAllText("foo.txt", ""); + using (new MockFileStream(fileSystem, "foo.txt", FileMode.Open, FileAccess.Read, share)) + { + await That(() => new MockFileStream(fileSystem, "foo.txt", FileMode.Open, access)).DoesNotThrow(); + } + } +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileSymlinkTests.cs b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileSymlinkTests.cs new file mode 100644 index 000000000..0b92c94b0 --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileSymlinkTests.cs @@ -0,0 +1,324 @@ +using NUnit.Framework; + +namespace System.IO.Abstractions.TestingHelpers.Tests; + +using XFS = MockUnixSupport; + +[TestFixture] +public class MockFileSymlinkTests +{ + +#if FEATURE_CREATE_SYMBOLIC_LINK + + [Test] + public async Task MockFile_CreateSymbolicLink_ShouldReturnFileSystemInfo() + { + // Arrange + var fileSystem = new MockFileSystem(); + var pathToTarget = XFS.Path(@"C:\Folder\foo.txt"); + var path = XFS.Path(@"C:\bar.txt"); + var data = new MockFileData("foobar"); + fileSystem.AddFile(pathToTarget, data); + + // Act + IFileSystemInfo fileSystemInfo = fileSystem.File.CreateSymbolicLink(path, pathToTarget); + + // Assert + await That(fileSystemInfo.FullName).IsEqualTo(path); + await That(fileSystemInfo.LinkTarget).IsEqualTo(pathToTarget); + } + + [Test] + public async Task MockFile_CreateSymbolicLink_ShouldSucceedFromFileInfo() + { + // Arrange + var fileSystem = new MockFileSystem(); + var pathToTarget = XFS.Path(@"C:\Folder\foo.txt"); + var path = XFS.Path(@"C:\bar.txt"); + var data = new MockFileData("foobar"); + fileSystem.AddFile(pathToTarget, data); + + // Act + fileSystem.File.CreateSymbolicLink(path, pathToTarget); + IFileInfo directoryInfo = fileSystem.FileInfo.New(path); + + // Assert + await That(directoryInfo.FullName).IsEqualTo(path); + await That(directoryInfo.LinkTarget).IsEqualTo(pathToTarget); + } + + [Test] + public async Task MockFile_CreateSymbolicLink_ShouldFailWithNullPath() + { + // Arrange + var fileSystem = new MockFileSystem(); + var pathToTarget = XFS.Path(@"C:\Folder\foo.txt"); + var data = new MockFileData("foobar"); + fileSystem.AddFile(pathToTarget, data); + + // Act + var ex = await That(() => fileSystem.File.CreateSymbolicLink(null, pathToTarget)).Throws(); + + // Assert + await That(ex.ParamName).IsEqualTo("path"); + } + + [Test] + public async Task MockFile_CreateSymbolicLink_ShouldFailWithNullTarget() + { + // Arrange + var fileSystem = new MockFileSystem(); + var path = XFS.Path(@"C:\Folder\foo.txt"); + var data = new MockFileData("foobar"); + fileSystem.AddFile(path, data); + + // Act + var ex = await That(() => fileSystem.File.CreateSymbolicLink(path, null)).Throws(); + + // Assert + await That(ex.ParamName).IsEqualTo("pathToTarget"); + } + + [Test] + public async Task MockFile_CreateSymbolicLink_ShouldFailWithEmptyPath() + { + // Arrange + var fileSystem = new MockFileSystem(); + var pathToTarget = XFS.Path(@"C:\Folder\foo.txt"); + var data = new MockFileData("foobar"); + fileSystem.AddFile(pathToTarget, data); + + // Act + var ex = await That(() => fileSystem.File.CreateSymbolicLink("", pathToTarget)).Throws(); + + // Assert + await That(ex.ParamName).IsEqualTo("path"); + } + + [Test] + public async Task MockFile_CreateSymbolicLink_ShouldFailWithEmptyTarget() + { + // Arrange + var fileSystem = new MockFileSystem(); + string path = XFS.Path(@"C:\Folder\foo.txt"); + var data = new MockFileData("foobar"); + fileSystem.AddFile(path, data); + + // Act + var ex = await That(() => fileSystem.File.CreateSymbolicLink(path, "")).Throws(); + + // Assert + await That(ex.ParamName).IsEqualTo("pathToTarget"); + } + + [Test] + public async Task MockFile_CreateSymbolicLink_ShouldFailWithIllegalPath() + { + // Arrange + var fileSystem = new MockFileSystem(); + string pathToTarget = XFS.Path(@"C:\Folder\foo.txt"); + var data = new MockFileData("foobar"); + fileSystem.AddFile(pathToTarget, data); + + // Act + var ex = await That(() => fileSystem.File.CreateSymbolicLink(" ", pathToTarget)).Throws(); + + // Assert + await That(ex.ParamName).IsEqualTo("path"); + } + + [Test] + public async Task MockFile_CreateSymbolicLink_ShouldFailWithIllegalTarget() + { + // Arrange + var fileSystem = new MockFileSystem(); + string path = XFS.Path(@"C:\Folder\foo.txt"); + var data = new MockFileData("foobar"); + fileSystem.AddFile(path, data); + + // Act + var ex = await That(() => fileSystem.File.CreateSymbolicLink(path, " ")).Throws(); + + // Assert + await That(ex.ParamName).IsEqualTo("pathToTarget"); + } + + [Test] + [WindowsOnly(WindowsSpecifics.StrictPathRules)] + public async Task MockFile_CreateSymbolicLink_ShouldFailWithIllegalCharactersInPath() + { + // Arrange + var fileSystem = new MockFileSystem(); + string pathToTarget = XFS.Path(@"C:\Folder\foo.txt"); + var data = new MockFileData("foobar"); + fileSystem.AddFile(pathToTarget, data); + + // Act + Action ex = () => fileSystem.File.CreateSymbolicLink(@"C:\bar.txt_?_", pathToTarget); + + // Assert + await That(ex).Throws(); + } + + [Test] + [WindowsOnly(WindowsSpecifics.StrictPathRules)] + + public async Task MockFile_CreateSymbolicLink_ShouldFailWithIllegalCharactersInTarget() + { + // Arrange + var fileSystem = new MockFileSystem(); + string path = XFS.Path(@"C:\Folder\foo.txt"); + + // Act + Action ex = () => fileSystem.File.CreateSymbolicLink(path, @"C:\bar.txt_?_"); + + // Assert + await That(ex).Throws(); + } + + [Test] + public async Task MockFile_CreateSymbolicLink_ShouldFailIfPathExists() + { + // Arrange + var fileSystem = new MockFileSystem(); + string pathToTarget = XFS.Path(@"C:\Folder\foo.txt"); + string path = XFS.Path(@"C:\Folder\bar.txt"); + var data = new MockFileData("foobar"); + fileSystem.AddFile(pathToTarget, data); + fileSystem.AddFile(path, data); + + // Act + var ex = await That(() => fileSystem.File.CreateSymbolicLink(path, pathToTarget)).Throws(); + + // Assert + await That(ex.Message).Contains("path"); + } + + [Test] + public async Task MockFile_CreateSymbolicLink_ShouldFailIfTargetDoesNotExist() + { + // Arrange + var fileSystem = new MockFileSystem(); + string dir = XFS.Path(@"C:\Folder"); + string path = XFS.Path(@"C:\Folder\foo.txt"); + string pathToTarget = XFS.Path(@"C:\bar.txt"); + fileSystem.AddDirectory(dir); + + // Act + var ex = await That(() => fileSystem.File.CreateSymbolicLink(path, pathToTarget)).Throws(); + + // Assert + await That(ex.Message).Contains(pathToTarget); + } + + [Test] + public async Task MockFile_CreateSymbolicLink_ShouldFailIfPathDirectoryDoesNotExist() + { + // Arrange + var fileSystem = new MockFileSystem(); + string path = XFS.Path(@"C:\Folder\foo.txt"); + string pathToTarget = XFS.Path(@"C:\bar.txt"); + var data = new MockFileData("foobar"); + fileSystem.AddFile(pathToTarget, data); + + // Act + var ex = await That(() => fileSystem.File.CreateSymbolicLink(path, pathToTarget)).Throws(); + + // Assert + await That(ex.Message).Contains(path); + } + + [Test] + public async Task MockFile_CreateSymbolicLink_ShouldSetReparsePointAttribute() + { + var path = "foo.txt"; + var pathToTarget = "bar.txt"; + var fileSystem = new MockFileSystem(); + fileSystem.File.WriteAllText(pathToTarget, "some content"); + + fileSystem.File.CreateSymbolicLink(path, pathToTarget); + + var attributes = fileSystem.FileInfo.New(path).Attributes; + await That(attributes.HasFlag(FileAttributes.ReparsePoint)).IsTrue(); + } + + [Test] + public async Task MockFile_ResolveLinkTarget_ShouldReturnPathOfTargetLink() + { + var fileSystem = new MockFileSystem(); + fileSystem.File.WriteAllText("bar", "some content"); + fileSystem.File.CreateSymbolicLink("foo", "bar"); + + var result = fileSystem.File.ResolveLinkTarget("foo", false); + + await That(result.Name).IsEqualTo("bar"); + } + + [Test] + public async Task MockFile_ResolveLinkTarget_WithFinalTarget_ShouldReturnPathOfTargetLink() + { + // The maximum number of symbolic links that are followed: + // https://learn.microsoft.com/en-us/dotnet/api/system.io.directory.resolvelinktarget?view=net-6.0#remarks + var maxResolveLinks = XFS.IsWindowsPlatform() ? 63 : 40; + var fileSystem = new MockFileSystem(); + fileSystem.File.WriteAllText("bar", "some content"); + var previousPath = "bar"; + for (int i = 0; i < maxResolveLinks; i++) + { + string newPath = $"foo-{i}"; + fileSystem.File.CreateSymbolicLink(newPath, previousPath); + previousPath = newPath; + } + + var result = fileSystem.File.ResolveLinkTarget(previousPath, true); + + await That(result.Name).IsEqualTo("bar"); + } + + [Test] + public async Task MockFile_ResolveLinkTarget_WithFinalTargetWithTooManyLinks_ShouldThrowIOException() + { + // The maximum number of symbolic links that are followed: + // https://learn.microsoft.com/en-us/dotnet/api/system.io.directory.resolvelinktarget?view=net-6.0#remarks + var maxResolveLinks = XFS.IsWindowsPlatform() ? 63 : 40; + maxResolveLinks++; + var fileSystem = new MockFileSystem(); + fileSystem.File.WriteAllText("bar", "some content"); + var previousPath = "bar"; + for (int i = 0; i < maxResolveLinks; i++) + { + string newPath = $"foo-{i}"; + fileSystem.File.CreateSymbolicLink(newPath, previousPath); + previousPath = newPath; + } + + await That(() => fileSystem.File.ResolveLinkTarget(previousPath, true)).Throws(); + } + + [Test] + public async Task MockFile_ResolveLinkTarget_WithoutFinalTarget_ShouldReturnFirstLink() + { + var fileSystem = new MockFileSystem(); + fileSystem.File.WriteAllText("bar", "some content"); + fileSystem.File.CreateSymbolicLink("foo", "bar"); + fileSystem.File.CreateSymbolicLink("foo1", "foo"); + + var result = fileSystem.File.ResolveLinkTarget("foo1", false); + + await That(result.Name).IsEqualTo("foo"); + } + + [Test] + public async Task MockFile_ResolveLinkTarget_WithoutTargetLink_ShouldThrowIOException() + { + var fileSystem = new MockFileSystem(); + fileSystem.File.WriteAllText("bar", "some content"); + fileSystem.File.CreateSymbolicLink("foo", "bar"); + + await That(() => + { + fileSystem.File.ResolveLinkTarget("bar", false); + }).Throws(); + } +#endif +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileSystemOptionTests.cs b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileSystemOptionTests.cs new file mode 100644 index 000000000..26cede9c4 --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileSystemOptionTests.cs @@ -0,0 +1,39 @@ +using NUnit.Framework; +using XFS = System.IO.Abstractions.TestingHelpers.MockUnixSupport; + +namespace System.IO.Abstractions.TestingHelpers.Tests; + +[TestFixture] +public class MockFileSystemOptionTests +{ + [Test] + [TestCase(true)] + [TestCase(false)] + public async Task CreateDefaultTempDir_ShouldBeConsidered(bool createTempDir) + { + var fileSystem = new MockFileSystem(new MockFileSystemOptions + { + CreateDefaultTempDir = createTempDir + }); + + var result = fileSystem.Directory.Exists(fileSystem.Path.GetTempPath()); + + await That(result).IsEqualTo(createTempDir); + } + + [Test] + [TestCase(@"C:\path")] + [TestCase(@"C:\foo\bar")] + public async Task CurrentDirectory_ShouldBeConsidered(string currentDirectory) + { + currentDirectory = XFS.Path(currentDirectory); + var fileSystem = new MockFileSystem(new MockFileSystemOptions + { + CurrentDirectory = currentDirectory + }); + + var result = fileSystem.Directory.GetCurrentDirectory(); + + await That(result).IsEqualTo(currentDirectory); + } +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileSystemSerializationTests.cs b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileSystemSerializationTests.cs new file mode 100644 index 000000000..9035ecaf0 --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileSystemSerializationTests.cs @@ -0,0 +1,42 @@ +#if !NET9_0_OR_GREATER +namespace System.IO.Abstractions.TestingHelpers.Tests +{ + using NUnit.Framework; + using Text; + using XFS = MockUnixSupport; + [TestFixture] + class MockFileSystemSerializationTests + { + [Test] + public async Task SerializationBytes() + { + // Arrange + string path = XFS.Path(@"c:\something\demo.txt"); + + var content = "Hello there!" + Environment.NewLine + "Second line!" + Environment.NewLine; + var expected = Encoding.ASCII.GetBytes(content); //Convert a C# string to a byte array + + var fileSystem = new MockFileSystem(); + fileSystem.AddDirectory(XFS.Path(@"c:\something")); + + fileSystem.File.WriteAllBytes(path, expected); + + //Act + var memoryStream = new MemoryStream(); +#pragma warning disable SYSLIB0011 + var serializer = new Runtime.Serialization.Formatters.Binary.BinaryFormatter(); + + serializer.Serialize(memoryStream, fileSystem); + memoryStream.Flush(); + memoryStream.Position = 0; + fileSystem = (MockFileSystem)serializer.Deserialize(memoryStream); +#pragma warning restore SYSLIB0011 + memoryStream.Dispose(); + + // Assert + await That(fileSystem.GetFile(path).Contents).IsEqualTo(expected); + await That(fileSystem.File.ReadAllBytes(path)).IsEqualTo(expected); + } + } +} +#endif diff --git a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileSystemTests.cs b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileSystemTests.cs new file mode 100644 index 000000000..7252317cd --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileSystemTests.cs @@ -0,0 +1,629 @@ +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.Linq; +using System.Reflection; +using System.Text; +using NUnit.Framework; +using XFS = System.IO.Abstractions.TestingHelpers.MockUnixSupport; + +namespace System.IO.Abstractions.TestingHelpers.Tests; + +[TestFixture] +public class MockFileSystemTests +{ + [Test] + public async Task MockFileSystem_GetFile_ShouldReturnNullWhenFileIsNotRegistered() + { + var fileSystem = new MockFileSystem(new Dictionary + { + { @"c:\something\demo.txt", new MockFileData("Demo\r\ntext\ncontent\rvalue") }, + { @"c:\something\other.gif", new MockFileData("gif content") } + }); + + var result = fileSystem.GetFile(@"c:\something\else.txt"); + + await That(result).IsNull(); + } + + [Test] + public async Task MockFileSystem_GetFile_ShouldReturnFileRegisteredInConstructor() + { + var file1 = new MockFileData("Demo\r\ntext\ncontent\rvalue"); + var fileSystem = new MockFileSystem(new Dictionary + { + { @"c:\something\demo.txt", file1 }, + { @"c:\something\other.gif", new MockFileData("gif content") } + }); + + var result = fileSystem.GetFile(@"c:\something\demo.txt"); + + await That(result).IsEqualTo(file1); + } + + [Test] + [WindowsOnly(WindowsSpecifics.CaseInsensitivity)] + public async Task MockFileSystem_GetFile_ShouldReturnFileRegisteredInConstructorWhenPathsDifferByCase() + { + var file1 = new MockFileData("Demo\r\ntext\ncontent\rvalue"); + var fileSystem = new MockFileSystem(new Dictionary + { + { @"c:\something\demo.txt", file1 }, + { @"c:\something\other.gif", new MockFileData("gif content") } + }); + + var result = fileSystem.GetFile(@"c:\SomeThing\DEMO.txt"); + + await That(result).IsEqualTo(file1); + } + + [Test] + [UnixOnly(UnixSpecifics.CaseSensitivity)] + public async Task MockFileSystem_GetFile_ShouldNotReturnFileRegisteredInConstructorWhenPathsDifferByCase() + { + var fileSystem = new MockFileSystem(new Dictionary + { + { "/something/demo.txt", new MockFileData("Demo\r\ntext\ncontent\rvalue") }, + { "/something/other.gif", new MockFileData("gif content") } + }); + + var result = fileSystem.GetFile("/SomeThing/DEMO.txt"); + + await That(result).IsNull(); + } + + [Test] + public async Task MockFileSystem_AddFile_ShouldHandleUnnormalizedSlashes() + { + var path = XFS.Path(@"c:\d1\d2\file.txt"); + var alternatePath = XFS.Path("c:/d1/d2/file.txt"); + var alternateParentPath = XFS.Path("c://d1//d2/"); + var fs = new MockFileSystem(); + fs.AddFile(path, new MockFileData("Hello")); + + var fileCount = fs.Directory.GetFiles(alternateParentPath).Length; + var fileExists = fs.File.Exists(alternatePath); + + await That(fileCount).IsEqualTo(1); + await That(fileExists).IsTrue(); + } + + [Test] + public async Task MockFileSystem_AddFile_ShouldHandleNullFileDataAsEmpty() + { + var path = XFS.Path(@"c:\something\nullish.txt"); + var fileSystem = new MockFileSystem(new Dictionary + { + { path, null } + }); + + var result = fileSystem.File.ReadAllText(path); + + await That(result).IsEmpty().Because("Null MockFileData should be allowed for and result in an empty file."); + } + + [Test] + public async Task MockFileSystem_AddFile_ShouldReplaceExistingFile() + { + var path = XFS.Path(@"c:\some\file.txt"); + const string existingContent = "Existing content"; + var fileSystem = new MockFileSystem(new Dictionary + { + { path, new MockFileData(existingContent) } + }); + await That(fileSystem.GetFile(path).TextContents).IsEqualTo(existingContent); + + const string newContent = "New content"; + fileSystem.AddFile(path, new MockFileData(newContent)); + + await That(fileSystem.GetFile(path).TextContents).IsEqualTo(newContent); + } + + [Test] + public async Task MockFileSystem_AddEmptyFile_ShouldBeEmpty() + { + var path = XFS.Path(@"c:\some\file.txt"); + var fileSystem = new MockFileSystem(); + + fileSystem.AddEmptyFile(path); + + await That(fileSystem.GetFile(path).TextContents).IsEqualTo(""); + } + + [Test] + public async Task MockFileSystem_AddEmptyFile_ShouldExist() + { + var fileSystem = new MockFileSystem(); + var path = fileSystem.FileInfo.New(XFS.Path(@"c:\some\file.txt")); + + fileSystem.AddEmptyFile(path); + + await That(path.Exists).IsTrue(); + } + + [Test] + public async Task MockFileSystem_AddFile_ShouldExist() + { + var fileSystem = new MockFileSystem(); + var path = fileSystem.FileInfo.New(XFS.Path(@"c:\some\file.txt")); + + fileSystem.AddFile(path, new MockFileData("stuff")); + + await That(path.Exists).IsTrue(); + } + + [Test] + public async Task MockFileSystem_AddDirectory_ShouldExist() + { + var fileSystem = new MockFileSystem(); + var path = fileSystem.DirectoryInfo.New(XFS.Path(@"c:\thedir")); + + fileSystem.AddDirectory(path); + + await That(path.Exists).IsTrue(); + } + +#if !NET9_0_OR_GREATER + [Test] + public async Task MockFileSystem_ByDefault_IsSerializable() + { + var file1 = new MockFileData("Demo\r\ntext\ncontent\rvalue"); + var fileSystem = new MockFileSystem(new Dictionary + { + { @"c:\something\demo.txt", file1 }, + { @"c:\something\other.gif", new MockFileData(new byte[] { 0x21, 0x58, 0x3f, 0xa9 }) } + }); + var memoryStream = new MemoryStream(); + +#pragma warning disable SYSLIB0011 + var serializer = new Runtime.Serialization.Formatters.Binary.BinaryFormatter(); + + serializer.Serialize(memoryStream, fileSystem); +#pragma warning restore SYSLIB0011 + + await That(memoryStream).HasLength().GreaterThan(0).Because("Length didn't increase after serialization task."); + } +#endif + + [Test] + public async Task MockFileSystem_AddDirectory_ShouldCreateDirectory() + { + string baseDirectory = XFS.Path(@"C:\Test"); + var fileSystem = new MockFileSystem(); + + fileSystem.AddDirectory(baseDirectory); + + await That(fileSystem.Directory.Exists(baseDirectory)).IsTrue(); + } + + [Test] + public async Task MockFileSystem_AddDirectory_ShouldThrowExceptionIfDirectoryIsReadOnly() + { + string baseDirectory = XFS.Path(@"C:\Test"); + var fileSystem = new MockFileSystem(); + fileSystem.AddFile(baseDirectory, new MockFileData(string.Empty)); + fileSystem.File.SetAttributes(baseDirectory, FileAttributes.ReadOnly); + + Action action = () => fileSystem.AddDirectory(baseDirectory); + + await That(action).Throws(); + } + + [Test] + public async Task MockFileSystem_AddDrive_ShouldExist() + { + string name = @"D:\"; + var fileSystem = new MockFileSystem(); + fileSystem.AddDrive(name, new MockDriveData()); + + var actualResults = fileSystem.DriveInfo.GetDrives().Select(d => d.Name); + + await That(actualResults).Contains(name); + } + + [Test] + public async Task MockFileSystem_DriveInfo_ShouldNotThrowAnyException() + { + var fileSystem = new MockFileSystem(); + fileSystem.AddDirectory(XFS.Path(@"C:\Test")); + + var actualResults = fileSystem.DriveInfo.GetDrives(); + + await That(actualResults).IsNotNull(); + } + + [Test] + public async Task MockFileSystem_AddFile_ShouldMatchCapitalization_PerfectMatch() + { + var fileSystem = new MockFileSystem(); + fileSystem.AddDirectory(XFS.Path(@"C:\test")); + fileSystem.AddDirectory(XFS.Path(@"C:\LOUD")); + + fileSystem.AddFile(XFS.Path(@"C:\test\file.txt"), "foo"); + fileSystem.AddFile(XFS.Path(@"C:\LOUD\file.txt"), "foo"); + fileSystem.AddDirectory(XFS.Path(@"C:\test\SUBDirectory")); + fileSystem.AddDirectory(XFS.Path(@"C:\LOUD\SUBDirectory")); + + await That(fileSystem.AllFiles.ToList()).Contains(XFS.Path(@"C:\test\file.txt")); + await That(fileSystem.AllFiles.ToList()).Contains(XFS.Path(@"C:\LOUD\file.txt")); + await That(fileSystem.AllDirectories.ToList()).Contains(XFS.Path(@"C:\test\SUBDirectory")); + await That(fileSystem.AllDirectories.ToList()).Contains(XFS.Path(@"C:\LOUD\SUBDirectory")); + } + + [Test] + [WindowsOnly(WindowsSpecifics.CaseInsensitivity)] + public async Task MockFileSystem_AddFile_ShouldMatchCapitalization_PartialMatch() + { + var fileSystem = new MockFileSystem(); + fileSystem.AddDirectory(XFS.Path(@"C:\test\subtest")); + fileSystem.AddDirectory(XFS.Path(@"C:\LOUD\SUBLOUD")); + + fileSystem.AddFile(XFS.Path(@"C:\test\SUBTEST\file.txt"), "foo"); + fileSystem.AddFile(XFS.Path(@"C:\LOUD\subloud\file.txt"), "foo"); + fileSystem.AddDirectory(XFS.Path(@"C:\test\SUBTEST\SUBDirectory")); + fileSystem.AddDirectory(XFS.Path(@"C:\LOUD\subloud\SUBDirectory")); + + await That(fileSystem.AllFiles.ToList()).Contains(XFS.Path(@"C:\test\subtest\file.txt")); + await That(fileSystem.AllFiles.ToList()).Contains(XFS.Path(@"C:\LOUD\SUBLOUD\file.txt")); + await That(fileSystem.AllDirectories.ToList()).Contains(XFS.Path(@"C:\test\subtest\SUBDirectory")); + await That(fileSystem.AllDirectories.ToList()).Contains(XFS.Path(@"C:\LOUD\SUBLOUD\SUBDirectory")); + } + + [Test] + [WindowsOnly(WindowsSpecifics.CaseInsensitivity)] + public async Task MockFileSystem_AddFile_ShouldMatchCapitalization_PartialMatch_FurtherLeft() + { + var fileSystem = new MockFileSystem(); + fileSystem.AddDirectory(XFS.Path(@"C:\test\subtest")); + fileSystem.AddDirectory(XFS.Path(@"C:\LOUD\SUBLOUD")); + + fileSystem.AddFile(XFS.Path(@"C:\test\SUBTEST\new\file.txt"), "foo"); + fileSystem.AddFile(XFS.Path(@"C:\LOUD\subloud\new\file.txt"), "foo"); + fileSystem.AddDirectory(XFS.Path(@"C:\test\SUBTEST\new\SUBDirectory")); + fileSystem.AddDirectory(XFS.Path(@"C:\LOUD\subloud\new\SUBDirectory")); + + await That(fileSystem.AllFiles.ToList()).Contains(XFS.Path(@"C:\test\subtest\new\file.txt")); + await That(fileSystem.AllFiles.ToList()).Contains(XFS.Path(@"C:\LOUD\SUBLOUD\new\file.txt")); + await That(fileSystem.AllDirectories.ToList()).Contains(XFS.Path(@"C:\test\subtest\new\SUBDirectory")); + await That(fileSystem.AllDirectories.ToList()).Contains(XFS.Path(@"C:\LOUD\SUBLOUD\new\SUBDirectory")); + } + + [Test] + public async Task MockFileSystem_AddFile_InitializesMockFileDataFileVersionInfoIfNull() + { + // Arrange + var fileSystem = new MockFileSystem(); + + // Act + fileSystem.AddFile(XFS.Path(@"C:\file.txt"), string.Empty); + + // Assert + IFileVersionInfo fileVersionInfo = fileSystem.FileVersionInfo.GetVersionInfo(XFS.Path(@"C:\file.txt")); + await That(fileVersionInfo).IsNotNull(); + await That(fileVersionInfo.FileName).IsEqualTo(XFS.Path(@"C:\file.txt")); + } + + [Test] + public async Task MockFileSystem_AddFileFromEmbeddedResource_ShouldAddTheFile() + { + var fileSystem = new MockFileSystem(); + + fileSystem.AddFileFromEmbeddedResource(XFS.Path(@"C:\TestFile.txt"), Assembly.GetExecutingAssembly(), "System.IO.Abstractions.TestingHelpers.Tests.TestFiles.TestFile.txt"); + var result = fileSystem.GetFile(XFS.Path(@"C:\TestFile.txt")); + + await That(result.Contents).IsEqualTo(new UTF8Encoding().GetBytes("This is a test file.")); + } + + [Test] + public async Task MockFileSystem_AddFilesFromEmbeddedResource_ShouldAddAllTheFiles() + { + var fileSystem = new MockFileSystem(); + + fileSystem.AddFilesFromEmbeddedNamespace(XFS.Path(@"C:\"), Assembly.GetExecutingAssembly(), "System.IO.Abstractions.TestingHelpers.Tests.TestFiles"); + + await That(fileSystem.AllFiles.ToList()).Contains(XFS.Path(@"C:\TestFile.txt")); + await That(fileSystem.AllFiles.ToList()).Contains(XFS.Path(@"C:\SecondTestFile.txt")); + } + + [Test] + public async Task MockFileSystem_MoveDirectory_MovesDirectoryWithoutRenamingFiles() + { + var fileSystem = new MockFileSystem(); + fileSystem.AddFile(XFS.Path(@"C:\dir1\dir1\dir1.txt"), string.Empty); + + fileSystem.MoveDirectory(XFS.Path(@"C:\dir1"), XFS.Path(@"C:\dir2")); + + var expected = new[] { XFS.Path(@"C:\dir2\dir1\dir1.txt") }; + await That(fileSystem.AllFiles).IsEqualTo(expected); + } + + [Test] + public async Task MockFileSystem_MoveDirectoryAndFile_ShouldMoveCorrectly() + { + var fileSystem = new MockFileSystem(); + fileSystem.AddFile(XFS.Path(@"C:\source\project.txt"), string.Empty); + fileSystem.AddFile(XFS.Path(@"C:\source\subdir\other.txt"), string.Empty); + + fileSystem.Directory.Move(XFS.Path(@"C:\source"), XFS.Path(@"C:\target")); + fileSystem.File.Move(XFS.Path(@"C:\target\project.txt"), XFS.Path(@"C:\target\proj.txt")); + + var expected = new[] { XFS.Path(@"C:\target\proj.txt"), XFS.Path(@"C:\target\subdir\other.txt") }; + await That(fileSystem.AllFiles).IsEqualTo(expected); + } + + [Test] + public async Task MockFileSystem_RemoveFile_RemovesFiles() + { + var fileSystem = new MockFileSystem(); + fileSystem.AddFile(@"C:\file.txt", new MockFileData("Content")); + + fileSystem.RemoveFile(@"C:\file.txt"); + + await That(fileSystem.FileExists(@"C:\file.txt")).IsFalse(); + } + + [Test] + public async Task MockFileSystem_RemoveFile_ThrowsUnauthorizedAccessExceptionIfFileIsReadOnly() + { + var path = XFS.Path(@"C:\file.txt"); + var readOnlyFile = new MockFileData("") + { + Attributes = FileAttributes.ReadOnly + }; + var fileSystem = new MockFileSystem(new Dictionary + { + { path, readOnlyFile }, + }); + + Action action = () => fileSystem.RemoveFile(path); + + await That(action).Throws(); + } + + [Test] + public async Task MockFileSystem_AllNodes_ShouldReturnAllNodes() + { + var fileSystem = new MockFileSystem(new Dictionary + { + { XFS.Path(@"c:\something\demo.txt"), string.Empty }, + { XFS.Path(@"c:\something\other.gif"), string.Empty }, + { XFS.Path(@"d:\foobar\"), new MockDirectoryData() }, + { XFS.Path(@"d:\foo\bar"), new MockDirectoryData( )} + }); + var expectedNodes = new[] + { + XFS.Path(@"c:\something\demo.txt"), + XFS.Path(@"c:\something\other.gif"), + XFS.Path(@"d:\foobar"), + XFS.Path(@"d:\foo\bar"), + XFS.Path(@"C:\temp") + }; + + var result = fileSystem.AllNodes; + + await That(result).IsEqualTo(expectedNodes); + } + + [Test] + [TestCase(@"C:\path")] + [TestCase(@"C:\path\")] + public async Task MockFileSystem_AddDirectory_TrailingSlashAllowedButNotRequired(string path) + { + var fileSystem = new MockFileSystem(); + var path2 = XFS.Path(path); + + fileSystem.AddDirectory(path2); + + await That(fileSystem.FileExists(path2)).IsTrue(); + } + + [Test] + public async Task MockFileSystem_GetFiles_ThrowsArgumentExceptionForInvalidCharacters() + { + // Arrange + const string path = @"c:\"; + var fileSystem = new MockFileSystem(); + fileSystem.AddDirectory(XFS.Path(path)); + + // Act + Action getFilesWithInvalidCharacterInPath = () => fileSystem.Directory.GetFiles($"{path}{'\0'}.txt"); + + // Assert + await That(getFilesWithInvalidCharacterInPath).Throws(); + } + + [Test] + [TestCase(null)] + [TestCase(@"C:\somepath")] + public async Task MockFileSystem_DefaultState_CurrentDirectoryExists(string currentDirectory) + { + var fs = new MockFileSystem(null, XFS.Path(currentDirectory)); + + var actualCurrentDirectory = fs.DirectoryInfo.New("."); + + await That(actualCurrentDirectory.Exists).IsTrue(); + } + + [Test] + public async Task MockFileSystem_Constructor_ThrowsForNonRootedCurrentDirectory() + { + await That(() => + new MockFileSystem(null, "non-rooted") + ).Throws() + .WithParamName("currentDirectory"); + } + + [Test] + [WindowsOnly(WindowsSpecifics.Drives)] + public async Task MockFileSystem_Constructor_ShouldSupportDifferentRootDrives() + { + var fileSystem = new MockFileSystem(new Dictionary + { + [@"c:\"] = new MockDirectoryData(), + [@"z:\"] = new MockDirectoryData(), + [@"d:\"] = new MockDirectoryData(), + }); + + var cExists = fileSystem.Directory.Exists(@"c:\"); + var zExists = fileSystem.Directory.Exists(@"z:\"); + var dExists = fileSystem.Directory.Exists(@"d:\"); + + await That(fileSystem).IsNotNull(); + await That(cExists).IsTrue(); + await That(zExists).IsTrue(); + await That(dExists).IsTrue(); + } + + [Test] + [WindowsOnly(WindowsSpecifics.Drives)] + public async Task MockFileSystem_Constructor_ShouldAddDifferentDrivesIfNotExist() + { + var fileSystem = new MockFileSystem(new Dictionary + { + [@"d:\foo\bar\"] = new MockDirectoryData(), + }); + + var drivesInfo = fileSystem.DriveInfo.GetDrives(); + var fooExists = fileSystem.Directory.Exists(@"d:\foo\"); + var barExists = fileSystem.Directory.Exists(@"d:\foo\bar\"); + + await That(drivesInfo.Any(d => string.Equals(d.Name, @"D:\", StringComparison.InvariantCultureIgnoreCase))).IsTrue(); + await That(fooExists).IsTrue(); + await That(barExists).IsTrue(); + } + + [Test] + [WindowsOnly(WindowsSpecifics.Drives)] + public async Task MockFileSystem_Constructor_ShouldNotDuplicateDrives() + { + var fileSystem = new MockFileSystem(new Dictionary + { + [@"d:\foo\bar\"] = new MockDirectoryData(), + [@"d:\"] = new MockDirectoryData() + }); + + var drivesInfo = fileSystem.DriveInfo.GetDrives(); + + await That(drivesInfo.Where(d => string.Equals(d.Name, @"D:\", StringComparison.InvariantCultureIgnoreCase))).HasCount().EqualTo(1); + } + + [Test] + public async Task MockFileSystem_DefaultState_DefaultTempDirectoryExists() + { + var tempDirectory = XFS.Path(@"C:\temp"); + + var mockFileSystem = new MockFileSystem(); + var mockFileSystemOverload = new MockFileSystem(null, string.Empty); + + await That(mockFileSystem.Directory.Exists(tempDirectory)).IsTrue(); + await That(mockFileSystemOverload.Directory.Exists(tempDirectory)).IsTrue(); + } + + [Test] + public async Task MockFileSystem_FileSystemWatcher_Can_Be_Overridden() + { + var path = XFS.Path(@"C:\root"); + var fileSystem = new TestFileSystem(new TestFileSystemWatcherFactory()); + var watcher = fileSystem.FileSystemWatcher.New(path); + await That(watcher.Path).IsEqualTo(path); + } + + [Test] + public async Task MockFileSystem_DeleteDirectoryRecursive_WithReadOnlyFile_ShouldThrowUnauthorizedException() + { + string baseDirectory = XFS.Path(@"C:\Test"); + string textFile = XFS.Path(@"C:\Test\file.txt"); + + var fileSystem = new MockFileSystem(); + fileSystem.AddFile(baseDirectory, new MockFileData(string.Empty)); + fileSystem.AddFile(textFile, new MockFileData("Content")); + fileSystem.File.SetAttributes(textFile, FileAttributes.ReadOnly); + + Action action = () => fileSystem.Directory.Delete(baseDirectory, true); + + await That(action).Throws(); + await That(fileSystem.File.Exists(textFile)).IsTrue(); + await That(fileSystem.Directory.Exists(baseDirectory)).IsTrue(); + } + + private class TestFileSystem : MockFileSystem + { + private readonly IFileSystemWatcherFactory fileSystemWatcherFactory; + + public TestFileSystem(IFileSystemWatcherFactory fileSystemWatcherFactory) + { + this.fileSystemWatcherFactory = fileSystemWatcherFactory; + } + + public override IFileSystemWatcherFactory FileSystemWatcher => fileSystemWatcherFactory; + } + + private class TestFileSystemWatcherFactory : IFileSystemWatcherFactory + { + public IFileSystemWatcher CreateNew() => New(); + public IFileSystemWatcher CreateNew(string path) => New(path); + public IFileSystemWatcher CreateNew(string path, string filter) => New(path, filter); + public IFileSystemWatcher New() + => new TestFileSystemWatcher(null); + + public IFileSystemWatcher New(string path) + => new TestFileSystemWatcher(path); + + public IFileSystemWatcher New(string path, string filter) + => new TestFileSystemWatcher(path, filter); + + public IFileSystemWatcher Wrap(FileSystemWatcher fileSystemWatcher) + => new TestFileSystemWatcher(fileSystemWatcher.Path, fileSystemWatcher.Filter); + + public IFileSystemWatcher FromPath(string path) => new TestFileSystemWatcher(path); + public IFileSystem FileSystem => null!; + } + + private class TestFileSystemWatcher : FileSystemWatcherBase + { + public TestFileSystemWatcher(string path) => Path = path; + + public TestFileSystemWatcher(string path, string filter) + { + Path = path; + Filter = filter; + } + + public override string Path { get; set; } + public override IFileSystem FileSystem { get; } + public override bool IncludeSubdirectories { get; set; } + public override IContainer Container { get; } + public override bool EnableRaisingEvents { get; set; } + public override string Filter { get; set; } + public override int InternalBufferSize { get; set; } + public override NotifyFilters NotifyFilter { get; set; } + public override ISite Site { get; set; } + public override ISynchronizeInvoke SynchronizingObject { get; set; } +#if FEATURE_FILE_SYSTEM_WATCHER_FILTERS + public override Collection Filters { get; } +#endif + public override void BeginInit() { } + public override void EndInit() { } + public override IWaitForChangedResult WaitForChanged(WatcherChangeTypes changeType) + { + _ = changeType; + return default(IWaitForChangedResult); + } + + public override IWaitForChangedResult WaitForChanged(WatcherChangeTypes changeType, int timeout) + { + _ = changeType; + _ = timeout; + return default(IWaitForChangedResult); + } + +#if FEATURE_FILE_SYSTEM_WATCHER_WAIT_WITH_TIMESPAN + public override IWaitForChangedResult WaitForChanged(WatcherChangeTypes changeType, TimeSpan timeout) + { + _ = changeType; + _ = timeout; + return default(IWaitForChangedResult); + } +#endif + } +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileSystemWatcherFactoryTests.cs b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileSystemWatcherFactoryTests.cs new file mode 100644 index 000000000..12b6a34ad --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileSystemWatcherFactoryTests.cs @@ -0,0 +1,50 @@ +using NUnit.Framework; +using XFS = System.IO.Abstractions.TestingHelpers.MockUnixSupport; + +namespace System.IO.Abstractions.TestingHelpers.Tests; + +[TestFixture] +public class MockFileSystemWatcherFactoryTests +{ + [Test] + public async Task MockFileSystemWatcherFactory_CreateNew_ShouldThrowNotImplementedException() + { + var factory = new MockFileSystemWatcherFactory(new MockFileSystem()); + await That(() => factory.New()).Throws(); + } + + [Test] + public async Task MockFileSystemWatcherFactory_CreateNewWithPath_ShouldThrowNotImplementedException() + { + var path = XFS.Path(@"y:\test"); + var factory = new MockFileSystemWatcherFactory(new MockFileSystem()); + await That(() => factory.New(path)).Throws(); + } + + [Test] + public async Task MockFileSystemWatcherFactory_CreateNewWithPathAndFilter_ShouldThrowNotImplementedException() + { + var path = XFS.Path(@"y:\test"); + var filter = "*.txt"; + var factory = new MockFileSystemWatcherFactory(new MockFileSystem()); + await That(() => factory.New(path, filter)).Throws(); + } + + [Test] + public async Task MockFileSystemWatcherFactory_FromPath_ShouldThrowNotImplementedException() + { + var path = XFS.Path(@"y:\test"); + var factory = new MockFileSystemWatcherFactory(new MockFileSystem()); + await That(() => factory.New(path)).Throws(); + } + + [Test] + public async Task MockFileSystemWatcherFactory_Wrap_WithNull_ShouldReturnNull() + { + var fileSystem = new MockFileSystem(); + + var result = fileSystem.FileSystemWatcher.Wrap(null); + + await That(result).IsNull(); + } +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileTests.cs b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileTests.cs new file mode 100644 index 000000000..3694c466e --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileTests.cs @@ -0,0 +1,749 @@ +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Runtime.Serialization.Formatters.Binary; +using System.Text; +using NUnit.Framework; + +namespace System.IO.Abstractions.TestingHelpers.Tests; + +using XFS = MockUnixSupport; + +[TestFixture] +public class MockFileTests +{ + [Test] + public async Task MockFile_Constructor_ShouldThrowArgumentNullExceptionIfMockFileDataAccessorIsNull() + { + // Arrange + // nothing to do + + // Act + Action action = () => new MockFile(null); + + // Assert + await That(action).Throws(); + } + + [Test] + public async Task MockFile_GetSetCreationTime_ShouldPersist() + { + // Arrange + string path = XFS.Path(@"c:\something\demo.txt"); + var fileSystem = new MockFileSystem(new Dictionary + { + { path, new MockFileData("Demo text content") } + }); + var file = new MockFile(fileSystem); + + // Act + var creationTime = new DateTime(2010, 6, 4, 13, 26, 42); + file.SetCreationTime(path, creationTime); + var result = file.GetCreationTime(path); + + // Assert + await That(result).IsEqualTo(creationTime); + } + + [Test] + public async Task MockFile_SetCreationTimeUtc_ShouldAffectCreationTime() + { + // Arrange + string path = XFS.Path(@"c:\something\demo.txt"); + var fileSystem = new MockFileSystem(new Dictionary + { + { path, new MockFileData("Demo text content") } + }); + var file = new MockFile(fileSystem); + + // Act + var creationTime = new DateTime(2010, 6, 4, 13, 26, 42); + file.SetCreationTimeUtc(path, creationTime.ToUniversalTime()); + var result = file.GetCreationTime(path); + + // Assert + await That(result).IsEqualTo(creationTime); + } + + [Test] + public async Task MockFile_SetCreationTime_ShouldAffectCreationTimeUtc() + { + // Arrange + string path = XFS.Path(@"c:\something\demo.txt"); + var fileSystem = new MockFileSystem(new Dictionary + { + { path, new MockFileData("Demo text content") } + }); + var file = new MockFile(fileSystem); + + // Act + var creationTime = new DateTime(2010, 6, 4, 13, 26, 42); + file.SetCreationTime(path, creationTime); + var result = file.GetCreationTimeUtc(path); + + // Assert + await That(result).IsEqualTo(creationTime.ToUniversalTime()); + } + + [Test] + public async Task MockFile_GetSetLastAccessTime_ShouldPersist() + { + // Arrange + string path = XFS.Path(@"c:\something\demo.txt"); + var fileSystem = new MockFileSystem(new Dictionary + { + { path, new MockFileData("Demo text content") } + }); + var file = new MockFile(fileSystem); + + // Act + var lastAccessTime = new DateTime(2010, 6, 4, 13, 26, 42); + file.SetLastAccessTime(path, lastAccessTime); + var result = file.GetLastAccessTime(path); + + // Assert + await That(result).IsEqualTo(lastAccessTime); + } + + [Test] + public async Task MockFile_SetLastAccessTimeUtc_ShouldAffectLastAccessTime() + { + // Arrange + string path = XFS.Path(@"c:\something\demo.txt"); + var fileSystem = new MockFileSystem(new Dictionary + { + { path, new MockFileData("Demo text content") } + }); + var file = new MockFile(fileSystem); + + // Act + var lastAccessTime = new DateTime(2010, 6, 4, 13, 26, 42); + file.SetLastAccessTimeUtc(path, lastAccessTime.ToUniversalTime()); + var result = file.GetLastAccessTime(path); + + // Assert + await That(result).IsEqualTo(lastAccessTime); + } + + [Test] + public async Task MockFile_SetLastAccessTime_ShouldAffectLastAccessTimeUtc() + { + // Arrange + string path = XFS.Path(@"c:\something\demo.txt"); + var fileSystem = new MockFileSystem(new Dictionary + { + { path, new MockFileData("Demo text content") } + }); + var file = new MockFile(fileSystem); + + // Act + var lastAccessTime = new DateTime(2010, 6, 4, 13, 26, 42); + file.SetLastAccessTime(path, lastAccessTime); + var result = file.GetLastAccessTimeUtc(path); + + // Assert + await That(result).IsEqualTo(lastAccessTime.ToUniversalTime()); + } + + [Test] + public async Task MockFile_GetSetLastWriteTime_ShouldPersist() + { + // Arrange + string path = XFS.Path(@"c:\something\demo.txt"); + var fileSystem = new MockFileSystem(new Dictionary + { + { path, new MockFileData("Demo text content") } + }); + var file = new MockFile(fileSystem); + + // Act + var lastWriteTime = new DateTime(2010, 6, 4, 13, 26, 42); + file.SetLastWriteTime(path, lastWriteTime); + var result = file.GetLastWriteTime(path); + + // Assert + await That(result).IsEqualTo(lastWriteTime); + } + + static async Task ExecuteDefaultValueTest(Func getDateValue) + { + var expected = new DateTime(1601, 01, 01, 00, 00, 00, DateTimeKind.Utc); + string path = XFS.Path(@"c:\something\demo.txt"); + var fileSystem = new MockFileSystem(); + var file = new MockFile(fileSystem); + + var actual = getDateValue(file, path); + + await That(actual.ToUniversalTime()).IsEqualTo(expected); + } + + [Test] + public async Task MockFile_GetLastWriteTimeOfNonExistentFile_ShouldReturnDefaultValue() + { + await ExecuteDefaultValueTest((f, p) => f.GetLastWriteTime(p)); + } + + [Test] + public async Task MockFile_GetLastWriteTimeUtcOfNonExistentFile_ShouldReturnDefaultValue() + { + await ExecuteDefaultValueTest((f, p) => f.GetLastWriteTimeUtc(p)); + } + + [Test] + public async Task MockFile_GetLastAccessTimeUtcOfNonExistentFile_ShouldReturnDefaultValue() + { + await ExecuteDefaultValueTest((f, p) => f.GetLastAccessTimeUtc(p)); + } + + [Test] + public async Task MockFile_GetLastAccessTimeOfNonExistentFile_ShouldReturnDefaultValue() + { + await ExecuteDefaultValueTest((f, p) => f.GetLastAccessTime(p)); + } + + [Test] + public async Task MockFile_GetAttributeOfNonExistentFileButParentDirectoryExists_ShouldThrowOneFileNotFoundException() + { + // Arrange + var fileSystem = new MockFileSystem(); + fileSystem.AddDirectory(XFS.Path(@"c:\something")); + + // Act + Action action = () => fileSystem.File.GetAttributes(XFS.Path(@"c:\something\demo.txt")); + + // Assert + await That(action).Throws(); + } + + [Test] + public async Task MockFile_GetAttributeOfNonExistentFile_ShouldThrowOneDirectoryNotFoundException() + { + // Arrange + var fileSystem = new MockFileSystem(); + + // Act + Action action = () => fileSystem.File.GetAttributes(XFS.Path(@"c:\something\demo.txt")); + + // Assert + await That(action).Throws(); + } + + [Test] + public async Task MockFile_GetAttributeOfExistingFile_ShouldReturnCorrectValue() + { + var filedata = new MockFileData("test") + { + Attributes = FileAttributes.Hidden + }; + var fileSystem = new MockFileSystem(new Dictionary + { + { XFS.Path(@"c:\something\demo.txt"), filedata } + }); + + var attributes = fileSystem.File.GetAttributes(XFS.Path(@"c:\something\demo.txt")); + await That(attributes).IsEqualTo(FileAttributes.Hidden); + } + + [Test] + [WindowsOnly(WindowsSpecifics.UNCPaths)] + public async Task MockFile_GetAttributeOfExistingUncDirectory_ShouldReturnCorrectValue() + { + var filedata = new MockFileData("test"); + var fileSystem = new MockFileSystem(new Dictionary + { + { XFS.Path(@"\\share\folder\demo.txt"), filedata } + }); + + var attributes = fileSystem.File.GetAttributes(XFS.Path(@"\\share\folder")); + await That(attributes).IsEqualTo(FileAttributes.Directory); + } + + [Test] + public async Task MockFile_GetAttributeWithEmptyParameter_ShouldThrowOneArgumentException() + { + // Arrange + var fileSystem = new MockFileSystem(); + + // Act + Action action = () => fileSystem.File.GetAttributes(string.Empty); + + // Assert + var exception = await That(action).Throws(); + await That(exception.Message).StartsWith("The path is not of a legal form."); + } + + [Test] + public async Task MockFile_GetAttributeWithIllegalParameter_ShouldThrowOneArgumentException() + { + // Arrange + var fileSystem = new MockFileSystem(); + + // Act + Action action = () => fileSystem.File.GetAttributes(string.Empty); + + // Assert + // Note: The actual type of the exception differs from the documentation. + // According to the documentation it should be of type NotSupportedException. + await That(action).Throws(); + } + + [Test] + public async Task MockFile_GetCreationTimeOfNonExistentFile_ShouldReturnDefaultValue() + { + await ExecuteDefaultValueTest((f, p) => f.GetCreationTime(p)); + } + + [Test] + public async Task MockFile_GetCreationTimeUtcOfNonExistentFile_ShouldReturnDefaultValue() + { + await ExecuteDefaultValueTest((f, p) => f.GetCreationTimeUtc(p)); + } + + [Test] + public async Task MockFile_SetLastWriteTimeUtc_ShouldAffectLastWriteTime() + { + // Arrange + string path = XFS.Path(@"c:\something\demo.txt"); + var fileSystem = new MockFileSystem(new Dictionary + { + { path, new MockFileData("Demo text content") } + }); + var file = new MockFile(fileSystem); + + // Act + var lastWriteTime = new DateTime(2010, 6, 4, 13, 26, 42); + file.SetLastWriteTimeUtc(path, lastWriteTime.ToUniversalTime()); + var result = file.GetLastWriteTime(path); + + // Assert + await That(result).IsEqualTo(lastWriteTime); + } + + [Test] + public async Task MockFile_SetLastWriteTime_ShouldAffectLastWriteTimeUtc() + { + // Arrange + string path = XFS.Path(@"c:\something\demo.txt"); + var fileSystem = new MockFileSystem(new Dictionary + { + { path, new MockFileData("Demo text content") } + }); + var file = new MockFile(fileSystem); + + // Act + var lastWriteTime = new DateTime(2010, 6, 4, 13, 26, 42); + file.SetLastWriteTime(path, lastWriteTime); + var result = file.GetLastWriteTimeUtc(path); + + // Assert + await That(result).IsEqualTo(lastWriteTime.ToUniversalTime()); + } + + [Test] + public async Task MockFile_ReadAllText_ShouldReturnOriginalTextData() + { + // Arrange + var fileSystem = new MockFileSystem(new Dictionary + { + { XFS.Path(@"c:\something\demo.txt"), new MockFileData("Demo text content") }, + { XFS.Path(@"c:\something\other.gif"), new MockFileData(new byte[] { 0x21, 0x58, 0x3f, 0xa9 }) } + }); + + var file = new MockFile(fileSystem); + + // Act + var result = file.ReadAllText(XFS.Path(@"c:\something\demo.txt")); + + // Assert + await That(result).IsEqualTo("Demo text content"); + } + + [Test] + public async Task MockFile_ReadAllText_ShouldReturnOriginalDataWithCustomEncoding() + { + // Arrange + string text = "Hello there!"; + var encodedText = Encoding.BigEndianUnicode.GetBytes(text); + var fileSystem = new MockFileSystem(new Dictionary + { + { XFS.Path(@"c:\something\demo.txt"), new MockFileData(encodedText) } + }); + + var file = new MockFile(fileSystem); + + // Act + var result = file.ReadAllText(XFS.Path(@"c:\something\demo.txt"), Encoding.BigEndianUnicode); + + // Assert + await That(result).IsEqualTo(text); + } + + public static IEnumerable GetEncodingsForReadAllText() + { + // little endian + yield return new UTF32Encoding(false, true, true); + + // big endian + yield return new UTF32Encoding(true, true, true); + yield return new UTF8Encoding(true, true); + + yield return new ASCIIEncoding(); + } + + [TestCaseSource(typeof(MockFileTests), nameof(GetEncodingsForReadAllText))] + public async Task MockFile_ReadAllText_ShouldReturnTheOriginalContentWhenTheFileContainsDifferentEncodings(Encoding encoding) + { + // Arrange + string text = "Hello there!"; + var encodedText = encoding.GetPreamble().Concat(encoding.GetBytes(text)).ToArray(); + var path = XFS.Path(@"c:\something\demo.txt"); + var fileSystem = new MockFileSystem(new Dictionary + { + { path, new MockFileData(encodedText) } + }); + + // Act + var actualText = fileSystem.File.ReadAllText(path); + + // Assert + await That(actualText).IsEqualTo(text); + } + + [Test] + public async Task MockFile_OpenWrite_ShouldCreateNewFiles() + { + string filePath = XFS.Path(@"c:\something\demo.txt"); + string fileContent = "this is some content"; + var fileSystem = new MockFileSystem(); + fileSystem.AddDirectory(XFS.Path(@"c:\something")); + + var bytes = new UTF8Encoding(true).GetBytes(fileContent); + var stream = fileSystem.File.OpenWrite(filePath); + stream.Write(bytes, 0, bytes.Length); + stream.Dispose(); + + await That(fileSystem.FileExists(filePath)).IsTrue(); + await That(fileSystem.GetFile(filePath).TextContents).IsEqualTo(fileContent); + } + + [Test] + public async Task MockFile_OpenWrite_ShouldNotCreateFolders() + { + string filePath = XFS.Path(@"c:\something\demo.txt"); // c:\something does not exist: OpenWrite should fail + var fileSystem = new MockFileSystem(); + + await That(() => fileSystem.File.OpenWrite(filePath)).Throws(); + } + + [Test] + public async Task MockFile_OpenWrite_ShouldOverwriteExistingFiles() + { + string filePath = XFS.Path(@"c:\something\demo.txt"); + string startFileContent = "this is some content"; + string endFileContent = "this is some other content"; + var fileSystem = new MockFileSystem(new Dictionary + { + {filePath, new MockFileData(startFileContent)} + }); + + var bytes = new UTF8Encoding(true).GetBytes(endFileContent); + var stream = fileSystem.File.OpenWrite(filePath); + stream.Write(bytes, 0, bytes.Length); + stream.Dispose(); + + await That(fileSystem.FileExists(filePath)).IsTrue(); + await That(fileSystem.GetFile(filePath).TextContents).IsEqualTo(endFileContent); + } + + [Test] + public async Task MockFile_Delete_ShouldRemoveFileFromFileSystem() + { + string fullPath = XFS.Path(@"c:\something\demo.txt"); + var fileSystem = new MockFileSystem(new Dictionary + { + { fullPath, new MockFileData("Demo text content") } + }); + + var file = new MockFile(fileSystem); + + file.Delete(fullPath); + + await That(fileSystem.FileExists(fullPath)).IsFalse(); + } + + [Test] + public async Task MockFile_Delete_Should_RemoveFiles() + { + string filePath = XFS.Path(@"c:\something\demo.txt"); + string fileContent = "this is some content"; + var fileSystem = new MockFileSystem(new Dictionary { { filePath, new MockFileData(fileContent) } }); + await That(fileSystem.AllFiles.Count()).IsEqualTo(1); + fileSystem.File.Delete(filePath); + await That(fileSystem.AllFiles.Count()).IsEqualTo(0); + } + + [Test] + public async Task MockFile_Delete_No_File_Does_Nothing() + { + var fileSystem = new MockFileSystem(new Dictionary() + { + { XFS.Path(@"c:\something\exist.txt"), new MockFileData("Demo text content") }, + }); + + string filePath = XFS.Path(@"c:\something\not_exist.txt"); + + await That(() => fileSystem.File.Delete(filePath)).DoesNotThrow(); + } + + [Test] + public async Task MockFile_Delete_ShouldThrowUnauthorizedAccessException_WhenPathIsADirectory() + { + // Arrange + var fileSystem = new MockFileSystem(new Dictionary + { + { XFS.Path(@"c:\bar"), new MockDirectoryData() }, + }); + + // Act + Action action = () => fileSystem.File.Delete(XFS.Path(@"c:\bar")); + + // Assert + await That(action).Throws(); + } + + [Test] + public async Task MockFile_AppendText_AppendTextToAnExistingFile() + { + string filepath = XFS.Path(@"c:\something\does\exist.txt"); + var filesystem = new MockFileSystem(new Dictionary + { + { filepath, new MockFileData("I'm here. ") } + }); + + var stream = filesystem.File.AppendText(filepath); + + stream.Write("Me too!"); + stream.Flush(); + stream.Dispose(); + + var file = filesystem.GetFile(filepath); + await That(file.TextContents).IsEqualTo("I'm here. Me too!"); + } + + [Test] + public async Task MockFile_AppendText_CreatesNewFileForAppendToNonExistingFile() + { + string filepath = XFS.Path(@"c:\something\doesnt\exist.txt"); + var filesystem = new MockFileSystem(new Dictionary()); + filesystem.AddDirectory(XFS.Path(@"c:\something\doesnt")); + + var stream = filesystem.File.AppendText(filepath); + + stream.Write("New too!"); + stream.Flush(); + stream.Dispose(); + + var file = filesystem.GetFile(filepath); + await That(file.TextContents).IsEqualTo("New too!"); + await That(filesystem.FileExists(filepath)).IsTrue(); + } + +#if !NET9_0_OR_GREATER + [Test] + public void Serializable_works() + { + //Arrange + MockFileData data = new MockFileData("Text Contents"); + + //Act +#pragma warning disable SYSLIB0011 + IFormatter formatter = new BinaryFormatter(); + Stream stream = new MemoryStream(); + + formatter.Serialize(stream, data); +#pragma warning restore SYSLIB0011 + + //Assert + Assert.Pass(); + } +#endif + +#if !NET9_0_OR_GREATER + [Test] + public async Task Serializable_can_deserialize() + { + //Arrange + string textContentStr = "Text Contents"; + + //Act + MockFileData data = new MockFileData(textContentStr); + +#pragma warning disable SYSLIB0011 + IFormatter formatter = new BinaryFormatter(); + Stream stream = new MemoryStream(); + formatter.Serialize(stream, data); + + stream.Seek(0, SeekOrigin.Begin); + + MockFileData deserialized = (MockFileData)formatter.Deserialize(stream); +#pragma warning restore SYSLIB0011 + + //Assert + await That(deserialized.TextContents).IsEqualTo(textContentStr); + } +#endif + + [Test] + public async Task MockFile_Encrypt_ShouldSetEncryptedAttribute() + { + // Arrange + var fileData = new MockFileData("Demo text content"); + var filePath = XFS.Path(@"c:\a.txt"); + var fileSystem = new MockFileSystem(new Dictionary + { + {filePath, fileData } + }); + + // Act +#pragma warning disable CA1416 + fileSystem.File.Encrypt(filePath); +#pragma warning restore CA1416 + var attributes = fileSystem.File.GetAttributes(filePath); + + // Assert + await That(attributes & FileAttributes.Encrypted).IsEqualTo(FileAttributes.Encrypted); + } + + [Test] + public async Task MockFile_Decrypt_ShouldRemoveEncryptedAttribute() + { + // Arrange + const string Content = "Demo text content"; + var fileData = new MockFileData(Content); + var filePath = XFS.Path(@"c:\a.txt"); + var fileSystem = new MockFileSystem(new Dictionary + { + {filePath, fileData } + }); +#pragma warning disable CA1416 + fileSystem.File.Encrypt(filePath); +#pragma warning restore CA1416 + + // Act +#pragma warning disable CA1416 + fileSystem.File.Decrypt(filePath); +#pragma warning restore CA1416 + var attributes = fileSystem.File.GetAttributes(filePath); + + // Assert + await That(attributes & FileAttributes.Encrypted).IsNotEqualTo(FileAttributes.Encrypted); + } + + [Test] + public async Task MockFile_Replace_ShouldReplaceFileContents() + { + // Arrange + var fileSystem = new MockFileSystem(); + var path1 = XFS.Path(@"c:\temp\file1.txt"); + var path2 = XFS.Path(@"c:\temp\file2.txt"); + fileSystem.AddFile(path1, new MockFileData("1")); + fileSystem.AddFile(path2, new MockFileData("2")); + + // Act + fileSystem.File.Replace(path1, path2, null); + + await That(fileSystem.File.ReadAllText(path2)).IsEqualTo("1"); + } + + [Test] + public async Task MockFile_Replace_ShouldCreateBackup() + { + // Arrange + var fileSystem = new MockFileSystem(); + var path1 = XFS.Path(@"c:\temp\file1.txt"); + var path2 = XFS.Path(@"c:\temp\file2.txt"); + var path3 = XFS.Path(@"c:\temp\file3.txt"); + fileSystem.AddFile(path1, new MockFileData("1")); + fileSystem.AddFile(path2, new MockFileData("2")); + + // Act + fileSystem.File.Replace(path1, path2, path3); + + await That(fileSystem.File.ReadAllText(path3)).IsEqualTo("2"); + } + + [Test] + public async Task MockFile_Replace_ShouldThrowIfDirectoryOfBackupPathDoesNotExist() + { + // Arrange + var fileSystem = new MockFileSystem(); + var path1 = XFS.Path(@"c:\temp\file1.txt"); + var path2 = XFS.Path(@"c:\temp\file2.txt"); + var path3 = XFS.Path(@"c:\temp\subdirectory\file3.txt"); + fileSystem.AddFile(path1, new MockFileData("1")); + fileSystem.AddFile(path2, new MockFileData("2")); + + // Act + await That(() => fileSystem.File.Replace(path1, path2, path3)).Throws(); + } + + [Test] + public async Task MockFile_Replace_ShouldThrowIfSourceFileDoesNotExist() + { + // Arrange + var fileSystem = new MockFileSystem(); + var path1 = XFS.Path(@"c:\temp\file1.txt"); + var path2 = XFS.Path(@"c:\temp\file2.txt"); + fileSystem.AddFile(path2, new MockFileData("2")); + + await That(() => fileSystem.File.Replace(path1, path2, null)).Throws(); + } + + [Test] + public async Task MockFile_Replace_ShouldThrowIfDestinationFileDoesNotExist() + { + // Arrange + var fileSystem = new MockFileSystem(); + var path1 = XFS.Path(@"c:\temp\file1.txt"); + var path2 = XFS.Path(@"c:\temp\file2.txt"); + fileSystem.AddFile(path1, new MockFileData("1")); + + await That(() => fileSystem.File.Replace(path1, path2, null)).Throws(); + } + + [Test] + public async Task MockFile_OpenRead_ShouldReturnReadOnlyStream() + { + // Tests issue #230 + // Arrange + string filePath = XFS.Path(@"c:\something\demo.txt"); + string startContent = "hi there"; + var fileSystem = new MockFileSystem(new Dictionary + { + { filePath, new MockFileData(startContent) } + }); + + // Act + var stream = fileSystem.File.OpenRead(filePath); + + // Assert + await That(stream.CanWrite).IsFalse(); + await That(() => stream.WriteByte(0)).Throws(); + } + + [Test] + [WindowsOnly(WindowsSpecifics.Drives)] + public async Task MockFile_Replace_SourceAndDestinationDifferOnlyInCasing_ShouldThrowIOException() + { + var fileSystem = new MockFileSystem(); + string sourceFilePath = @"c:\temp\demo.txt"; + string destFilePath = @"c:\temp\DEMO.txt"; + string fileContent = "content"; + fileSystem.File.WriteAllText(sourceFilePath, fileContent); + + void Act() => fileSystem.File.Replace(sourceFilePath, destFilePath, null, true); + + await That(Act).Throws() + .HasMessage("The process cannot access the file because it is being used by another process."); + } +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileVersionInfoFactoryTests.cs b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileVersionInfoFactoryTests.cs new file mode 100644 index 000000000..e4573f0d1 --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileVersionInfoFactoryTests.cs @@ -0,0 +1,42 @@ +using NUnit.Framework; +using System.Collections.Generic; + +namespace System.IO.Abstractions.TestingHelpers.Tests; + +[TestFixture] +public class MockFileVersionInfoFactoryTests +{ + [Test] + public async Task MockFileVersionInfoFactory_GetVersionInfo_ShouldReturnTheFileVersionInfoOfTheMockFileData() + { + // Arrange + var fileVersionInfo = new MockFileVersionInfo(@"c:\a.txt"); + var fileSystem = new MockFileSystem(new Dictionary + { + { @"c:\a.txt", new MockFileData("Demo text content") { FileVersionInfo = fileVersionInfo } } + }); + + // Act + var result = fileSystem.FileVersionInfo.GetVersionInfo(@"c:\a.txt"); + + // Assert + await That(result).IsEqualTo(fileVersionInfo); + } + + [Test] + public async Task MockFileVersionInfoFactory_GetVersionInfo_ShouldThrowFileNotFoundExceptionIfFileDoesNotExist() + { + // Arrange + var fileSystem = new MockFileSystem(new Dictionary + { + { @"c:\a.txt", new MockFileData("Demo text content") }, + { @"c:\a\b\c.txt", new MockFileData("Demo text content") }, + }); + + // Act + Action code = () => fileSystem.FileVersionInfo.GetVersionInfo(@"c:\foo.txt"); + + // Assert + await That(code).Throws(); + } +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileVersionInfoTests.cs b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileVersionInfoTests.cs new file mode 100644 index 000000000..1a269df36 --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileVersionInfoTests.cs @@ -0,0 +1,85 @@ +using NUnit.Framework; + +namespace System.IO.Abstractions.TestingHelpers.Tests; + +[TestFixture] +public class MockFileVersionInfoTests +{ + [Test] + public async Task MockFileVersionInfo_ToString_ShouldReturnTheDefaultFormat() + { + // Arrange + var mockFileVersionInfo = new MockFileVersionInfo( + fileName: @"c:\b.txt", + fileVersion: "1.0.0.0", + productVersion: "1.0.0.0", + fileDescription: "b", + productName: "b", + companyName: null, + comments: null, + internalName: "b.txt", + isDebug: true, + isPatched: true, + isPrivateBuild: true, + isPreRelease: true, + isSpecialBuild: true, + language: "English", + legalCopyright: null, + legalTrademarks: null, + originalFilename: "b.txt", + privateBuild: null, + specialBuild: null); + + string expected = @"File: c:\b.txt +InternalName: b.txt +OriginalFilename: b.txt +FileVersion: 1.0.0.0 +FileDescription: b +Product: b +ProductVersion: 1.0.0.0 +Debug: True +Patched: True +PreRelease: True +PrivateBuild: True +SpecialBuild: True +Language: English +"; + + // Act & Assert + await That(mockFileVersionInfo.ToString()).IsEqualTo(expected); + } + + [Test] + public async Task MockFileVersionInfo_Constructor_ShouldSetFileAndProductVersionNumbersIfFileAndProductVersionAreNotNull() + { + // Arrange + var mockFileVersionInfo = new MockFileVersionInfo(@"c:\file.txt", fileVersion: "1.2.3.4", productVersion: "5.6.7.8"); + + // Assert + await That(mockFileVersionInfo.FileMajorPart).IsEqualTo(1); + await That(mockFileVersionInfo.FileMinorPart).IsEqualTo(2); + await That(mockFileVersionInfo.FileBuildPart).IsEqualTo(3); + await That(mockFileVersionInfo.FilePrivatePart).IsEqualTo(4); + await That(mockFileVersionInfo.ProductMajorPart).IsEqualTo(5); + await That(mockFileVersionInfo.ProductMinorPart).IsEqualTo(6); + await That(mockFileVersionInfo.ProductBuildPart).IsEqualTo(7); + await That(mockFileVersionInfo.ProductPrivatePart).IsEqualTo(8); + } + + [Test] + public async Task MockFileVersionInfo_Constructor_ShouldNotSetFileAndProductVersionNumbersIfFileAndProductVersionAreNull() + { + // Act + var mockFileVersionInfo = new MockFileVersionInfo(@"c:\a.txt"); + + // Assert + await That(mockFileVersionInfo.FileMajorPart).IsEqualTo(0); + await That(mockFileVersionInfo.FileMinorPart).IsEqualTo(0); + await That(mockFileVersionInfo.FileBuildPart).IsEqualTo(0); + await That(mockFileVersionInfo.FilePrivatePart).IsEqualTo(0); + await That(mockFileVersionInfo.ProductMajorPart).IsEqualTo(0); + await That(mockFileVersionInfo.ProductMinorPart).IsEqualTo(0); + await That(mockFileVersionInfo.ProductBuildPart).IsEqualTo(0); + await That(mockFileVersionInfo.ProductPrivatePart).IsEqualTo(0); + } +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileWriteAllBytesTests.cs b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileWriteAllBytesTests.cs new file mode 100644 index 000000000..76d9d6875 --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileWriteAllBytesTests.cs @@ -0,0 +1,204 @@ +using System.Collections.Generic; +using NUnit.Framework; +using XFS = System.IO.Abstractions.TestingHelpers.MockUnixSupport; +using System.Threading.Tasks; +using System.Threading; + +namespace System.IO.Abstractions.TestingHelpers.Tests; + +public class MockFileWriteAllBytesTests +{ + [Test] + public async Task MockFile_WriteAllBytes_ShouldThrowDirectoryNotFoundExceptionIfPathDoesNotExists() + { + var fileSystem = new MockFileSystem(); + string path = XFS.Path(@"c:\something\file.txt"); + var fileContent = new byte[] { 1, 2, 3, 4 }; + + Action action = () => fileSystem.File.WriteAllBytes(path, fileContent); + + await That(action).Throws(); + } + + [Test] + public async Task MockFile_WriteAllBytes_ShouldWriteDataToMemoryFileSystem() + { + string path = XFS.Path(@"c:\something\demo.txt"); + var fileSystem = new MockFileSystem(); + var fileContent = new byte[] { 1, 2, 3, 4 }; + fileSystem.AddDirectory(XFS.Path(@"c:\something")); + + fileSystem.File.WriteAllBytes(path, fileContent); + + await That(fileSystem.GetFile(path).Contents).IsEqualTo(fileContent); + } + + [Test] + public async Task MockFile_WriteAllBytes_ShouldThrowAnUnauthorizedAccessExceptionIfFileIsHidden() + { + string path = XFS.Path(@"c:\something\demo.txt"); + var fileSystem = new MockFileSystem(new Dictionary + { + { path, new MockFileData("this is hidden") }, + }); + fileSystem.File.SetAttributes(path, FileAttributes.Hidden); + + Action action = () => fileSystem.File.WriteAllBytes(path, new byte[] { 123 }); + + await That(action).Throws() + .Because($"Access to the path '{path}' is denied."); + } + + [Test] + [WindowsOnly(WindowsSpecifics.StrictPathRules)] + public async Task MockFile_WriteAllBytes_ShouldThrowAnArgumentExceptionIfContainsIllegalCharacters() + { + var fileSystem = new MockFileSystem(); + fileSystem.AddDirectory(XFS.Path(@"C:")); + + Action action = () => fileSystem.File.WriteAllBytes(XFS.Path(@"C:\a(); + } + + [Test] + public async Task MockFile_WriteAllBytes_ShouldThrowAnArgumentNullExceptionIfPathIsNull() + { + var fileSystem = new MockFileSystem(); + + Action action = () => fileSystem.File.WriteAllBytes(null, new byte[] { 123 }); + + await That(action).Throws(); + } + + [Test] + public async Task MockFile_WriteAllBytes_ShouldThrowAnArgumentNullExceptionIfBytesAreNull() + { + var fileSystem = new MockFileSystem(); + string path = XFS.Path(@"c:\something\demo.txt"); + + Action action = () => fileSystem.File.WriteAllBytes(path, null); + + var exception = await That(action).Throws(); + await That(exception.Message).StartsWith("Value cannot be null."); + await That(exception.ParamName).IsEqualTo("bytes"); + } + + [Test] + public async Task MockFile_WriteAllBytes_ShouldWriteASeparateCopyToTheFileSystem() + { + var fileSystem = new MockFileSystem(); + string path = XFS.Path(@"c:\something\file.bin"); + fileSystem.AddDirectory(XFS.Path(@"c:\something")); + var fileContent = new byte[] { 1, 2, 3, 4 }; + + fileSystem.File.WriteAllBytes(path, fileContent); + + for(int i = 0; i < fileContent.Length; i++) + { + fileContent[i] += 1; + } + + var readAgain = fileSystem.File.ReadAllBytes(path); + + await That(fileContent).IsNotEqualTo(readAgain); + } + + +#if FEATURE_ASYNC_FILE + [Test] + public async Task MockFile_WriteAllBytesAsync_ShouldThrowDirectoryNotFoundExceptionIfPathDoesNotExists() + { + var fileSystem = new MockFileSystem(); + string path = XFS.Path(@"c:\something\file.txt"); + var fileContent = new byte[] { 1, 2, 3, 4 }; + + Func action = () => fileSystem.File.WriteAllBytesAsync(path, fileContent); + + await That(action).Throws(); + } + + [Test] + public async Task MockFile_WriteAllTextAsync_ShouldThrowOperationCanceledExceptionIfCancelled() + { + // Arrange + const string path = "test.txt"; + var fileSystem = new MockFileSystem(); + + // Act + async Task Act() => + await fileSystem.File.WriteAllTextAsync( + path, + "content", + new CancellationToken(canceled: true)); + await That(Act).Throws(); + + // Assert + await That(fileSystem.File.Exists(path)).IsFalse(); + } + + [Test] + public async Task MockFile_WriteAllBytesAsync_ShouldWriteDataToMemoryFileSystem() + { + string path = XFS.Path(@"c:\something\demo.txt"); + var fileSystem = new MockFileSystem(); + var fileContent = new byte[] { 1, 2, 3, 4 }; + fileSystem.AddDirectory(XFS.Path(@"c:\something")); + + await fileSystem.File.WriteAllBytesAsync(path, fileContent); + + await That(fileSystem.GetFile(path).Contents).IsEqualTo(fileContent); + } + + [Test] + public async Task MockFile_WriteAllBytesAsync_ShouldThrowAnUnauthorizedAccessExceptionIfFileIsHidden() + { + string path = XFS.Path(@"c:\something\demo.txt"); + var fileSystem = new MockFileSystem(new Dictionary + { + { path, new MockFileData("this is hidden") }, + }); + fileSystem.File.SetAttributes(path, FileAttributes.Hidden); + + Func action = () => fileSystem.File.WriteAllBytesAsync(path, new byte[] { 123 }); + + await That(action).Throws() + .Because($"Access to the path '{path}' is denied."); + } + + [Test] + [WindowsOnly(WindowsSpecifics.StrictPathRules)] + public async Task MockFile_WriteAllBytesAsync_ShouldThrowAnArgumentExceptionIfContainsIllegalCharacters() + { + var fileSystem = new MockFileSystem(); + fileSystem.AddDirectory(XFS.Path(@"C:")); + + Func action = () => fileSystem.File.WriteAllBytesAsync(XFS.Path(@"C:\a(); + } + + [Test] + public async Task MockFile_WriteAllBytesAsync_ShouldThrowAnArgumentNullExceptionIfPathIsNull() + { + var fileSystem = new MockFileSystem(); + + Func action = () => fileSystem.File.WriteAllBytesAsync(null, new byte[] { 123 }); + + await That(action).Throws(); + } + + [Test] + public async Task MockFile_WriteAllBytesAsync_ShouldThrowAnArgumentNullExceptionIfBytesAreNull() + { + var fileSystem = new MockFileSystem(); + string path = XFS.Path(@"c:\something\demo.txt"); + + Func action = () => fileSystem.File.WriteAllBytesAsync(path, null); + + var exception = await That(action).Throws(); + await That(exception.Message).StartsWith("Value cannot be null."); + await That(exception.ParamName).IsEqualTo("bytes"); + } +#endif +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileWriteAllLinesTests.cs b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileWriteAllLinesTests.cs new file mode 100644 index 000000000..1ff9eef6d --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileWriteAllLinesTests.cs @@ -0,0 +1,613 @@ +using System.Collections; +using System.Collections.Generic; +using System.Globalization; +using System.Text; +using System.Threading; +using NUnit.Framework; +using XFS = System.IO.Abstractions.TestingHelpers.MockUnixSupport; + +namespace System.IO.Abstractions.TestingHelpers.Tests; + +public class MockFileWriteAllLinesTests +{ + private class TestDataForWriteAllLines + { + public static readonly string Path = XFS.Path(@"c:\something\demo.txt"); + + public static IEnumerable ForDifferentEncoding + { + get + { + var fileSystem = new MockFileSystem(); + fileSystem.AddDirectory(XFS.Path(@"c:\something")); + var fileContentEnumerable = new List { "first line", "second line", "third line", "fourth and last line" }; + var fileContentArray = fileContentEnumerable.ToArray(); + Action writeEnumerable = () => fileSystem.File.WriteAllLines(Path, fileContentEnumerable); + Action writeEnumerableUtf32 = () => fileSystem.File.WriteAllLines(Path, fileContentEnumerable, Encoding.UTF32); + Action writeArray = () => fileSystem.File.WriteAllLines(Path, fileContentArray); + Action writeArrayUtf32 = () => fileSystem.File.WriteAllLines(Path, fileContentArray, Encoding.UTF32); + var expectedContent = string.Format(CultureInfo.InvariantCulture, + "first line{0}second line{0}third line{0}fourth and last line{0}", Environment.NewLine); + + // IEnumerable + yield return new TestCaseData(fileSystem, writeEnumerable, expectedContent) + .SetName("WriteAllLines(string, IEnumerable)"); + yield return new TestCaseData(fileSystem, writeEnumerableUtf32, expectedContent) + .SetName("WriteAllLines(string, IEnumerable, Encoding.UTF32)"); + + // string[] + yield return new TestCaseData(fileSystem, writeArray, expectedContent) + .SetName("WriteAllLines(string, string[])"); + yield return new TestCaseData(fileSystem, writeArrayUtf32, expectedContent) + .SetName("WriteAllLines(string, string[], Encoding.UTF32)"); + } + } + + public static IEnumerable ForIllegalPath + { + get + { + const string illegalPath = "<<<"; + return GetCasesForArgumentChecking(illegalPath); + } + } + + public static IEnumerable ForNullPath + { + get + { + const string illegalPath = null; + return GetCasesForArgumentChecking(illegalPath); + } + } + + private static IEnumerable GetCasesForArgumentChecking(string path) + { + var fileSystem = new MockFileSystem(); + var fileContentEnumerable = new List(); + var fileContentArray = fileContentEnumerable.ToArray(); + Action writeEnumerable = () => fileSystem.File.WriteAllLines(path, fileContentEnumerable); + Action writeEnumerableUtf32 = () => fileSystem.File.WriteAllLines(path, fileContentEnumerable, Encoding.UTF32); + Action writeArray = () => fileSystem.File.WriteAllLines(path, fileContentArray); + Action writeArrayUtf32 = () => fileSystem.File.WriteAllLines(path, fileContentArray, Encoding.UTF32); + + // IEnumerable + yield return new TestCaseData(writeEnumerable) + .SetName("WriteAllLines(string, IEnumerable) input: " + path); + yield return new TestCaseData(writeEnumerableUtf32) + .SetName("WriteAllLines(string, IEnumerable, Encoding.UTF32) input: " + path); + + // string[] + yield return new TestCaseData(writeArray) + .SetName("WriteAllLines(string, string[]) input: " + path); + yield return new TestCaseData(writeArrayUtf32) + .SetName("WriteAllLines(string, string[], Encoding.UTF32) input: " + path); + } + + private static IEnumerable ForNullEncoding + { + get + { + var fileSystem = new MockFileSystem(); + var fileContentEnumerable = new List(); + var fileContentArray = fileContentEnumerable.ToArray(); + Action writeEnumerableNull = () => fileSystem.File.WriteAllLines(Path, fileContentEnumerable, null); + Action writeArrayNull = () => fileSystem.File.WriteAllLines(Path, fileContentArray, null); + + // IEnumerable + yield return new TestCaseData(writeEnumerableNull) + .SetName("WriteAllLines(string, IEnumerable, Encoding.UTF32)"); + + // string[] + yield return new TestCaseData(writeArrayNull) + .SetName("WriteAllLines(string, string[], Encoding.UTF32)"); + } + } + + public static IEnumerable ForPathIsDirectory + { + get + { + var fileSystem = new MockFileSystem(); + var path = XFS.Path(@"c:\something"); + fileSystem.Directory.CreateDirectory(path); + var fileContentEnumerable = new List(); + var fileContentArray = fileContentEnumerable.ToArray(); + Action writeEnumerable = () => fileSystem.File.WriteAllLines(path, fileContentEnumerable); + Action writeEnumerableUtf32 = () => fileSystem.File.WriteAllLines(path, fileContentEnumerable, Encoding.UTF32); + Action writeArray = () => fileSystem.File.WriteAllLines(path, fileContentArray); + Action writeArrayUtf32 = () => fileSystem.File.WriteAllLines(path, fileContentArray, Encoding.UTF32); + + // IEnumerable + yield return new TestCaseData(writeEnumerable, path) + .SetName("WriteAllLines(string, IEnumerable)"); + yield return new TestCaseData(writeEnumerableUtf32, path) + .SetName("WriteAllLines(string, IEnumerable, Encoding.UTF32)"); + + // string[] + yield return new TestCaseData(writeArray, path) + .SetName("WriteAllLines(string, string[])"); + yield return new TestCaseData(writeArrayUtf32, path) + .SetName("WriteAllLines(string, string[], Encoding.UTF32)"); + } + } + + public static IEnumerable ForFileIsReadOnly + { + get + { + var fileSystem = new MockFileSystem(); + var path = XFS.Path(@"c:\something\file.txt"); + var mockFileData = new MockFileData(string.Empty); + mockFileData.Attributes = FileAttributes.ReadOnly; + fileSystem.AddFile(path, mockFileData); + var fileContentEnumerable = new List(); + var fileContentArray = fileContentEnumerable.ToArray(); + Action writeEnumerable = () => fileSystem.File.WriteAllLines(path, fileContentEnumerable); + Action writeEnumerableUtf32 = () => fileSystem.File.WriteAllLines(path, fileContentEnumerable, Encoding.UTF32); + Action writeArray = () => fileSystem.File.WriteAllLines(path, fileContentArray); + Action writeArrayUtf32 = () => fileSystem.File.WriteAllLines(path, fileContentArray, Encoding.UTF32); + + // IEnumerable + yield return new TestCaseData(writeEnumerable, path) + .SetName("WriteAllLines(string, IEnumerable)"); + yield return new TestCaseData(writeEnumerableUtf32, path) + .SetName("WriteAllLines(string, IEnumerable, Encoding.UTF32)"); + + // string[] + yield return new TestCaseData(writeArray, path) + .SetName("WriteAllLines(string, string[])"); + yield return new TestCaseData(writeArrayUtf32, path) + .SetName("WriteAllLines(string, string[], Encoding.UTF32)"); + } + } + + public static IEnumerable ForContentsIsNull + { + get + { + var fileSystem = new MockFileSystem(); + var path = XFS.Path(@"c:\something\file.txt"); + var mockFileData = new MockFileData(string.Empty); + mockFileData.Attributes = FileAttributes.ReadOnly; + fileSystem.AddDirectory(XFS.Path(@"c:\something")); + fileSystem.AddFile(path, mockFileData); + List fileContentEnumerable = null; + string[] fileContentArray = null; + + // ReSharper disable ExpressionIsAlwaysNull + Action writeEnumerable = () => fileSystem.File.WriteAllLines(path, fileContentEnumerable); + Action writeEnumerableUtf32 = () => fileSystem.File.WriteAllLines(path, fileContentEnumerable, Encoding.UTF32); + Action writeArray = () => fileSystem.File.WriteAllLines(path, fileContentArray); + Action writeArrayUtf32 = () => fileSystem.File.WriteAllLines(path, fileContentArray, Encoding.UTF32); + // ReSharper restore ExpressionIsAlwaysNull + + // IEnumerable + yield return new TestCaseData(writeEnumerable) + .SetName("WriteAllLines(string, IEnumerable)"); + yield return new TestCaseData(writeEnumerableUtf32) + .SetName("WriteAllLines(string, IEnumerable, Encoding.UTF32)"); + + // string[] + yield return new TestCaseData(writeArray) + .SetName("WriteAllLines(string, string[])"); + yield return new TestCaseData(writeArrayUtf32) + .SetName("WriteAllLines(string, string[], Encoding.UTF32)"); + } + } + +#if FEATURE_ASYNC_FILE + public static IEnumerable ForDifferentEncodingAsync + { + get + { + var fileSystem = new MockFileSystem(); + fileSystem.AddDirectory(XFS.Path(@"c:\something")); + var fileContentEnumerable = new List { "first line", "second line", "third line", "fourth and last line" }; + var fileContentArray = fileContentEnumerable.ToArray(); + Action writeEnumberable = () => fileSystem.File.WriteAllLinesAsync(Path, fileContentEnumerable); + Action writeEnumberableUtf32 = () => fileSystem.File.WriteAllLinesAsync(Path, fileContentEnumerable, Encoding.UTF32); + Action writeArray = () => fileSystem.File.WriteAllLinesAsync(Path, fileContentArray); + Action writeArrayUtf32 = () => fileSystem.File.WriteAllLinesAsync(Path, fileContentArray, Encoding.UTF32); + var expectedContent = string.Format(CultureInfo.InvariantCulture, + "first line{0}second line{0}third line{0}fourth and last line{0}", Environment.NewLine); + + // IEnumerable + yield return new TestCaseData(fileSystem, writeEnumberable, expectedContent) + .SetName("WriteAllLinesAsync(string, IEnumerable)"); + yield return new TestCaseData(fileSystem, writeEnumberableUtf32, expectedContent) + .SetName("WriteAllLinesAsync(string, IEnumerable, Encoding.UTF32)"); + + // string[] + yield return new TestCaseData(fileSystem, writeArray, expectedContent) + .SetName("WriteAllLinesAsync(string, string[])"); + yield return new TestCaseData(fileSystem, writeArrayUtf32, expectedContent) + .SetName("WriteAllLinesAsync(string, string[], Encoding.UTF32)"); + } + } + + public static IEnumerable ForIllegalPathAsync + { + get + { + const string illegalPath = "<<<"; + return GetCasesForArgumentCheckingAsync(illegalPath); + } + } + + public static IEnumerable ForNullPathAsync + { + get + { + const string illegalPath = null; + return GetCasesForArgumentCheckingAsync(illegalPath); + } + } + + private static IEnumerable GetCasesForArgumentCheckingAsync(string path) + { + var fileSystem = new MockFileSystem(); + var fileContentEnumerable = new List(); + var fileContentArray = fileContentEnumerable.ToArray(); + Func writeEnumberable = () => fileSystem.File.WriteAllLinesAsync(path, fileContentEnumerable); + Func writeEnumberableUtf32 = () => fileSystem.File.WriteAllLinesAsync(path, fileContentEnumerable, Encoding.UTF32); + Func writeArray = () => fileSystem.File.WriteAllLinesAsync(path, fileContentArray); + Func writeArrayUtf32 = () => fileSystem.File.WriteAllLinesAsync(path, fileContentArray, Encoding.UTF32); + + // IEnumerable + yield return new TestCaseData(writeEnumberable) + .SetName("WriteAllLinesAsync(string, IEnumerable) input: " + path); + yield return new TestCaseData(writeEnumberableUtf32) + .SetName("WriteAllLinesAsync(string, IEnumerable, Encoding.UTF32) input: " + path); + + // string[] + yield return new TestCaseData(writeArray) + .SetName("WriteAllLinesAsync(string, string[]) input: " + path); + yield return new TestCaseData(writeArrayUtf32) + .SetName("WriteAllLinesAsync(string, string[], Encoding.UTF32) input: " + path); + } + + private static IEnumerable ForNullEncodingAsync + { + get + { + var fileSystem = new MockFileSystem(); + var fileContentEnumerable = new List(); + var fileContentArray = fileContentEnumerable.ToArray(); + Func writeEnumberableNull = () => fileSystem.File.WriteAllLinesAsync(Path, fileContentEnumerable, null); + Func writeArrayNull = () => fileSystem.File.WriteAllLinesAsync(Path, fileContentArray, null); + + // IEnumerable + yield return new TestCaseData(writeEnumberableNull) + .SetName("WriteAllLinesAsync(string, IEnumerable, Encoding.UTF32)"); + + // string[] + yield return new TestCaseData(writeArrayNull) + .SetName("WriteAllLinesAsync(string, string[], Encoding.UTF32)"); + } + } + + public static IEnumerable ForPathIsDirectoryAsync + { + get + { + var fileSystem = new MockFileSystem(); + var path = XFS.Path(@"c:\something"); + fileSystem.Directory.CreateDirectory(path); + var fileContentEnumerable = new List(); + var fileContentArray = fileContentEnumerable.ToArray(); + Func writeEnumberable = () => fileSystem.File.WriteAllLinesAsync(path, fileContentEnumerable); + Func writeEnumberableUtf32 = () => fileSystem.File.WriteAllLinesAsync(path, fileContentEnumerable, Encoding.UTF32); + Func writeArray = () => fileSystem.File.WriteAllLinesAsync(path, fileContentArray); + Func writeArrayUtf32 = () => fileSystem.File.WriteAllLinesAsync(path, fileContentArray, Encoding.UTF32); + + // IEnumerable + yield return new TestCaseData(writeEnumberable, path) + .SetName("WriteAllLinesAsync(string, IEnumerable)"); + yield return new TestCaseData(writeEnumberableUtf32, path) + .SetName("WriteAllLinesAsync(string, IEnumerable, Encoding.UTF32)"); + + // string[] + yield return new TestCaseData(writeArray, path) + .SetName("WriteAllLinesAsync(string, string[])"); + yield return new TestCaseData(writeArrayUtf32, path) + .SetName("WriteAllLinesAsync(string, string[], Encoding.UTF32)"); + } + } + + public static IEnumerable ForFileIsReadOnlyAsync + { + get + { + var fileSystem = new MockFileSystem(); + var path = XFS.Path(@"c:\something\file.txt"); + var mockFileData = new MockFileData(string.Empty); + mockFileData.Attributes = FileAttributes.ReadOnly; + fileSystem.AddFile(path, mockFileData); + var fileContentEnumerable = new List(); + var fileContentArray = fileContentEnumerable.ToArray(); + Func writeEnumberable = () => fileSystem.File.WriteAllLinesAsync(path, fileContentEnumerable); + Func writeEnumberableUtf32 = () => fileSystem.File.WriteAllLinesAsync(path, fileContentEnumerable, Encoding.UTF32); + Func writeArray = () => fileSystem.File.WriteAllLinesAsync(path, fileContentArray); + Func writeArrayUtf32 = () => fileSystem.File.WriteAllLinesAsync(path, fileContentArray, Encoding.UTF32); + + // IEnumerable + yield return new TestCaseData(writeEnumberable, path) + .SetName("WriteAllLinesAsync(string, IEnumerable)"); + yield return new TestCaseData(writeEnumberableUtf32, path) + .SetName("WriteAllLinesAsync(string, IEnumerable, Encoding.UTF32)"); + + // string[] + yield return new TestCaseData(writeArray, path) + .SetName("WriteAllLinesAsync(string, string[])"); + yield return new TestCaseData(writeArrayUtf32, path) + .SetName("WriteAllLinesAsync(string, string[], Encoding.UTF32)"); + } + } + + public static IEnumerable ForContentsIsNullAsync + { + get + { + var fileSystem = new MockFileSystem(); + var path = XFS.Path(@"c:\something\file.txt"); + var mockFileData = new MockFileData(string.Empty); + mockFileData.Attributes = FileAttributes.ReadOnly; + fileSystem.AddDirectory(XFS.Path(@"c:\something")); + fileSystem.AddFile(path, mockFileData); + List fileContentEnumerable = null; + string[] fileContentArray = null; + + // ReSharper disable ExpressionIsAlwaysNull + Func writeEnumberable = () => fileSystem.File.WriteAllLinesAsync(path, fileContentEnumerable); + Func writeEnumberableUtf32 = () => fileSystem.File.WriteAllLinesAsync(path, fileContentEnumerable, Encoding.UTF32); + Func writeArray = () => fileSystem.File.WriteAllLinesAsync(path, fileContentArray); + Func writeArrayUtf32 = () => fileSystem.File.WriteAllLinesAsync(path, fileContentArray, Encoding.UTF32); + // ReSharper restore ExpressionIsAlwaysNull + + // IEnumerable + yield return new TestCaseData(writeEnumberable) + .SetName("WriteAllLinesAsync(string, IEnumerable)"); + yield return new TestCaseData(writeEnumberableUtf32) + .SetName("WriteAllLinesAsync(string, IEnumerable, Encoding.UTF32)"); + + // string[] + yield return new TestCaseData(writeArray) + .SetName("WriteAllLinesAsync(string, string[])"); + yield return new TestCaseData(writeArrayUtf32) + .SetName("WriteAllLinesAsync(string, string[], Encoding.UTF32)"); + } + } + + [Test] + public async Task MockFile_WriteAllLinesAsync_ShouldThrowOperationCanceledExceptionIfCancelled() + { + // Arrange + const string path = "test.txt"; + var fileSystem = new MockFileSystem(); + + // Act + async Task Act() => + await fileSystem.File.WriteAllLinesAsync( + path, + new[] { "line 1", "line 2" }, + new CancellationToken(canceled: true)); + await That(Act).Throws(); + + // Assert + await That(fileSystem.File.Exists(path)).IsFalse(); + } +#endif + + } + + [TestCaseSource(typeof(TestDataForWriteAllLines), nameof(TestDataForWriteAllLines.ForDifferentEncoding))] + public async Task MockFile_WriteAllLinesGeneric_ShouldWriteTheCorrectContent(IMockFileDataAccessor fileSystem, Action action, string expectedContent) + { + // Arrange + // is done in the test case source + + // Act + action(); + + // Assert + var actualContent = fileSystem.GetFile(TestDataForWriteAllLines.Path).TextContents; + await That(actualContent).IsEqualTo(expectedContent); + } + + [TestCaseSource(typeof(TestDataForWriteAllLines), nameof(TestDataForWriteAllLines.ForNullPath))] + public async Task MockFile_WriteAllLinesGeneric_ShouldThrowAnArgumentNullExceptionIfPathIsNull(Action action) + { + // Arrange + // is done in the test case source + + // Act + // is done in the test case source + + // Assert + var exception = await That(action).Throws(); + await That(exception.Message).StartsWith("Value cannot be null."); + await That(exception.ParamName).StartsWith("path"); + } + + [TestCaseSource(typeof(TestDataForWriteAllLines), "ForNullEncoding")] + public async Task MockFile_WriteAllLinesGeneric_ShouldThrowAnArgumentNullExceptionIfEncodingIsNull(Action action) + { + // Arrange + // is done in the test case source + + // Act + // is done in the test case source + + // Assert + var exception = await That(action).Throws(); + await That(exception.Message).StartsWith("Value cannot be null."); + await That(exception.ParamName).StartsWith("encoding"); + } + + [TestCaseSource(typeof(TestDataForWriteAllLines), nameof(TestDataForWriteAllLines.ForIllegalPath))] + [WindowsOnly(WindowsSpecifics.StrictPathRules)] + public async Task MockFile_WriteAllLinesGeneric_ShouldThrowAnArgumentExceptionIfPathContainsIllegalCharacters(Action action) + { + // Arrange + // is done in the test case source + + // Act + // is done in the test case source + + // Assert + var exception = await That(action).Throws(); + await That(exception.Message).IsEqualTo("Illegal characters in path."); + } + + [TestCaseSource(typeof(TestDataForWriteAllLines), nameof(TestDataForWriteAllLines.ForPathIsDirectory))] + public async Task MockFile_WriteAllLinesGeneric_ShouldThrowAnUnauthorizedAccessExceptionIfPathIsOneDirectory(Action action, string path) + { + // Arrange + // is done in the test case source + + // Act + // is done in the test case source + + // Assert + var exception = await That(action).Throws(); + var expectedMessage = string.Format(CultureInfo.InvariantCulture, "Access to the path '{0}' is denied.", path); + await That(exception.Message).IsEqualTo(expectedMessage); + } + + [TestCaseSource(typeof(TestDataForWriteAllLines), nameof(TestDataForWriteAllLines.ForFileIsReadOnly))] + public async Task MockFile_WriteAllLinesGeneric_ShouldThrowOneUnauthorizedAccessExceptionIfFileIsReadOnly(Action action, string path) + { + // Arrange + // is done in the test case source + + // Act + // is done in the test case source + + // Assert + var exception = await That(action).Throws(); + var expectedMessage = string.Format(CultureInfo.InvariantCulture, "Access to the path '{0}' is denied.", path); + await That(exception.Message).IsEqualTo(expectedMessage); + } + + [TestCaseSource(typeof(TestDataForWriteAllLines), nameof(TestDataForWriteAllLines.ForContentsIsNull))] + public async Task MockFile_WriteAllLinesGeneric_ShouldThrowAnArgumentNullExceptionIfContentsIsNull(Action action) + { + // Arrange + // is done in the test case source + + // Act + // is done in the test case sourceForContentsIsNull + + // Assert + var exception = await That(action).Throws(); + await That(exception.Message).StartsWith("Value cannot be null."); + await That(exception.ParamName).IsEqualTo("contents"); + } + +#if FEATURE_ASYNC_FILE + [TestCaseSource(typeof(TestDataForWriteAllLines), nameof(TestDataForWriteAllLines.ForDifferentEncodingAsync))] + public async Task MockFile_WriteAllLinesAsyncGeneric_ShouldWriteTheCorrectContent(IMockFileDataAccessor fileSystem, Action action, string expectedContent) + { + // Arrange + // is done in the test case source + + // Act + action(); + + // Assert + var actualContent = fileSystem.GetFile(TestDataForWriteAllLines.Path).TextContents; + await That(actualContent).IsEqualTo(expectedContent); + } + + [TestCaseSource(typeof(TestDataForWriteAllLines), nameof(TestDataForWriteAllLines.ForNullPathAsync))] + public async Task MockFile_WriteAllLinesAsyncGeneric_ShouldThrowAnArgumentNullExceptionIfPathIsNull(Func action) + { + // Arrange + // is done in the test case source + + // Act + // is done in the test case source + + // Assert + var exception = await That(action).Throws(); + await That(exception.Message).StartsWith("Value cannot be null."); + await That(exception.ParamName).StartsWith("path"); + } + + [TestCaseSource(typeof(TestDataForWriteAllLines), "ForNullEncodingAsync")] + public async Task MockFile_WriteAllLinesAsyncGeneric_ShouldThrowAnArgumentNullExceptionIfEncodingIsNull(Func action) + { + // Arrange + // is done in the test case source + + // Act + // is done in the test case source + + // Assert + var exception = await That(action).Throws(); + await That(exception.Message).StartsWith("Value cannot be null."); + await That(exception.ParamName).StartsWith("encoding"); + } + + [TestCaseSource(typeof(TestDataForWriteAllLines), nameof(TestDataForWriteAllLines.ForIllegalPathAsync))] + [WindowsOnly(WindowsSpecifics.StrictPathRules)] + public async Task MockFile_WriteAllLinesAsyncGeneric_ShouldThrowAnArgumentExceptionIfPathContainsIllegalCharacters(Func action) + { + // Arrange + // is done in the test case source + + // Act + // is done in the test case source + + // Assert + var exception = await That(action).Throws(); + await That(exception.Message).IsEqualTo("Illegal characters in path."); + } + + [TestCaseSource(typeof(TestDataForWriteAllLines), nameof(TestDataForWriteAllLines.ForPathIsDirectoryAsync))] + public async Task MockFile_WriteAllLinesAsyncGeneric_ShouldThrowAnUnauthorizedAccessExceptionIfPathIsOneDirectory(Func action, string path) + { + // Arrange + // is done in the test case source + + // Act + // is done in the test case source + + // Assert + var exception = await That(action).Throws(); + var expectedMessage = string.Format(CultureInfo.InvariantCulture, "Access to the path '{0}' is denied.", path); + await That(exception.Message).IsEqualTo(expectedMessage); + } + + [TestCaseSource(typeof(TestDataForWriteAllLines), nameof(TestDataForWriteAllLines.ForFileIsReadOnlyAsync))] + public async Task MockFile_WriteAllLinesAsyncGeneric_ShouldThrowOneUnauthorizedAccessExceptionIfFileIsReadOnly(Func action, string path) + { + // Arrange + // is done in the test case source + + // Act + // is done in the test case source + + // Assert + var exception = await That(action).Throws(); + var expectedMessage = string.Format(CultureInfo.InvariantCulture, "Access to the path '{0}' is denied.", path); + await That(exception.Message).IsEqualTo(expectedMessage); + } + + [TestCaseSource(typeof(TestDataForWriteAllLines), nameof(TestDataForWriteAllLines.ForContentsIsNullAsync))] + public async Task MockFile_WriteAllLinesAsyncGeneric_ShouldThrowAnArgumentNullExceptionIfContentsIsNull(Func action) + { + // Arrange + // is done in the test case source + + // Act + // is done in the test case sourceForContentsIsNull + + // Assert + var exception = await That(action).Throws(); + await That(exception.Message).StartsWith("Value cannot be null."); + await That(exception.ParamName).IsEqualTo("contents"); + } +#endif +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileWriteAllTextTests.cs b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileWriteAllTextTests.cs new file mode 100644 index 000000000..5cd2cd64c --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileWriteAllTextTests.cs @@ -0,0 +1,412 @@ +namespace System.IO.Abstractions.TestingHelpers.Tests; + +using Collections.Generic; + +using NUnit.Framework; + +using Text; + +using XFS = MockUnixSupport; + +using System.Threading.Tasks; +using System.Threading; + +public class MockFileWriteAllTextTests +{ + [Test] + public async Task MockFile_WriteAllText_ShouldWriteTextFileToMemoryFileSystem() + { + // Arrange + string path = XFS.Path(@"c:\something\demo.txt"); + string fileContent = "Hello there!"; + var fileSystem = new MockFileSystem(); + fileSystem.AddDirectory(XFS.Path(@"c:\something")); + + // Act + fileSystem.File.WriteAllText(path, fileContent); + + // Assert + await That(fileSystem.GetFile(path).TextContents).IsEqualTo(fileContent); + } + + [Test] + public async Task MockFile_WriteAllText_ShouldOverwriteAnExistingFile() + { + // http://msdn.microsoft.com/en-us/library/ms143375.aspx + + // Arrange + string path = XFS.Path(@"c:\something\demo.txt"); + var fileSystem = new MockFileSystem(); + fileSystem.AddDirectory(XFS.Path(@"c:\something")); + + // Act + fileSystem.File.WriteAllText(path, "foo"); + fileSystem.File.WriteAllText(path, "bar"); + + // Assert + await That(fileSystem.GetFile(path).TextContents).IsEqualTo("bar"); + } + + [Test] + public async Task MockFile_WriteAllText_ShouldThrowAnUnauthorizedAccessExceptionIfFileIsHidden() + { + // Arrange + string path = XFS.Path(@"c:\something\demo.txt"); + var fileSystem = new MockFileSystem(new Dictionary + { + { path, new MockFileData("this is hidden") }, + }); + fileSystem.File.SetAttributes(path, FileAttributes.Hidden); + + // Act + Action action = () => fileSystem.File.WriteAllText(path, "hello world"); + + // Assert + await That(action).Throws() + .Because($"Access to the path '{path}' is denied."); + } + + [Test] + public async Task MockFile_WriteAllText_ShouldThrowAnArgumentExceptionIfThePathIsEmpty() + { + // Arrange + var fileSystem = new MockFileSystem(); + + // Act + Action action = () => fileSystem.File.WriteAllText(string.Empty, "hello world"); + + // Assert + await That(action).Throws(); + } + + [Test] + public async Task MockFile_WriteAllText_ShouldNotThrowAnArgumentNullExceptionIfTheContentIsNull() + { + // Arrange + var fileSystem = new MockFileSystem(); + string directoryPath = XFS.Path(@"c:\something"); + string filePath = XFS.Path(@"c:\something\demo.txt"); + fileSystem.AddDirectory(directoryPath); + + // Act + fileSystem.File.WriteAllText(filePath, null); + + // Assert + // no exception should be thrown, also the documentation says so + var data = fileSystem.GetFile(filePath); + await That(data.Contents).IsEmpty(); + } + + [Test] + public async Task MockFile_WriteAllText_ShouldThrowAnUnauthorizedAccessExceptionIfTheFileIsReadOnly() + { + // Arrange + var fileSystem = new MockFileSystem(); + string filePath = XFS.Path(@"c:\something\demo.txt"); + var mockFileData = new MockFileData(new byte[0]); + mockFileData.Attributes = FileAttributes.ReadOnly; + fileSystem.AddFile(filePath, mockFileData); + + // Act + Action action = () => fileSystem.File.WriteAllText(filePath, null); + + // Assert + await That(action).Throws(); + } + + [Test] + public async Task MockFile_WriteAllText_ShouldThrowAnUnauthorizedAccessExceptionIfThePathIsOneDirectory() + { + // Arrange + var fileSystem = new MockFileSystem(); + string directoryPath = XFS.Path(@"c:\something"); + fileSystem.AddDirectory(directoryPath); + + // Act + Action action = () => fileSystem.File.WriteAllText(directoryPath, null); + + // Assert + await That(action).Throws(); + } + + [Test] + public async Task MockFile_WriteAllText_ShouldThrowDirectoryNotFoundExceptionIfPathDoesNotExists() + { + // Arrange + var fileSystem = new MockFileSystem(); + string path = XFS.Path(@"c:\something\file.txt"); + + // Act + Action action = () => fileSystem.File.WriteAllText(path, string.Empty); + + // Assert + await That(action).Throws(); + } + + public static IEnumerable> GetEncodingsWithExpectedBytes() + { + Encoding utf8WithoutBom = new UTF8Encoding(false, true); + return new Dictionary + { + // ASCII does not need a BOM + { Encoding.ASCII, new byte[] { 72, 101, 108, 108, 111, 32, 116, + 104, 101, 114, 101, 33, 32, 68, 122, 105, 63, 107, 105, 46 } }, + + // BigEndianUnicode needs a BOM, the BOM is the first two bytes + { Encoding.BigEndianUnicode, new byte [] { 254, 255, 0, 72, 0, 101, + 0, 108, 0, 108, 0, 111, 0, 32, 0, 116, 0, 104, 0, 101, 0, 114, + 0, 101, 0, 33, 0, 32, 0, 68, 0, 122, 0, 105, 1, 25, 0, 107, 0, 105, 0, 46 } }, + + // UTF-32 needs a BOM, the BOM is the first four bytes + { Encoding.UTF32, new byte [] {255, 254, 0, 0, 72, 0, 0, 0, 101, + 0, 0, 0, 108, 0, 0, 0, 108, 0, 0, 0, 111, 0, 0, 0, 32, 0, 0, + 0, 116, 0, 0, 0, 104, 0, 0, 0, 101, 0, 0, 0, 114, 0, 0, 0, + 101, 0, 0, 0, 33, 0, 0, 0, 32, 0, 0, 0, 68, 0, 0, 0, 122, 0, + 0, 0, 105, 0, 0, 0, 25, 1, 0, 0, 107, 0, 0, 0, 105, 0, 0, 0, 46, 0, 0, 0 } }, + +#pragma warning disable SYSLIB0001 + // UTF-7 does not need a BOM + { Encoding.UTF7, new byte [] {72, 101, 108, 108, 111, 32, 116, + 104, 101, 114, 101, 43, 65, 67, 69, 45, 32, 68, 122, 105, + 43, 65, 82, 107, 45, 107, 105, 46 } }, +#pragma warning restore SYSLIB0001 + + // The default encoding does not need a BOM + { utf8WithoutBom, new byte [] { 72, 101, 108, 108, 111, 32, 116, + 104, 101, 114, 101, 33, 32, 68, 122, 105, 196, 153, 107, 105, 46 } }, + + // Unicode needs a BOM, the BOM is the first two bytes + { Encoding.Unicode, new byte [] { 255, 254, 72, 0, 101, 0, 108, + 0, 108, 0, 111, 0, 32, 0, 116, 0, 104, 0, 101, 0, 114, 0, + 101, 0, 33, 0, 32, 0, 68, 0, 122, 0, 105, 0, 25, 1, 107, 0, + 105, 0, 46, 0 } } + }; + } + + [TestCaseSource(typeof(MockFileWriteAllTextTests), nameof(GetEncodingsWithExpectedBytes))] + public async Task MockFile_WriteAllText_Encoding_ShouldWriteTextFileToMemoryFileSystem(KeyValuePair encodingsWithContents) + { + // Arrange + const string FileContent = "Hello there! Dzięki."; + string path = XFS.Path(@"c:\something\demo.txt"); + byte[] expectedBytes = encodingsWithContents.Value; + Encoding encoding = encodingsWithContents.Key; + var fileSystem = new MockFileSystem(); + fileSystem.AddDirectory(XFS.Path(@"c:\something")); + + // Act + fileSystem.File.WriteAllText(path, FileContent, encoding); + + // Assert + var actualBytes = fileSystem.GetFile(path).Contents; + await That(actualBytes).IsEqualTo(expectedBytes); + } + + [Test] + public async Task MockFile_WriteAllTextMultipleLines_ShouldWriteTextFileToMemoryFileSystem() + { + // Arrange + string path = XFS.Path(@"c:\something\demo.txt"); + + var fileContent = new List { "Hello there!", "Second line!" }; + var expected = "Hello there!" + Environment.NewLine + "Second line!" + Environment.NewLine; + + var fileSystem = new MockFileSystem(); + fileSystem.AddDirectory(XFS.Path(@"c:\something")); + + // Act + fileSystem.File.WriteAllLines(path, fileContent); + + // Assert + await That(fileSystem.GetFile(path).TextContents).IsEqualTo(expected); + } + +#if FEATURE_ASYNC_FILE + [Test] + public async Task MockFile_WriteAllTextAsync_ShouldWriteTextFileToMemoryFileSystem() + { + // Arrange + string path = XFS.Path(@"c:\something\demo.txt"); + string fileContent = "Hello there!"; + var fileSystem = new MockFileSystem(); + fileSystem.AddDirectory(XFS.Path(@"c:\something")); + + // Act + await fileSystem.File.WriteAllTextAsync(path, fileContent); + + // Assert + await That(fileSystem.GetFile(path).TextContents).IsEqualTo(fileContent); + } + + [Test] + public async Task MockFile_WriteAllTextAsync_ShouldThrowOperationCanceledExceptionIfCancelled() + { + // Arrange + const string path = "test.txt"; + var fileSystem = new MockFileSystem(); + + // Act + async Task Act() => + await fileSystem.File.WriteAllTextAsync( + path, + "line", + new CancellationToken(canceled: true)); + await That(Act).Throws(); + + // Assert + await That(fileSystem.File.Exists(path)).IsFalse(); + } + + [Test] + public async Task MockFile_WriteAllTextAsync_ShouldOverriteAnExistingFile() + { + // http://msdn.microsoft.com/en-us/library/ms143375.aspx + + // Arrange + string path = XFS.Path(@"c:\something\demo.txt"); + var fileSystem = new MockFileSystem(); + fileSystem.AddDirectory(XFS.Path(@"c:\something")); + + // Act + await fileSystem.File.WriteAllTextAsync(path, "foo"); + await fileSystem.File.WriteAllTextAsync(path, "bar"); + + // Assert + await That(fileSystem.GetFile(path).TextContents).IsEqualTo("bar"); + } + + [Test] + public async Task MockFile_WriteAllTextAsync_ShouldThrowAnUnauthorizedAccessExceptionIfFileIsHidden() + { + // Arrange + string path = XFS.Path(@"c:\something\demo.txt"); + var fileSystem = new MockFileSystem(new Dictionary + { + { path, new MockFileData("this is hidden") }, + }); + fileSystem.File.SetAttributes(path, FileAttributes.Hidden); + + // Act + Func action = () => fileSystem.File.WriteAllTextAsync(path, "hello world"); + + // Assert + await That(action).Throws() + .Because($"Access to the path '{path}' is denied."); + } + + [Test] + public async Task MockFile_WriteAllTextAsync_ShouldThrowAnArgumentExceptionIfThePathIsEmpty() + { + // Arrange + var fileSystem = new MockFileSystem(); + + // Act + Func action = () => fileSystem.File.WriteAllTextAsync(string.Empty, "hello world"); + + // Assert + await That(action).Throws(); + } + + [Test] + public async Task MockFile_WriteAllTextAsync_ShouldNotThrowAnArgumentNullExceptionIfTheContentIsNull() + { + // Arrange + var fileSystem = new MockFileSystem(); + string directoryPath = XFS.Path(@"c:\something"); + string filePath = XFS.Path(@"c:\something\demo.txt"); + fileSystem.AddDirectory(directoryPath); + + // Act + await fileSystem.File.WriteAllTextAsync(filePath, ""); + + // Assert + // no exception should be thrown, also the documentation says so + var data = fileSystem.GetFile(filePath); + await That(data.Contents).IsEmpty(); + } + + [Test] + public async Task MockFile_WriteAllTextAsync_ShouldThrowAnUnauthorizedAccessExceptionIfTheFileIsReadOnly() + { + // Arrange + var fileSystem = new MockFileSystem(); + string filePath = XFS.Path(@"c:\something\demo.txt"); + var mockFileData = new MockFileData(new byte[0]); + mockFileData.Attributes = FileAttributes.ReadOnly; + fileSystem.AddFile(filePath, mockFileData); + + // Act + Func action = () => fileSystem.File.WriteAllTextAsync(filePath, ""); + + // Assert + await That(action).Throws(); + } + + [Test] + public async Task MockFile_WriteAllTextAsync_ShouldThrowAnUnauthorizedAccessExceptionIfThePathIsOneDirectory() + { + // Arrange + var fileSystem = new MockFileSystem(); + string directoryPath = XFS.Path(@"c:\something"); + fileSystem.AddDirectory(directoryPath); + + // Act + Func action = () => fileSystem.File.WriteAllTextAsync(directoryPath, ""); + + // Assert + await That(action).Throws(); + } + + [Test] + public async Task MockFile_WriteAllTextAsync_ShouldThrowDirectoryNotFoundExceptionIfPathDoesNotExists() + { + // Arrange + var fileSystem = new MockFileSystem(); + string path = XFS.Path(@"c:\something\file.txt"); + + // Act + Func action = () => fileSystem.File.WriteAllTextAsync(path, string.Empty); + + // Assert + await That(action).Throws(); + } + + [TestCaseSource(typeof(MockFileWriteAllTextTests), nameof(GetEncodingsWithExpectedBytes))] + public async Task MockFile_WriteAllTextAsync_Encoding_ShouldWriteTextFileToMemoryFileSystem(KeyValuePair encodingsWithContents) + { + // Arrange + const string FileContent = "Hello there! Dzięki."; + string path = XFS.Path(@"c:\something\demo.txt"); + byte[] expectedBytes = encodingsWithContents.Value; + Encoding encoding = encodingsWithContents.Key; + var fileSystem = new MockFileSystem(); + fileSystem.AddDirectory(XFS.Path(@"c:\something")); + + // Act + await fileSystem.File.WriteAllTextAsync(path, FileContent, encoding); + + // Assert + var actualBytes = fileSystem.GetFile(path).Contents; + await That(actualBytes).IsEqualTo(expectedBytes); + } + + [Test] + public async Task MockFile_WriteAllTextAsyncMultipleLines_ShouldWriteTextFileToMemoryFileSystem() + { + // Arrange + string path = XFS.Path(@"c:\something\demo.txt"); + + var fileContent = new List { "Hello there!", "Second line!" }; + var expected = "Hello there!" + Environment.NewLine + "Second line!" + Environment.NewLine; + + var fileSystem = new MockFileSystem(); + fileSystem.AddDirectory(XFS.Path(@"c:\something")); + + // Act + await fileSystem.File.WriteAllLinesAsync(path, fileContent); + + // Assert + await That(fileSystem.GetFile(path).TextContents).IsEqualTo(expected); + } +#endif +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockPathTests.cs b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockPathTests.cs new file mode 100644 index 000000000..e614de495 --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockPathTests.cs @@ -0,0 +1,652 @@ +using NUnit.Framework; +using System.Collections.Generic; + +namespace System.IO.Abstractions.TestingHelpers.Tests; + +using XFS = MockUnixSupport; + +public class MockPathTests +{ + static readonly string TestPath = XFS.Path("C:\\test\\test.bmp"); + + [Test] + public async Task ChangeExtension_ExtensionNoPeriod_PeriodAdded() + { + //Arrange + var mockPath = new MockPath(new MockFileSystem()); + + //Act + var result = mockPath.ChangeExtension(TestPath, "doc"); + + //Assert + await That(result).IsEqualTo(XFS.Path("C:\\test\\test.doc")); + } + + [Test] + public async Task Combine_SentTwoPaths_Combines() + { + //Arrange + var mockPath = new MockPath(new MockFileSystem()); + + //Act + var result = mockPath.Combine(XFS.Path("C:\\test"), "test.bmp"); + + //Assert + await That(result).IsEqualTo(XFS.Path("C:\\test\\test.bmp")); + } + + [Test] + public async Task Combine_SentThreePaths_Combines() + { + //Arrange + var mockPath = new MockPath(new MockFileSystem()); + + //Act + var result = mockPath.Combine(XFS.Path("C:\\test"), "subdir1", "test.bmp"); + + //Assert + await That(result).IsEqualTo(XFS.Path("C:\\test\\subdir1\\test.bmp")); + } + + [Test] + public async Task Combine_SentFourPaths_Combines() + { + //Arrange + var mockPath = new MockPath(new MockFileSystem()); + + //Act + var result = mockPath.Combine(XFS.Path("C:\\test"), "subdir1", "subdir2", "test.bmp"); + + //Assert + await That(result).IsEqualTo(XFS.Path("C:\\test\\subdir1\\subdir2\\test.bmp")); + } + + [Test] + public async Task Combine_SentFivePaths_Combines() + { + //Arrange + var mockPath = new MockPath(new MockFileSystem()); + + //Act + var result = mockPath.Combine(XFS.Path("C:\\test"), "subdir1", "subdir2", "subdir3", "test.bmp"); + + //Assert + await That(result).IsEqualTo(XFS.Path("C:\\test\\subdir1\\subdir2\\subdir3\\test.bmp")); + } + + [Test] + public async Task GetDirectoryName_SentPath_ReturnsDirectory() + { + //Arrange + var mockPath = new MockPath(new MockFileSystem()); + + //Act + var result = mockPath.GetDirectoryName(TestPath); + + //Assert + await That(result).IsEqualTo(XFS.Path("C:\\test")); + } + + [Test] + public async Task GetExtension_SendInPath_ReturnsExtension() + { + //Arrange + var mockPath = new MockPath(new MockFileSystem()); + + //Act + var result = mockPath.GetExtension(TestPath); + + //Assert + await That(result).IsEqualTo(".bmp"); + } + + [Test] + public async Task GetFileName_SendInPath_ReturnsFilename() + { + //Arrange + var mockPath = new MockPath(new MockFileSystem()); + + //Act + var result = mockPath.GetFileName(TestPath); + + //Assert + await That(result).IsEqualTo("test.bmp"); + } + + [Test] + public async Task GetFileNameWithoutExtension_SendInPath_ReturnsFileNameNoExt() + { + //Arrange + var mockPath = new MockPath(new MockFileSystem()); + + //Act + var result = mockPath.GetFileNameWithoutExtension(TestPath); + + //Assert + await That(result).IsEqualTo("test"); + } + + [Test] + public async Task GetFullPath_SendInPath_ReturnsFullPath() + { + //Arrange + var mockPath = new MockPath(new MockFileSystem()); + + //Act + var result = mockPath.GetFullPath(TestPath); + + //Assert + await That(result).IsEqualTo(TestPath); + } + + public static IEnumerable GetFullPath_RelativePaths_Cases + { + get + { + yield return new[] { XFS.Path(@"c:\a"), "b", XFS.Path(@"c:\a\b") }; + yield return new[] { XFS.Path(@"c:\a\b"), "c", XFS.Path(@"c:\a\b\c") }; + yield return new[] { XFS.Path(@"c:\a\b"), XFS.Path(@"c\"), XFS.Path(@"c:\a\b\c\") }; + yield return new[] { XFS.Path(@"c:\a\b"), XFS.Path(@"..\c"), XFS.Path(@"c:\a\c") }; + yield return new[] { XFS.Path(@"c:\a\b\c"), XFS.Path(@"..\c\..\"), XFS.Path(@"c:\a\b\") }; + yield return new[] { XFS.Path(@"c:\a\b\c"), XFS.Path(@"..\..\..\..\..\d"), XFS.Path(@"c:\d") }; + yield return new[] { XFS.Path(@"c:\a\b\c"), XFS.Path(@"..\..\..\..\..\d\"), XFS.Path(@"c:\d\") }; + } + } + + [TestCaseSource(nameof(GetFullPath_RelativePaths_Cases))] + public async Task GetFullPath_RelativePaths_ShouldReturnTheAbsolutePathWithCurrentDirectory(string currentDir, string relativePath, string expectedResult) + { + //Arrange + var mockFileSystem = new MockFileSystem(); + mockFileSystem.Directory.SetCurrentDirectory(currentDir); + var mockPath = new MockPath(mockFileSystem); + + //Act + var actualResult = mockPath.GetFullPath(relativePath); + + //Assert + await That(actualResult).IsEqualTo(expectedResult); + } + + public static IEnumerable GetFullPath_RootedPathWithRelativeSegments_Cases + { + get + { + yield return new[] { XFS.Path(@"c:\a\b\..\c"), XFS.Path(@"c:\a\c") }; + yield return new[] { XFS.Path(@"c:\a\b\.\.\..\.\c"), XFS.Path(@"c:\a\c") }; + yield return new[] { XFS.Path(@"c:\a\b\.\c"), XFS.Path(@"c:\a\b\c") }; + yield return new[] { XFS.Path(@"c:\a\b\.\.\.\.\c"), XFS.Path(@"c:\a\b\c") }; + yield return new[] { XFS.Path(@"c:\a\..\..\c"), XFS.Path(@"c:\c") }; + } + } + + [TestCaseSource(nameof(GetFullPath_RootedPathWithRelativeSegments_Cases))] + public async Task GetFullPath_RootedPathWithRelativeSegments_ShouldReturnAnRootedAbsolutePath(string rootedPath, string expectedResult) + { + //Arrange + var mockFileSystem = new MockFileSystem(); + var mockPath = new MockPath(mockFileSystem); + + //Act + var actualResult = mockPath.GetFullPath(rootedPath); + + //Assert + await That(actualResult).IsEqualTo(expectedResult); + } + + public static IEnumerable GetFullPath_AbsolutePaths_Cases + { + get + { + yield return new[] { XFS.Path(@"c:\a"), XFS.Path(@"/b"), XFS.Path(@"c:\b") }; + yield return new[] { XFS.Path(@"c:\a"), XFS.Path(@"/b\"), XFS.Path(@"c:\b\") }; + yield return new[] { XFS.Path(@"c:\a"), XFS.Path(@"\b"), XFS.Path(@"c:\b") }; + yield return new[] { XFS.Path(@"c:\a"), XFS.Path(@"\b\..\c"), XFS.Path(@"c:\c") }; + yield return new[] { XFS.Path(@"z:\a"), XFS.Path(@"\b\..\c"), XFS.Path(@"z:\c") }; + yield return new[] { XFS.Path(@"z:\a"), XFS.Path(@"\\computer\share\c"), XFS.Path(@"\\computer\share\c") }; + yield return new[] { XFS.Path(@"z:\a"), XFS.Path(@"\\computer\share\c\..\d"), XFS.Path(@"\\computer\share\d") }; + yield return new[] { XFS.Path(@"z:\a"), XFS.Path(@"\\computer\share\c\..\..\d"), XFS.Path(@"\\computer\share\d") }; + } + } + + [TestCaseSource(nameof(GetFullPath_AbsolutePaths_Cases))] + public async Task GetFullPath_AbsolutePaths_ShouldReturnThePathWithTheRoot_Or_Unc(string currentDir, string absolutePath, string expectedResult) + { + //Arrange + var mockFileSystem = new MockFileSystem(); + mockFileSystem.Directory.SetCurrentDirectory(currentDir); + var mockPath = new MockPath(mockFileSystem); + + //Act + var actualResult = mockPath.GetFullPath(absolutePath); + + //Assert + await That(actualResult).IsEqualTo(expectedResult); + } + + [Test] + public async Task GetFullPath_InvalidUNCPaths_ShouldThrowArgumentException() + { + //Arrange + var mockFileSystem = new MockFileSystem(); + var mockPath = new MockPath(mockFileSystem); + + //Act + Action action = () => mockPath.GetFullPath(XFS.Path(@"\\shareZ")); + + //Assert + await That(action).Throws(); + } + + [Test] + public async Task GetFullPath_NullValue_ShouldThrowArgumentNullException() + { + //Arrange + var mockFileSystem = new MockFileSystem(); + var mockPath = new MockPath(mockFileSystem); + + //Act + Action action = () => mockPath.GetFullPath(null); + + //Assert + await That(action).Throws(); + } + + [Test] + public async Task GetFullPath_EmptyValue_ShouldThrowArgumentException() + { + //Arrange + var mockFileSystem = new MockFileSystem(); + var mockPath = new MockPath(mockFileSystem); + + //Act + Action action = () => mockPath.GetFullPath(string.Empty); + + //Assert + await That(action).Throws(); + } + + [Test] + public async Task GetFullPath_WithWhiteSpace_ShouldThrowArgumentException() + { + var mockFileSystem = new MockFileSystem(); + + Action action = () => mockFileSystem.Path.GetFullPath(" "); + + await That(action).Throws(); + } + + [Test] + public async Task GetFullPath_WithMultipleDirectorySeparators_ShouldReturnTheNormalizedForm() + { + //Arrange + var mockFileSystem = new MockFileSystem(); + var mockPath = new MockPath(mockFileSystem); + + //Act + var actualFullPath = mockPath.GetFullPath(XFS.Path(@"c:\foo\\//bar\file.dat")); + + //Assert + await That(actualFullPath).IsEqualTo(XFS.Path(@"c:\foo\bar\file.dat")); + } + + [Test] + public async Task GetInvalidFileNameChars_Called_ReturnsChars() + { + //Arrange + var mockPath = new MockPath(new MockFileSystem()); + + //Act + var result = mockPath.GetInvalidFileNameChars(); + + //Assert + await That(result.Length > 0).IsTrue(); + } + + [Test] + public async Task GetInvalidPathChars_Called_ReturnsChars() + { + //Arrange + var mockPath = new MockPath(new MockFileSystem()); + + //Act + var result = mockPath.GetInvalidPathChars(); + + //Assert + await That(result.Length > 0).IsTrue(); + } + + [Test] + public async Task GetPathRoot_SendInPath_ReturnsRoot() + { + //Arrange + var mockPath = new MockPath(new MockFileSystem()); + + //Act + var result = mockPath.GetPathRoot(TestPath); + + //Assert + await That(result).IsEqualTo(XFS.Path("C:\\")); + } + + [Test] + public async Task GetRandomFileName_Called_ReturnsStringLengthGreaterThanZero() + { + //Arrange + var mockPath = new MockPath(new MockFileSystem()); + + //Act + var result = mockPath.GetRandomFileName(); + + //Assert + await That(result.Length > 0).IsTrue(); + } + + [Test] + public async Task GetTempFileName_Called_ReturnsStringLengthGreaterThanZero() + { + //Arrange + var mockPath = new MockPath(new MockFileSystem()); + + //Act + var result = mockPath.GetTempFileName(); + + //Assert + await That(result.Length > 0).IsTrue(); + } + + [Test] + public async Task GetTempFileName_Called_CreatesEmptyFileInTempDirectory() + { + //Arrange + var fileSystem = new MockFileSystem(); + var mockPath = new MockPath(fileSystem); + + //Act + var result = mockPath.GetTempFileName(); + + await That(fileSystem.FileExists(result)).IsTrue(); + await That(fileSystem.FileInfo.New(result).Length).IsEqualTo(0); + } + + [Test] + public async Task GetTempPath_Called_ReturnsStringLengthGreaterThanZero() + { + //Arrange + var mockPath = new MockPath(new MockFileSystem()); + + //Act + var result = mockPath.GetTempPath(); + + //Assert + await That(result.Length > 0).IsTrue(); + } + + [Test] + public async Task GetTempPath_ShouldEndWithDirectorySeparator() + { + //Arrange + var mockPath = new MockFileSystem().Path; + var directorySeparator = mockPath.DirectorySeparatorChar.ToString(); + + //Act + var result = mockPath.GetTempPath(); + + //Assert + await That(result).EndsWith(directorySeparator); + } + + [Test] + [TestCase(null)] + [TestCase("")] + [TestCase(@"C:\temp")] + public async Task GetTempPath_Called_ReturnsStringLengthGreaterThanZero(string tempDirectory) + { + //Arrange + var mockPath = new MockPath(new MockFileSystem(), string.IsNullOrEmpty(tempDirectory) ? tempDirectory : XFS.Path(tempDirectory)); + + //Act + var result = mockPath.GetTempPath(); + + //Assert + await That(result.Length > 0).IsTrue(); + } + + [Test] + public async Task GetTempPath_Called_WithNonNullVirtualTempDirectory_ReturnsVirtualTempDirectory() + { + //Arrange + var tempDirectory = XFS.Path(@"C:\temp"); + + var mockPath = new MockPath(new MockFileSystem(), tempDirectory); + + //Act + var result = mockPath.GetTempPath(); + + //Assert + await That(result).IsEqualTo(tempDirectory); + } + + [Test] + [TestCase(null)] + [TestCase("")] + public async Task GetTempPath_Called_WithNullOrEmptyVirtualTempDirectory_ReturnsFallbackTempDirectory(string tempDirectory) + { + //Arrange + var mockPath = new MockPath(new MockFileSystem(), tempDirectory); + + //Act + var result = mockPath.GetTempPath(); + + //Assert + await That(result.Length > 0).IsTrue(); + } + + [Test] + public async Task HasExtension_PathSentIn_DeterminesExtension() + { + //Arrange + var mockPath = new MockPath(new MockFileSystem()); + + //Act + var result = mockPath.HasExtension(TestPath); + + //Assert + await That(result).IsTrue(); + } + + [Test] + public async Task IsPathRooted_PathSentIn_DeterminesPathExists() + { + //Arrange + var mockPath = new MockPath(new MockFileSystem()); + + //Act + var result = mockPath.IsPathRooted(TestPath); + + //Assert + await That(result).IsTrue(); + } + +#if FEATURE_ADVANCED_PATH_OPERATIONS + [Test] + public async Task IsPathFullyQualified_WithAbsolutePath_ReturnsTrue() + { + //Arrange + var mockPath = new MockPath(new MockFileSystem()); + + //Act + var result = mockPath.IsPathFullyQualified(XFS.Path("C:\\directory\\file.txt")); + + //Assert + await That(result).IsTrue(); + } + + [Test] + public async Task IsPathFullyQualified_WithRelativePath_ReturnsFalse() + { + //Arrange + var mockPath = new MockPath(new MockFileSystem()); + + //Act + var result = mockPath.IsPathRooted(XFS.Path("directory\\file.txt")); + + //Assert + await That(result).IsFalse(); + } + + [Test] + public async Task IsPathFullyQualified_WithRelativePathParts_ReturnsFalse() + { + //Arrange + var mockPath = new MockPath(new MockFileSystem()); + + //Act + var result = mockPath.IsPathRooted(XFS.Path("directory\\..\\file.txt")); + + //Assert + await That(result).IsFalse(); + } + + [Test] + public async Task GetRelativePath_Works() + { + //Arrange + var mockPath = new MockPath(new MockFileSystem()); + + //Act + var result = mockPath.GetRelativePath(XFS.Path("c:\\d"), XFS.Path("c:\\d\\e\\f.txt")); + + //Assert + await That(result).IsEqualTo(XFS.Path("e\\f.txt")); + } + + [Test] + public async Task GetRelativePath_WhenPathIsNull_ShouldThrowArgumentNullException() + { + var mockPath = new MockFileSystem().Path; + + var exception = await That(() => + { + mockPath.GetRelativePath("foo", null); + }).Throws(); + + await That(exception.ParamName).IsEqualTo("path"); + } + + [Test] + public async Task GetRelativePath_WhenPathIsWhitespace_ShouldThrowArgumentException() + { + var mockPath = new MockFileSystem().Path; + + var exception = await That(() => + { + mockPath.GetRelativePath("foo", " "); + }).Throws(); + + await That(exception.ParamName).IsEqualTo("path"); + } + + [Test] + public async Task GetRelativePath_WhenRelativeToNull_ShouldThrowArgumentNullException() + { + var mockPath = new MockFileSystem().Path; + + var exception = await That(() => + { + mockPath.GetRelativePath(null, "foo"); + }).Throws(); + + await That(exception.ParamName).IsEqualTo("relativeTo"); + } + + [Test] + public async Task GetRelativePath_WhenRelativeToIsWhitespace_ShouldThrowArgumentException() + { + var mockPath = new MockFileSystem().Path; + + var exception = await That(() => + { + mockPath.GetRelativePath(" ", "foo"); + }).Throws(); + + await That(exception.ParamName).IsEqualTo("relativeTo"); + } +#endif + +#if FEATURE_PATH_EXISTS + [Test] + public async Task Exists_Null_ShouldReturnFalse() + { + var fileSystem = new MockFileSystem(); + bool result = fileSystem.Path.Exists(null); + + await That(result).IsFalse(); + } + + [Test] + public async Task Exists_ShouldWorkWithAbsolutePaths() + { + var fileSystem = new MockFileSystem(); + string path = "some-path"; + string absolutePath = fileSystem.Path.GetFullPath(path); + fileSystem.Directory.CreateDirectory(path); + + bool result = fileSystem.Path.Exists(absolutePath); + + await That(result).IsTrue(); + } + + [Test] + public async Task Exists_ExistingFile_ShouldReturnTrue() + { + var fileSystem = new MockFileSystem(); + string path = "some-path"; + fileSystem.File.WriteAllText(path, "some content"); + + bool result = fileSystem.Path.Exists(path); + + await That(result).IsTrue(); + } + + [Test] + public async Task Exists_ExistingDirectory_ShouldReturnTrue() + { + var fileSystem = new MockFileSystem(); + string path = "some-path"; + fileSystem.Directory.CreateDirectory(path); + + bool result = fileSystem.Path.Exists(path); + + await That(result).IsTrue(); + } + + [Test] + public async Task Exists_ExistingFileOrDirectory_ShouldReturnTrue() + { + var fileSystem = new MockFileSystem(); + string path = "some-path"; + bool result = fileSystem.Path.Exists(path); + + await That(result).IsFalse(); + } +#endif + +#if FEATURE_ADVANCED_PATH_OPERATIONS + [Test] + public async Task GetRelativePath_ShouldUseCurrentDirectoryFromMockFileSystem() + { + var fs = new MockFileSystem(); + + fs.AddDirectory("input"); + fs.AddDirectory("output"); + fs.Directory.SetCurrentDirectory("input"); + + fs.AddFile("input/a.txt", "foo"); + + var result = fs.Path.GetRelativePath("/input", "a.txt"); + + await That(result).IsEqualTo("a.txt"); + } +#endif +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockUnixSupportTests.cs b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockUnixSupportTests.cs new file mode 100644 index 000000000..9f17d8567 --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockUnixSupportTests.cs @@ -0,0 +1,23 @@ +using NUnit.Framework; + +namespace System.IO.Abstractions.TestingHelpers.Tests; + +using XFS = MockUnixSupport; + +[TestFixture] +public class MockUnixSupportTests +{ + [Test] + [UnixOnly(UnixSpecifics.SlashRoot)] + public async Task Should_Convert_Backslashes_To_Slashes_On_Unix() + { + await That(XFS.Path(@"\test\")).IsEqualTo("/test/"); + } + + [Test] + [UnixOnly(UnixSpecifics.SlashRoot)] + public async Task Should_Remove_Drive_Letter_On_Unix() + { + await That(XFS.Path(@"c:\test\")).IsEqualTo("/test/"); + } +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/Polyfills/SupportedOSPlatformAttribute.cs b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/Polyfills/SupportedOSPlatformAttribute.cs new file mode 100644 index 000000000..ef6635b4f --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/Polyfills/SupportedOSPlatformAttribute.cs @@ -0,0 +1,12 @@ +#if !FEATURE_SUPPORTED_OS_ATTRIBUTE +namespace System.Runtime.Versioning +{ + [AttributeUsage(AttributeTargets.All)] + internal class SupportedOSPlatformAttribute : Attribute + { + public SupportedOSPlatformAttribute(string _) + { + } + } +} +#endif diff --git a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/ProductVersionParserTests.cs b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/ProductVersionParserTests.cs new file mode 100644 index 000000000..967c08498 --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/ProductVersionParserTests.cs @@ -0,0 +1,103 @@ +using NUnit.Framework; + +namespace System.IO.Abstractions.TestingHelpers.Tests; + +[TestFixture] +public class ProductVersionParserTests +{ + [Test] + public async Task ProductVersionParser_Parse_ShouldIgnoreTheSegmentsWhenThereAreMoreThanFiveOfThem() + { + // Arrange + string productVersion = "1.2.3.4.5"; + + // Act + var versionInfo = new MockFileVersionInfo("foo", productVersion: productVersion); + + // Assert + await ThatAll( + That(versionInfo.ProductMajorPart).IsEqualTo(0), + That(versionInfo.ProductMinorPart).IsEqualTo(0), + That(versionInfo.ProductBuildPart).IsEqualTo(0), + That(versionInfo.ProductPrivatePart).IsEqualTo(0) + ); + } + + [Test] + [TestCase("test.2.3.4", 0, 0, 0, 0)] + [TestCase("1.test.3.4", 1, 0, 0, 0)] + [TestCase("1.2.test.4", 1, 2, 0, 0)] + [TestCase("1.2.3.test", 1, 2, 3, 0)] + public async Task ProductVersionParser_Parse_ShouldSkipTheRestOfTheSegmentsWhenOneIsNotValidNumber( + string productVersion, + int expectedMajor, + int expectedMinor, + int expectedBuild, + int expectedRevision) + { + // Act + var versionInfo = new MockFileVersionInfo("foo", productVersion: productVersion); + + // Assert + await ThatAll( + That(versionInfo.ProductMajorPart).IsEqualTo(expectedMajor), + That(versionInfo.ProductMinorPart).IsEqualTo(expectedMinor), + That(versionInfo.ProductBuildPart).IsEqualTo(expectedBuild), + That(versionInfo.ProductPrivatePart).IsEqualTo(expectedRevision) + ); + } + + [Test] + [TestCase("1-test.2.3.4", 1, 0, 0, 0)] + [TestCase("1-test5.2.3.4", 1, 0, 0, 0)] + [TestCase("1.2-test.3.4", 1, 2, 0, 0)] + [TestCase("1.2-test5.3.4", 1, 2, 0, 0)] + [TestCase("1.2.3-test.4", 1, 2, 3, 0)] + [TestCase("1.2.3-test5.4", 1, 2, 3, 0)] + [TestCase("1.2.3.4-test", 1, 2, 3, 4)] + [TestCase("1.2.3.4-test5", 1, 2, 3, 4)] + public async Task ProductVersionParser_Parse_ShouldSkipTheRestOfTheSegmentsWhenOneContainsMoreThanJustOneNumber( + string productVersion, + int expectedMajor, + int expectedMinor, + int expectedBuild, + int expectedRevision) + { + // Act + var versionInfo = new MockFileVersionInfo("foo", productVersion: productVersion); + + // Assert + + await ThatAll( + That(versionInfo.ProductMajorPart).IsEqualTo(expectedMajor), + That(versionInfo.ProductMinorPart).IsEqualTo(expectedMinor), + That(versionInfo.ProductBuildPart).IsEqualTo(expectedBuild), + That(versionInfo.ProductPrivatePart).IsEqualTo(expectedRevision) + ); + } + + [Test] + [TestCase("", 0, 0, 0, 0)] + [TestCase("1", 1, 0, 0, 0)] + [TestCase("1.2", 1, 2, 0, 0)] + [TestCase("1.2.3", 1, 2, 3, 0)] + [TestCase("1.2.3.4", 1, 2, 3, 4)] + public async Task ProductVersionParser_Parse_ShouldParseEachProvidedSegment( + string productVersion, + int expectedMajor, + int expectedMinor, + int expectedBuild, + int expectedRevision) + { + // Act + var versionInfo = new MockFileVersionInfo("foo", productVersion: productVersion); + + // Assert + await ThatAll( + That(versionInfo.ProductMajorPart).IsEqualTo(expectedMajor), + That(versionInfo.ProductMinorPart).IsEqualTo(expectedMinor), + That(versionInfo.ProductBuildPart).IsEqualTo(expectedBuild), + That(versionInfo.ProductPrivatePart).IsEqualTo(expectedRevision) + ); + } +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/Shared.cs b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/Shared.cs new file mode 100644 index 000000000..78b5ce51f --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/Shared.cs @@ -0,0 +1,20 @@ +namespace System.IO.Abstractions.TestingHelpers.Tests; + +internal static class Shared +{ + /// + /// These chars are not valid path chars but do not cause the same + /// errors that other Path.GetInvalidFileNameChars() will. + /// + public static char[] SpecialInvalidPathChars(IFileSystem fileSystem) => new[] + { + // These are not allowed in a file name, but + // inserting them a path does not make it invalid + fileSystem.Path.DirectorySeparatorChar, + fileSystem.Path.AltDirectorySeparatorChar, + + // Raises a different type of exception from other + // invalid chars and is covered by other tests + fileSystem.Path.VolumeSeparatorChar + }; +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/TestFiles/SecondTestFile.txt b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/TestFiles/SecondTestFile.txt new file mode 100644 index 000000000..b10d0344d --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/TestFiles/SecondTestFile.txt @@ -0,0 +1 @@ +This is a the second test file. \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/TestFiles/TestFile.txt b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/TestFiles/TestFile.txt new file mode 100644 index 000000000..af27ff498 --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/TestFiles/TestFile.txt @@ -0,0 +1 @@ +This is a test file. \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests.csproj b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests.csproj new file mode 100644 index 000000000..5d83134e6 --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests.csproj @@ -0,0 +1,28 @@ + + + + The unit tests for our pre-built mocks + System.IO.Abstractions.TestingHelpers.Tests + System.IO.Abstractions.TestingHelpers.Tests + + + + + + + + + true + + + + + + + + + + diff --git a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/UnixOnlyAttribute.cs b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/UnixOnlyAttribute.cs new file mode 100644 index 000000000..8b26fc8e7 --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/UnixOnlyAttribute.cs @@ -0,0 +1,26 @@ +using NUnit.Framework; +using NUnit.Framework.Interfaces; + +namespace System.IO.Abstractions.TestingHelpers.Tests; + +internal sealed class UnixOnlyAttribute : Attribute, ITestAction +{ + private readonly string reason; + + public UnixOnlyAttribute(string reason) + { + this.reason = reason; + } + + public ActionTargets Targets => ActionTargets.Test; + + public void BeforeTest(ITest test) + { + if (!MockUnixSupport.IsUnixPlatform()) + { + Assert.Inconclusive(reason); + } + } + + public void AfterTest(ITest test) { } +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/UnixSpecifics.cs b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/UnixSpecifics.cs new file mode 100644 index 000000000..24dcf0f59 --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/UnixSpecifics.cs @@ -0,0 +1,8 @@ +namespace System.IO.Abstractions.TestingHelpers.Tests; + +internal static class UnixSpecifics +{ + public const string SlashRoot = "Filesystem root is just '/' on Unix"; + + public const string CaseSensitivity = "Paths are case-sensitive on Unix"; +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/Usings.cs b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/Usings.cs new file mode 100644 index 000000000..2f2279eb4 --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/Usings.cs @@ -0,0 +1,4 @@ +global using System.Threading.Tasks; +global using NUnit.Framework; +global using aweXpect; +global using static aweXpect.Expect; diff --git a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/WindowsOnlyAttribute.cs b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/WindowsOnlyAttribute.cs new file mode 100644 index 000000000..ae7c30b1d --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/WindowsOnlyAttribute.cs @@ -0,0 +1,26 @@ +using NUnit.Framework; +using NUnit.Framework.Interfaces; + +namespace System.IO.Abstractions.TestingHelpers.Tests; + +internal sealed class WindowsOnlyAttribute : Attribute, ITestAction +{ + private readonly string reason; + + public WindowsOnlyAttribute(string reason) + { + this.reason = reason; + } + + public ActionTargets Targets => ActionTargets.Test; + + public void BeforeTest(ITest test) + { + if (!MockUnixSupport.IsWindowsPlatform()) + { + Assert.Inconclusive(reason); + } + } + + public void AfterTest(ITest test) { } +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/WindowsSpecifics.cs b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/WindowsSpecifics.cs new file mode 100644 index 000000000..1dcf4bf59 --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/WindowsSpecifics.cs @@ -0,0 +1,14 @@ +namespace System.IO.Abstractions.TestingHelpers.Tests; + +internal static class WindowsSpecifics +{ + public const string Drives = "Drives are a Windows-only concept"; + + public const string AccessControlLists = "ACLs are a Windows-only concept"; + + public const string UNCPaths = "UNC paths are a Windows-only concept"; + + public const string StrictPathRules = "Windows has stricter path rules than other platforms"; + + public const string CaseInsensitivity = "Paths are case-insensitive on Windows"; +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.Wrappers.Tests/DirectoryInfoFactoryTests.cs b/tests/TestableIO.System.IO.Abstractions.Wrappers.Tests/DirectoryInfoFactoryTests.cs new file mode 100644 index 000000000..49032ae83 --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.Wrappers.Tests/DirectoryInfoFactoryTests.cs @@ -0,0 +1,15 @@ +namespace System.IO.Abstractions.Tests; + +[TestFixture] +public class DirectoryInfoFactoryTests +{ + [Test] + public async Task Wrap_WithNull_ShouldReturnNull() + { + var fileSystem = new FileSystem(); + + var result = fileSystem.DirectoryInfo.Wrap(null); + + await That(result).IsNull(); + } +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.Wrappers.Tests/DirectoryInfoTests.cs b/tests/TestableIO.System.IO.Abstractions.Wrappers.Tests/DirectoryInfoTests.cs new file mode 100644 index 000000000..2b7da0833 --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.Wrappers.Tests/DirectoryInfoTests.cs @@ -0,0 +1,17 @@ +namespace System.IO.Abstractions.Tests; + +[TestFixture] +public class DirectoryInfoTests +{ + [Test] + public async Task Parent_ForRootDirectory_ShouldReturnNull() + { + var wrapperFilesystem = new FileSystem(); + + var current = wrapperFilesystem.Directory.GetCurrentDirectory(); + var root = wrapperFilesystem.DirectoryInfo.New(current).Root; + var rootsParent = root.Parent; + + await That(rootsParent).IsNull(); + } +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.Wrappers.Tests/DirectoryWrapperTests.cs b/tests/TestableIO.System.IO.Abstractions.Wrappers.Tests/DirectoryWrapperTests.cs new file mode 100644 index 000000000..75547515e --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.Wrappers.Tests/DirectoryWrapperTests.cs @@ -0,0 +1,50 @@ +namespace System.IO.Abstractions.Tests; + +[TestFixture] +public class DirectoryWrapperTests +{ + [Test] + public async Task GetParent_ForRootDirectory_ShouldReturnNull() + { + // Arrange + var wrapperFilesystem = new FileSystem(); + var root = wrapperFilesystem.Directory.GetDirectoryRoot("."); + + // Act + var result = wrapperFilesystem.Directory.GetParent(root); + + // Assert + await That(result).IsNull(); + } + + [Test] + public async Task GetParent_ForSimpleSubfolderPath_ShouldReturnRoot() + { + // Arrange + var wrapperFilesystem = new FileSystem(); + var root = wrapperFilesystem.Directory.GetDirectoryRoot("."); + var subfolder = wrapperFilesystem.Path.Combine(root, "some-folder"); + + // Act + var result = wrapperFilesystem.Directory.GetParent(subfolder); + + // Assert + await That(result.FullName).IsEqualTo(root); + } + + [Test] + public async Task GetParent_ForSimpleFilePath_ShouldReturnSubfolder() + { + // Arrange + var wrapperFilesystem = new FileSystem(); + var root = wrapperFilesystem.Directory.GetDirectoryRoot("."); + var subfolder = wrapperFilesystem.Path.Combine(root, "some-folder"); + var file = wrapperFilesystem.Path.Combine(subfolder, "some-file.txt"); + + // Act + var result = wrapperFilesystem.Directory.GetParent(file); + + // Assert + await That(result.FullName).IsEqualTo(subfolder); + } +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.Wrappers.Tests/DriveInfoFactoryTests.cs b/tests/TestableIO.System.IO.Abstractions.Wrappers.Tests/DriveInfoFactoryTests.cs new file mode 100644 index 000000000..23819e141 --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.Wrappers.Tests/DriveInfoFactoryTests.cs @@ -0,0 +1,15 @@ +namespace System.IO.Abstractions.Tests; + +[TestFixture] +public class DriveInfoFactoryTests +{ + [Test] + public async Task Wrap_WithNull_ShouldReturnNull() + { + var fileSystem = new FileSystem(); + + var result = fileSystem.DriveInfo.Wrap(null); + + await That(result).IsNull(); + } +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.Wrappers.Tests/FileInfoBaseConversionTests.cs b/tests/TestableIO.System.IO.Abstractions.Wrappers.Tests/FileInfoBaseConversionTests.cs new file mode 100644 index 000000000..ad00fda81 --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.Wrappers.Tests/FileInfoBaseConversionTests.cs @@ -0,0 +1,23 @@ +namespace System.IO.Abstractions.Tests; + +/// +/// Unit tests for the conversion operators of the class. +/// +public class FileInfoBaseConversionTests +{ + /// + /// Tests that a null is correctly converted to a null without exception. + /// + [Test] + public async Task FileInfoBase_FromFileInfo_ShouldReturnNullIfFileInfoIsNull() + { + // Arrange + FileInfo fileInfo = null; + + // Act + FileInfoBase actual = fileInfo; + + // Assert + await That(actual).IsNull(); + } +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.Wrappers.Tests/FileInfoFactoryTests.cs b/tests/TestableIO.System.IO.Abstractions.Wrappers.Tests/FileInfoFactoryTests.cs new file mode 100644 index 000000000..26c849685 --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.Wrappers.Tests/FileInfoFactoryTests.cs @@ -0,0 +1,15 @@ +namespace System.IO.Abstractions.Tests; + +[TestFixture] +public class FileInfoFactoryTests +{ + [Test] + public async Task Wrap_WithNull_ShouldReturnNull() + { + var fileSystem = new FileSystem(); + + var result = fileSystem.FileInfo.Wrap(null); + + await That(result).IsNull(); + } +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.Wrappers.Tests/FileSystemTests.cs b/tests/TestableIO.System.IO.Abstractions.Wrappers.Tests/FileSystemTests.cs new file mode 100644 index 000000000..7a99d2086 --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.Wrappers.Tests/FileSystemTests.cs @@ -0,0 +1,113 @@ +using Mockolate; + +namespace System.IO.Abstractions.Tests; + +[TestFixture] +public class FileSystemTests +{ +#if !NET9_0_OR_GREATER + [Test] + public async Task Is_Serializable() + { + var fileSystem = new FileSystem(); + var memoryStream = new MemoryStream(); + +#pragma warning disable SYSLIB0011 + var serializer = new Runtime.Serialization.Formatters.Binary.BinaryFormatter(); + + serializer.Serialize(memoryStream, fileSystem); +#pragma warning restore SYSLIB0011 + + await That(memoryStream).HasLength().GreaterThan(0) + .Because("Length didn't increase after serialization task."); + } +#endif + + [Test] + public async Task Mock_File_Succeeds() + { + var fileSystemMock = Mock.Create(fs => + fs.Property.File.InitializeWith(Mock.Create())); + + await That(() => + fileSystemMock.File.SetupMock.Method.ReadAllText(It.IsAny()).Returns("") + ).DoesNotThrow(); + } + + [Test] + public async Task Mock_Directory_Succeeds() + { + var fileSystemMock = Mock.Create(fs => + fs.Property.Directory.InitializeWith(Mock.Create())); + + await That(() => + fileSystemMock.Directory.SetupMock.Method.CreateDirectory(It.IsAny()) + ).DoesNotThrow(); + } + + [Test] + public async Task Mock_FileInfo_Succeeds() + { + var fileSystemMock = Mock.Create(fs => + fs.Property.FileInfo.InitializeWith(Mock.Create())); + + await That(() => + fileSystemMock.FileInfo.SetupMock.Method.New(It.IsAny()) + ).DoesNotThrow(); + } + + [Test] + public async Task Mock_FileStream_Succeeds() + { + var fileSystemMock = Mock.Create(fs => + fs.Property.FileStream.InitializeWith(Mock.Create())); + + await That(() => + fileSystemMock.FileStream.SetupMock.Method.New(It.IsAny(), It.IsAny()) + ).DoesNotThrow(); + } + + [Test] + public async Task Mock_Path_Succeeds() + { + var fileSystemMock = Mock.Create(fs => + fs.Property.Path.InitializeWith(Mock.Create())); + + await That(() => + fileSystemMock.Path.SetupMock.Method.Combine(It.IsAny(), It.IsAny()) + ).DoesNotThrow(); + } + + [Test] + public async Task Mock_DirectoryInfo_Succeeds() + { + var fileSystemMock = Mock.Create(fs => + fs.Property.DirectoryInfo.InitializeWith(Mock.Create())); + + await That(() => + fileSystemMock.DirectoryInfo.SetupMock.Method.New(It.IsAny()) + ).DoesNotThrow(); + } + + [Test] + public async Task Mock_DriveInfo_Succeeds() + { + var fileSystemMock = Mock.Create(fs => + fs.Property.DriveInfo.InitializeWith(Mock.Create())); + + await That(() => + fileSystemMock.DriveInfo.SetupMock.Method.New(It.IsAny()) + ).DoesNotThrow(); + } + + [Test] + public async Task Mock_FileSystemWatcher_Succeeds() + { + var fileSystemMock = Mock.Create(fs => + fs.Property.FileSystemWatcher.InitializeWith(Mock.Create())); + + await That(() => + fileSystemMock.FileSystemWatcher.SetupMock.Method.New(It.IsAny()) + ).DoesNotThrow(); + } +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.Wrappers.Tests/FileSystemWatcherFactoryTests.cs b/tests/TestableIO.System.IO.Abstractions.Wrappers.Tests/FileSystemWatcherFactoryTests.cs new file mode 100644 index 000000000..4762aa35d --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.Wrappers.Tests/FileSystemWatcherFactoryTests.cs @@ -0,0 +1,15 @@ +namespace System.IO.Abstractions.Tests; + +[TestFixture] +public class FileSystemWatcherFactoryTests +{ + [Test] + public async Task Wrap_WithNull_ShouldReturnNull() + { + var fileSystem = new FileSystem(); + + var result = fileSystem.FileSystemWatcher.Wrap(null); + + await That(result).IsNull(); + } +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.Wrappers.Tests/FileVersionInfoBaseConversionTests.cs b/tests/TestableIO.System.IO.Abstractions.Wrappers.Tests/FileVersionInfoBaseConversionTests.cs new file mode 100644 index 000000000..f1d436e1b --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.Wrappers.Tests/FileVersionInfoBaseConversionTests.cs @@ -0,0 +1,25 @@ +using System.Diagnostics; + +namespace System.IO.Abstractions.Tests; + +/// +/// Unit tests for the conversion operators of the class. +/// +public class FileVersionInfoBaseConversionTests +{ + /// + /// Tests that a null is correctly converted to a null without exception. + /// + [Test] + public async Task FileVersionInfoBase_FromFileVersionInfo_ShouldReturnNullIfFileVersionInfoIsNull() + { + // Arrange + FileVersionInfo fileVersionInfo = null; + + // Act + FileVersionInfoBase actual = fileVersionInfo; + + // Assert + await That(actual).IsNull(); + } +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.Wrappers.Tests/TestableIO.System.IO.Abstractions.Wrappers.Tests.csproj b/tests/TestableIO.System.IO.Abstractions.Wrappers.Tests/TestableIO.System.IO.Abstractions.Wrappers.Tests.csproj new file mode 100644 index 000000000..fa122d5bc --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.Wrappers.Tests/TestableIO.System.IO.Abstractions.Wrappers.Tests.csproj @@ -0,0 +1,13 @@ + + + + The unit tests for our the core abstractions + System.IO.Abstractions.Tests + System.IO.Abstractions.Tests + + + + + + + diff --git a/tests/TestableIO.System.IO.Abstractions.Wrappers.Tests/Usings.cs b/tests/TestableIO.System.IO.Abstractions.Wrappers.Tests/Usings.cs new file mode 100644 index 000000000..2f2279eb4 --- /dev/null +++ b/tests/TestableIO.System.IO.Abstractions.Wrappers.Tests/Usings.cs @@ -0,0 +1,4 @@ +global using System.Threading.Tasks; +global using NUnit.Framework; +global using aweXpect; +global using static aweXpect.Expect;