/
TestUtilities.cs
100 lines (88 loc) · 3.18 KB
/
TestUtilities.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
using Validation;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
/// <summary>
/// Test utility methods.
/// </summary>
internal static class TestUtilities
{
/// <summary>
/// Recursively delete a directory, even after a git commit has been authored within it.
/// </summary>
/// <param name="path">The path to delete.</param>
internal static void DeleteDirectory(string path)
{
Requires.NotNullOrEmpty(path, nameof(path));
Requires.Argument(Path.IsPathRooted(path), nameof(path), "Must be rooted.");
try
{
Directory.Delete(path, true);
}
catch (UnauthorizedAccessException)
{
// Unknown why this fails so often.
// Somehow making commits with libgit2sharp locks files
// such that we can't delete them (but Windows Explorer can).
var psi = new ProcessStartInfo("cmd.exe", $"/c rd /s /q \"{path}\"");
psi.WorkingDirectory = Path.GetTempPath();
psi.WindowStyle = ProcessWindowStyle.Hidden;
var process = Process.Start(psi);
process.WaitForExit();
}
}
internal static Stream GetEmbeddedResource(string resourcePath)
{
Requires.NotNullOrEmpty(resourcePath, nameof(resourcePath));
return Assembly.GetExecutingAssembly().GetManifestResourceStream($"{ThisAssembly.RootNamespace}.{resourcePath.Replace('\\', '.')}");
}
internal static void ExtractEmbeddedResource(string resourcePath, string extractedFilePath)
{
Requires.NotNullOrEmpty(resourcePath, nameof(resourcePath));
Requires.NotNullOrEmpty(extractedFilePath, nameof(extractedFilePath));
using (var stream = GetEmbeddedResource(resourcePath))
{
Requires.Argument(stream != null, nameof(resourcePath), "Resource not found.");
using (var extractedFile = File.OpenWrite(extractedFilePath))
{
stream.CopyTo(extractedFile);
}
}
}
internal static ExpandedRepo ExtractRepoArchive(string repoArchiveName)
{
string archiveFilePath = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
string expandedFolderPath = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
ExtractEmbeddedResource($"repos.{repoArchiveName}.zip", archiveFilePath);
try
{
System.IO.Compression.ZipFile.ExtractToDirectory(archiveFilePath, expandedFolderPath);
return new ExpandedRepo(expandedFolderPath);
}
finally
{
File.Delete(archiveFilePath);
}
}
internal class ExpandedRepo : IDisposable
{
internal ExpandedRepo(string repoPath)
{
Requires.NotNullOrEmpty(repoPath, nameof(repoPath));
this.RepoPath = repoPath;
}
public string RepoPath { get; private set; }
public void Dispose()
{
if (Directory.Exists(this.RepoPath))
{
DeleteDirectory(this.RepoPath);
}
}
}
}