Skip to content

Instantly share code, notes, and snippets.

@mscottreed
Created October 23, 2017 20:21
Show Gist options
  • Save mscottreed/0f3c3756feed3d3aa7a156cdbe703d37 to your computer and use it in GitHub Desktop.
Save mscottreed/0f3c3756feed3d3aa7a156cdbe703d37 to your computer and use it in GitHub Desktop.
public class Approvals
{
public static void Verify(string text, [CallerFilePath] string callerFilePath = null, [CallerMemberName] string callerName = null)
{
string approvedText = null;
string filePath = BuildApprovalFilePath(callerFilePath, callerName);
var approvedFilePath = filePath + ".approved.txt";
var receivedFilePath = filePath + ".received.txt";
if (File.Exists(approvedFilePath))
{
approvedText = File.ReadAllText(approvedFilePath);
}
else
{
File.WriteAllText(receivedFilePath, text);
throw new Exception($"Approval file {approvedFilePath} does not exist");
}
if (approvedText != text)
{
File.WriteAllText(receivedFilePath, text);
Process.Start(@"C:\Program Files (x86)\WinMerge\WinMergeU.exe", $"\"{receivedFilePath}\" \"{approvedFilePath}\"");
}
else
{
if (File.Exists(receivedFilePath))
{
File.Delete(receivedFilePath);
}
}
Assert.Equal(approvedText, text);
}
public static void VerifyAll<T>(IEnumerable<T> collection, [CallerFilePath] string callerFilePath = null,
[CallerMemberName] string callerName = null)
{
Verify(string.Join(Environment.NewLine, collection), callerFilePath, callerName);
}
private static string BuildApprovalFilePath(string callerFilePath, string callerName)
{
var directory = Path.GetDirectoryName(callerFilePath);
return Path.Combine(directory, callerName);
}
}
@Foovanadil
Copy link

@mscottreed

Small tweak that I think is better

Change the throwing of an exception when the approved file doesn't exist to simply create an empty file.

That way when you run the first time you don't just always get an exception but a diff failure with the actual and an empty file as the expected.

change:

throw new Exception($"Approval file {approvedFilePath} does not exist");

to

File.Create(approvedFilePath);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment