示例#1
0
        private static void CheckApproval(Assembly assembly, [CallerMemberName] string memberName = null, [CallerFilePath] string filePath = null)
        {
            var targetFrameworkName = Assembly.GetExecutingAssembly().GetTargetFrameworkName();

            var sourceDirectory = Path.GetDirectoryName(filePath);

            var approvedFileName = Path.Combine(sourceDirectory, $"ApiApprovalTests.{memberName}.{targetFrameworkName}.approved.txt");
            var receivedFileName = Path.Combine(sourceDirectory, $"ApiApprovalTests.{memberName}.{targetFrameworkName}.received.txt");

            if (!File.Exists(receivedFileName))
            {
                File.Create(receivedFileName);
            }

            if (!File.Exists(approvedFileName))
            {
                File.Create(approvedFileName);
            }

            var approvedPublicApi = File.ReadAllText(approvedFileName);

            var receivedPublicApi = Filter(ApiGenerator.GeneratePublicApi(assembly, null));

            if (!string.Equals(receivedPublicApi, approvedPublicApi, StringComparison.InvariantCulture))
            {
                File.WriteAllText(receivedFileName, receivedPublicApi);
                DiffRunner.Launch(receivedFileName, approvedFileName);
            }

            Assert.Equal(approvedPublicApi, receivedPublicApi);
        }
 public void Report(string approved, string received)
 {
     if (DiffRunner.Launch(received, approved) == LaunchResult.NoDiffToolForExtension)
     {
         throw new Exception($"Could not find a diff tool for extension: {Path.GetExtension(received)}");
     }
 }
示例#3
0
        /// <summary>
        /// Checks to make sure the API is approved.
        /// </summary>
        /// <param name="assembly">The assembly that is being checked.</param>
        /// <param name="memberName">The caller member.</param>
        /// <param name="filePath">The caller file path.</param>
        public static void CheckApproval(this Assembly assembly, [CallerMemberName] string memberName = null, [CallerFilePath] string filePath = null)
        {
            var targetFrameworkName = Assembly.GetExecutingAssembly().GetTargetFrameworkName();

            var sourceDirectory = Path.GetDirectoryName(filePath);

            var approvedFileName = Path.Combine(sourceDirectory, $"ApiApprovalTests.{memberName}.{targetFrameworkName}.approved.txt");
            var receivedFileName = Path.Combine(sourceDirectory, $"ApiApprovalTests.{memberName}.{targetFrameworkName}.received.txt");

            string approvedPublicApi = string.Empty;

            if (File.Exists(approvedFileName))
            {
                approvedPublicApi = File.ReadAllText(approvedFileName);
            }

            var generatorOptions = new ApiGeneratorOptions {
                WhitelistedNamespacePrefixes = new[] { "Splat" }
            };
            var receivedPublicApi = Filter(ApiGenerator.GeneratePublicApi(assembly, generatorOptions));

            if (!string.Equals(receivedPublicApi, approvedPublicApi, StringComparison.InvariantCulture))
            {
                File.WriteAllText(receivedFileName, receivedPublicApi);
                DiffRunner.Launch(receivedFileName, approvedFileName);
            }

            Assert.Equal(approvedPublicApi, receivedPublicApi);
        }
 public void Launch()
 {
     if (DiffTools.TryGetTextDiff("txt", out var diffTool))
     {
         DiffRunner.Launch(diffTool, Path.Combine(SourceDirectory, "DiffRunnerFile1.txt"), Path.Combine(SourceDirectory, "DiffRunnerFile2.txt"));
     }
 }
示例#5
0
        protected void RunTest(string folderName, string fileName)
        {
            var filePath = Path.Combine(
                this.rootDirectory.FullName,
                "TestFiles",
                folderName,
                fileName + ".cst"
                );
            var fileReaderResult =
                FileReader.ReadFile(filePath, new FileSystem(), CancellationToken.None).Result;

            var formatter = new CodeFormatter();
            var result    = formatter.Format(
                fileReaderResult.FileContents,
                new PrinterOptions()
            {
                Width = PrinterOptions.WidthUsedByTests
            }
                );

            var actualFilePath = filePath.Replace(".cst", ".actual.cst");

            File.WriteAllText(actualFilePath, result.Code, fileReaderResult.Encoding);

            var filePathToChange = filePath;
            var expectedFilePath = actualFilePath.Replace(".actual.", ".expected.");

            var expectedCode = fileReaderResult.FileContents;

            if (File.Exists(expectedFilePath))
            {
                expectedCode     = File.ReadAllText(expectedFilePath, Encoding.UTF8);
                filePathToChange = expectedFilePath;
            }

            if (Environment.GetEnvironmentVariable("NormalizeLineEndings") != null)
            {
                expectedCode = expectedCode.Replace("\r\n", "\n");
                result.Code  = result.Code.Replace("\r\n", "\n");
            }

            var comparer = new SyntaxNodeComparer(
                expectedCode,
                result.Code,
                CancellationToken.None
                );

            result.Errors.Should().BeEmpty();
            result.FailureMessage.Should().BeEmpty();

            if (result.Code != expectedCode && !BuildServerDetector.Detected)
            {
                DiffRunner.Launch(filePathToChange, actualFilePath);
            }
            result.Code.Should().Be(expectedCode);

            var compareResult = comparer.CompareSource();

            compareResult.Should().BeNullOrEmpty();
        }
