├── .github
├── dependabot.yml
└── workflows
│ ├── CI.yml
│ └── Official.yml
├── .gitignore
├── Directory.Build.props
├── Directory.Build.rsp
├── Directory.Build.targets
├── Directory.Packages.props
├── Directory.Solution.props
├── EnvironmentAbstractions.sln
├── LICENSE
├── NuGet.config
├── README.md
├── build
├── PackageIcon.png
├── key.snk
├── stylecop.json
└── xunit.runner.json
├── src
├── EnvironmentAbstractions.BannedApiAnalyzer
│ ├── EnvironmentAbstractions.BannedApiAnalyzer.csproj
│ ├── README.md
│ ├── build
│ │ ├── BannedSymbols.EnvironmentAbstractions.IEnvironmentProvider.txt
│ │ ├── BannedSymbols.EnvironmentAbstractions.IEnvironmentVariableProvider.txt
│ │ ├── EnvironmentAbstractions.BannedApiAnalyzer.props
│ │ └── EnvironmentAbstractions.BannedApiAnalyzer.targets
│ └── buildTransitive
│ │ ├── EnvironmentAbstractions.BannedApiAnalyzer.props
│ │ └── EnvironmentAbstractions.BannedApiAnalyzer.targets
├── EnvironmentAbstractions.TestHelpers.UnitTests
│ ├── EnvironmentAbstractions.TestHelpers.UnitTests.csproj
│ └── MockEnvironmentVariableProviderTests.cs
├── EnvironmentAbstractions.TestHelpers
│ ├── EnvironmentAbstractions.TestHelpers.csproj
│ ├── MockEnvironmentProvider.cs
│ ├── MockEnvironmentVariableProvider.cs
│ ├── PublicAPI
│ │ ├── net6.0
│ │ │ ├── PublicAPI.Shipped.txt
│ │ │ └── PublicAPI.Unshipped.txt
│ │ ├── net8.0
│ │ │ ├── PublicAPI.Shipped.txt
│ │ │ └── PublicAPI.Unshipped.txt
│ │ ├── net9.0
│ │ │ ├── PublicAPI.Shipped.txt
│ │ │ └── PublicAPI.Unshipped.txt
│ │ └── netstandard2.0
│ │ │ ├── PublicAPI.Shipped.txt
│ │ │ └── PublicAPI.Unshipped.txt
│ └── README.md
├── EnvironmentAbstractions.UnitTests
│ ├── EnvironmentAbstractions.UnitTests.csproj
│ ├── HashtableIDictionaryWrapperTests.cs
│ ├── IEnvironmentVariableProviderTests.cs
│ ├── MoqTests.cs
│ ├── SystemEnvironmentProviderTests.cs
│ ├── SystemEnvironmentVariableProviderTests.cs
│ └── TestBase.cs
├── EnvironmentAbstractions
│ ├── EnvironmentAbstractions.csproj
│ ├── GetEnvironmentVariablesWrapper.cs
│ ├── IEnvironmentProvider.cs
│ ├── IEnvironmentVariableProvider.cs
│ ├── PublicAPI
│ │ ├── net6.0
│ │ │ ├── PublicAPI.Shipped.txt
│ │ │ └── PublicAPI.Unshipped.txt
│ │ ├── net8.0
│ │ │ ├── PublicAPI.Shipped.txt
│ │ │ └── PublicAPI.Unshipped.txt
│ │ ├── net9.0
│ │ │ ├── PublicAPI.Shipped.txt
│ │ │ └── PublicAPI.Unshipped.txt
│ │ └── netstandard2.0
│ │ │ ├── PublicAPI.Shipped.txt
│ │ │ └── PublicAPI.Unshipped.txt
│ ├── README.md
│ ├── SystemEnvironmentProvider.cs
│ └── SystemEnvironmentVariableProvider.cs
└── GlobalSuppressions.cs
└── version.json
/.github/dependabot.yml:
--------------------------------------------------------------------------------
1 |
2 | # To get started with Dependabot version updates, you'll need to specify which
3 | # package ecosystems to update and where the package manifests are located.
4 | # Please see the documentation for all configuration options:
5 | # https://help.github.com/github/administering-a-repository/configuration-options-for-dependency-updates
6 |
7 | version: 2
8 | updates:
9 | - package-ecosystem: "nuget" # See documentation for possible values
10 | directory: "/" # Location of package manifests
11 | schedule:
12 | interval: "weekly"
13 | assignees:
14 | - "jeffkl"
15 | labels:
16 | - "maintenance"
--------------------------------------------------------------------------------
/.github/workflows/CI.yml:
--------------------------------------------------------------------------------
1 | name: CI
2 |
3 | on:
4 | workflow_dispatch:
5 | push:
6 | branches:
7 | - main
8 | - rel/*
9 | pull_request:
10 | branches:
11 | - main
12 | - rel/*
13 |
14 | env:
15 | ArtifactsDirectoryName: 'artifacts'
16 | TestResultsDirectoryName: 'coverage'
17 | CommonTestArguments: '--no-restore --no-build --logger trx /noautorsp'
18 | BuildConfiguration: 'Debug'
19 | BuildPlatform: 'Any CPU'
20 | ContinuousIntegrationBuild: 'true'
21 |
22 | jobs:
23 | BuildAndTest:
24 | strategy:
25 | matrix:
26 | os: [windows-latest, ubuntu-latest, macos-latest]
27 | include:
28 | - os: windows-latest
29 | name: Windows
30 | testarguments: ''
31 | - os: ubuntu-latest
32 | name: Linux
33 | testarguments: '--collect:"XPlat Code Coverage"'
34 | - os: macos-latest
35 | name: MacOS
36 | testarguments: ''
37 | fail-fast: false
38 |
39 | name: Build and Test (${{ matrix.name }})
40 | runs-on: ${{ matrix.os }}
41 |
42 | steps:
43 | - name: Checkout
44 | uses: actions/checkout@v4
45 | with:
46 | fetch-depth: 0
47 |
48 | - name: Install .NET 6.x and 8.x
49 | uses: actions/setup-dotnet@v4
50 | with:
51 | dotnet-version: |
52 | 6.x
53 | 8.x
54 |
55 | - name: Install .NET 9.0
56 | uses: actions/setup-dotnet@v4
57 | with:
58 | dotnet-version: 9.x
59 | dotnet-quality: 'preview'
60 |
61 | - name: Build Solution
62 | run: dotnet build "/Property:Platform=${{ env.BuildPlatform }};Configuration=${{ env.BuildConfiguration }}" "/BinaryLogger:${{ env.ArtifactsDirectoryName }}/build.binlog"
63 |
64 | - name: Run Unit Tests (.NET Framework)
65 | if: ${{ matrix.name == 'Windows' }}
66 | run: dotnet test ${{ env.CommonTestArguments }} ${{ matrix.TestArguments}} --framework net472 "/Property:Platform=${{ env.BuildPlatform }};Configuration=${{ env.BuildConfiguration }}" "/BinaryLogger:${{ env.ArtifactsDirectoryName }}/test-net472.binlog"
67 |
68 | - name: Run Unit Tests (.NET 6.0)
69 | run: dotnet test ${{ env.CommonTestArguments }} ${{ matrix.TestArguments}} --framework net6.0 "/Property:Platform=${{ env.BuildPlatform }};Configuration=${{ env.BuildConfiguration }}" "/BinaryLogger:${{ env.ArtifactsDirectoryName }}/test-net6.0.binlog"
70 |
71 | - name: Run Unit Tests (.NET 8.0)
72 | run: dotnet test ${{ env.CommonTestArguments }} ${{ matrix.TestArguments}} --framework net8.0 "/Property:Platform=${{ env.BuildPlatform }};Configuration=${{ env.BuildConfiguration }}" "/BinaryLogger:${{ env.ArtifactsDirectoryName }}/test-net8.0.binlog"
73 |
74 | - name: Run Unit Tests (.NET 9.0)
75 | run: dotnet test ${{ env.CommonTestArguments }} ${{ matrix.TestArguments}} --framework net9.0 "/Property:Platform=${{ env.BuildPlatform }};Configuration=${{ env.BuildConfiguration }}" "/BinaryLogger:${{ env.ArtifactsDirectoryName }}/test-net9.0.binlog"
76 |
77 | - name: Code Coverage Report
78 | if: ${{ matrix.name == 'Linux' }}
79 | uses: irongut/CodeCoverageSummary@v1.3.0
80 | with:
81 | filename: '**/TestResults/**/coverage.cobertura.xml'
82 | badge: true
83 | format: markdown
84 | hide_complexity: true
85 | indicators: true
86 | output: both
87 | thresholds: '60 80'
88 |
89 | - name: Add Code Coverage Report to Summary
90 | if: ${{ matrix.name == 'Linux' }}
91 | run: cat code-coverage-results.md >> $GITHUB_STEP_SUMMARY
92 |
93 | - name: Upload Test Results
94 | uses: actions/upload-artifact@v4
95 | if: success() || failure()
96 | with:
97 | name: test-results-${{ matrix.name }}
98 | path: '**/TestResults/*.trx'
99 | if-no-files-found: error
100 |
101 | - name: Upload Artifacts
102 | uses: actions/upload-artifact@v4
103 | if: success() || failure()
104 | with:
105 | name: ${{ env.ArtifactsDirectoryName }}-${{ matrix.name }}
106 | path: ${{ env.ArtifactsDirectoryName }}
--------------------------------------------------------------------------------
/.github/workflows/Official.yml:
--------------------------------------------------------------------------------
1 | name: Official Build
2 |
3 | on:
4 | push:
5 | branches:
6 | - main
7 | - rel/*
8 | tags:
9 | - v*.*.*
10 |
11 | env:
12 | ArtifactsDirectoryName: 'artifacts'
13 | BuildConfiguration: 'Release'
14 | BuildPlatform: 'Any CPU'
15 | ContinuousIntegrationBuild: 'true'
16 | jobs:
17 | build:
18 | runs-on: windows-latest
19 | environment: Production
20 |
21 | steps:
22 | - name: Checkout
23 | uses: actions/checkout@v4
24 | with:
25 | fetch-depth: 0
26 |
27 | - name: Install .NET SDKs
28 | uses: actions/setup-dotnet@v4
29 | with:
30 | dotnet-version: 9.x
31 | dotnet-quality: 'preview'
32 |
33 | - name: Build Solution
34 | run: dotnet build "/Property:Platform=${{ env.BuildPlatform }};Configuration=${{ env.BuildConfiguration }}" "/BinaryLogger:${{ env.ArtifactsDirectoryName }}\build.binlog"
35 |
36 | - name: Upload Artifacts
37 | uses: actions/upload-artifact@v4
38 | if: success() || failure()
39 | with:
40 | name: ${{ env.ArtifactsDirectoryName }}
41 | path: ${{ env.ArtifactsDirectoryName }}
42 |
43 | - name: Push Packages
44 | run: dotnet nuget push --skip-duplicate --api-key ${{ secrets.NuGetApiKey }} ${{ env.ArtifactsDirectoryName }}\**\*.nupkg
45 | if: ${{ startsWith(github.ref, 'refs/tags/v') }}
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | ## Ignore Visual Studio temporary files, build results, and
2 | ## files generated by popular Visual Studio add-ons.
3 | ##
4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
5 |
6 | # User-specific files
7 | *.rsuser
8 | *.suo
9 | *.user
10 | *.userosscache
11 | *.sln.docstates
12 |
13 | # User-specific files (MonoDevelop/Xamarin Studio)
14 | *.userprefs
15 |
16 | # Mono auto generated files
17 | mono_crash.*
18 |
19 | # Build results
20 | [Dd]ebug/
21 | [Dd]ebugPublic/
22 | [Rr]elease/
23 | [Rr]eleases/
24 | x64/
25 | x86/
26 | [Aa][Rr][Mm]/
27 | [Aa][Rr][Mm]64/
28 | bld/
29 | [Bb]in/
30 | [Oo]bj/
31 | [Ll]og/
32 | [Ll]ogs/
33 |
34 | # Visual Studio 2015/2017 cache/options directory
35 | .vs/
36 | # Uncomment if you have tasks that create the project's static files in wwwroot
37 | #wwwroot/
38 |
39 | # Visual Studio 2017 auto generated files
40 | Generated\ Files/
41 |
42 | # MSTest test Results
43 | [Tt]est[Rr]esult*/
44 | [Bb]uild[Ll]og.*
45 |
46 | # NUnit
47 | *.VisualState.xml
48 | TestResult.xml
49 | nunit-*.xml
50 |
51 | # Build Results of an ATL Project
52 | [Dd]ebugPS/
53 | [Rr]eleasePS/
54 | dlldata.c
55 |
56 | # Benchmark Results
57 | BenchmarkDotNet.Artifacts/
58 |
59 | # .NET Core
60 | project.lock.json
61 | project.fragment.lock.json
62 | artifacts/
63 |
64 | # StyleCop
65 | StyleCopReport.xml
66 |
67 | # Files built by Visual Studio
68 | *_i.c
69 | *_p.c
70 | *_h.h
71 | *.ilk
72 | *.meta
73 | *.obj
74 | *.iobj
75 | *.pch
76 | *.pdb
77 | *.ipdb
78 | *.pgc
79 | *.pgd
80 | *.rsp
81 | *.sbr
82 | *.tlb
83 | *.tli
84 | *.tlh
85 | *.tmp
86 | *.tmp_proj
87 | *_wpftmp.csproj
88 | *.log
89 | *.vspscc
90 | *.vssscc
91 | .builds
92 | *.pidb
93 | *.svclog
94 | *.scc
95 |
96 | # Chutzpah Test files
97 | _Chutzpah*
98 |
99 | # Visual C++ cache files
100 | ipch/
101 | *.aps
102 | *.ncb
103 | *.opendb
104 | *.opensdf
105 | *.sdf
106 | *.cachefile
107 | *.VC.db
108 | *.VC.VC.opendb
109 |
110 | # Visual Studio profiler
111 | *.psess
112 | *.vsp
113 | *.vspx
114 | *.sap
115 |
116 | # Visual Studio Trace Files
117 | *.e2e
118 |
119 | # TFS 2012 Local Workspace
120 | $tf/
121 |
122 | # Guidance Automation Toolkit
123 | *.gpState
124 |
125 | # ReSharper is a .NET coding add-in
126 | _ReSharper*/
127 | *.[Rr]e[Ss]harper
128 | *.DotSettings.user
129 |
130 | # TeamCity is a build add-in
131 | _TeamCity*
132 |
133 | # DotCover is a Code Coverage Tool
134 | *.dotCover
135 |
136 | # AxoCover is a Code Coverage Tool
137 | .axoCover/*
138 | !.axoCover/settings.json
139 |
140 | # Visual Studio code coverage results
141 | *.coverage
142 | *.coveragexml
143 |
144 | # NCrunch
145 | _NCrunch_*
146 | .*crunch*.local.xml
147 | nCrunchTemp_*
148 |
149 | # MightyMoose
150 | *.mm.*
151 | AutoTest.Net/
152 |
153 | # Web workbench (sass)
154 | .sass-cache/
155 |
156 | # Installshield output folder
157 | [Ee]xpress/
158 |
159 | # DocProject is a documentation generator add-in
160 | DocProject/buildhelp/
161 | DocProject/Help/*.HxT
162 | DocProject/Help/*.HxC
163 | DocProject/Help/*.hhc
164 | DocProject/Help/*.hhk
165 | DocProject/Help/*.hhp
166 | DocProject/Help/Html2
167 | DocProject/Help/html
168 |
169 | # Click-Once directory
170 | publish/
171 |
172 | # Publish Web Output
173 | *.[Pp]ublish.xml
174 | *.azurePubxml
175 | # Note: Comment the next line if you want to checkin your web deploy settings,
176 | # but database connection strings (with potential passwords) will be unencrypted
177 | *.pubxml
178 | *.publishproj
179 |
180 | # Microsoft Azure Web App publish settings. Comment the next line if you want to
181 | # checkin your Azure Web App publish settings, but sensitive information contained
182 | # in these scripts will be unencrypted
183 | PublishScripts/
184 |
185 | # NuGet Packages
186 | *.nupkg
187 | # NuGet Symbol Packages
188 | *.snupkg
189 | # The packages folder can be ignored because of Package Restore
190 | **/[Pp]ackages/*
191 | # except build/, which is used as an MSBuild target.
192 | !**/[Pp]ackages/build/
193 | # Uncomment if necessary however generally it will be regenerated when needed
194 | #!**/[Pp]ackages/repositories.config
195 | # NuGet v3's project.json files produces more ignorable files
196 | *.nuget.props
197 | *.nuget.targets
198 |
199 | # Microsoft Azure Build Output
200 | csx/
201 | *.build.csdef
202 |
203 | # Microsoft Azure Emulator
204 | ecf/
205 | rcf/
206 |
207 | # Windows Store app package directories and files
208 | AppPackages/
209 | BundleArtifacts/
210 | Package.StoreAssociation.xml
211 | _pkginfo.txt
212 | *.appx
213 | *.appxbundle
214 | *.appxupload
215 |
216 | # Visual Studio cache files
217 | # files ending in .cache can be ignored
218 | *.[Cc]ache
219 | # but keep track of directories ending in .cache
220 | !?*.[Cc]ache/
221 |
222 | # Others
223 | ClientBin/
224 | ~$*
225 | *~
226 | *.dbmdl
227 | *.dbproj.schemaview
228 | *.jfm
229 | *.pfx
230 | *.publishsettings
231 | orleans.codegen.cs
232 |
233 | # Including strong name files can present a security risk
234 | # (https://github.com/github/gitignore/pull/2483#issue-259490424)
235 | #*.snk
236 |
237 | # Since there are multiple workflows, uncomment next line to ignore bower_components
238 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
239 | #bower_components/
240 |
241 | # RIA/Silverlight projects
242 | Generated_Code/
243 |
244 | # Backup & report files from converting an old project file
245 | # to a newer Visual Studio version. Backup files are not needed,
246 | # because we have git ;-)
247 | _UpgradeReport_Files/
248 | Backup*/
249 | UpgradeLog*.XML
250 | UpgradeLog*.htm
251 | ServiceFabricBackup/
252 | *.rptproj.bak
253 |
254 | # SQL Server files
255 | *.mdf
256 | *.ldf
257 | *.ndf
258 |
259 | # Business Intelligence projects
260 | *.rdl.data
261 | *.bim.layout
262 | *.bim_*.settings
263 | *.rptproj.rsuser
264 | *- [Bb]ackup.rdl
265 | *- [Bb]ackup ([0-9]).rdl
266 | *- [Bb]ackup ([0-9][0-9]).rdl
267 |
268 | # Microsoft Fakes
269 | FakesAssemblies/
270 |
271 | # GhostDoc plugin setting file
272 | *.GhostDoc.xml
273 |
274 | # Node.js Tools for Visual Studio
275 | .ntvs_analysis.dat
276 | node_modules/
277 |
278 | # Visual Studio 6 build log
279 | *.plg
280 |
281 | # Visual Studio 6 workspace options file
282 | *.opt
283 |
284 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
285 | *.vbw
286 |
287 | # Visual Studio LightSwitch build output
288 | **/*.HTMLClient/GeneratedArtifacts
289 | **/*.DesktopClient/GeneratedArtifacts
290 | **/*.DesktopClient/ModelManifest.xml
291 | **/*.Server/GeneratedArtifacts
292 | **/*.Server/ModelManifest.xml
293 | _Pvt_Extensions
294 |
295 | # Paket dependency manager
296 | .paket/paket.exe
297 | paket-files/
298 |
299 | # FAKE - F# Make
300 | .fake/
301 |
302 | # CodeRush personal settings
303 | .cr/personal
304 |
305 | # Python Tools for Visual Studio (PTVS)
306 | __pycache__/
307 | *.pyc
308 |
309 | # Cake - Uncomment if you are using it
310 | # tools/**
311 | # !tools/packages.config
312 |
313 | # Tabs Studio
314 | *.tss
315 |
316 | # Telerik's JustMock configuration file
317 | *.jmconfig
318 |
319 | # BizTalk build output
320 | *.btp.cs
321 | *.btm.cs
322 | *.odx.cs
323 | *.xsd.cs
324 |
325 | # OpenCover UI analysis results
326 | OpenCover/
327 |
328 | # Azure Stream Analytics local run output
329 | ASALocalRun/
330 |
331 | # MSBuild Binary and Structured Log
332 | *.binlog
333 |
334 | # NVidia Nsight GPU debugger configuration file
335 | *.nvuser
336 |
337 | # MFractors (Xamarin productivity tool) working folder
338 | .mfractor/
339 |
340 | # Local History for Visual Studio
341 | .localhistory/
342 |
343 | # BeatPulse healthcheck temp database
344 | healthchecksdb
345 |
346 | # Backup folder for Package Reference Convert tool in Visual Studio 2017
347 | MigrationBackup/
348 |
349 | # Ionide (cross platform F# VS Code tools) working folder
350 | .ionide/
351 |
--------------------------------------------------------------------------------
/Directory.Build.props:
--------------------------------------------------------------------------------
1 |
2 |
3 | $(MSBuildThisFileDirectory)artifacts\
4 | *log
5 | false
6 | Latest
7 | true
8 | enable
9 | true
10 | true
11 |
12 |
--------------------------------------------------------------------------------
/Directory.Build.rsp:
--------------------------------------------------------------------------------
1 | /Restore
2 | /ConsoleLoggerParameters:Verbosity=Minimal;Summary;ForceNoAlign
3 | /MaxCPUCount
4 | /NodeReuse:false
--------------------------------------------------------------------------------
/Directory.Build.targets:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | true
5 | $(MSBuildThisFileDirectory)build\key.snk
6 |
7 |
8 |
9 |
10 | jeffkl
11 | jeffkl
12 | © Jeff Kluge. All rights reserved.
13 | true
14 | true
15 | PackageIcon.png
16 | $(MSBuildThisFileDirectory)build\$(PackageIcon)
17 | MIT
18 | https://github.com/jeffkl/EnvironmentAbstractions
19 | README.md
20 | true
21 | true
22 | https://github.com/jeffkl/EnvironmentAbstractions.git
23 | snupkg
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 | $(NoWarn);SA0001;SA1600
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
46 |
50 |
51 |
52 |
53 |
54 |
56 |
57 |
58 |
--------------------------------------------------------------------------------
/Directory.Packages.props:
--------------------------------------------------------------------------------
1 |
2 |
3 | true
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
--------------------------------------------------------------------------------
/Directory.Solution.props:
--------------------------------------------------------------------------------
1 |
2 |
3 | true
4 |
5 |
--------------------------------------------------------------------------------
/EnvironmentAbstractions.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio Version 17
4 | VisualStudioVersion = 17.3.32614.404
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{55D8C0E6-4848-49DD-852C-CAA32BBD3C69}"
7 | ProjectSection(SolutionItems) = preProject
8 | .gitignore = .gitignore
9 | Directory.Build.props = Directory.Build.props
10 | Directory.Build.rsp = Directory.Build.rsp
11 | Directory.Build.targets = Directory.Build.targets
12 | Directory.Packages.props = Directory.Packages.props
13 | LICENSE = LICENSE
14 | README.md = README.md
15 | version.json = version.json
16 | EndProjectSection
17 | EndProject
18 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "EnvironmentAbstractions", "src\EnvironmentAbstractions\EnvironmentAbstractions.csproj", "{80AA9A82-F46B-47C4-BB3E-5EA2BEBDFCB5}"
19 | EndProject
20 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "EnvironmentAbstractions.UnitTests", "src\EnvironmentAbstractions.UnitTests\EnvironmentAbstractions.UnitTests.csproj", "{74C0D9E2-3383-4EC5-AD28-39AE187DF4D9}"
21 | EndProject
22 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "EnvironmentAbstractions.TestHelpers", "src\EnvironmentAbstractions.TestHelpers\EnvironmentAbstractions.TestHelpers.csproj", "{21233AD9-E8C2-4D6F-956D-C61C64938C74}"
23 | EndProject
24 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "EnvironmentAbstractions.TestHelpers.UnitTests", "src\EnvironmentAbstractions.TestHelpers.UnitTests\EnvironmentAbstractions.TestHelpers.UnitTests.csproj", "{45A84466-C79E-4B56-A89E-C8C3BDB3E795}"
25 | EndProject
26 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "EnvironmentAbstractions.BannedApiAnalyzer", "src\EnvironmentAbstractions.BannedApiAnalyzer\EnvironmentAbstractions.BannedApiAnalyzer.csproj", "{576C1129-D7A4-495A-8E55-2F45C8D779FD}"
27 | EndProject
28 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "workflows", "workflows", "{FF9B8558-0D22-4504-9D65-2B6F85914F44}"
29 | ProjectSection(SolutionItems) = preProject
30 | .github\workflows\CI.yml = .github\workflows\CI.yml
31 | .github\workflows\Official.yml = .github\workflows\Official.yml
32 | EndProjectSection
33 | EndProject
34 | Global
35 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
36 | Debug|Any CPU = Debug|Any CPU
37 | Release|Any CPU = Release|Any CPU
38 | EndGlobalSection
39 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
40 | {80AA9A82-F46B-47C4-BB3E-5EA2BEBDFCB5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
41 | {80AA9A82-F46B-47C4-BB3E-5EA2BEBDFCB5}.Debug|Any CPU.Build.0 = Debug|Any CPU
42 | {80AA9A82-F46B-47C4-BB3E-5EA2BEBDFCB5}.Release|Any CPU.ActiveCfg = Release|Any CPU
43 | {80AA9A82-F46B-47C4-BB3E-5EA2BEBDFCB5}.Release|Any CPU.Build.0 = Release|Any CPU
44 | {74C0D9E2-3383-4EC5-AD28-39AE187DF4D9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
45 | {74C0D9E2-3383-4EC5-AD28-39AE187DF4D9}.Debug|Any CPU.Build.0 = Debug|Any CPU
46 | {74C0D9E2-3383-4EC5-AD28-39AE187DF4D9}.Release|Any CPU.ActiveCfg = Release|Any CPU
47 | {74C0D9E2-3383-4EC5-AD28-39AE187DF4D9}.Release|Any CPU.Build.0 = Release|Any CPU
48 | {21233AD9-E8C2-4D6F-956D-C61C64938C74}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
49 | {21233AD9-E8C2-4D6F-956D-C61C64938C74}.Debug|Any CPU.Build.0 = Debug|Any CPU
50 | {21233AD9-E8C2-4D6F-956D-C61C64938C74}.Release|Any CPU.ActiveCfg = Release|Any CPU
51 | {21233AD9-E8C2-4D6F-956D-C61C64938C74}.Release|Any CPU.Build.0 = Release|Any CPU
52 | {45A84466-C79E-4B56-A89E-C8C3BDB3E795}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
53 | {45A84466-C79E-4B56-A89E-C8C3BDB3E795}.Debug|Any CPU.Build.0 = Debug|Any CPU
54 | {45A84466-C79E-4B56-A89E-C8C3BDB3E795}.Release|Any CPU.ActiveCfg = Release|Any CPU
55 | {45A84466-C79E-4B56-A89E-C8C3BDB3E795}.Release|Any CPU.Build.0 = Release|Any CPU
56 | {576C1129-D7A4-495A-8E55-2F45C8D779FD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
57 | {576C1129-D7A4-495A-8E55-2F45C8D779FD}.Debug|Any CPU.Build.0 = Debug|Any CPU
58 | {576C1129-D7A4-495A-8E55-2F45C8D779FD}.Release|Any CPU.ActiveCfg = Release|Any CPU
59 | {576C1129-D7A4-495A-8E55-2F45C8D779FD}.Release|Any CPU.Build.0 = Release|Any CPU
60 | EndGlobalSection
61 | GlobalSection(SolutionProperties) = preSolution
62 | HideSolutionNode = FALSE
63 | EndGlobalSection
64 | GlobalSection(NestedProjects) = preSolution
65 | {FF9B8558-0D22-4504-9D65-2B6F85914F44} = {55D8C0E6-4848-49DD-852C-CAA32BBD3C69}
66 | EndGlobalSection
67 | GlobalSection(ExtensibilityGlobals) = postSolution
68 | SolutionGuid = {7A2E8992-3C4B-47AB-8EF9-5278E783E51B}
69 | EndGlobalSection
70 | EndGlobal
71 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2022 Jeff Kluge
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/NuGet.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # `System.Environment` Abstractions for .NET
2 |
3 | [](https://nuget.org/packages/EnvironmentAbstractions)
4 | [](https://nuget.org/packages/EnvironmentAbstractions.TestHelpers)
5 | [](https://nuget.org/packages/EnvironmentAbstractions.BannedApiAnalyzer)
6 | [](https://github.com/jeffkl/EnvironmentAbstractions/actions/workflows/Official.yml)
7 |
8 | EnvironmentAbstractions is an interface abstraction for the `System.Environment` class in .NET to make testing components easier. A lot of repositories have code that accesses environment variables
9 | and corresponding logic to mock the functionality in a unit test. Some people set environment variables during tests while others have their own interfaces. However,
10 | setting environment variables applies to the entire process which can limit the parallelism of test execution. This API is similar to [System.IO.Abstractions](https://github.com/TestableIO/System.IO.Abstractions)
11 | but intended for environment variable access.
12 |
13 | There are two interfaces available, `IEnvironmentProvider` and `IEnvironmentVariableProvider`. The `IEnvironmentProvider` abstracts away everything in `System.Environment` while `IEnvironmentVariableProvider` only provides abstractions for accessing environment variables.
14 |
15 | ## Getting Started
16 |
17 | Add a `` to the [EnvironmentAbstractions](https://nuget.org/packages/EnvironmentAbstractions) package:
18 |
19 | ```xml
20 |
21 | ```
22 |
23 | ## `IEnvironmentProvider`
24 |
25 | The `IEnvironmentProvider` interface provides an abstraction for everything in the `System.Environment` class including getting system information, user information, or accessing environment variables.
26 |
27 | Use the `IEnvironmentProvider` interface when accessing the environment your code:
28 |
29 | ```c#
30 | public static void SayHello(IEnvironmentProvider environmentProvider)
31 | {
32 | Console.WriteLine("Hello, {0}!", environmentProvider.UserName);
33 | }
34 |
35 | public static void PrintSortedEnvironmentVariables(IEnvironmentProvider environmentProvider)
36 | {
37 | foreach (KeyValuePair item in environmentProvider.GetEnvironmentVariables()
38 | .OrderBy(i => i.Key))
39 | {
40 | Console.WriteLine("{0}={1}", item.Key, item.Value);
41 | }
42 | }
43 | ```
44 |
45 | Then you can call that code with the default environment variable provider `SystemEnvironmentProvider` and its singleton `SystemEnvironmentProvider.Instance`:
46 |
47 | ```c#
48 | public static void Main(string[] args)
49 | {
50 | IEnvironmentProvider environmentProvider = SystemEnvironmentProvider.Instance;
51 |
52 | SayHello(environmentProvider);
53 |
54 | PrintSortedEnvironmentVariables(environmentProvider);
55 | }
56 |
57 | public static void SayHello(IEnvironmentProvider environmentProvider)
58 | {
59 | Console.WriteLine("Hello, {0}!", environmentProvider.UserName);
60 | }
61 |
62 | public static void PrintSortedEnvironmentVariables(IEnvironmentProvider environmentProvider)
63 | {
64 | foreach (KeyValuePair item in environmentProvider.GetEnvironmentVariables()
65 | .OrderBy(i => i.Key))
66 | {
67 | Console.WriteLine("{0}={1}", item.Key, item.Value);
68 | }
69 | }
70 | ```
71 |
72 | Unit tests can use the `MockEnvironmentProvider` class from the [EnvironmentAbstractions.TestHelpers package](https://nuget.org/packages/EnvironmentAbstractions.TestHelpers)
73 | to mock the values returned by environment access:
74 |
75 | ```c#
76 | using EnvironmentAbstractions.TestHelpers;
77 | using Xunit;
78 |
79 | [Fact]
80 | public void Test1()
81 | {
82 | IEnvironmentProvider environmentProvider = new MockEnvironmentProvider();
83 |
84 | environmentVariableProvider["Variable1"] = "Value1";
85 | environmentVariableProvider["Variable2"] = "Value2";
86 |
87 | Program.PrintSortedEnvironmentVariables(environmentVariableProvider);
88 | }
89 |
90 | [Fact]
91 | public void Test2()
92 | {
93 | IEnvironmentProvider environmentProvider = new MockEnvironmentProvider();
94 |
95 | environmentProvider.UserName = "UserA";
96 |
97 | Program.SayHello(environmentVariableProvider);
98 | }
99 | ```
100 |
101 | Unit tests can also use any system capable of mocking interfaces like [Moq](https://nuget.org/packages/Moq)
102 | ```c#
103 | using Moq;
104 |
105 | [Fact]
106 | public void GetEnvironmentVariableMoqTest()
107 | {
108 | Mock environmentProviderMock = new Mock();
109 |
110 | environmentProviderMock.Setup(i => i.GetEnvironmentVariable(It.Is(i => i.Equals("Var1"))))
111 | .Returns("Value1");
112 |
113 | environmentProviderMock.Setup(i => i.GetEnvironmentVariable(It.Is(i => i.Equals("Var2"))))
114 | .Returns("Value2");
115 |
116 | IEnvironmentProvider environmentProvider = environmentProviderMock.Object;
117 |
118 | Program.PrintSortedEnvironmentVariables(environmentProvider);
119 | }
120 | ```
121 |
122 | ## `IEnvironmentVariableProvider`
123 |
124 | If your project only wants to abstract environment variable access, you can use only the `IEnvironmentVariableProvider` interface.
125 |
126 | Use the `IEnvironmentVariableProvider` interface when accessing environment variables in your code:
127 |
128 | ```c#
129 | public static void PrintSortedEnvironmentVariables(IEnvironmentVariableProvider environmentVariableProvider)
130 | {
131 | foreach (KeyValuePair item in environmentVariableProvider.GetEnvironmentVariables()
132 | .OrderBy(i => i.Key))
133 | {
134 | Console.WriteLine("{0}={1}", item.Key, item.Value);
135 | }
136 | }
137 | ```
138 |
139 | Then you can call that code with the default environment variable provider `SystemEnvironmentVariableProvider` and its singleton `SystemEnvironmentVariableProvider.Instance`:
140 |
141 | ```c#
142 | public static void Main(string[] args)
143 | {
144 | PrintSortedEnvironmentVariables(SystemEnvironmentVariableProvider.Instance);
145 | }
146 |
147 | public static void PrintSortedEnvironmentVariables(IEnvironmentVariableProvider environmentVariableProvider)
148 | {
149 | foreach (KeyValuePair item in environmentVariableProvider.GetEnvironmentVariables()
150 | .OrderBy(i => i.Key))
151 | {
152 | Console.WriteLine("{0}={1}", item.Key, item.Value);
153 | }
154 | }
155 | ```
156 |
157 | Unit tests can use the `MockEnvironmentVariableProvider` class from the [EnvironmentAbstractions.TestHelpers package](https://nuget.org/packages/EnvironmentAbstractions.TestHelpers)
158 | to mock environment variables:
159 |
160 | ```c#
161 | using EnvironmentAbstractions.TestHelpers;
162 | using Xunit;
163 |
164 | [Fact]
165 | public void Test1()
166 | {
167 | IEnvironmentVariableProvider environmentVariableProvider = new MockEnvironmentVariableProvider();
168 |
169 | environmentVariableProvider["Variable1"] = "Value1";
170 | environmentVariableProvider["Variable2"] = "Value2";
171 |
172 | Program.PrintSortedEnvironmentVariables(environmentVariableProvider);
173 | }
174 | ```
175 |
176 | Unit tests can also use any system capable of mocking interfaces like [Moq](https://nuget.org/packages/Moq)
177 | ```c#
178 | using Moq;
179 |
180 | [Fact]
181 | public void GetEnvironmentVariableMoqTest()
182 | {
183 | Mock environmentVariableProviderMock = new Mock();
184 |
185 | environmentVariableProviderMock.Setup(i => i.GetEnvironmentVariable(It.Is(i => i.Equals("Var1"))))
186 | .Returns("Value1");
187 |
188 | environmentVariableProviderMock.Setup(i => i.GetEnvironmentVariable(It.Is(i => i.Equals("Var2"))))
189 | .Returns("Value2");
190 |
191 | IEnvironmentVariableProvider environmentVariableProvider = environmentVariableProviderMock.Object;
192 |
193 | Program.PrintSortedEnvironmentVariables(environmentVariableProvider);
194 | }
195 | ```
196 |
197 | ## Preventing usage of `System.Environment`
198 |
199 | If you want to use `IEnvironmentVariableProvider` exclusively in your repository, you can reference the
200 | [EnvironmentAbstractions.BannedApiAnalyzer](https://nuget.org/packages/EnvironmentAbstractions.BannedApiAnalyzer) package which uses the
201 | [Microsoft.CodeAnalysis.BannedApiAnalyzers](https://github.com/dotnet/roslyn-analyzers/blob/main/src/Microsoft.CodeAnalysis.BannedApiAnalyzers/BannedApiAnalyzers.Help.md)
202 | Roslyn analyzer to prevent code from accessing the `System.Environment` APIs.
203 |
204 | Sample project
205 | ```xml
206 |
207 |
208 | netstandard2.0
209 |
210 |
211 |
212 |
213 |
214 | ```
215 |
216 | Sample source code
217 | ```c#
218 | public static void Main(string[] args)
219 | {
220 | Console.WriteLine("Hello, {0}!", System.Environment.GetEnvironmentVariable("USERNAME"));
221 | }
222 | ```
223 |
224 | Sample error
225 | ```
226 | warning RS0030: The symbol 'Environment.GetEnvironmentVariable(string)' is banned in this project: Use IEnvironmentProvider.GetEnvironmentVariable(string) instead.
227 |
--------------------------------------------------------------------------------
/build/PackageIcon.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jeffkl/EnvironmentAbstractions/6560521e990d66a062c2e4cd0e5f11b9c94777cf/build/PackageIcon.png
--------------------------------------------------------------------------------
/build/key.snk:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jeffkl/EnvironmentAbstractions/6560521e990d66a062c2e4cd0e5f11b9c94777cf/build/key.snk
--------------------------------------------------------------------------------
/build/stylecop.json:
--------------------------------------------------------------------------------
1 | {
2 | "$schema": "https://raw.githubusercontent.com/DotNetAnalyzers/StyleCopAnalyzers/master/StyleCop.Analyzers/StyleCop.Analyzers/Settings/stylecop.schema.json",
3 | "settings": {
4 | "orderingRules": {
5 | "usingDirectivesPlacement": "outsideNamespace",
6 | "systemUsingDirectivesFirst": false,
7 | "blankLinesBetweenUsingGroups": "require"
8 | },
9 | "namingRules": {
10 | "allowCommonHungarianPrefixes": true
11 | },
12 | "documentationRules": {
13 | "companyName": "Jeff Kluge",
14 | "copyrightText": "Copyright (c) {companyName}.\n\nLicensed under the MIT license.",
15 | "xmlHeader": false
16 | }
17 | }
18 | }
--------------------------------------------------------------------------------
/build/xunit.runner.json:
--------------------------------------------------------------------------------
1 | {
2 | "$schema": "https://xunit.net/schema/current/xunit.runner.schema.json",
3 | "shadowCopy": false
4 | }
--------------------------------------------------------------------------------
/src/EnvironmentAbstractions.BannedApiAnalyzer/EnvironmentAbstractions.BannedApiAnalyzer.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 | netstandard2.0
4 | Adds rules for Microsoft.CodeAnalysis.BannedApiAnalyzers to ensure projects don't use the System.Environment class to manipulate environment variables..
5 | Environment Variable Abstraction env var banned api
6 | $(BaseArtifactsPath)\$(MSBuildProjectName)\
7 | true
8 | false
9 | false
10 |
11 | $(NoWarn);NU5128;SA0001
12 | true
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
--------------------------------------------------------------------------------
/src/EnvironmentAbstractions.BannedApiAnalyzer/README.md:
--------------------------------------------------------------------------------
1 | # EnvironmentAbstractions.BannedApiAnalyzer
2 | 
3 |
4 | The `EnvironmentAbstractions.BannedApiAnalyzer` package uses the
5 | [Microsoft.CodeAnalysis.BannedApiAnalyzers](https://github.com/dotnet/roslyn-analyzers/blob/main/src/Microsoft.CodeAnalysis.BannedApiAnalyzers/BannedApiAnalyzers.Help.md)
6 | package to prevent usages of `System.Environment` to access the environment.
7 |
8 | Adding a `` to the package in your project is all you need:
9 |
10 | ```xml
11 |
12 |
13 | netstandard2.0
14 |
15 |
16 |
17 |
18 |
19 | ```
20 |
21 | Then when anyone attempts to call the built-in methods for accessing the environment, they'll receive a build warning indicating that they should use `IEnvironmentProvider` instead:
22 |
23 | ```c#
24 | public static void Main(string[] args)
25 | {
26 | Console.WriteLine("Hello, {0}!", System.Environment.UserName);
27 | }
28 | ```
29 |
30 | ```
31 | warning RS0030: The symbol 'Environment.UserName' is banned in this project: Use IEnvironmentProvider.UserName instead.
32 | ```
33 |
34 | If you want to only ban access to environment variables, you'll need to first set the MSBuild property `BanSystemEnvironmentVariableAPIs` to `true` in your project:
35 |
36 | ```xml
37 |
38 |
39 | true
40 |
41 | ```
42 |
43 | Then only accessing environment variables will emit a compile-time error telling developers to use `IEnvironmentVariableProvider` instead:
44 |
45 | ```c#
46 | public static void Main(string[] args)
47 | {
48 | Console.WriteLine("Hello, {0}!", System.Environment.GetEnvironmentVariable("USERNAME"));
49 | }
50 | ```
51 |
52 | ```
53 | warning RS0030: The symbol 'Environment.GetEnvironmentVariable(string)' is banned in this project: Use IEnvironmentVariableProvider.GetEnvironmentVariable(string) instead.
54 | ```
55 |
--------------------------------------------------------------------------------
/src/EnvironmentAbstractions.BannedApiAnalyzer/build/BannedSymbols.EnvironmentAbstractions.IEnvironmentProvider.txt:
--------------------------------------------------------------------------------
1 | M:System.Environment.Exit(System.Int32);Use IEnvironmentProvider.Exit(int) instead.
2 | M:System.Environment.ExpandEnvironmentVariables(System.String);Use IEnvironmentProvider.ExpandEnvironmentVariables(string) instead.
3 | M:System.Environment.FailFast(System.String);Use IEnvironmentProvider.FailFast(string) instead.
4 | M:System.Environment.FailFast(System.String,System.Exception);Use IEnvironmentProvider.FailFast(string, Exception) instead.
5 | M:System.Environment.GetCommandLineArgs;Use IEnvironmentProvider.GetCommandLineArgs() instead.
6 | M:System.Environment.GetEnvironmentVariable(System.String);Use IEnvironmentProvider.GetEnvironmentVariable(string) instead.
7 | M:System.Environment.GetEnvironmentVariable(System.String,System.EnvironmentVariableTarget);Use IEnvironmentProvider.GetEnvironmentVariable(string, EnvironmentVariableTarget) instead.
8 | M:System.Environment.GetEnvironmentVariables(System.EnvironmentVariableTarget);Use IEnvironmentProvider.GetEnvironmentVariables(EnvironmentVariableTarget) instead.
9 | M:System.Environment.GetEnvironmentVariables;Use IEnvironmentProvider.GetEnvironmentVariables(string) instead.
10 | M:System.Environment.GetFolderPath(System.Environment.SpecialFolder);Use IEnvironmentProvider.GetFolderPath(Environment.SpecialFolder) instead.
11 | M:System.Environment.GetFolderPath(System.Environment.SpecialFolder,System.Environment.SpecialFolderOption);Use IEnvironmentProvider.GetFolderPath(Environment.SpecialFolder, Environment.SpecialFolderOption) instead.
12 | M:System.Environment.GetLogicalDrives;Use IEnvironmentProvider.GetLogicalDrives() instead.
13 | M:System.Environment.SetEnvironmentVariable(System.String,System.String);Use IEnvironmentProvider.SetEnvironmentVariable(string, string) instead.
14 | M:System.Environment.SetEnvironmentVariable(System.String,System.String,System.EnvironmentVariableTarget);Use IEnvironmentProvider.SetEnvironmentVariable(string, string, EnvironmentVariableTarget) instead.
15 | P:System.Environment.CommandLine;Use IEnvironmentProvider.CommandLine instead.
16 | P:System.Environment.CurrentDirectory;Use IEnvironmentProvider.CurrentDirectory instead.
17 | P:System.Environment.CurrentManagedThreadId;Use IEnvironmentProvider.CurrentManagedThreadId instead.
18 | P:System.Environment.ExitCode;Use IEnvironmentProvider.ExitCode instead.
19 | P:System.Environment.HasShutdownStarted;Use IEnvironmentProvider.HasShutdownStarted instead.
20 | P:System.Environment.Is64BitOperatingSystem;Use IEnvironmentProvider.Is64BitOperatingSystem instead.
21 | P:System.Environment.Is64BitProcess;Use IEnvironmentProvider.Is64BitProcess instead.
22 | P:System.Environment.IsPrivilegedProcess;Use IEnvironmentProvider.IsPrivilegedProcess instead.
23 | P:System.Environment.MachineName;Use IEnvironmentProvider.MachineName instead.
24 | P:System.Environment.NewLine;Use IEnvironmentProvider.NewLine instead.
25 | P:System.Environment.OSVersion;Use IEnvironmentProvider.OSVersion instead.
26 | P:System.Environment.ProcessCpuUsage;Use IEnvironmentProvider.ProcessCpuUsage instead.
27 | P:System.Environment.ProcessId;Use IEnvironmentProvider.ProcessId instead.
28 | P:System.Environment.ProcessorCount;Use IEnvironmentProvider.ProcessorCount instead.
29 | P:System.Environment.ProcessPath;Use IEnvironmentProvider.ProcessPath instead.
30 | P:System.Environment.StackTrace;Use IEnvironmentProvider.StackTrace instead.
31 | P:System.Environment.SystemDirectory;Use IEnvironmentProvider.SystemDirectory instead.
32 | P:System.Environment.SystemPageSize;Use IEnvironmentProvider.SystemPageSize instead.
33 | P:System.Environment.TickCount;Use IEnvironmentProvider.TickCount instead.
34 | P:System.Environment.TickCount64;Use IEnvironmentProvider.TickCount64 instead.
35 | P:System.Environment.UserDomainName;Use IEnvironmentProvider.UserDomainName instead.
36 | P:System.Environment.UserInteractive;Use IEnvironmentProvider.UserInteractive instead.
37 | P:System.Environment.UserName;Use IEnvironmentProvider.UserName instead.
38 | P:System.Environment.Version;Use IEnvironmentProvider.Version instead.
39 | P:System.Environment.WorkingSet;Use IEnvironmentProvider.WorkingSet instead.
40 |
--------------------------------------------------------------------------------
/src/EnvironmentAbstractions.BannedApiAnalyzer/build/BannedSymbols.EnvironmentAbstractions.IEnvironmentVariableProvider.txt:
--------------------------------------------------------------------------------
1 | M:System.Environment.ExpandEnvironmentVariables(System.String);Use IEnvironmentVariableProvider.ExpandEnvironmentVariables(string) instead.
2 | M:System.Environment.GetEnvironmentVariable(System.String);Use IEnvironmentVariableProvider.GetEnvironmentVariable(string) instead.
3 | M:System.Environment.GetEnvironmentVariable(System.String,System.EnvironmentVariableTarget);Use IEnvironmentVariableProvider.GetEnvironmentVariable(string, EnvironmentVariableTarget) instead.
4 | M:System.Environment.GetEnvironmentVariables;Use IEnvironmentProvider.GetEnvironmentVariables(string) instead.
5 | M:System.Environment.GetEnvironmentVariables(System.EnvironmentVariableTarget);Use IEnvironmentProvider.GetEnvironmentVariables(EnvironmentVariableTarget) instead.
6 | M:System.Environment.SetEnvironmentVariable(System.String,System.String);Use IEnvironmentVariableProvider.SetEnvironmentVariable(string, string) instead.
7 | M:System.Environment.SetEnvironmentVariable(System.String,System.String,System.EnvironmentVariableTarget);Use IEnvironmentVariableProvider.SetEnvironmentVariable(string, string, EnvironmentVariableTarget) instead.
8 |
--------------------------------------------------------------------------------
/src/EnvironmentAbstractions.BannedApiAnalyzer/build/EnvironmentAbstractions.BannedApiAnalyzer.props:
--------------------------------------------------------------------------------
1 |
2 |
--------------------------------------------------------------------------------
/src/EnvironmentAbstractions.BannedApiAnalyzer/build/EnvironmentAbstractions.BannedApiAnalyzer.targets:
--------------------------------------------------------------------------------
1 |
2 |
3 |
6 |
7 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/src/EnvironmentAbstractions.BannedApiAnalyzer/buildTransitive/EnvironmentAbstractions.BannedApiAnalyzer.props:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
--------------------------------------------------------------------------------
/src/EnvironmentAbstractions.BannedApiAnalyzer/buildTransitive/EnvironmentAbstractions.BannedApiAnalyzer.targets:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
--------------------------------------------------------------------------------
/src/EnvironmentAbstractions.TestHelpers.UnitTests/EnvironmentAbstractions.TestHelpers.UnitTests.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 | net472;net6.0;net8.0;net9.0
4 | false
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
--------------------------------------------------------------------------------
/src/EnvironmentAbstractions.TestHelpers.UnitTests/MockEnvironmentVariableProviderTests.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Jeff Kluge.
2 | //
3 | // Licensed under the MIT license.
4 |
5 | using Shouldly;
6 | using System;
7 | using System.Collections.Generic;
8 | using Xunit;
9 |
10 | namespace EnvironmentAbstractions.TestHelpers.UnitTests
11 | {
12 | public class MockEnvironmentVariableProviderTests
13 | {
14 | private const string EnvironmentVariable1Name = "Var1";
15 | private const string EnvironmentVariable1Value = "Value1";
16 | private const string EnvironmentVariable2Name = "Var2";
17 | private const string EnvironmentVariable2Value = "Value2";
18 | private const string EnvironmentVariable3Name = "Var3";
19 | private const string EnvironmentVariable3Value = "Value3";
20 |
21 | [Fact]
22 | public void AddsExistingEnvironmentVariablesTest()
23 | {
24 | IEnvironmentVariableProvider environmentVariableProvider = new MockEnvironmentVariableProvider(addExistingEnvironmentVariables: true)
25 | {
26 | ["COMPUTERNAME"] = "MyComputer01",
27 | };
28 |
29 | environmentVariableProvider.GetEnvironmentVariable("COMPUTERNAME")
30 | .ShouldBe("MyComputer01");
31 |
32 | environmentVariableProvider.GetEnvironmentVariable("USERNAME")
33 | .ShouldBe(SystemEnvironmentVariableProvider.Instance.GetEnvironmentVariable("USERNAME"));
34 | }
35 |
36 | [Fact]
37 | public void AddTest()
38 | {
39 | MockEnvironmentVariableProvider mockEnvironmentVariableProvider = new MockEnvironmentVariableProvider();
40 |
41 | mockEnvironmentVariableProvider[EnvironmentVariable1Name].ShouldBeNull();
42 |
43 | mockEnvironmentVariableProvider.Add(EnvironmentVariable1Name, EnvironmentVariable1Value);
44 |
45 | mockEnvironmentVariableProvider[EnvironmentVariable1Name].ShouldBe(EnvironmentVariable1Value);
46 | }
47 |
48 | [Fact]
49 | public void ExpandEnvironmentVariablesTest()
50 | {
51 | IEnvironmentVariableProvider environmentVariableProvider = new MockEnvironmentVariableProvider
52 | {
53 | [EnvironmentVariable1Name] = EnvironmentVariable1Value,
54 | [EnvironmentVariable2Name] = EnvironmentVariable2Value,
55 | };
56 |
57 | environmentVariableProvider.ExpandEnvironmentVariables("Leading text %VAR1% middle text %VAR2% trailing text")
58 | .ShouldBe("Leading text Value1 middle text Value2 trailing text");
59 | }
60 |
61 | [Theory]
62 | [InlineData(EnvironmentVariableTarget.Machine)]
63 | [InlineData(EnvironmentVariableTarget.Process)]
64 | [InlineData(EnvironmentVariableTarget.User)]
65 | [InlineData(null)]
66 | public void GetEnvironmentVariablesTest(EnvironmentVariableTarget? environmentVariableTarget)
67 | {
68 | IEnvironmentVariableProvider environmentVariableProvider = new MockEnvironmentVariableProvider
69 | {
70 | [EnvironmentVariable1Name] = EnvironmentVariable1Value,
71 | [EnvironmentVariable2Name] = EnvironmentVariable2Value,
72 | };
73 |
74 | IReadOnlyDictionary actual = environmentVariableTarget == null
75 | ? environmentVariableProvider.GetEnvironmentVariables()
76 | : environmentVariableProvider.GetEnvironmentVariables(environmentVariableTarget.Value);
77 |
78 | actual
79 | .ShouldBe(
80 | new Dictionary
81 | {
82 | [EnvironmentVariable1Name] = EnvironmentVariable1Value,
83 | [EnvironmentVariable2Name] = EnvironmentVariable2Value,
84 | },
85 | ignoreOrder: true);
86 | }
87 |
88 | [Theory]
89 | [InlineData(EnvironmentVariableTarget.Machine)]
90 | [InlineData(EnvironmentVariableTarget.Process)]
91 | [InlineData(EnvironmentVariableTarget.User)]
92 | [InlineData(null)]
93 | public void GetEnvironmentVariableWithEnvironmentVariableTarget(EnvironmentVariableTarget? environmentVariableTarget)
94 | {
95 | IEnvironmentVariableProvider environmentVariableProvider = new MockEnvironmentVariableProvider
96 | {
97 | [EnvironmentVariable1Name] = EnvironmentVariable1Value,
98 | };
99 |
100 | environmentVariableProvider.SetEnvironmentVariable(EnvironmentVariable2Name, EnvironmentVariable2Value, EnvironmentVariableTarget.User);
101 | environmentVariableProvider.SetEnvironmentVariable(EnvironmentVariable3Name, EnvironmentVariable3Value, EnvironmentVariableTarget.Machine);
102 |
103 | switch (environmentVariableTarget)
104 | {
105 | case EnvironmentVariableTarget.Machine:
106 | environmentVariableProvider.GetEnvironmentVariable(EnvironmentVariable3Name, environmentVariableTarget.Value)
107 | .ShouldBe(EnvironmentVariable3Value);
108 |
109 | break;
110 | case EnvironmentVariableTarget.User:
111 | environmentVariableProvider.GetEnvironmentVariable(EnvironmentVariable2Name, environmentVariableTarget.Value)
112 | .ShouldBe(EnvironmentVariable2Value);
113 | break;
114 | default:
115 | string? actual = environmentVariableTarget == null
116 | ? environmentVariableProvider.GetEnvironmentVariable(EnvironmentVariable1Name)
117 | : environmentVariableProvider.GetEnvironmentVariable(EnvironmentVariable1Name, environmentVariableTarget.Value);
118 | actual.ShouldBe(EnvironmentVariable1Value);
119 | break;
120 | }
121 | }
122 |
123 | [Fact]
124 | public void IndexerTest()
125 | {
126 | MockEnvironmentVariableProvider mockEnvironmentVariableProvider = new MockEnvironmentVariableProvider();
127 |
128 | mockEnvironmentVariableProvider[EnvironmentVariable1Name].ShouldBeNull();
129 |
130 | mockEnvironmentVariableProvider[EnvironmentVariable1Name] = EnvironmentVariable1Value;
131 |
132 | mockEnvironmentVariableProvider[EnvironmentVariable1Name].ShouldBe(EnvironmentVariable1Value);
133 |
134 | mockEnvironmentVariableProvider[EnvironmentVariable2Name] = EnvironmentVariable2Value;
135 |
136 | mockEnvironmentVariableProvider[EnvironmentVariable2Name].ShouldBe(EnvironmentVariable2Value);
137 | }
138 |
139 | [Theory]
140 | [InlineData(EnvironmentVariableTarget.Machine)]
141 | [InlineData(EnvironmentVariableTarget.Process)]
142 | [InlineData(EnvironmentVariableTarget.User)]
143 | [InlineData(null)]
144 | public void SetEnvironmentVariableTest(EnvironmentVariableTarget? environmentVariableTarget)
145 | {
146 | IEnvironmentVariableProvider environmentVariableProvider = new MockEnvironmentVariableProvider();
147 |
148 | if (environmentVariableTarget == null)
149 | {
150 | environmentVariableProvider.SetEnvironmentVariable(EnvironmentVariable1Name, EnvironmentVariable2Value);
151 | }
152 | else
153 | {
154 | environmentVariableProvider.SetEnvironmentVariable(EnvironmentVariable1Name, EnvironmentVariable2Value, environmentVariableTarget.Value);
155 | }
156 |
157 | string? actual = environmentVariableTarget == null
158 | ? environmentVariableProvider.GetEnvironmentVariable(EnvironmentVariable1Name)
159 | : environmentVariableProvider.GetEnvironmentVariable(EnvironmentVariable1Name, environmentVariableTarget.Value);
160 |
161 | actual.ShouldBe(EnvironmentVariable2Value);
162 |
163 | if (environmentVariableTarget == null)
164 | {
165 | environmentVariableProvider.SetEnvironmentVariable(EnvironmentVariable1Name, null);
166 | }
167 | else
168 | {
169 | environmentVariableProvider.SetEnvironmentVariable(EnvironmentVariable1Name, null, environmentVariableTarget.Value);
170 | }
171 |
172 | environmentVariableProvider.GetEnvironmentVariable(EnvironmentVariable1Name)
173 | .ShouldBeNull();
174 | }
175 | }
176 | }
--------------------------------------------------------------------------------
/src/EnvironmentAbstractions.TestHelpers/EnvironmentAbstractions.TestHelpers.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 | netstandard2.0;net6.0;net8.0;net9.0
4 | Provides implementations of IEnvironmentVariableProvider so that unit tests can mock calls that retrieve environment variable.
5 | Environment Variable Abstraction env var test helper
6 | $(BaseArtifactsPath)\$(MSBuildProjectName)\
7 | true
8 | true
9 | System
10 | true
11 |
12 |
13 |
14 |
15 |
16 |
--------------------------------------------------------------------------------
/src/EnvironmentAbstractions.TestHelpers/MockEnvironmentProvider.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Jeff Kluge.
2 | //
3 | // Licensed under the MIT license.
4 |
5 | using EnvironmentAbstractions.TestHelpers;
6 | using System.Collections.Generic;
7 | using System.Linq;
8 |
9 | namespace System
10 | {
11 | ///
12 | /// Represents an implementation of that stores values in memory.
13 | ///
14 | public class MockEnvironmentProvider : MockEnvironmentVariableProvider, IEnvironmentProvider
15 | {
16 | private static readonly OperatingSystem NullOperatingSystem = new OperatingSystem(0, new Version(1, 0));
17 |
18 | private static readonly Version Version1dot0 = NullOperatingSystem.Version;
19 |
20 | private string[] _commandLineArgs = Array.Empty();
21 | private string[] _logicalDrives = Array.Empty();
22 |
23 | private Dictionary _specialFolders = new Dictionary();
24 |
25 | ///
26 | /// Initializes a new instance of the class.
27 | ///
28 | /// true (default) to have all existing environment properties set from the current system, otherwise false.
29 | /// true to have all existing environment variables added, otherwise false (default).
30 | public MockEnvironmentProvider(bool useExistingEnvironmentValues = true, bool addExistingEnvironmentVariables = false)
31 | : base(addExistingEnvironmentVariables)
32 | {
33 | if (useExistingEnvironmentValues)
34 | {
35 | CommandLine = Environment.CommandLine;
36 | #if NET9_0_OR_GREATER
37 | CpuUsage = Environment.CpuUsage;
38 | #endif
39 | CurrentDirectory = Environment.CurrentDirectory;
40 | CurrentManagedThreadId = Environment.CurrentManagedThreadId;
41 | ExitCode = Environment.ExitCode;
42 | HasShutdownStarted = Environment.HasShutdownStarted;
43 | Is64BitOperatingSystem = Environment.Is64BitOperatingSystem;
44 | Is64BitProcess = Environment.Is64BitProcess;
45 | #if NET9_0_OR_GREATER
46 | IsPrivilegedProcess = Environment.IsPrivilegedProcess;
47 | #endif
48 | MachineName = Environment.MachineName;
49 | NewLine = Environment.NewLine;
50 | OSVersion = Environment.OSVersion;
51 | #if NET5_0_OR_GREATER
52 | ProcessId = Environment.ProcessId;
53 | #endif
54 | ProcessorCount = Environment.ProcessorCount;
55 | #if NET6_0_OR_GREATER
56 | ProcessPath = Environment.ProcessPath;
57 | #endif
58 | StackTrace = Environment.StackTrace;
59 | SystemDirectory = Environment.SystemDirectory;
60 | SystemPageSize = Environment.SystemPageSize;
61 | TickCount = Environment.TickCount;
62 | #if NETCOREAPP3_1_OR_GREATER
63 | TickCount64 = Environment.TickCount64;
64 | #endif
65 | UserDomainName = Environment.UserDomainName;
66 | UserInteractive = Environment.UserInteractive;
67 | UserName = Environment.UserName;
68 | Version = Environment.Version;
69 | WorkingSet = Environment.WorkingSet;
70 |
71 | _commandLineArgs = Environment.GetCommandLineArgs();
72 | _logicalDrives = Environment.GetLogicalDrives();
73 |
74 | foreach (Environment.SpecialFolder folder in Enum.GetValues(typeof(Environment.SpecialFolder)).Cast())
75 | {
76 | _specialFolders[folder] = Environment.GetFolderPath(folder);
77 | }
78 | }
79 | else
80 | {
81 | CommandLine = string.Empty;
82 | CurrentDirectory = string.Empty;
83 | MachineName = string.Empty;
84 | NewLine = string.Empty;
85 | OSVersion = NullOperatingSystem;
86 | StackTrace = string.Empty;
87 | SystemDirectory = string.Empty;
88 | UserDomainName = string.Empty;
89 | UserName = string.Empty;
90 | Version = Version1dot0;
91 | }
92 | }
93 |
94 | ///
95 | public string CommandLine { get; set; }
96 |
97 | #if NET9_0_OR_GREATER
98 | ///
99 | public Environment.ProcessCpuUsage CpuUsage { get; set; }
100 | #endif
101 |
102 | ///
103 | public string CurrentDirectory { get; set; }
104 |
105 | ///
106 | public int CurrentManagedThreadId { get; set; }
107 |
108 | ///
109 | public int ExitCode { get; set; }
110 |
111 | ///
112 | public bool HasShutdownStarted { get; set; }
113 |
114 | ///
115 | public bool Is64BitOperatingSystem { get; set; }
116 |
117 | ///
118 | public bool Is64BitProcess { get; set; }
119 |
120 | #if NET9_0_OR_GREATER
121 | ///
122 | public bool IsPrivilegedProcess { get; }
123 | #endif
124 |
125 | ///
126 | public string MachineName { get; set; }
127 |
128 | ///
129 | public string NewLine { get; set; }
130 |
131 | ///
132 | public OperatingSystem OSVersion { get; set; }
133 |
134 | #if NET5_0_OR_GREATER
135 | ///
136 | public int ProcessId { get; set; }
137 | #endif
138 |
139 | ///
140 | public int ProcessorCount { get; set; }
141 |
142 | #if NET6_0_OR_GREATER
143 | ///
144 | public string? ProcessPath { get; set; }
145 | #endif
146 |
147 | ///
148 | public string StackTrace { get; set; }
149 |
150 | ///
151 | public string SystemDirectory { get; set; }
152 |
153 | ///
154 | public int SystemPageSize { get; set; }
155 |
156 | ///
157 | public int TickCount { get; set; }
158 |
159 | #if NETCOREAPP3_1_OR_GREATER
160 | ///
161 | public long TickCount64 { get; set; }
162 | #endif
163 |
164 | ///
165 | public string UserDomainName { get; set; }
166 |
167 | ///
168 | public bool UserInteractive { get; set; }
169 |
170 | ///
171 | public string UserName { get; set; }
172 |
173 | ///
174 | public Version Version { get; set; }
175 |
176 | ///
177 | public long WorkingSet { get; set; }
178 |
179 | ///
180 | public void Exit(int exitCode) => ExitCode = exitCode;
181 |
182 | ///
183 | /// The does not currently support calling the method.
184 | public void FailFast(string? message) => throw new NotSupportedException($"The {nameof(MockEnvironmentProvider)} does not currently support calling the {nameof(FailFast)} method.");
185 |
186 | ///
187 | /// The does not currently support calling the method.
188 | public void FailFast(string? message, Exception? exception) => throw new NotSupportedException($"The {nameof(MockEnvironmentProvider)} does not currently support calling the {nameof(FailFast)} method.");
189 |
190 | ///
191 | public string[] GetCommandLineArgs() => _commandLineArgs;
192 |
193 | ///
194 | public string GetFolderPath(Environment.SpecialFolder folder) => _specialFolders.TryGetValue(folder, out string? value) ? value : string.Empty;
195 |
196 | ///
197 | public string GetFolderPath(Environment.SpecialFolder folder, Environment.SpecialFolderOption option) => _specialFolders.TryGetValue(folder, out string? value) ? value : string.Empty;
198 |
199 | ///
200 | public string[] GetLogicalDrives() => _logicalDrives;
201 |
202 | ///
203 | /// Sets the command-line arguments returned by .
204 | ///
205 | /// The command-line arguments to set.
206 | public void SetCommandLineArgs(string[] args) => _commandLineArgs = args;
207 |
208 | ///
209 | /// Sets a folder path returned by .
210 | ///
211 | /// The to set the path of.
212 | /// The path to set.
213 | public void SetFolderPath(Environment.SpecialFolder folder, string path) => _specialFolders[folder] = path;
214 |
215 | ///
216 | /// Sets the logical drives returned by .
217 | ///
218 | /// The drives to set.
219 | public void SetLogicalDrives(string[] drives) => _logicalDrives = drives;
220 | }
221 | }
--------------------------------------------------------------------------------
/src/EnvironmentAbstractions.TestHelpers/MockEnvironmentVariableProvider.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Jeff Kluge.
2 | //
3 | // Licensed under the MIT license.
4 |
5 | using System;
6 | using System.Collections.Concurrent;
7 | using System.Collections.Generic;
8 | using System.Linq;
9 | using System.Text;
10 |
11 | namespace EnvironmentAbstractions.TestHelpers
12 | {
13 | ///
14 | /// Represents an implementation of that stores values in memory.
15 | ///
16 | public class MockEnvironmentVariableProvider : IEnvironmentVariableProvider
17 | {
18 | private readonly ConcurrentDictionary[] _dictionaries = new[]
19 | {
20 | new ConcurrentDictionary(StringComparer.OrdinalIgnoreCase),
21 | new ConcurrentDictionary(StringComparer.OrdinalIgnoreCase),
22 | new ConcurrentDictionary(StringComparer.OrdinalIgnoreCase),
23 | };
24 |
25 | ///
26 | /// Initializes a new instance of the class.
27 | ///
28 | /// true to have all existing environment variables added, otherwise false (the default).
29 | public MockEnvironmentVariableProvider(bool addExistingEnvironmentVariables = false)
30 | {
31 | if (addExistingEnvironmentVariables)
32 | {
33 | for (int i = (int)EnvironmentVariableTarget.Machine; i >= 0; i--)
34 | {
35 | EnvironmentVariableTarget environmentVariableTarget = (EnvironmentVariableTarget)i;
36 |
37 | foreach (KeyValuePair item in SystemEnvironmentVariableProvider.Instance.GetEnvironmentVariables(environmentVariableTarget))
38 | {
39 | Add(item.Key, item.Value, environmentVariableTarget);
40 | }
41 | }
42 | }
43 | }
44 |
45 | ///
46 | public string? this[string name]
47 | {
48 | get
49 | {
50 | return GetEnvironmentVariable(name);
51 | }
52 |
53 | set
54 | {
55 | SetEnvironmentVariable(name, value);
56 | }
57 | }
58 |
59 | ///
60 | public void Add(string name, string? value)
61 | {
62 | SetEnvironmentVariable(name, value);
63 | }
64 |
65 | ///
66 | public void Add(string name, string? value, EnvironmentVariableTarget environmentVariableTarget)
67 | {
68 | SetEnvironmentVariable(name, value, environmentVariableTarget);
69 | }
70 |
71 | ///
72 | public string? ExpandEnvironmentVariables(string name)
73 | {
74 | const char EnvironmentVariableCharacter = '%';
75 |
76 | StringBuilder result = new StringBuilder();
77 |
78 | int lastPosition = 0;
79 | int currentPosition;
80 |
81 | while (lastPosition < name.Length && (currentPosition = name.IndexOf(EnvironmentVariableCharacter, lastPosition + 1)) >= 0)
82 | {
83 | if (name[lastPosition] == EnvironmentVariableCharacter)
84 | {
85 | string key = name.Substring(lastPosition + 1, currentPosition - lastPosition - 1);
86 |
87 | string? value = GetEnvironmentVariable(key);
88 |
89 | if (value != null)
90 | {
91 | result.Append(value);
92 |
93 | lastPosition = currentPosition + 1;
94 |
95 | continue;
96 | }
97 | }
98 |
99 | result.Append(name.Substring(lastPosition, currentPosition - lastPosition));
100 |
101 | lastPosition = currentPosition;
102 | }
103 |
104 | result.Append(name.Substring(lastPosition));
105 |
106 | return result.ToString();
107 | }
108 |
109 | ///
110 | public string? GetEnvironmentVariable(string name, EnvironmentVariableTarget target)
111 | {
112 | ConcurrentDictionary dictionary = _dictionaries[(int)target];
113 |
114 | return dictionary.TryGetValue(name, out string? value) ? value : default;
115 | }
116 |
117 | ///
118 | public string? GetEnvironmentVariable(string name)
119 | {
120 | return GetEnvironmentVariable(name, EnvironmentVariableTarget.Process);
121 | }
122 |
123 | ///
124 | public IReadOnlyDictionary GetEnvironmentVariables()
125 | {
126 | return GetEnvironmentVariables(EnvironmentVariableTarget.Process);
127 | }
128 |
129 | ///
130 | public IReadOnlyDictionary GetEnvironmentVariables(EnvironmentVariableTarget target)
131 | {
132 | Dictionary environmentVariables = new Dictionary(capacity: _dictionaries.Sum(i => i.Count), StringComparer.OrdinalIgnoreCase);
133 |
134 | for (int i = (int)EnvironmentVariableTarget.Machine; i >= 0; i--)
135 | {
136 | ConcurrentDictionary dictionary = _dictionaries[i];
137 |
138 | foreach (var item in dictionary)
139 | {
140 | environmentVariables[item.Key] = item.Value;
141 | }
142 | }
143 |
144 | return environmentVariables;
145 | }
146 |
147 | ///
148 | public void SetEnvironmentVariable(string name, string? value)
149 | {
150 | SetEnvironmentVariable(name, value, EnvironmentVariableTarget.Process);
151 | }
152 |
153 | ///
154 | public void SetEnvironmentVariable(string name, string? value, EnvironmentVariableTarget target)
155 | {
156 | ConcurrentDictionary dictionary = _dictionaries[(int)target];
157 |
158 | if (value != null)
159 | {
160 | dictionary[name] = value;
161 | }
162 | else
163 | {
164 | dictionary.TryRemove(name, out _);
165 | }
166 | }
167 | }
168 | }
--------------------------------------------------------------------------------
/src/EnvironmentAbstractions.TestHelpers/PublicAPI/net6.0/PublicAPI.Shipped.txt:
--------------------------------------------------------------------------------
1 | #nullable enable
2 | EnvironmentAbstractions.TestHelpers.MockEnvironmentVariableProvider
3 | EnvironmentAbstractions.TestHelpers.MockEnvironmentVariableProvider.Add(string! name, string? value) -> void
4 | EnvironmentAbstractions.TestHelpers.MockEnvironmentVariableProvider.ExpandEnvironmentVariables(string! name) -> string?
5 | EnvironmentAbstractions.TestHelpers.MockEnvironmentVariableProvider.GetEnvironmentVariable(string! name) -> string?
6 | EnvironmentAbstractions.TestHelpers.MockEnvironmentVariableProvider.GetEnvironmentVariable(string! name, System.EnvironmentVariableTarget target) -> string?
7 | EnvironmentAbstractions.TestHelpers.MockEnvironmentVariableProvider.GetEnvironmentVariables() -> System.Collections.Generic.IReadOnlyDictionary!
8 | EnvironmentAbstractions.TestHelpers.MockEnvironmentVariableProvider.GetEnvironmentVariables(System.EnvironmentVariableTarget target) -> System.Collections.Generic.IReadOnlyDictionary!
9 | EnvironmentAbstractions.TestHelpers.MockEnvironmentVariableProvider.MockEnvironmentVariableProvider(bool addExistingEnvironmentVariables = false) -> void
10 | EnvironmentAbstractions.TestHelpers.MockEnvironmentVariableProvider.SetEnvironmentVariable(string! name, string? value) -> void
11 | EnvironmentAbstractions.TestHelpers.MockEnvironmentVariableProvider.SetEnvironmentVariable(string! name, string? value, System.EnvironmentVariableTarget target) -> void
12 | EnvironmentAbstractions.TestHelpers.MockEnvironmentVariableProvider.this[string! name].get -> string?
13 | EnvironmentAbstractions.TestHelpers.MockEnvironmentVariableProvider.this[string! name].set -> void
14 | System.MockEnvironmentProvider
15 | System.MockEnvironmentProvider.CommandLine.get -> string!
16 | System.MockEnvironmentProvider.CommandLine.set -> void
17 | System.MockEnvironmentProvider.CurrentDirectory.get -> string!
18 | System.MockEnvironmentProvider.CurrentDirectory.set -> void
19 | System.MockEnvironmentProvider.CurrentManagedThreadId.get -> int
20 | System.MockEnvironmentProvider.CurrentManagedThreadId.set -> void
21 | System.MockEnvironmentProvider.Exit(int exitCode) -> void
22 | System.MockEnvironmentProvider.ExitCode.get -> int
23 | System.MockEnvironmentProvider.ExitCode.set -> void
24 | System.MockEnvironmentProvider.FailFast(string? message) -> void
25 | System.MockEnvironmentProvider.FailFast(string? message, System.Exception? exception) -> void
26 | System.MockEnvironmentProvider.GetCommandLineArgs() -> string![]!
27 | System.MockEnvironmentProvider.GetFolderPath(System.Environment.SpecialFolder folder) -> string!
28 | System.MockEnvironmentProvider.GetFolderPath(System.Environment.SpecialFolder folder, System.Environment.SpecialFolderOption option) -> string!
29 | System.MockEnvironmentProvider.GetLogicalDrives() -> string![]!
30 | System.MockEnvironmentProvider.HasShutdownStarted.get -> bool
31 | System.MockEnvironmentProvider.HasShutdownStarted.set -> void
32 | System.MockEnvironmentProvider.Is64BitOperatingSystem.get -> bool
33 | System.MockEnvironmentProvider.Is64BitOperatingSystem.set -> void
34 | System.MockEnvironmentProvider.Is64BitProcess.get -> bool
35 | System.MockEnvironmentProvider.Is64BitProcess.set -> void
36 | System.MockEnvironmentProvider.MachineName.get -> string!
37 | System.MockEnvironmentProvider.MachineName.set -> void
38 | System.MockEnvironmentProvider.MockEnvironmentProvider(bool useExistingEnvironmentValues = true, bool addExistingEnvironmentVariables = false) -> void
39 | System.MockEnvironmentProvider.NewLine.get -> string!
40 | System.MockEnvironmentProvider.NewLine.set -> void
41 | System.MockEnvironmentProvider.OSVersion.get -> System.OperatingSystem!
42 | System.MockEnvironmentProvider.OSVersion.set -> void
43 | System.MockEnvironmentProvider.ProcessId.get -> int
44 | System.MockEnvironmentProvider.ProcessId.set -> void
45 | System.MockEnvironmentProvider.ProcessorCount.get -> int
46 | System.MockEnvironmentProvider.ProcessorCount.set -> void
47 | System.MockEnvironmentProvider.ProcessPath.get -> string?
48 | System.MockEnvironmentProvider.ProcessPath.set -> void
49 | System.MockEnvironmentProvider.SetCommandLineArgs(string![]! args) -> void
50 | System.MockEnvironmentProvider.SetFolderPath(System.Environment.SpecialFolder folder, string! path) -> void
51 | System.MockEnvironmentProvider.SetLogicalDrives(string![]! drives) -> void
52 | System.MockEnvironmentProvider.StackTrace.get -> string!
53 | System.MockEnvironmentProvider.StackTrace.set -> void
54 | System.MockEnvironmentProvider.SystemDirectory.get -> string!
55 | System.MockEnvironmentProvider.SystemDirectory.set -> void
56 | System.MockEnvironmentProvider.SystemPageSize.get -> int
57 | System.MockEnvironmentProvider.SystemPageSize.set -> void
58 | System.MockEnvironmentProvider.TickCount.get -> int
59 | System.MockEnvironmentProvider.TickCount.set -> void
60 | System.MockEnvironmentProvider.TickCount64.get -> long
61 | System.MockEnvironmentProvider.TickCount64.set -> void
62 | System.MockEnvironmentProvider.UserDomainName.get -> string!
63 | System.MockEnvironmentProvider.UserDomainName.set -> void
64 | System.MockEnvironmentProvider.UserInteractive.get -> bool
65 | System.MockEnvironmentProvider.UserInteractive.set -> void
66 | System.MockEnvironmentProvider.UserName.get -> string!
67 | System.MockEnvironmentProvider.UserName.set -> void
68 | System.MockEnvironmentProvider.Version.get -> System.Version!
69 | System.MockEnvironmentProvider.Version.set -> void
70 | System.MockEnvironmentProvider.WorkingSet.get -> long
71 | System.MockEnvironmentProvider.WorkingSet.set -> void
72 |
--------------------------------------------------------------------------------
/src/EnvironmentAbstractions.TestHelpers/PublicAPI/net6.0/PublicAPI.Unshipped.txt:
--------------------------------------------------------------------------------
1 | #nullable enable
2 | EnvironmentAbstractions.TestHelpers.MockEnvironmentVariableProvider.Add(string! name, string? value, System.EnvironmentVariableTarget environmentVariableTarget) -> void
3 |
--------------------------------------------------------------------------------
/src/EnvironmentAbstractions.TestHelpers/PublicAPI/net8.0/PublicAPI.Shipped.txt:
--------------------------------------------------------------------------------
1 | #nullable enable
2 | EnvironmentAbstractions.TestHelpers.MockEnvironmentVariableProvider
3 | EnvironmentAbstractions.TestHelpers.MockEnvironmentVariableProvider.Add(string! name, string? value) -> void
4 | EnvironmentAbstractions.TestHelpers.MockEnvironmentVariableProvider.ExpandEnvironmentVariables(string! name) -> string?
5 | EnvironmentAbstractions.TestHelpers.MockEnvironmentVariableProvider.GetEnvironmentVariable(string! name) -> string?
6 | EnvironmentAbstractions.TestHelpers.MockEnvironmentVariableProvider.GetEnvironmentVariable(string! name, System.EnvironmentVariableTarget target) -> string?
7 | EnvironmentAbstractions.TestHelpers.MockEnvironmentVariableProvider.GetEnvironmentVariables() -> System.Collections.Generic.IReadOnlyDictionary!
8 | EnvironmentAbstractions.TestHelpers.MockEnvironmentVariableProvider.GetEnvironmentVariables(System.EnvironmentVariableTarget target) -> System.Collections.Generic.IReadOnlyDictionary!
9 | EnvironmentAbstractions.TestHelpers.MockEnvironmentVariableProvider.MockEnvironmentVariableProvider(bool addExistingEnvironmentVariables = false) -> void
10 | EnvironmentAbstractions.TestHelpers.MockEnvironmentVariableProvider.SetEnvironmentVariable(string! name, string? value) -> void
11 | EnvironmentAbstractions.TestHelpers.MockEnvironmentVariableProvider.SetEnvironmentVariable(string! name, string? value, System.EnvironmentVariableTarget target) -> void
12 | EnvironmentAbstractions.TestHelpers.MockEnvironmentVariableProvider.this[string! name].get -> string?
13 | EnvironmentAbstractions.TestHelpers.MockEnvironmentVariableProvider.this[string! name].set -> void
14 | System.MockEnvironmentProvider
15 | System.MockEnvironmentProvider.CommandLine.get -> string!
16 | System.MockEnvironmentProvider.CommandLine.set -> void
17 | System.MockEnvironmentProvider.CurrentDirectory.get -> string!
18 | System.MockEnvironmentProvider.CurrentDirectory.set -> void
19 | System.MockEnvironmentProvider.CurrentManagedThreadId.get -> int
20 | System.MockEnvironmentProvider.CurrentManagedThreadId.set -> void
21 | System.MockEnvironmentProvider.Exit(int exitCode) -> void
22 | System.MockEnvironmentProvider.ExitCode.get -> int
23 | System.MockEnvironmentProvider.ExitCode.set -> void
24 | System.MockEnvironmentProvider.FailFast(string? message) -> void
25 | System.MockEnvironmentProvider.FailFast(string? message, System.Exception? exception) -> void
26 | System.MockEnvironmentProvider.GetCommandLineArgs() -> string![]!
27 | System.MockEnvironmentProvider.GetFolderPath(System.Environment.SpecialFolder folder) -> string!
28 | System.MockEnvironmentProvider.GetFolderPath(System.Environment.SpecialFolder folder, System.Environment.SpecialFolderOption option) -> string!
29 | System.MockEnvironmentProvider.GetLogicalDrives() -> string![]!
30 | System.MockEnvironmentProvider.HasShutdownStarted.get -> bool
31 | System.MockEnvironmentProvider.HasShutdownStarted.set -> void
32 | System.MockEnvironmentProvider.Is64BitOperatingSystem.get -> bool
33 | System.MockEnvironmentProvider.Is64BitOperatingSystem.set -> void
34 | System.MockEnvironmentProvider.Is64BitProcess.get -> bool
35 | System.MockEnvironmentProvider.Is64BitProcess.set -> void
36 | System.MockEnvironmentProvider.MachineName.get -> string!
37 | System.MockEnvironmentProvider.MachineName.set -> void
38 | System.MockEnvironmentProvider.MockEnvironmentProvider(bool useExistingEnvironmentValues = true, bool addExistingEnvironmentVariables = false) -> void
39 | System.MockEnvironmentProvider.NewLine.get -> string!
40 | System.MockEnvironmentProvider.NewLine.set -> void
41 | System.MockEnvironmentProvider.OSVersion.get -> System.OperatingSystem!
42 | System.MockEnvironmentProvider.OSVersion.set -> void
43 | System.MockEnvironmentProvider.ProcessId.get -> int
44 | System.MockEnvironmentProvider.ProcessId.set -> void
45 | System.MockEnvironmentProvider.ProcessorCount.get -> int
46 | System.MockEnvironmentProvider.ProcessorCount.set -> void
47 | System.MockEnvironmentProvider.ProcessPath.get -> string?
48 | System.MockEnvironmentProvider.ProcessPath.set -> void
49 | System.MockEnvironmentProvider.SetCommandLineArgs(string![]! args) -> void
50 | System.MockEnvironmentProvider.SetFolderPath(System.Environment.SpecialFolder folder, string! path) -> void
51 | System.MockEnvironmentProvider.SetLogicalDrives(string![]! drives) -> void
52 | System.MockEnvironmentProvider.StackTrace.get -> string!
53 | System.MockEnvironmentProvider.StackTrace.set -> void
54 | System.MockEnvironmentProvider.SystemDirectory.get -> string!
55 | System.MockEnvironmentProvider.SystemDirectory.set -> void
56 | System.MockEnvironmentProvider.SystemPageSize.get -> int
57 | System.MockEnvironmentProvider.SystemPageSize.set -> void
58 | System.MockEnvironmentProvider.TickCount.get -> int
59 | System.MockEnvironmentProvider.TickCount.set -> void
60 | System.MockEnvironmentProvider.TickCount64.get -> long
61 | System.MockEnvironmentProvider.TickCount64.set -> void
62 | System.MockEnvironmentProvider.UserDomainName.get -> string!
63 | System.MockEnvironmentProvider.UserDomainName.set -> void
64 | System.MockEnvironmentProvider.UserInteractive.get -> bool
65 | System.MockEnvironmentProvider.UserInteractive.set -> void
66 | System.MockEnvironmentProvider.UserName.get -> string!
67 | System.MockEnvironmentProvider.UserName.set -> void
68 | System.MockEnvironmentProvider.Version.get -> System.Version!
69 | System.MockEnvironmentProvider.Version.set -> void
70 | System.MockEnvironmentProvider.WorkingSet.get -> long
71 | System.MockEnvironmentProvider.WorkingSet.set -> void
72 |
--------------------------------------------------------------------------------
/src/EnvironmentAbstractions.TestHelpers/PublicAPI/net8.0/PublicAPI.Unshipped.txt:
--------------------------------------------------------------------------------
1 | #nullable enable
2 | EnvironmentAbstractions.TestHelpers.MockEnvironmentVariableProvider.Add(string! name, string? value, System.EnvironmentVariableTarget environmentVariableTarget) -> void
3 |
--------------------------------------------------------------------------------
/src/EnvironmentAbstractions.TestHelpers/PublicAPI/net9.0/PublicAPI.Shipped.txt:
--------------------------------------------------------------------------------
1 | #nullable enable
2 | EnvironmentAbstractions.TestHelpers.MockEnvironmentVariableProvider
3 | EnvironmentAbstractions.TestHelpers.MockEnvironmentVariableProvider.Add(string! name, string? value) -> void
4 | EnvironmentAbstractions.TestHelpers.MockEnvironmentVariableProvider.ExpandEnvironmentVariables(string! name) -> string?
5 | EnvironmentAbstractions.TestHelpers.MockEnvironmentVariableProvider.GetEnvironmentVariable(string! name) -> string?
6 | EnvironmentAbstractions.TestHelpers.MockEnvironmentVariableProvider.GetEnvironmentVariable(string! name, System.EnvironmentVariableTarget target) -> string?
7 | EnvironmentAbstractions.TestHelpers.MockEnvironmentVariableProvider.GetEnvironmentVariables() -> System.Collections.Generic.IReadOnlyDictionary!
8 | EnvironmentAbstractions.TestHelpers.MockEnvironmentVariableProvider.GetEnvironmentVariables(System.EnvironmentVariableTarget target) -> System.Collections.Generic.IReadOnlyDictionary!
9 | EnvironmentAbstractions.TestHelpers.MockEnvironmentVariableProvider.MockEnvironmentVariableProvider(bool addExistingEnvironmentVariables = false) -> void
10 | EnvironmentAbstractions.TestHelpers.MockEnvironmentVariableProvider.SetEnvironmentVariable(string! name, string? value) -> void
11 | EnvironmentAbstractions.TestHelpers.MockEnvironmentVariableProvider.SetEnvironmentVariable(string! name, string? value, System.EnvironmentVariableTarget target) -> void
12 | EnvironmentAbstractions.TestHelpers.MockEnvironmentVariableProvider.this[string! name].get -> string?
13 | EnvironmentAbstractions.TestHelpers.MockEnvironmentVariableProvider.this[string! name].set -> void
14 | System.MockEnvironmentProvider
15 | System.MockEnvironmentProvider.CommandLine.get -> string!
16 | System.MockEnvironmentProvider.CommandLine.set -> void
17 | System.MockEnvironmentProvider.CpuUsage.get -> System.Environment.ProcessCpuUsage
18 | System.MockEnvironmentProvider.CpuUsage.set -> void
19 | System.MockEnvironmentProvider.CurrentDirectory.get -> string!
20 | System.MockEnvironmentProvider.CurrentDirectory.set -> void
21 | System.MockEnvironmentProvider.CurrentManagedThreadId.get -> int
22 | System.MockEnvironmentProvider.CurrentManagedThreadId.set -> void
23 | System.MockEnvironmentProvider.Exit(int exitCode) -> void
24 | System.MockEnvironmentProvider.ExitCode.get -> int
25 | System.MockEnvironmentProvider.ExitCode.set -> void
26 | System.MockEnvironmentProvider.FailFast(string? message) -> void
27 | System.MockEnvironmentProvider.FailFast(string? message, System.Exception? exception) -> void
28 | System.MockEnvironmentProvider.GetCommandLineArgs() -> string![]!
29 | System.MockEnvironmentProvider.GetFolderPath(System.Environment.SpecialFolder folder) -> string!
30 | System.MockEnvironmentProvider.GetFolderPath(System.Environment.SpecialFolder folder, System.Environment.SpecialFolderOption option) -> string!
31 | System.MockEnvironmentProvider.GetLogicalDrives() -> string![]!
32 | System.MockEnvironmentProvider.HasShutdownStarted.get -> bool
33 | System.MockEnvironmentProvider.HasShutdownStarted.set -> void
34 | System.MockEnvironmentProvider.Is64BitOperatingSystem.get -> bool
35 | System.MockEnvironmentProvider.Is64BitOperatingSystem.set -> void
36 | System.MockEnvironmentProvider.Is64BitProcess.get -> bool
37 | System.MockEnvironmentProvider.Is64BitProcess.set -> void
38 | System.MockEnvironmentProvider.IsPrivilegedProcess.get -> bool
39 | System.MockEnvironmentProvider.MachineName.get -> string!
40 | System.MockEnvironmentProvider.MachineName.set -> void
41 | System.MockEnvironmentProvider.MockEnvironmentProvider(bool useExistingEnvironmentValues = true, bool addExistingEnvironmentVariables = false) -> void
42 | System.MockEnvironmentProvider.NewLine.get -> string!
43 | System.MockEnvironmentProvider.NewLine.set -> void
44 | System.MockEnvironmentProvider.OSVersion.get -> System.OperatingSystem!
45 | System.MockEnvironmentProvider.OSVersion.set -> void
46 | System.MockEnvironmentProvider.ProcessId.get -> int
47 | System.MockEnvironmentProvider.ProcessId.set -> void
48 | System.MockEnvironmentProvider.ProcessorCount.get -> int
49 | System.MockEnvironmentProvider.ProcessorCount.set -> void
50 | System.MockEnvironmentProvider.ProcessPath.get -> string?
51 | System.MockEnvironmentProvider.ProcessPath.set -> void
52 | System.MockEnvironmentProvider.SetCommandLineArgs(string![]! args) -> void
53 | System.MockEnvironmentProvider.SetFolderPath(System.Environment.SpecialFolder folder, string! path) -> void
54 | System.MockEnvironmentProvider.SetLogicalDrives(string![]! drives) -> void
55 | System.MockEnvironmentProvider.StackTrace.get -> string!
56 | System.MockEnvironmentProvider.StackTrace.set -> void
57 | System.MockEnvironmentProvider.SystemDirectory.get -> string!
58 | System.MockEnvironmentProvider.SystemDirectory.set -> void
59 | System.MockEnvironmentProvider.SystemPageSize.get -> int
60 | System.MockEnvironmentProvider.SystemPageSize.set -> void
61 | System.MockEnvironmentProvider.TickCount.get -> int
62 | System.MockEnvironmentProvider.TickCount.set -> void
63 | System.MockEnvironmentProvider.TickCount64.get -> long
64 | System.MockEnvironmentProvider.TickCount64.set -> void
65 | System.MockEnvironmentProvider.UserDomainName.get -> string!
66 | System.MockEnvironmentProvider.UserDomainName.set -> void
67 | System.MockEnvironmentProvider.UserInteractive.get -> bool
68 | System.MockEnvironmentProvider.UserInteractive.set -> void
69 | System.MockEnvironmentProvider.UserName.get -> string!
70 | System.MockEnvironmentProvider.UserName.set -> void
71 | System.MockEnvironmentProvider.Version.get -> System.Version!
72 | System.MockEnvironmentProvider.Version.set -> void
73 | System.MockEnvironmentProvider.WorkingSet.get -> long
74 | System.MockEnvironmentProvider.WorkingSet.set -> void
75 |
--------------------------------------------------------------------------------
/src/EnvironmentAbstractions.TestHelpers/PublicAPI/net9.0/PublicAPI.Unshipped.txt:
--------------------------------------------------------------------------------
1 | #nullable enable
2 | EnvironmentAbstractions.TestHelpers.MockEnvironmentVariableProvider.Add(string! name, string? value, System.EnvironmentVariableTarget environmentVariableTarget) -> void
3 |
--------------------------------------------------------------------------------
/src/EnvironmentAbstractions.TestHelpers/PublicAPI/netstandard2.0/PublicAPI.Shipped.txt:
--------------------------------------------------------------------------------
1 | #nullable enable
2 | EnvironmentAbstractions.TestHelpers.MockEnvironmentVariableProvider
3 | EnvironmentAbstractions.TestHelpers.MockEnvironmentVariableProvider.Add(string! name, string? value) -> void
4 | EnvironmentAbstractions.TestHelpers.MockEnvironmentVariableProvider.ExpandEnvironmentVariables(string! name) -> string?
5 | EnvironmentAbstractions.TestHelpers.MockEnvironmentVariableProvider.GetEnvironmentVariable(string! name) -> string?
6 | EnvironmentAbstractions.TestHelpers.MockEnvironmentVariableProvider.GetEnvironmentVariable(string! name, System.EnvironmentVariableTarget target) -> string?
7 | EnvironmentAbstractions.TestHelpers.MockEnvironmentVariableProvider.GetEnvironmentVariables() -> System.Collections.Generic.IReadOnlyDictionary!
8 | EnvironmentAbstractions.TestHelpers.MockEnvironmentVariableProvider.GetEnvironmentVariables(System.EnvironmentVariableTarget target) -> System.Collections.Generic.IReadOnlyDictionary!
9 | EnvironmentAbstractions.TestHelpers.MockEnvironmentVariableProvider.MockEnvironmentVariableProvider(bool addExistingEnvironmentVariables = false) -> void
10 | EnvironmentAbstractions.TestHelpers.MockEnvironmentVariableProvider.SetEnvironmentVariable(string! name, string? value) -> void
11 | EnvironmentAbstractions.TestHelpers.MockEnvironmentVariableProvider.SetEnvironmentVariable(string! name, string? value, System.EnvironmentVariableTarget target) -> void
12 | EnvironmentAbstractions.TestHelpers.MockEnvironmentVariableProvider.this[string! name].get -> string?
13 | EnvironmentAbstractions.TestHelpers.MockEnvironmentVariableProvider.this[string! name].set -> void
14 | System.MockEnvironmentProvider
15 | System.MockEnvironmentProvider.CommandLine.get -> string!
16 | System.MockEnvironmentProvider.CommandLine.set -> void
17 | System.MockEnvironmentProvider.CurrentDirectory.get -> string!
18 | System.MockEnvironmentProvider.CurrentDirectory.set -> void
19 | System.MockEnvironmentProvider.CurrentManagedThreadId.get -> int
20 | System.MockEnvironmentProvider.CurrentManagedThreadId.set -> void
21 | System.MockEnvironmentProvider.Exit(int exitCode) -> void
22 | System.MockEnvironmentProvider.ExitCode.get -> int
23 | System.MockEnvironmentProvider.ExitCode.set -> void
24 | System.MockEnvironmentProvider.FailFast(string? message) -> void
25 | System.MockEnvironmentProvider.FailFast(string? message, System.Exception? exception) -> void
26 | System.MockEnvironmentProvider.GetCommandLineArgs() -> string![]!
27 | System.MockEnvironmentProvider.GetFolderPath(System.Environment.SpecialFolder folder) -> string!
28 | System.MockEnvironmentProvider.GetFolderPath(System.Environment.SpecialFolder folder, System.Environment.SpecialFolderOption option) -> string!
29 | System.MockEnvironmentProvider.GetLogicalDrives() -> string![]!
30 | System.MockEnvironmentProvider.HasShutdownStarted.get -> bool
31 | System.MockEnvironmentProvider.HasShutdownStarted.set -> void
32 | System.MockEnvironmentProvider.Is64BitOperatingSystem.get -> bool
33 | System.MockEnvironmentProvider.Is64BitOperatingSystem.set -> void
34 | System.MockEnvironmentProvider.Is64BitProcess.get -> bool
35 | System.MockEnvironmentProvider.Is64BitProcess.set -> void
36 | System.MockEnvironmentProvider.MachineName.get -> string!
37 | System.MockEnvironmentProvider.MachineName.set -> void
38 | System.MockEnvironmentProvider.MockEnvironmentProvider(bool useExistingEnvironmentValues = true, bool addExistingEnvironmentVariables = false) -> void
39 | System.MockEnvironmentProvider.NewLine.get -> string!
40 | System.MockEnvironmentProvider.NewLine.set -> void
41 | System.MockEnvironmentProvider.OSVersion.get -> System.OperatingSystem!
42 | System.MockEnvironmentProvider.OSVersion.set -> void
43 | System.MockEnvironmentProvider.ProcessorCount.get -> int
44 | System.MockEnvironmentProvider.ProcessorCount.set -> void
45 | System.MockEnvironmentProvider.SetCommandLineArgs(string![]! args) -> void
46 | System.MockEnvironmentProvider.SetFolderPath(System.Environment.SpecialFolder folder, string! path) -> void
47 | System.MockEnvironmentProvider.SetLogicalDrives(string![]! drives) -> void
48 | System.MockEnvironmentProvider.StackTrace.get -> string!
49 | System.MockEnvironmentProvider.StackTrace.set -> void
50 | System.MockEnvironmentProvider.SystemDirectory.get -> string!
51 | System.MockEnvironmentProvider.SystemDirectory.set -> void
52 | System.MockEnvironmentProvider.SystemPageSize.get -> int
53 | System.MockEnvironmentProvider.SystemPageSize.set -> void
54 | System.MockEnvironmentProvider.TickCount.get -> int
55 | System.MockEnvironmentProvider.TickCount.set -> void
56 | System.MockEnvironmentProvider.UserDomainName.get -> string!
57 | System.MockEnvironmentProvider.UserDomainName.set -> void
58 | System.MockEnvironmentProvider.UserInteractive.get -> bool
59 | System.MockEnvironmentProvider.UserInteractive.set -> void
60 | System.MockEnvironmentProvider.UserName.get -> string!
61 | System.MockEnvironmentProvider.UserName.set -> void
62 | System.MockEnvironmentProvider.Version.get -> System.Version!
63 | System.MockEnvironmentProvider.Version.set -> void
64 | System.MockEnvironmentProvider.WorkingSet.get -> long
65 | System.MockEnvironmentProvider.WorkingSet.set -> void
66 |
--------------------------------------------------------------------------------
/src/EnvironmentAbstractions.TestHelpers/PublicAPI/netstandard2.0/PublicAPI.Unshipped.txt:
--------------------------------------------------------------------------------
1 | #nullable enable
2 | EnvironmentAbstractions.TestHelpers.MockEnvironmentVariableProvider.Add(string! name, string? value, System.EnvironmentVariableTarget environmentVariableTarget) -> void
3 |
--------------------------------------------------------------------------------
/src/EnvironmentAbstractions.TestHelpers/README.md:
--------------------------------------------------------------------------------
1 | # EnvironmentAbstractions.TestHelpers
2 | 
3 |
4 |
5 |
6 | ## Examples of `MockEnvironmentProvider`
7 |
8 | The `EnvironmentAbstractions.TestHelpers` provides a helper implementation of `IEnvironmentProvider` which can be passed to classes to mock access to the environment.
9 |
10 | By default, all existing values are set from the current environment.
11 | ```c#
12 | [Fact]
13 | public void MethodReturnsExpectedValue()
14 | {
15 | IEnvironmentProvider environmentProvider = new MockEnvironmentProvider();
16 |
17 | MyClass instance = new MyClass(environmentProvider);
18 |
19 | string value = instance.Method();
20 | }
21 | ```
22 |
23 | To use an instance of the environment without any values already set, specify the `useExistingEnvironmentValues` parameter to the `MockEnvironmentProvider` constructor:
24 | ```c#
25 | [Fact]
26 | public void MethodReturnsExpectedValue()
27 | {
28 | IEnvironmentProvider environmentProvider = new MockEnvironmentProvider(useExistingEnvironmentValues: false);
29 |
30 | // The only Environment property with a value will be UserName
31 | environmentProvider.UserName = "UserA";
32 | }
33 | ```
34 |
35 | To use an instance of the environment with existing environment variable values, specify the `addExistingEnvironmentVariables` parameter to the `MockEnvironmentProvider` constructor:
36 | ```c#
37 | [Fact]
38 | public void MethodReturnsExpectedValue()
39 | {
40 | IEnvironmentProvider environmentProvider = new MockEnvironmentProvider(addExistingEnvironmentVariables: true);
41 |
42 | // All existing environment variables are set but UserName is overidden
43 | environmentProvider["UserName"] = "UserA";
44 | }
45 | ```
46 |
47 |
48 |
49 |
50 | ## Examples of `MockEnvironmentVariableProvider`
51 |
52 | The `EnvironmentAbstractions.TestHelpers` provides a helper implementation of `IEnvironmentVariableProvider` which can be passed to classes to mock environment variable values.
53 |
54 | Use a clean set of environment variables where only what is added is available
55 | ```c#
56 | [Fact]
57 | public void MethodReturnsExpectedValue()
58 | {
59 | IEnvironmentVariableProvider environmentVariableProvider = new MockEnvironmentVariableProvider
60 | {
61 | ["Variable1"] = "Value1";
62 | };
63 |
64 | MyClass instance = new MyClass(environmentVariableProvider);
65 |
66 | string value = instance.Method();
67 | }
68 | ```
69 |
70 | To make all existing environment variables available, specify the `addExistingEnvironmentVariables` parameter to the `MockEnvironmentVariableProvider` constructor:
71 | ```c#
72 | [Fact]
73 | public void MethodReturnsExpectedValue()
74 | {
75 | IEnvironmentVariableProvider environmentVariableProvider = new MockEnvironmentVariableProvider(addExistingEnvironmentVariables: true);
76 |
77 | environmentVariableProvider["UserName"] = @"User1";
78 |
79 | // Accessing environment variables returns actual values except %UserName% has been changed for just this test
80 | }
81 | ```
82 |
--------------------------------------------------------------------------------
/src/EnvironmentAbstractions.UnitTests/EnvironmentAbstractions.UnitTests.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 | net472;net6.0;net8.0;net9.0
4 | false
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
--------------------------------------------------------------------------------
/src/EnvironmentAbstractions.UnitTests/HashtableIDictionaryWrapperTests.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Jeff Kluge.
2 | //
3 | // Licensed under the MIT license.
4 |
5 | using Shouldly;
6 | using System;
7 | using System.Collections;
8 | using System.Collections.Generic;
9 | using System.Linq;
10 | using Xunit;
11 | using Xunit.Abstractions;
12 |
13 | namespace EnvironmentAbstractions.UnitTests
14 | {
15 | public class HashtableIDictionaryWrapperTests : TestBase
16 | {
17 | public HashtableIDictionaryWrapperTests(ITestOutputHelper testOutput)
18 | : base(testOutput)
19 | {
20 | }
21 |
22 | [Fact]
23 | public void GetEnvironmentVariablesWrapperContainsKeyReturnsSameValueAsGetEnvironmentVariable()
24 | {
25 | IDictionary environmentVariables = Environment.GetEnvironmentVariables();
26 |
27 | GetEnvironmentVariablesWrapper wrapper = new GetEnvironmentVariablesWrapper(environmentVariables);
28 |
29 | foreach (KeyValuePair environmentVariable in environmentVariables.Cast().Select(i => new KeyValuePair((string)i.Key, (string)i.Value!)))
30 | {
31 | wrapper.ContainsKey(environmentVariable.Key).ShouldBeTrue();
32 | }
33 | }
34 |
35 | [Fact]
36 | public void GetEnvironmentVariablesWrapperEnumerateSeveralTimes()
37 | {
38 | GetEnvironmentVariablesWrapper wrapper = new GetEnvironmentVariablesWrapper();
39 |
40 | foreach (int iteration in Enumerable.Range(0, 3))
41 | {
42 | int count = 0;
43 |
44 | foreach (var item in wrapper)
45 | {
46 | count++;
47 |
48 | item.Key.ShouldNotBeNull();
49 | }
50 |
51 | count.ShouldNotBe(0);
52 | }
53 | }
54 |
55 | [Fact]
56 | public void GetEnvironmentVariablesWrapperGetEnumeratorSameAsGetEnvironmentVariables()
57 | {
58 | IDictionary environmentVariables = Environment.GetEnvironmentVariables();
59 |
60 | GetEnvironmentVariablesWrapper wrapper = new GetEnvironmentVariablesWrapper(environmentVariables);
61 |
62 | Dictionary expected = environmentVariables.Cast().ToDictionary(i => (string)i.Key, i => (string)i.Value!);
63 |
64 | wrapper.ToDictionary(i => i.Key, i => i.Value).ShouldBeSubsetOf(expected);
65 | }
66 |
67 | [Fact]
68 | public void GetEnvironmentVariablesWrapperIndexerReturnsSameValueAsGetEnvironmentVariable()
69 | {
70 | IDictionary environmentVariables = Environment.GetEnvironmentVariables();
71 |
72 | GetEnvironmentVariablesWrapper wrapper = new GetEnvironmentVariablesWrapper(environmentVariables);
73 |
74 | foreach (KeyValuePair environmentVariable in environmentVariables.Cast().Select(i => new KeyValuePair((string)i.Key, (string)i.Value!)))
75 | {
76 | string actual = wrapper[environmentVariable.Key];
77 |
78 | actual.ShouldBe(environmentVariable.Value);
79 | }
80 | }
81 |
82 | [Fact]
83 | public void GetEnvironmentVariablesWrapperKeysSameAsGetEnvironmentVariables()
84 | {
85 | IDictionary environmentVariables = Environment.GetEnvironmentVariables();
86 |
87 | GetEnvironmentVariablesWrapper wrapper = new GetEnvironmentVariablesWrapper(environmentVariables);
88 |
89 | IEnumerable expected = environmentVariables.Cast().Select(i => (string)i.Key);
90 |
91 | wrapper.Keys.ShouldBe(expected);
92 | }
93 |
94 | [Fact]
95 | public void GetEnvironmentVariablesWrapperNonExistentValueSameAsGetEnvironmentVariable()
96 | {
97 | GetEnvironmentVariablesWrapper wrapper = new GetEnvironmentVariablesWrapper();
98 |
99 | wrapper.TryGetValue("SOMETHINGTHATDOESNOTEXIST", out string value).ShouldBeFalse();
100 |
101 | value.ShouldBeNull();
102 | }
103 |
104 | [Fact]
105 | public void GetEnvironmentVariablesWrapperTryGetValueReturnsSameValueAsGetEnvironmentVariable()
106 | {
107 | IDictionary environmentVariables = Environment.GetEnvironmentVariables();
108 |
109 | GetEnvironmentVariablesWrapper wrapper = new GetEnvironmentVariablesWrapper(environmentVariables);
110 |
111 | foreach (KeyValuePair environmentVariable in environmentVariables.Cast().Select(i => new KeyValuePair((string)i.Key, (string)i.Value!)))
112 | {
113 | wrapper.TryGetValue(environmentVariable.Key, out string actual).ShouldBeTrue($"{environmentVariable.Key} should exist");
114 |
115 | actual.ShouldBe(environmentVariable.Value);
116 | }
117 | }
118 |
119 | [Fact]
120 | public void GetEnvironmentVariablesWrapperValuesSameAsGetEnvironmentVariables()
121 | {
122 | IDictionary environmentVariables = Environment.GetEnvironmentVariables();
123 |
124 | GetEnvironmentVariablesWrapper wrapper = new GetEnvironmentVariablesWrapper(environmentVariables);
125 |
126 | IEnumerable expected = environmentVariables.Cast().Select(i => (string)i.Value!);
127 |
128 | wrapper.Values.ShouldBe(expected);
129 | }
130 | }
131 | }
--------------------------------------------------------------------------------
/src/EnvironmentAbstractions.UnitTests/IEnvironmentVariableProviderTests.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Jeff Kluge.
2 | //
3 | // Licensed under the MIT license.
4 |
5 | using Shouldly;
6 | using System;
7 | using System.Collections.Generic;
8 | using Xunit;
9 |
10 | namespace EnvironmentAbstractions.UnitTests
11 | {
12 | public class IEnvironmentVariableProviderTests
13 | {
14 | [Fact]
15 | public void GetEnvironmentVariableTest()
16 | {
17 | IEnvironmentVariableProvider mock = new ImplementationOfIIEnvironmentVariableProvider();
18 |
19 | mock.GetEnvironmentVariable("Test").ShouldBe("Test");
20 | }
21 |
22 | private class ImplementationOfIIEnvironmentVariableProvider : IEnvironmentVariableProvider
23 | {
24 | public string? ExpandEnvironmentVariables(string name)
25 | {
26 | throw new NotImplementedException();
27 | }
28 |
29 | public string? GetEnvironmentVariable(string name, EnvironmentVariableTarget target)
30 | {
31 | return name;
32 | }
33 |
34 | public string? GetEnvironmentVariable(string name)
35 | {
36 | return name;
37 | }
38 |
39 | public IReadOnlyDictionary GetEnvironmentVariables()
40 | {
41 | throw new NotImplementedException();
42 | }
43 |
44 | public IReadOnlyDictionary GetEnvironmentVariables(EnvironmentVariableTarget target)
45 | {
46 | throw new NotImplementedException();
47 | }
48 |
49 | public void SetEnvironmentVariable(string name, string? value)
50 | {
51 | }
52 |
53 | public void SetEnvironmentVariable(string name, string? value, EnvironmentVariableTarget target)
54 | {
55 | }
56 | }
57 | }
58 | }
--------------------------------------------------------------------------------
/src/EnvironmentAbstractions.UnitTests/MoqTests.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Jeff Kluge.
2 | //
3 | // Licensed under the MIT license.
4 |
5 | using Moq;
6 | using Shouldly;
7 | using System;
8 | using Xunit;
9 |
10 | namespace EnvironmentAbstractions.UnitTests
11 | {
12 | public class MoqTests
13 | {
14 | [Fact]
15 | public void GetEnvironmentVariableMoqTest()
16 | {
17 | Mock environmentVariableProviderMock = new Mock();
18 |
19 | environmentVariableProviderMock.Setup(i => i.GetEnvironmentVariable(It.Is(i => i.Equals("Var1"))))
20 | .Returns("Value1");
21 |
22 | environmentVariableProviderMock.Setup(i => i.GetEnvironmentVariable(It.Is(i => i.Equals("Var2"))))
23 | .Returns("Value2");
24 |
25 | IEnvironmentVariableProvider environmentVariableProvider = environmentVariableProviderMock.Object;
26 |
27 | environmentVariableProvider.GetEnvironmentVariable("Var1")
28 | .ShouldBe("Value1");
29 |
30 | environmentVariableProvider.GetEnvironmentVariable("Var2")
31 | .ShouldBe("Value2");
32 | }
33 |
34 | [Theory]
35 | [InlineData(EnvironmentVariableTarget.Machine)]
36 | [InlineData(EnvironmentVariableTarget.Process)]
37 | [InlineData(EnvironmentVariableTarget.User)]
38 | public void GetEnvironmentVariableWithEnvironmentVariableTargetMoqTest(EnvironmentVariableTarget environmentVariableTarget)
39 | {
40 | Mock environmentVariableProviderMock = new Mock();
41 |
42 | environmentVariableProviderMock.Setup(i => i.GetEnvironmentVariable(It.IsAny(), It.Is(i => i.Equals(environmentVariableTarget))))
43 | .Returns("Value1");
44 |
45 | IEnvironmentVariableProvider environmentVariableProvider = environmentVariableProviderMock.Object;
46 |
47 | environmentVariableProvider.GetEnvironmentVariable("Anything", environmentVariableTarget)
48 | .ShouldBe("Value1");
49 | }
50 | }
51 | }
--------------------------------------------------------------------------------
/src/EnvironmentAbstractions.UnitTests/SystemEnvironmentProviderTests.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Jeff Kluge.
2 | //
3 | // Licensed under the MIT license.
4 |
5 | using Shouldly;
6 | using System;
7 | using System.Collections.Generic;
8 | using System.Linq;
9 | using Xunit;
10 | using Xunit.Abstractions;
11 |
12 | namespace EnvironmentAbstractions.UnitTests
13 | {
14 | public class SystemEnvironmentProviderTests : TestBase
15 | {
16 | private const string EnvironentVariablePrefix = "__TEST_ENVVAR_FROM_";
17 |
18 | private readonly IEnvironmentProvider _environmentVariableProvider = SystemEnvironmentProvider.Instance;
19 |
20 | public SystemEnvironmentProviderTests(ITestOutputHelper testOutput)
21 | : base(testOutput)
22 | {
23 | }
24 |
25 | public static IEnumerable