|
| 1 | +// Copyright (c) Microsoft. All rights reserved. |
| 2 | +// Licensed under the MIT license. See LICENSE file in the project root for full license information. |
| 3 | + |
| 4 | +using System.Runtime.CompilerServices; |
| 5 | + |
| 6 | +namespace System.IO |
| 7 | +{ |
| 8 | + /// <summary>Base class for test classes the use temporary files that need to be cleaned up.</summary> |
| 9 | + public abstract class TemporaryFilesCleanupTestBase : IDisposable |
| 10 | + { |
| 11 | + /// <summary>Initialize the test class base.</summary> |
| 12 | + protected TemporaryFilesCleanupTestBase() |
| 13 | + { |
| 14 | + // Use a unique test directory per test class |
| 15 | + TestDirectory = Path.Combine(Path.GetTempPath(), GetType().Name + "_" + Guid.NewGuid().ToString("N")); |
| 16 | + try |
| 17 | + { |
| 18 | + Directory.CreateDirectory(TestDirectory); |
| 19 | + } |
| 20 | + catch |
| 21 | + { |
| 22 | + // Don't throw exceptions during test class construction. Attempts to use paths |
| 23 | + // under this directory will instead appropriately fail later. |
| 24 | + } |
| 25 | + } |
| 26 | + |
| 27 | + ~TemporaryFilesCleanupTestBase() |
| 28 | + { |
| 29 | + Dispose(false); |
| 30 | + } |
| 31 | + |
| 32 | + public void Dispose() |
| 33 | + { |
| 34 | + Dispose(true); |
| 35 | + GC.SuppressFinalize(this); |
| 36 | + } |
| 37 | + |
| 38 | + protected void Dispose(bool disposing) |
| 39 | + { |
| 40 | + // No managed resources to clean up. |
| 41 | + |
| 42 | + try { Directory.Delete(TestDirectory, recursive: true); } |
| 43 | + catch { } // avoid exceptions from Dispose |
| 44 | + } |
| 45 | + |
| 46 | + /// <summary>Gets the test directory into which all files and directories created by tests should be stored.</summary> |
| 47 | + protected string TestDirectory { get; private set; } |
| 48 | + |
| 49 | + /// <summary>Generates a test file full path that is unique to the call site.</summary> |
| 50 | + protected string GetTestFilePath([CallerMemberName]string fileName = null, [CallerLineNumber] int lineNumber = 0) |
| 51 | + { |
| 52 | + return Path.Combine(TestDirectory, GetTestFileName(fileName, lineNumber)); |
| 53 | + } |
| 54 | + |
| 55 | + /// <summary>Generates a test file name that is unique to the call site.</summary> |
| 56 | + protected string GetTestFileName([CallerMemberName]string fileName = null, [CallerLineNumber] int lineNumber = 0) |
| 57 | + { |
| 58 | + return string.Format("{0}_{1}", fileName ?? "TestBase", lineNumber); |
| 59 | + } |
| 60 | + } |
| 61 | +} |
0 commit comments