示例#6
0
    public async Task LaunchAndKillDisabled()
    {
        DiffRunner.Disabled = true;
        try
        {
            Assert.False(IsRunning());
            Assert.False(ProcessCleanup.IsRunning(command));
            var result = await DiffRunner.Launch(file1, file2);

            Assert.Equal(LaunchResult.Disabled, result);
            Thread.Sleep(500);
            ProcessCleanup.Refresh();
            Assert.False(IsRunning());
            Assert.False(ProcessCleanup.IsRunning(command));
            DiffRunner.Kill(file1, file2);
            Thread.Sleep(500);
            ProcessCleanup.Refresh();
            Assert.False(IsRunning());
            Assert.False(ProcessCleanup.IsRunning(command));
        }
        finally
        {
            DiffRunner.Disabled = false;
        }
    }
示例#7
0
    public async Task MaxInstancesToLaunch()
    {
        DiffRunner.MaxInstancesToLaunch(1);
        try
        {
            await Task.Delay(500);

            ProcessCleanup.Refresh();
            var result = await DiffRunner.Launch(file1, "fake.txt");

            await Task.Delay(300);

            Assert.Equal(LaunchResult.StartedNewInstance, result);
            ProcessCleanup.Refresh();
            result = await DiffRunner.Launch(file2, "fake.txt");

            Assert.Equal(LaunchResult.TooManyRunningDiffTools, result);
            ProcessCleanup.Refresh();
            DiffRunner.Kill(file1, "fake.txt");
            DiffRunner.Kill(file2, "fake.txt");
        }
        finally
        {
            DiffRunner.MaxInstancesToLaunch(5);
        }
    }
示例#8
0
    async Task ProcessMissing(StringBuilder builder)
    {
        if (!missings.Any())
        {
            return;
        }

        builder.AppendLine("Pending:");
        foreach (var item in missings)
        {
            builder.AppendLine($"  {Path.GetFileName(item.Verified)}");
            if (BuildServerDetector.Detected)
            {
                continue;
            }
            if (settings.clipboardEnabled)
            {
                await ClipboardCapture.AppendMove(item.Received, item.Verified);
            }

            if (diffTool != null &&
                settings.diffEnabled)
            {
                if (EmptyFilesWrapper.TryWriteEmptyFile(item.Extension, item.Verified))
                {
                    DiffRunner.Launch(diffTool, item.Received, item.Verified);
                }
            }
        }
    }
示例#9
0
        protected static void CheckApproval(Assembly assembly, [CallerMemberName] string?memberName = null, [CallerFilePath] string?filePath = null)
        {
            var targetFrameworkName = Assembly.GetExecutingAssembly().GetTargetFrameworkName();

            var sourceDirectory = Path.GetDirectoryName(filePath);

            if (sourceDirectory == null)
            {
                throw new ArgumentNullException(filePath);
            }

            var approvedFileName = Path.Combine(sourceDirectory, $"ApiApprovalTests.{memberName}.{targetFrameworkName}.approved.txt");
            var receivedFileName = Path.Combine(sourceDirectory, $"ApiApprovalTests.{memberName}.{targetFrameworkName}.received.txt");

            string approvedPublicApi = string.Empty;

            if (File.Exists(approvedFileName))
            {
                approvedPublicApi = File.ReadAllText(approvedFileName);
            }

            var generatorOptions = new ApiGeneratorOptions {
                WhitelistedNamespacePrefixes = new[] { "ReactiveUI", "System.Reactive" }
            };
            var receivedPublicApi = Filter(ApiGenerator.GeneratePublicApi(assembly, generatorOptions));

            if (!string.Equals(receivedPublicApi, approvedPublicApi, StringComparison.InvariantCulture))
            {
                File.WriteAllText(receivedFileName, receivedPublicApi);
                try
                {
                    DiffRunner.Launch(receivedFileName, approvedFileName);
                }
                catch (Exception)
                {
                    var process = new Process
                    {
                        StartInfo = new ProcessStartInfo
                        {
                            Arguments              = $"\"{approvedFileName}\" \"{receivedFileName}\"",
                            UseShellExecute        = false,
                            RedirectStandardOutput = true,
                            CreateNoWindow         = true
                        }
                    };
#if NET_461
                    process.StartInfo.FileName = "FC";
#else
                    process.StartInfo.FileName = "diff";
#endif
                    process.Start();
                    string output = process.StandardOutput.ReadToEnd();
                    process.WaitForExit();

                    throw new Exception("Invalid API configuration: " + Environment.NewLine + output);
                }
            }

            Assert.Equal(approvedPublicApi, receivedPublicApi);
        }
示例#10
0
    public void Launch()
    {
        var path1 = Path.Combine(SourceDirectory, "DiffRunner.file1.txt");
        var path2 = Path.Combine(SourceDirectory, "DiffRunner.file2.txt");

        #region DiffRunnerLaunch
        DiffRunner.Launch(path1, path2);
        #endregion
    }
示例#11
0
    public async Task Kill()
    {
        await DiffRunner.Launch(file1, file2);

        ProcessCleanup.Refresh();
        #region DiffRunnerKill
        DiffRunner.Kill(file1, file2);
        #endregion
    }
示例#12
0
    public void Launch()
    {
        var tempFile   = Path.Combine(SourceDirectory, "DiffRunner.file1.txt");
        var targetFile = Path.Combine(SourceDirectory, "DiffRunner.file2.txt");

        #region DiffRunnerLaunch
        DiffRunner.Launch(tempFile, targetFile);
        #endregion
    }
示例#13
0
        public void Report(string approved, string received)
        {
            var launch = DiffRunner.Launch(received, approved)
                         .GetAwaiter()
                         .GetResult();

            if (launch == LaunchResult.NoDiffToolFound)
            {
                throw new Exception($"Could not find a diff tool for extension: {Path.GetExtension(received)}");
            }
        }
示例#14
0
    async Task Launch()
    {
        string targetFile = "";
        string tempFile   = "";

        #region DiffRunnerLaunch

        await DiffRunner.Launch(tempFile, targetFile);

        #endregion
    }
    public void LaunchAndKill()
    {
        Assert.False(IsRunning());
        Assert.False(ProcessCleanup.IsRunning(command));
        var result = DiffRunner.Launch(file1, file2);

        Assert.Equal(LaunchResult.StartedNewInstance, result);
        Thread.Sleep(500);
        ProcessCleanup.Refresh();
        Assert.True(IsRunning());
        Assert.True(ProcessCleanup.IsRunning(command));
        DiffRunner.Kill(file1, file2);
        Thread.Sleep(500);
        ProcessCleanup.Refresh();
        Assert.False(IsRunning());
        Assert.False(ProcessCleanup.IsRunning(command));
    }
示例#16
0
        protected void RunTest(string folderName, string fileName)
        {
            var filePath = Path.Combine(
                this.rootDirectory.FullName,
                "TestFiles",
                folderName,
                fileName + ".cst"
                );
            var code = File.ReadAllText(filePath);

            var formatter = new CodeFormatter();
            var result    = formatter.Format(code, new Options());

            var actualFilePath = filePath.Replace(".cst", ".actual.cst");

            File.WriteAllText(actualFilePath, result.Code, Encoding.UTF8);

            var filePathToChange = filePath;
            var expectedFilePath = actualFilePath.Replace(
                ".actual.",
                ".expected."
                );

            if (File.Exists(expectedFilePath))
            {
                code             = File.ReadAllText(expectedFilePath, Encoding.UTF8);
                filePathToChange = expectedFilePath;
            }

            var comparer = new SyntaxNodeComparer(
                code,
                result.Code,
                CancellationToken.None
                );

            if (result.Code != code && !BuildServerDetector.Detected)
            {
                DiffRunner.Launch(filePathToChange, actualFilePath);
            }
            result.Code.Should().Be(code);

            var compareResult = comparer.CompareSource();

            compareResult.Should().BeNullOrEmpty();
        }
示例#17
0
    async Task ProcessNotEquals(StringBuilder builder)
    {
        if (!notEquals.Any())
        {
            return;
        }

        builder.AppendLine("Differences:");
        foreach (var item in notEquals)
        {
            builder.AppendLine($"{Path.GetFileName(item.Received)}");
            if (Extensions.IsTextExtension(item.Extension))
            {
                builder.AppendLine($"{File.ReadAllText(item.Received)}");
                if (File.Exists(item.Verified))
                {
                    builder.AppendLine($"{Path.GetFileName(item.Verified)}");
                    builder.AppendLine($"{File.ReadAllText(item.Verified)}");
                }
            }
            if (BuildServerDetector.Detected)
            {
                continue;
            }
            if (settings.autoVerify)
            {
                AcceptChanges(item);
                continue;
            }
            if (settings.clipboardEnabled)
            {
                await ClipboardCapture.AppendMove(item.Received, item.Verified);
            }

            if (diffTool != null &&
                settings.diffEnabled)
            {
                DiffRunner.Launch(diffTool, item.Received, item.Verified);
            }
        }
    }
示例#18
0
    async Task ProcessNotEquals(StringBuilder builder, FilePair item)
    {
        if (settings.handleOnVerifyMismatch != null)
        {
            await settings.handleOnVerifyMismatch(item.Received, item.Verified);
        }
        builder.AppendLine($"{Path.GetFileName(item.Received)}");
        if (Extensions.IsText(item.Extension))
        {
            builder.AppendLine($"{await FileHelpers.ReadText(item.Received)}");
            if (File.Exists(item.Verified))
            {
                builder.AppendLine($"{Path.GetFileName(item.Verified)}");
                builder.AppendLine($"{await FileHelpers.ReadText(item.Verified)}");
            }
        }

        if (BuildServerDetector.Detected)
        {
            return;
        }

        if (settings.autoVerify)
        {
            AcceptChanges(item);
            return;
        }

        if (settings.clipboardEnabled)
        {
            await ClipboardCapture.AppendMove(item.Received, item.Verified);
        }

        if (!settings.diffEnabled)
        {
            return;
        }

        DiffRunner.Launch(item.Received, item.Verified);
    }
示例#19
0
    public void LaunchAndKill()
    {
        if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
        {
            return;
        }
        DiffTools.AddTool(
            name: "FakeDiffTool",
            autoRefresh: true,
            isMdi: false,
            supportsText: true,
            requiresTarget: true,
            arguments: (path1, path2) => $"\"{path1}\" \"{path2}\"",
            exePath: FakeDiffTool.Exe,
            binaryExtensions: new[] { "knownBin" });
        var tempFile   = Path.Combine(SourceDirectory, "DiffRunner.file1.txt");
        var targetFile = Path.Combine(SourceDirectory, "DiffRunner.file2.txt");

        DiffRunner.Launch(tempFile, targetFile);
        Assert.True(IsRunning());
        ProcessCleanup.Refresh();
        DiffRunner.Kill(tempFile, targetFile);
        Assert.False(IsRunning());
    }
        public static void ShouldMatchApproved(this string actual, string?customMessage, Action <ShouldMatchConfigurationBuilder> configureOptions)
        {
            var codeGetter = new ActualCodeTextGetter();
            var stackTrace = new StackTrace(true);

            codeGetter.GetCodeText(actual, stackTrace);

            var configurationBuilder = new ShouldMatchConfigurationBuilder(ShouldlyConfiguration.ShouldMatchApprovedDefaults.Build());

            configureOptions(configurationBuilder);
            var config = configurationBuilder.Build();

            if (config.Scrubber != null)
            {
                actual = config.Scrubber(actual);
            }

            var testMethodInfo = config.TestMethodFinder.GetTestMethodInfo(stackTrace, codeGetter.ShouldlyFrameOffset);
            var discriminator  = config.FilenameDiscriminator == null ? null : "." + config.FilenameDiscriminator;
            var outputFolder   = testMethodInfo.SourceFileDirectory;

            if (string.IsNullOrEmpty(outputFolder))
            {
                throw new Exception($"Source information not available, make sure you are compiling with full debug information. Frame: {testMethodInfo.DeclaringTypeName}.{testMethodInfo.MethodName}");
            }
            if (!string.IsNullOrEmpty(config.ApprovalFileSubFolder))
            {
                outputFolder = Path.Combine(outputFolder, config.ApprovalFileSubFolder);
                Directory.CreateDirectory(outputFolder);
            }

            var approvedFile = Path.Combine(outputFolder, config.FilenameGenerator(testMethodInfo, discriminator, "approved", config.FileExtension));
            var receivedFile = Path.Combine(outputFolder, config.FilenameGenerator(testMethodInfo, discriminator, "received", config.FileExtension));

            File.WriteAllText(receivedFile, actual);

            if (!File.Exists(approvedFile))
            {
                if (!config.PreventDiff)
                {
                    DiffRunner.Launch(receivedFile, approvedFile);
                }

                throw new ShouldMatchApprovedException($@"Approval file {approvedFile}
    does not exist", receivedFile, approvedFile);
            }

            var approvedFileContents = File.ReadAllText(approvedFile);
            var receivedFileContents = File.ReadAllText(receivedFile);
            var assertion            = StringShouldBeAssertionFactory
                                       .Create(approvedFileContents, receivedFileContents, config.StringCompareOptions);
            var contentsMatch = assertion.IsSatisfied();

            if (!contentsMatch)
            {
                if (!config.PreventDiff)
                {
                    DiffRunner.Launch(receivedFile, approvedFile);
                }
                throw new ShouldMatchApprovedException(assertion.GenerateMessage(customMessage), receivedFile, approvedFile);
            }

            File.Delete(receivedFile);
        }
 public void Report(string approved, string received)
 {
     DiffRunner.Launch(diffTool, received, approved);
 }